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
d522bc150024129c5228765640518b246aff9d4a
917
cpp
C++
src/plugins/secman/persistentstorage.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
120
2015-01-22T14:10:39.000Z
2021-11-25T12:57:16.000Z
src/plugins/secman/persistentstorage.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
8
2015-02-07T19:38:19.000Z
2017-11-30T20:18:28.000Z
src/plugins/secman/persistentstorage.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
33
2015-02-07T16:59:55.000Z
2021-10-12T00:36:40.000Z
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2010 Vadim Misbakh-Soloviev, Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #include "persistentstorage.h" #include <QVariant> #include "core.h" namespace LC { namespace SecMan { PersistentStorage::PersistentStorage () { } bool PersistentStorage::HasKey (const QByteArray& key) { return Core::Instance ().Load (key).isValid (); } QVariant PersistentStorage::Get (const QByteArray& key) { return Core::Instance ().Load (key); } void PersistentStorage::Set (const QByteArray& key, const QVariant& value) { Core::Instance ().Store (key, value); } } }
24.783784
83
0.606325
Maledictus
d5260f9491adb7dc7e37e3a26d813b233c0b2b38
1,068
cpp
C++
1. PreliminaryAlgorithm/BinarySearch/1.A1085.cpp
huangjiayu-zju/PAT-A
ecb07409727c56d556a5af1b201158bab0d0d2e8
[ "MIT" ]
null
null
null
1. PreliminaryAlgorithm/BinarySearch/1.A1085.cpp
huangjiayu-zju/PAT-A
ecb07409727c56d556a5af1b201158bab0d0d2e8
[ "MIT" ]
null
null
null
1. PreliminaryAlgorithm/BinarySearch/1.A1085.cpp
huangjiayu-zju/PAT-A
ecb07409727c56d556a5af1b201158bab0d0d2e8
[ "MIT" ]
null
null
null
#include<cstdio> #include<algorithm> using namespace std; //从左至右扫描序列,对其中的每个数a[i],在a[i+1]~a[n-1]内二分查找第一个超过a[i]*p的数的位置j //这样j-i就是对位置i来说满足条件的最远长度,取所有j-i的最大值即可 const int maxn = 100010; int n, p, seq[maxn]; int binarySearch(int i, long long x) { //在[i+1,n-1]范围内查找第一个大于x的数的位置 if (seq[n - 1] <= x) { return n; } int l = i + 1, r = n - 1, mid; while (l < r) { mid = (l + r) / 2; if (seq[mid] > x) { r = mid; } else { l = mid + 1; } } return l; } int main() { scanf("%d%d", &n, &p); for (int i = 0; i < n; i++) { scanf("%d", &seq[i]); } sort(seq, seq + n); //递增排序 int ans = 1; //最大长度,初值为1,表示至少有一个数 for (int i = 0; i < n; i++) { //在seq[i+1,n-1]中查找第一个超过seq[i]*q的数,返回其位置给j int j = binarySearch(i, (long long)seq[i] * p);//注意必须强制类型转换 //int j = upper_bound(seq + i + 1, seq + n, (long long)seq[i] * p) - a;//无需自定义二分查找 ans = max(ans, j - i); } printf("%d\n", ans); return 0; }
21.36
90
0.469101
huangjiayu-zju
d52980a6264b1af8232d923405dda33df7abda2d
4,716
cpp
C++
contrib/preflate/preflate_seq_chain.cpp
Razor12911/xtool
4797195ad310e8f6dc2eae8eb86fe14683f77cf0
[ "MIT" ]
11
2022-01-17T22:05:37.000Z
2022-02-23T19:18:19.000Z
contrib/preflate/preflate_seq_chain.cpp
Razor12911/xtool
4797195ad310e8f6dc2eae8eb86fe14683f77cf0
[ "MIT" ]
null
null
null
contrib/preflate/preflate_seq_chain.cpp
Razor12911/xtool
4797195ad310e8f6dc2eae8eb86fe14683f77cf0
[ "MIT" ]
null
null
null
/* Copyright 2018 Dirk Steinke Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "pch.h" #include <algorithm> #include <string.h> #include "preflate_constants.h" #include "preflate_seq_chain.h" PreflateSeqChain::PreflateSeqChain( const std::vector<unsigned char>& input_) : _input(input_) , totalShift(-8) , curPos(0) { prev = new SeqChainEntry[1 << 16]; memset(heads, 0x00, sizeof(heads)); _build(8, std::min<uint32_t>((1 << 16) - 8, _input.remaining())); } PreflateSeqChain::~PreflateSeqChain() { delete[] prev; } void PreflateSeqChain::_reshift() { const unsigned short delta = 0x7e00; unsigned remaining = (1 << 16) - (delta + 8); // If the head of large sequence is shifted out, // but the tail remains in the cache, // we need to adapt the head and all pointers to it, // that is all members, the next non-member pointing to it // or heads if (prev[delta + 8].distToNext != 0xffff && prev[delta + 8].length < PreflateConstants::MIN_MATCH) { unsigned d = prev[delta + 8].distToNext; prev[delta + 8].distToNext = 0xffff; prev[delta + 8].length = prev[delta + 8 - d].length - d; for (unsigned i = 3; i < prev[delta + 8].length; ++i) { prev[delta + 8 + i - 2].distToNext -= d; } uint8_t c = *_input.curChars(-(int)remaining); if (heads[c] == delta + 8 - d) { heads[c] += d; } else { for (unsigned i = prev[delta + 8].length; i < remaining; ++i) { if (prev[delta + 8 + i].distToNext == i + d) { prev[delta + 8 + i].distToNext -= d; break; } } } } for (unsigned i = 0; i < 256; ++i) { heads[i] = max(heads[i], delta) - delta; } memmove(prev + 8, prev + (delta + 8), sizeof(SeqChainEntry) * remaining); totalShift += delta; _build(8 + remaining, std::min<uint32_t>(delta, _input.remaining())); } void PreflateSeqChain::_build(const unsigned off0, const unsigned size) { if (!size) { return; } const unsigned char* b = _input.curChars(); uint8_t curChar = b[0]; SeqChainEntry startOfSeq = {0xffff, 0x0}, *ptrToFirstOfSeq; unsigned startOff = off0; prev[off0] = startOfSeq; if (off0 > 8 && curChar == b[-1]) { --startOff; // new block continues the old if (curChar == b[-2]) { --startOff; // this is definitely a sequence if (curChar == b[-3]) { // This was already a sequence in the previous block, // just append startOff = heads[curChar]; prev[off0 - 2].distToNext = off0 - startOff - 2; prev[off0 - 1].distToNext = off0 - startOff - 1; prev[off0].distToNext = off0 - startOff; prev[off0].length = 1; } else { // Otherwise enter the sequence in the books prev[startOff].distToNext = startOff - heads[curChar]; prev[startOff + 1].distToNext = 1; prev[startOff + 2].distToNext = 2; prev[startOff + 2].length = 1; heads[curChar] = startOff; } } else { prev[startOff + 1].distToNext = 1; prev[startOff + 1].length = 1; } } ptrToFirstOfSeq = &prev[startOff]; ++ptrToFirstOfSeq->length; uint8_t prevChar = curChar; for (unsigned i = 1; i < size; ++i) { curChar = b[i]; if (prevChar == curChar) { if (++ptrToFirstOfSeq->length == 3) { prev[startOff].distToNext = startOff - heads[prevChar]; heads[prevChar] = startOff; } prev[off0 + i].distToNext = off0 + i - startOff; prev[off0 + i].length = 1; } else { // Last two of a sequence are not a sequence themselves if (ptrToFirstOfSeq->length >= 2) { if (ptrToFirstOfSeq->length >= 3) { prev[off0 + i - 2].distToNext = 0xffff; } prev[off0 + i - 1].distToNext = 0xffff; } prev[off0 + i] = startOfSeq; startOff = off0 + i; ptrToFirstOfSeq = &prev[startOff]; ++ptrToFirstOfSeq->length; } prevChar = curChar; } // Last two of a sequence are not a sequence themselves if (ptrToFirstOfSeq->length >= 2) { if (ptrToFirstOfSeq->length >= 3) { prev[off0 + size - 2].distToNext = 0xffff; } prev[off0 + size - 1].distToNext = 0xffff; } _input.advance(size); }
33.446809
102
0.610263
Razor12911
d5299f014cc7416aa941ddcf4d3e010d2ee6026a
3,648
cpp
C++
clang-tools-extra/clangd/refactor/tweaks/SwapIfBranches.cpp
Santhosh-KS/llvm-project
3f59ff7ab43dc4a56eb5beadc03ab18ba62d478d
[ "Apache-2.0" ]
305
2019-09-14T17:16:05.000Z
2022-03-31T15:05:20.000Z
clang-tools-extra/clangd/refactor/tweaks/SwapIfBranches.cpp
Santhosh-KS/llvm-project
3f59ff7ab43dc4a56eb5beadc03ab18ba62d478d
[ "Apache-2.0" ]
11
2019-10-17T21:11:52.000Z
2022-02-17T20:10:00.000Z
clang-tools-extra/clangd/refactor/tweaks/SwapIfBranches.cpp
Santhosh-KS/llvm-project
3f59ff7ab43dc4a56eb5beadc03ab18ba62d478d
[ "Apache-2.0" ]
24
2019-10-03T11:22:11.000Z
2022-01-25T09:59:30.000Z
//===--- SwapIfBranches.cpp --------------------------------------*- C++-*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "ParsedAST.h" #include "SourceCode.h" #include "refactor/Tweak.h" #include "support/Logger.h" #include "clang/AST/ASTContext.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/AST/Stmt.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/SourceLocation.h" #include "clang/Basic/SourceManager.h" #include "clang/Lex/Lexer.h" #include "clang/Tooling/Core/Replacement.h" #include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Casting.h" #include "llvm/Support/Error.h" namespace clang { namespace clangd { namespace { /// Swaps the 'then' and 'else' branch of the if statement. /// Before: /// if (foo) { return 10; } else { continue; } /// ^^^^^^^ ^^^^ /// After: /// if (foo) { continue; } else { return 10; } class SwapIfBranches : public Tweak { public: const char *id() const override final; bool prepare(const Selection &Inputs) override; Expected<Effect> apply(const Selection &Inputs) override; std::string title() const override { return "Swap if branches"; } Intent intent() const override { return Refactor; } bool hidden() const override { return true; } private: const IfStmt *If = nullptr; }; REGISTER_TWEAK(SwapIfBranches) bool SwapIfBranches::prepare(const Selection &Inputs) { for (const SelectionTree::Node *N = Inputs.ASTSelection.commonAncestor(); N && !If; N = N->Parent) { // Stop once we hit a block, e.g. a lambda in the if condition. if (dyn_cast_or_null<CompoundStmt>(N->ASTNode.get<Stmt>())) return false; If = dyn_cast_or_null<IfStmt>(N->ASTNode.get<Stmt>()); } // avoid dealing with single-statement brances, they require careful handling // to avoid changing semantics of the code (i.e. dangling else). return If && dyn_cast_or_null<CompoundStmt>(If->getThen()) && dyn_cast_or_null<CompoundStmt>(If->getElse()); } Expected<Tweak::Effect> SwapIfBranches::apply(const Selection &Inputs) { auto &Ctx = Inputs.AST->getASTContext(); auto &SrcMgr = Inputs.AST->getSourceManager(); auto ThenRng = toHalfOpenFileRange(SrcMgr, Ctx.getLangOpts(), If->getThen()->getSourceRange()); if (!ThenRng) return error("Could not obtain range of the 'then' branch. Macros?"); auto ElseRng = toHalfOpenFileRange(SrcMgr, Ctx.getLangOpts(), If->getElse()->getSourceRange()); if (!ElseRng) return error("Could not obtain range of the 'else' branch. Macros?"); auto ThenCode = toSourceCode(SrcMgr, *ThenRng); auto ElseCode = toSourceCode(SrcMgr, *ElseRng); tooling::Replacements Result; if (auto Err = Result.add(tooling::Replacement(Ctx.getSourceManager(), ThenRng->getBegin(), ThenCode.size(), ElseCode))) return std::move(Err); if (auto Err = Result.add(tooling::Replacement(Ctx.getSourceManager(), ElseRng->getBegin(), ElseCode.size(), ThenCode))) return std::move(Err); return Effect::mainFileEdit(SrcMgr, std::move(Result)); } } // namespace } // namespace clangd } // namespace clang
38
80
0.626371
Santhosh-KS
d52a43c89110d2ba055080f9d39630405447198c
784
cpp
C++
backend/tests/test-helib-fp-int8_t-encrypt-serialize.cpp
vkurilin/SHEEP
2ccaef32c16efcf5dbc8eefd1dc243bed4ac2fbb
[ "MIT" ]
40
2018-12-03T13:01:06.000Z
2022-02-23T13:04:12.000Z
backend/tests/test-helib-fp-int8_t-encrypt-serialize.cpp
vkurilin/SHEEP
2ccaef32c16efcf5dbc8eefd1dc243bed4ac2fbb
[ "MIT" ]
63
2018-09-11T14:13:31.000Z
2020-01-14T16:12:39.000Z
backend/tests/test-helib-fp-int8_t-encrypt-serialize.cpp
vkurilin/SHEEP
2ccaef32c16efcf5dbc8eefd1dc243bed4ac2fbb
[ "MIT" ]
7
2019-07-10T14:48:31.000Z
2022-03-23T09:12:11.000Z
#include <algorithm> #include <cassert> #include <cstdint> #include "circuit-test-util.hpp" #include "context-helib.hpp" #include "simple-circuits.hpp" using namespace SHEEP; typedef ContextHElib_Fp<int8_t>::Plaintext Plaintext; typedef ContextHElib_Fp<int8_t>::Ciphertext Ciphertext; // Encrypt a value, decrypt the result, and check that we are // left with the original value. void test_single(ContextHElib_Fp<int8_t>& context) { std::vector<Plaintext> pt_orig = {111}; std::string serialized_ciphertext = context.encrypt_and_serialize(pt_orig); std::cout << std::to_string(pt_orig[0]) << " => " << serialized_ciphertext << std::endl; assert(serialized_ciphertext.size() > 0); } int main(void) { ContextHElib_Fp<int8_t> context; test_single(context); }
29.037037
77
0.737245
vkurilin
d52b181fbda472a41941228395103825e045e65e
1,415
cpp
C++
MonoNative/mscorlib/System/Security/Policy/mscorlib_System_Security_Policy_ApplicationTrustEnumerator.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
7
2015-03-10T03:36:16.000Z
2021-11-05T01:16:58.000Z
MonoNative/mscorlib/System/Security/Policy/mscorlib_System_Security_Policy_ApplicationTrustEnumerator.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
1
2020-06-23T10:02:33.000Z
2020-06-24T02:05:47.000Z
MonoNative/mscorlib/System/Security/Policy/mscorlib_System_Security_Policy_ApplicationTrustEnumerator.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
null
null
null
#include <mscorlib/System/Security/Policy/mscorlib_System_Security_Policy_ApplicationTrustEnumerator.h> #include <mscorlib/System/Security/Policy/mscorlib_System_Security_Policy_ApplicationTrust.h> #include <mscorlib/System/mscorlib_System_Type.h> #include <mscorlib/System/mscorlib_System_String.h> namespace mscorlib { namespace System { namespace Security { namespace Policy { //Public Methods mscorlib::System::Boolean ApplicationTrustEnumerator::MoveNext() { MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Policy", "ApplicationTrustEnumerator", 0, NULL, "MoveNext", __native_object__, 0, NULL, NULL, NULL); return *(mscorlib::System::Boolean*)mono_object_unbox(__result__); } void ApplicationTrustEnumerator::Reset() { Global::InvokeMethod("mscorlib", "System.Security.Policy", "ApplicationTrustEnumerator", 0, NULL, "Reset", __native_object__, 0, NULL, NULL, NULL); } //Get Set Properties Methods // Get:Current mscorlib::System::Security::Policy::ApplicationTrust ApplicationTrustEnumerator::get_Current() const { MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Policy", "ApplicationTrustEnumerator", 0, NULL, "get_Current", __native_object__, 0, NULL, NULL, NULL); return mscorlib::System::Security::Policy::ApplicationTrust(__result__); } } } } }
32.906977
183
0.741343
brunolauze
d52c13fb7cc5d68dd3b9ded7b4ce033eecb3378b
4,444
cpp
C++
tem/src/v20210701/model/CreateCosTokenRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
tem/src/v20210701/model/CreateCosTokenRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
tem/src/v20210701/model/CreateCosTokenRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/tem/v20210701/model/CreateCosTokenRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Tem::V20210701::Model; using namespace std; CreateCosTokenRequest::CreateCosTokenRequest() : m_applicationIdHasBeenSet(false), m_pkgNameHasBeenSet(false), m_optTypeHasBeenSet(false), m_sourceChannelHasBeenSet(false), m_timeVersionHasBeenSet(false) { } string CreateCosTokenRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); if (m_applicationIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ApplicationId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_applicationId.c_str(), allocator).Move(), allocator); } if (m_pkgNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "PkgName"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_pkgName.c_str(), allocator).Move(), allocator); } if (m_optTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "OptType"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_optType, allocator); } if (m_sourceChannelHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "SourceChannel"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_sourceChannel, allocator); } if (m_timeVersionHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TimeVersion"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_timeVersion.c_str(), allocator).Move(), allocator); } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } string CreateCosTokenRequest::GetApplicationId() const { return m_applicationId; } void CreateCosTokenRequest::SetApplicationId(const string& _applicationId) { m_applicationId = _applicationId; m_applicationIdHasBeenSet = true; } bool CreateCosTokenRequest::ApplicationIdHasBeenSet() const { return m_applicationIdHasBeenSet; } string CreateCosTokenRequest::GetPkgName() const { return m_pkgName; } void CreateCosTokenRequest::SetPkgName(const string& _pkgName) { m_pkgName = _pkgName; m_pkgNameHasBeenSet = true; } bool CreateCosTokenRequest::PkgNameHasBeenSet() const { return m_pkgNameHasBeenSet; } int64_t CreateCosTokenRequest::GetOptType() const { return m_optType; } void CreateCosTokenRequest::SetOptType(const int64_t& _optType) { m_optType = _optType; m_optTypeHasBeenSet = true; } bool CreateCosTokenRequest::OptTypeHasBeenSet() const { return m_optTypeHasBeenSet; } int64_t CreateCosTokenRequest::GetSourceChannel() const { return m_sourceChannel; } void CreateCosTokenRequest::SetSourceChannel(const int64_t& _sourceChannel) { m_sourceChannel = _sourceChannel; m_sourceChannelHasBeenSet = true; } bool CreateCosTokenRequest::SourceChannelHasBeenSet() const { return m_sourceChannelHasBeenSet; } string CreateCosTokenRequest::GetTimeVersion() const { return m_timeVersion; } void CreateCosTokenRequest::SetTimeVersion(const string& _timeVersion) { m_timeVersion = _timeVersion; m_timeVersionHasBeenSet = true; } bool CreateCosTokenRequest::TimeVersionHasBeenSet() const { return m_timeVersionHasBeenSet; }
26.141176
98
0.729073
suluner
d52d2d1e47065a18db8eb3ef3f8c7da9ff8e291a
37,157
hpp
C++
thirdparty/json-voorhees/include/jsonv/value.hpp
liftchampion/nativejson-benchmark
6d575ffa4359a5c4230f74b07d994602a8016fb5
[ "MIT" ]
null
null
null
thirdparty/json-voorhees/include/jsonv/value.hpp
liftchampion/nativejson-benchmark
6d575ffa4359a5c4230f74b07d994602a8016fb5
[ "MIT" ]
null
null
null
thirdparty/json-voorhees/include/jsonv/value.hpp
liftchampion/nativejson-benchmark
6d575ffa4359a5c4230f74b07d994602a8016fb5
[ "MIT" ]
null
null
null
/** \file jsonv/value.hpp * * Copyright (c) 2012-2015 by Travis Gockel. All rights reserved. * * This program is free software: you can redistribute it and/or modify it under the terms of the Apache License * as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later * version. * * \author Travis Gockel (travis@gockelhut.com) **/ #ifndef __JSONV_VALUE_HPP_INCLUDED__ #define __JSONV_VALUE_HPP_INCLUDED__ #include <jsonv/config.hpp> #include <jsonv/string_view.hpp> #include <jsonv/detail/basic_view.hpp> #include <cstddef> #include <cstdint> #include <initializer_list> #include <iosfwd> #include <iterator> #include <functional> #include <map> #include <stdexcept> #include <string> #include <type_traits> #include <utility> namespace jsonv { class path; class value; namespace detail { class object_impl; class array_impl; class string_impl; union value_storage { object_impl* object; array_impl* array; string_impl* string; int64_t integer; double decimal; bool boolean; constexpr value_storage() : object(nullptr) { } }; } /** Describes the \e kind of data a \c value holds. See \c value for more information. * * \see http://json.org/ **/ enum class kind : unsigned char { null, object, array, string, integer, decimal, boolean }; /** Print out the name of the \c kind. **/ JSONV_PUBLIC std::ostream& operator<<(std::ostream&, const kind&); /** Get the name of the \c kind. **/ JSONV_PUBLIC std::string to_string(const kind&); /** Get a string representation of the given \c value. **/ JSONV_PUBLIC std::string to_string(const value&); /** Thrown from various \c value methods when attempting to perform an operation which is not valid for the \c kind of * value. **/ class JSONV_PUBLIC kind_error : public std::logic_error { public: explicit kind_error(const std::string& description); virtual ~kind_error() noexcept; }; /** Represents a single JSON value, which can be any one of a potential \c kind, each behaving slightly differently. * Instances will vary their behavior based on their kind -- functions will throw a \c kind_error if the operation does * not apply to the value's kind. For example, it does not make sense to call \c find on an \c integer. * * - \c kind::null * You cannot do anything with this...it is just null. * - \c kind::boolean * These values can be \c true or \c false. * - \c kind::integer * A numeric value which can be added, subtracted and all the other things you would expect. * - \c kind::decimal * Floating-point values should be considered "more general" than integers -- you may request an integer value as a * decimal, but you cannot request a decimal as an integer, even when doing so would not require rounding. The * literal \c 20.0 will always have \c kind::decimal. * - \c kind::string * A UTF-8 encoded string which is mostly accessed through the \c std::string class. Some random functions work in * the cases where it makes sense (for example: \c empty and \c size), but in general, string manipulation should be * done after calling \c as_string. * - \c kind::array * An array behaves like a \c std::deque because it is ultimately backed by one. If you feel the documentation is * lacking, read this: http://en.cppreference.com/w/cpp/container/deque. * - \c kind::object * An object behaves lake a \c std::map because it is ultimately backed by one. If you feel the documentation is * lacking, read this: http://en.cppreference.com/w/cpp/container/map. This library follows the recommendation in * RFC 7159 to not allow for duplicate keys because most other libraries can not deal with it. It would also make * the AST significantly more painful. * * \see http://json.org/ * \see http://tools.ietf.org/html/rfc7159 **/ class JSONV_PUBLIC value { public: typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; /** \addtogroup Array * \{ * The base type for iterating over array values. **/ template <typename T, typename TArrayView> struct basic_array_iterator : public std::iterator<std::random_access_iterator_tag, T> { public: basic_array_iterator() : _owner(0), _index(0) { } basic_array_iterator(TArrayView* owner, size_type index) : _owner(owner), _index(index) { } template <typename U, typename UArrayView> basic_array_iterator(const basic_array_iterator<U, UArrayView>& source, typename std::enable_if<std::is_convertible<U*, T*>::value>::type* = 0 ) : _owner(source._owner), _index(source._index) { } basic_array_iterator& operator++() { ++_index; return *this; } basic_array_iterator operator++(int) const { basic_array_iterator clone = *this; ++clone; return clone; } basic_array_iterator& operator--() { --_index; return *this; } basic_array_iterator operator--(int) const { basic_array_iterator clone = *this; --clone; return clone; } template <typename U, typename UArrayView> bool operator==(const basic_array_iterator<U, UArrayView>& other) const { return _owner == other._owner && _index == other._index; } template <typename U, typename UArrayView> bool operator!=(const basic_array_iterator<U, UArrayView>& other) const { return !operator==(other); } T& operator*() const { return _owner->operator[](_index); } T* operator->() const { return &_owner->operator[](_index); } basic_array_iterator& operator+=(size_type n) { _index += n; return *this; } basic_array_iterator operator+(size_type n) const { basic_array_iterator clone = *this; clone += n; return clone; } basic_array_iterator& operator-=(size_type n) { _index -= n; return *this; } basic_array_iterator operator-(size_type n) const { basic_array_iterator clone = *this; clone -= n; return clone; } difference_type operator-(const basic_array_iterator& other) const { return difference_type(_index) - difference_type(other._index); } bool operator<(const basic_array_iterator& rhs) const { return _index < rhs._index; } bool operator<=(const basic_array_iterator& rhs) const { return _index <= rhs._index; } bool operator>(const basic_array_iterator& rhs) const { return _index > rhs._index; } bool operator>=(const basic_array_iterator& rhs) const { return _index >= rhs._index; } T& operator[](size_type n) const { return _owner->operator[](_index + n); } private: template <typename U, typename UArrayView> friend struct basic_array_iterator; friend class value; private: TArrayView* _owner; size_type _index; }; /** The \c array_iterator is applicable when \c kind is \c kind::array. It allows you to use algorithms as if * a \c value was a normal sequence container. **/ typedef basic_array_iterator<value, value> array_iterator; typedef basic_array_iterator<const value, const value> const_array_iterator; /** If \c kind is \c kind::array, an \c array_view allows you to access a value as a sequence container. This is * most useful for range-based for loops. **/ typedef detail::basic_view<array_iterator, const_array_iterator> array_view; typedef detail::basic_view<const_array_iterator> const_array_view; typedef detail::basic_owning_view<value, array_iterator, const_array_iterator> owning_array_view; /** \} **/ /** \addtogroup Object * \{ * The base iterator type for iterating over object types. It is a bidirectional iterator similar to a * \c std::map<std::string, jsonv::value>. **/ template <typename T, typename TIterator> struct basic_object_iterator : public std::iterator<std::bidirectional_iterator_tag, T> { public: basic_object_iterator() : _impl() { } basic_object_iterator(const basic_object_iterator& source) : _impl(source._impl) { } /** This allows assignment from an \c object_iterator to a \c const_object_iterator. **/ template <typename U, typename UIterator> basic_object_iterator(const basic_object_iterator<U, UIterator>& source, typename std::enable_if<std::is_convertible<U*, T*>::value>::type* = 0 ) : _impl(source._impl) { } basic_object_iterator& operator=(const basic_object_iterator& source) { _impl = source._impl; return *this; } template <typename U, typename UIterator> typename std::enable_if<std::is_convertible<U*, T*>::value, basic_object_iterator&>::type operator=(const basic_object_iterator<U, UIterator>& source) { return operator=(basic_object_iterator(source)); } basic_object_iterator& operator++() { increment(); return *this; } basic_object_iterator operator++(int) const { basic_object_iterator clone(*this); clone.increment(); return clone; } basic_object_iterator& operator--() { decrement(); return *this; } basic_object_iterator operator--(int) const { basic_object_iterator clone(*this); clone.decrement(); return clone; } template <typename U, typename UIterator> bool operator ==(const basic_object_iterator<U, UIterator>& other) const { return _impl == other._impl; } template <typename U, typename UIterator> bool operator !=(const basic_object_iterator<U, UIterator>& other) const { return _impl != other._impl; } T& operator *() const { return current(); } T* operator ->() const { return &current(); } private: friend class value; template <typename UIterator> explicit basic_object_iterator(const UIterator& iter) : _impl(iter) { } void increment() { ++_impl; } void decrement() { --_impl; } T& current() const { return *_impl; } private: TIterator _impl; }; /** The type of value stored when \c kind is \c kind::object. **/ typedef std::pair<const std::string, value> object_value_type; /** The \c object_iterator is applicable when \c kind is \c kind::object. It allows you to use algorithms as if * a \c value was a normal associative container. **/ typedef basic_object_iterator<object_value_type, std::map<std::string, value>::iterator> object_iterator; typedef basic_object_iterator<const object_value_type, std::map<std::string, value>::const_iterator> const_object_iterator; /** If \c kind is \c kind::object, an \c object_view allows you to access a value as an associative container. * This is most useful for range-based for loops. **/ typedef detail::basic_view<object_iterator, const_object_iterator> object_view; typedef detail::basic_view<const_object_iterator> const_object_view; typedef detail::basic_owning_view<value, object_iterator, const_object_iterator> owning_object_view; /** \} **/ public: /** Default-construct this to null. **/ constexpr value() : _kind(jsonv::kind::null) { } /** The nullptr overload will fail to compile -- use \c null if you want a \c kind::null. **/ value(std::nullptr_t) = delete; /** Copy the contents of \a source into a new instance. **/ value(const value& source); /** Create a \c kind::string with the given \a value. **/ value(const std::string& value); /** Create a \c kind::string with the given \a value. * * \param value The value to create with. This must be null-terminated. **/ value(const char* value); /** Create a \c kind::string with the given \a value. Keep in mind that it will be converted to and stored as a * UTF-8 encoded string. **/ value(const std::wstring& value); /** Create a \c kind::string with the given \a value. Keep in mind that it will be converted to and stored as a * UTF-8 encoded string. * * \param value The value to create with. This must be null-terminated. **/ value(const wchar_t* value); /** Create a \c kind::integer with the given \a value. **/ value(int64_t value); /** Create a \c kind::decimal with the given \a value. **/ value(double value); /** Create a \c kind::decimal with the given \a value. **/ value(float value); /** Create a \c kind::boolean with the given \a value. **/ value(bool value); #define JSONV_VALUE_INTEGER_ALTERNATIVE_CTOR_PROTO_GENERATOR(type_) \ value(type_ val); JSONV_INTEGER_ALTERNATES_LIST(JSONV_VALUE_INTEGER_ALTERNATIVE_CTOR_PROTO_GENERATOR) /** Destruction will never throw. **/ ~value() noexcept; /** Copy-assigns \c source to this. * * If an exception is thrown during the copy, it is propagated out. This instance will remain unchanged. **/ value& operator=(const value& source); /** Move-construct this instance, leaving \a source as a null value. **/ value(value&& source) noexcept; /** Move-assigns \c source to this, leaving \a source as a null value. * * Unlike a copy, this will never throw. **/ value& operator=(value&& source) noexcept; /** \addtogroup Conversions * These functions are used for accessing specific kinds of values. * \{ **/ /** Get this value as a string. * * \throws kind_error if this value does not represent a string. **/ const std::string& as_string() const; /** Tests if this \c kind is \c kind::string. **/ bool is_string() const; /** Get this value as a wide string. Keep in mind that this is slower than \c as_string, as the internal storage is * the \c char base \c std::string. * * \throws kind_error if this value does not represent a string. **/ std::wstring as_wstring() const; /** Get this value as an integer. * * \throws kind_error if this value does not represent an integer. **/ int64_t as_integer() const; /** Tests if this \c kind is \c kind::integer. **/ bool is_integer() const; /** Get this value as a decimal. If the value's underlying kind is actually an integer type, cast the integer to a * double before returning. This ignores the potential loss of precision. * * \throws kind_error if this value does not represent a decimal or integer. **/ double as_decimal() const; /** Tests if this \c kind is \c kind::integer or \c kind::decimal. **/ bool is_decimal() const; /** Get this value as a boolean. * * \throws kind_error if this value does not represent a boolean. **/ bool as_boolean() const; /** Tests if this \c kind is \c kind::boolean. **/ bool is_boolean() const; /** Tests if this \c kind is \c kind::array. **/ bool is_array() const; /** Tests if this \c kind is \c kind::object. **/ bool is_object() const; /** Tests if this \c kind is \c kind::null. **/ bool is_null() const; /** \} **/ /** \addtogroup Shared * These functions are applicable to all kinds of values and have the same fundemental meaning for all kinds. * \{ **/ /** Resets this value to null. **/ void clear(); /** Get this value's kind. **/ inline jsonv::kind kind() const { return _kind; } /** Get the value specified by the path \a p. * * \throws std::out_of_range if any path along the chain did not exist. * \throws kind_error if the path traversal is not valid for the value (for example: if the path specifies an array * index when the value is a string). * \throws parse_error if a \c string_view was specified that did not have a valid specification (see * \c path::create). **/ value& at_path(const path& p); value& at_path(string_view p); value& at_path(size_type p); const value& at_path(const path& p) const; const value& at_path(string_view p) const; const value& at_path(size_type p) const; /** Similar to \c count, but walks the given path \a p to determine its presence. * * \returns \c 1 if the path finds an element; \c 0 if there is no such path in the tree. * * \throws parse_error if a \c string_view was specified that did not have a valid specification (see * \c path::create). **/ size_type count_path(const path& p) const; size_type count_path(string_view p) const; size_type count_path(size_type p) const; /** Get or create the value specified by the path \a p. This is the moral equivalent to \c operator[] for paths. If * no value exists at the path, a new one is created as the default (\c null) value. If any path along the way * either does not exist or is \c null, it is created for you, based on the \e implications of the specification * \a p. Unlike \c at_path, which will throw if accessing a non-existent key of an \c object or going past the end * of an \c array, this will simply create that path and fill in the blanks with \c null values. * * \throws kind_error if the path traversal is not valid for the value (for example: if the path specifies an array * index when the value is a string). * \throws parse_error if a \c string_view was specified that did not have a valid specification (see * \c path::create). * * \see at_path **/ value& path(const path& p); value& path(string_view p); value& path(size_type p); /** Swap the value this instance represents with \a other. **/ void swap(value& other) noexcept; /** Compares two JSON values for equality. Two JSON values are equal if and only if all of the following conditions * apply: * * 1. They have the same valid value for \c kind. * - If \c kind is invalid (memory corruption), then two JSON values are \e not equal, even if they have been * corrupted in the same way and even if they share \c this (a corrupt object is not equal to itself). * 2. The kind comparison is also equal: * - Two null values are always equivalent. * - string, integer, decimal and boolean follow the classic rules for their type. * - objects are equal if they have the same keys and values corresponding with the same key are also equal. * - arrays are equal if they have the same length and the values at each index are also equal. * * \note * The rules for equality are based on Python \c dict and \c list. **/ bool operator==(const value& other) const; /** Compares two JSON values for inequality. The rules for inequality are the exact opposite of equality. **/ bool operator!=(const value& other) const; /** Used to build a strict-ordering of JSON values. When comparing values of the same kind, the ordering should * align with your intuition. When comparing values of different kinds, some arbitrary rules were created based on * how "complicated" the author thought the type to be. * * - null: less than everything but null, which it is equal to. * - boolean: false is less than true. * - integer, decimal: compared by their numeric value. Comparisons between two integers do not cast, but comparison * between an integer and a decimal will coerce to decimal. * - string: compared lexicographically by character code (with basic char strings and non-ASCII encoding, this * might lead to surprising results) * - array: compared lexicographically by elements (recursively following this same technique) * - object: entries in the object are sorted and compared lexicographically, first by key then by value * * \returns -1 if this is less than other by the rules stated above; 0 if this is equal to other; -1 if otherwise. **/ int compare(const value& other) const; bool operator< (const value& other) const; bool operator> (const value& other) const; bool operator<=(const value& other) const; bool operator>=(const value& other) const; /** Output this value to a stream. **/ friend std::ostream& operator<<(std::ostream& stream, const value& val); /** Get a string representation of the given \c value. **/ friend std::string to_string(const value&); /** \} **/ /** \addtogroup Array * These functions are only applicable if the kind of this value is an array. * \{ **/ /** Get an iterator to the beginning of this array. * * \throws kind_error if the kind is not an array. **/ array_iterator begin_array(); const_array_iterator begin_array() const; /** Get an iterator to the end of this array. * * \throws kind_error if the kind is not an array. **/ array_iterator end_array(); const_array_iterator end_array() const; /** View this instance as an array. * * \throws kind_error if the kind is not an array. **/ array_view as_array() &; const_array_view as_array() const &; owning_array_view as_array() &&; /** Get the value in this array at the given \a idx. The overloads which accept an \c int are required to resolve * the type ambiguity of the literal \c 0 between a size_type and a char*. * * \throws kind_error if the kind is not an array. **/ value& operator[](size_type idx); const value& operator[](size_type idx) const; inline value& operator[](int idx) { return operator[](size_type(idx)); } inline const value& operator[](int idx) const { return operator[](size_type(idx)); } /** Get the value in this array at the given \a idx. * * \throws kind_error if the kind is not an array. * \throws std::out_of_range if the provided \a idx is above \c size. **/ value& at(size_type idx); const value& at(size_type idx) const; /** Push \a item to the back of this array. * * \throws kind_error if the kind is not an array. **/ void push_back(value item); /** Pop an item off the back of this array. * * \throws kind_error if the kind is not an array. * \throws std::logic_error if the array is empty. **/ void pop_back(); /** Push \a item to the front of this array. * * \throws kind_error if the kind is not an array. **/ void push_front(value item); /** Pop an item from the front of this array. * * \throws kind_error if the kind is not an array. * \throws std::logic_error if the array is empty. **/ void pop_front(); /** Insert an item into \a position on this array. * * \throws kind_error if the kind is not an array. **/ array_iterator insert(const_array_iterator position, value item); /** Insert the range defined by [\a first, \a last) at \a position in this array. * * \throws kind_error if the kind is not an array. **/ template <typename TForwardIterator> array_iterator insert(const_array_iterator position, TForwardIterator first, TForwardIterator last) { difference_type orig_offset = std::distance(const_array_iterator(begin_array()), position); for (difference_type offset = orig_offset ; first != last; ++first, ++offset) insert(begin_array() + offset, *first); return begin_array() + orig_offset; } /** Assign \a count elements to this array with \a val. * * \throws kind_error if the kind is not an array. **/ void assign(size_type count, const value& val); /** Assign the contents of range [\a first, \a last) to this array. * * \throws kind_error if the kind is not an array. **/ template <typename TForwardIterator> void assign(TForwardIterator first, TForwardIterator last) { resize(std::distance(first, last), value()); auto iter = begin_array(); while (first != last) { *iter = *first; ++iter; ++first; } } /** Assign the given \a items to this array. * * \throws kind_error if the kind is not an array. **/ void assign(std::initializer_list<value> items); /** Resize the length of this array to \a count items. If the resize creates new elements, fill those newly-created * elements with \a val. * * \throws kind_error if the kind is not an array. **/ void resize(size_type count, const value& val = value()); /** Erase the item at this array's \a position. * * \throws kind_error if the kind is not an array. **/ array_iterator erase(const_array_iterator position); /** Erase the range [\a first, \a last) from this array. * * \throws kind_error if the kind is not an array. **/ array_iterator erase(const_array_iterator first, const_array_iterator last); /** \} **/ /** \addtogroup Object * These functions are only applicable if the kind of this value is an object. * \{ **/ /** Get an iterator to the first key-value pair in this object. * * \throws kind_error if the kind is not an object. **/ object_iterator begin_object(); const_object_iterator begin_object() const; /** Get an iterator to the one past the end of this object. * * \throws kind_error if the kind is not an object. **/ object_iterator end_object(); const_object_iterator end_object() const; /** View this instance as an object. * * \throws kind_error if the kind is not an object. **/ object_view as_object() &; const_object_view as_object() const &; owning_object_view as_object() &&; /** Get the value associated with the given \a key of this object. If the \a key does not exist, it will be created. * * \throws kind_error if the kind is not an object. **/ value& operator[](const std::string& key); value& operator[](std::string&& key); value& operator[](const std::wstring& key); /** Get the value associated with the given \a key of this object. * * \throws kind_error if the kind is not an object. * \throws std::out_of_range if the \a key is not in this object. **/ value& at(const std::string& key); value& at(const std::wstring& key); const value& at(const std::string& key) const; const value& at(const std::wstring& key) const; /** Check if the given \a key exists in this object. * * \throws kind_error if the kind is not an object. **/ size_type count(const std::string& key) const; size_type count(const std::wstring& key) const; /** Attempt to locate a key-value pair with the provided \a key in this object. * * \throws kind_error if the kind is not an object. **/ object_iterator find(const std::string& key); object_iterator find(const std::wstring& key); const_object_iterator find(const std::string& key) const; const_object_iterator find(const std::wstring& key) const; /** Insert \a pair into this object. If \a hint is provided, this insertion could be optimized. * * \returns A pair whose \c first refers to the newly-inserted element (or the element which shares the key). * \throws kind_error if the kind is not an object. **/ std::pair<object_iterator, bool> insert(std::pair<std::string, value> pair); std::pair<object_iterator, bool> insert(std::pair<std::wstring, value> pair); object_iterator insert(const_object_iterator hint, std::pair<std::string, value> pair); object_iterator insert(const_object_iterator hint, std::pair<std::wstring, value> pair); /** Insert range defined by [\a first, \a last) into this object. * * \throws kind_error if the kind is not an object. **/ template <typename TForwardIterator> void insert(TForwardIterator first, TForwardIterator last) { for ( ; first != last; ++first) insert(*first); } /** Insert \a items into this object. * * \throws kind_error if the kind is not an object. **/ void insert(std::initializer_list<std::pair<std::string, value>> items); void insert(std::initializer_list<std::pair<std::wstring, value>> items); /** Erase the item with the given \a key. * * \returns 1 if \a key was erased; 0 if it did not. * \throws kind_error if the kind is not an object. **/ size_type erase(const std::string& key); size_type erase(const std::wstring& key); /** Erase the item at the given \a position. * * \throws kind_error if the kind is not an object. **/ object_iterator erase(const_object_iterator position); /** Erase the range defined by [\a first, \a last). * * \throws kind_error if the kind is not an object. **/ object_iterator erase(const_object_iterator first, const_object_iterator last); /** \} **/ /** \addtogroup Shared * These functions are only applicable if the kind of this value is an array. * \{ **/ /** Is the underlying structure empty? This has similar meaning for all types it works on and is always equivalent * to asking if the size is 0. * * - object: Are there no keys? * - array: Are there no values? * - string: Is the string 0 length? * * \throws kind_error if the kind is not an object, array or string. **/ bool empty() const; /** Get the number of items in this value. * * - object: The number of key/value pairs. * - array: The number of values. * - string: The number of code points in the string (including \c \\0 values and counting multi-byte encodings as * more than one value). * * \throws kind_error if the kind is not an object, array or string. **/ size_type size() const; /** \} **/ /** \addtogroup Algorithm * \{ **/ /** Run a function over the values of this instance. The behavior of this function is different, depending on the * \c kind. For scalar kinds (\c kind::integer, \c kind::null, etc), \a func is called once with the value. If this * is \c kind::array, \c func is called for every value in the array and the output will be an array with each * element transformed by \a func. If this is \c kind::object, the result will be an object with each key * transformed by \a func. * * \param func The function to apply to the element or elements of this instance. **/ value map(const std::function<value (const value&)>& func) const&; /** Run a function over the values of this instance. The behavior of this function is different, depending on the * \c kind. For scalar kinds (\c kind::integer, \c kind::null, etc), \a func is called once with the value. If this * is \c kind::array, \c func is called for every value in the array and the output will be an array with each * element transformed by \a func. If this is \c kind::object, the result will be an object with each key * transformed by \a func. * * \param func The function to apply to the element or elements of this instance. * * \note * This version of \c map provides only a basic exception-safety guarantee. If an exception is thrown while * transforming a non-scalar \c kind, there is no rollback action, so \c this is left in a usable, but * \e unpredictable state. If you need a strong exception guarantee, use the constant reference version of \c map. **/ value map(const std::function<value (value)>& func) &&; /** \} **/ private: friend JSONV_PUBLIC value array(); friend JSONV_PUBLIC value object(); private: detail::value_storage _data; jsonv::kind _kind; }; /** An instance with \c kind::null. This is intended to be used for convenience and readability (as opposed to using the * default constructor of \c value. **/ JSONV_PUBLIC extern const value null; /** A user-defined literal for parsing JSON. Uses the default (non-strict) \c parse_options. * * \code * R"({ * "taco": "cat", * "burrito": "dog", * "whatever": [ "goes", "here", 1, 2, 3, 4 ] * })"_json; * \endcode **/ JSONV_PUBLIC value operator"" _json(const char* str, std::size_t len); /** Swap the values \a a and \a b. **/ JSONV_PUBLIC void swap(value& a, value& b) noexcept; /** \addtogroup Creation * Free functions meant for easily creating \c value instances. * \{ **/ /** Create an empty array value. **/ JSONV_PUBLIC value array(); /** Create an array value from the given source. **/ JSONV_PUBLIC value array(std::initializer_list<value> source); /** Create an array with contents defined by range [\a first, \a last). **/ template <typename TForwardIterator> value array(TForwardIterator first, TForwardIterator last) { value arr = array(); arr.assign(first, last); return arr; } /** Create an empty object. **/ JSONV_PUBLIC value object(); /** Create an object with key-value pairs from the given \a source. **/ JSONV_PUBLIC value object(std::initializer_list<std::pair<std::string, value>> source); JSONV_PUBLIC value object(std::initializer_list<std::pair<std::wstring, value>> source); /** Create an object whose contents are defined by range [\a first, \a last). **/ template <typename TForwardIterator> value object(TForwardIterator first, TForwardIterator last) { value obj = object(); obj.insert(first, last); return obj; } /** \} **/ } namespace std { /** Explicit specialization of \c std::hash for \c jsonv::value types so you can store a \c value in an unordered * container. Hashing results depend on the \c kind for the provided value -- most kinds directly use the hasher for * their kind (hashing a \c jsonv::value for integer \c 5 should have the same hash value as directly hashing the same * integer). For aggregate kinds \c array and \c object, hashing visits every sub-element recursively. This might be * expensive, but is required when storing multiple values with similar layouts in the a set (which is the most common * use case). **/ template <> struct JSONV_PUBLIC hash<jsonv::value> { std::size_t operator()(const jsonv::value& val) const noexcept; }; } #endif/*__JSONV_VALUE_HPP_INCLUDED__*/
35.086874
127
0.613613
liftchampion
d52d3ef79885ead4daab4a834fefb5dc9f7d710d
6,539
cpp
C++
framework/src/bundle/BundleVersion.cpp
CMakeezer/CppMicroServices
b787be130391bc278386b75da541b6661fe2f553
[ "Apache-2.0" ]
1
2020-08-13T15:21:11.000Z
2020-08-13T15:21:11.000Z
framework/src/bundle/BundleVersion.cpp
CMakeezer/CppMicroServices
b787be130391bc278386b75da541b6661fe2f553
[ "Apache-2.0" ]
null
null
null
framework/src/bundle/BundleVersion.cpp
CMakeezer/CppMicroServices
b787be130391bc278386b75da541b6661fe2f553
[ "Apache-2.0" ]
1
2020-08-13T15:21:45.000Z
2020-08-13T15:21:45.000Z
/*============================================================================= Library: CppMicroServices Copyright (c) The CppMicroServices developers. See the COPYRIGHT file at the top-level directory of this distribution and at https://github.com/CppMicroServices/CppMicroServices/COPYRIGHT . Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "cppmicroservices/BundleVersion.h" #include <algorithm> #include <cctype> #include <sstream> #include <stdexcept> #include <vector> namespace cppmicroservices { const char BundleVersion::SEPARATOR = '.'; bool IsInvalidQualifier(char c) { return !(std::isalnum(c) || c == '_' || c == '-'); } BundleVersion BundleVersion::EmptyVersion() { static BundleVersion emptyV(false); return emptyV; } BundleVersion BundleVersion::UndefinedVersion() { static BundleVersion undefinedV(true); return undefinedV; } BundleVersion& BundleVersion::operator=(const BundleVersion& v) { majorVersion = v.majorVersion; minorVersion = v.minorVersion; microVersion = v.microVersion; qualifier = v.qualifier; undefined = v.undefined; return *this; } BundleVersion::BundleVersion(bool undefined) : majorVersion(0) , minorVersion(0) , microVersion(0) , qualifier("") , undefined(undefined) {} void BundleVersion::Validate() { if (std::find_if(qualifier.begin(), qualifier.end(), IsInvalidQualifier) != qualifier.end()) throw std::invalid_argument(std::string("invalid qualifier: ") + qualifier); undefined = false; } BundleVersion::BundleVersion(unsigned int majorVersion, unsigned int minorVersion, unsigned int microVersion) : majorVersion(majorVersion) , minorVersion(minorVersion) , microVersion(microVersion) , qualifier("") , undefined(false) {} BundleVersion::BundleVersion(unsigned int majorVersion, unsigned int minorVersion, unsigned int microVersion, const std::string& qualifier) : majorVersion(majorVersion) , minorVersion(minorVersion) , microVersion(microVersion) , qualifier(qualifier) , undefined(true) { this->Validate(); } BundleVersion::BundleVersion(const std::string& version) : majorVersion(0) , minorVersion(0) , microVersion(0) , undefined(true) { unsigned int maj = 0; unsigned int min = 0; unsigned int mic = 0; std::string qual(""); std::vector<std::string> st; std::stringstream ss(version); std::string token; while (std::getline(ss, token, SEPARATOR)) { st.push_back(token); } if (st.empty()) return; bool ok = true; ss.clear(); ss.str(st[0]); ss >> maj; ok = !ss.fail(); if (st.size() > 1) { ss.clear(); ss.str(st[1]); ss >> min; ok = !ss.fail(); if (st.size() > 2) { ss.clear(); ss.str(st[2]); ss >> mic; ok = !ss.fail(); if (st.size() > 3) { qual = st[3]; if (st.size() > 4) { ok = false; } } } } if (!ok) throw std::invalid_argument("invalid format"); majorVersion = maj; minorVersion = min; microVersion = mic; qualifier = qual; this->Validate(); } BundleVersion::BundleVersion(const BundleVersion& version) : majorVersion(version.majorVersion) , minorVersion(version.minorVersion) , microVersion(version.microVersion) , qualifier(version.qualifier) , undefined(version.undefined) {} BundleVersion BundleVersion::ParseVersion(const std::string& version) { if (version.empty()) { return EmptyVersion(); } std::string version2(version); version2.erase(0, version2.find_first_not_of(' ')); version2.erase(version2.find_last_not_of(' ') + 1); if (version2.empty()) { return EmptyVersion(); } return BundleVersion(version2); } bool BundleVersion::IsUndefined() const { return undefined; } unsigned int BundleVersion::GetMajor() const { if (undefined) throw std::logic_error("Version undefined"); return majorVersion; } unsigned int BundleVersion::GetMinor() const { if (undefined) throw std::logic_error("Version undefined"); return minorVersion; } unsigned int BundleVersion::GetMicro() const { if (undefined) throw std::logic_error("Version undefined"); return microVersion; } std::string BundleVersion::GetQualifier() const { if (undefined) throw std::logic_error("Version undefined"); return qualifier; } std::string BundleVersion::ToString() const { if (undefined) return "undefined"; std::stringstream ss; ss << majorVersion << SEPARATOR << minorVersion << SEPARATOR << microVersion; if (!qualifier.empty()) { ss << SEPARATOR << qualifier; } return ss.str(); } bool BundleVersion::operator==(const BundleVersion& other) const { if (&other == this) { // quicktest return true; } if (other.undefined && this->undefined) return true; if (this->undefined) throw std::logic_error("Version undefined"); if (other.undefined) return false; return (majorVersion == other.majorVersion) && (minorVersion == other.minorVersion) && (microVersion == other.microVersion) && qualifier == other.qualifier; } int BundleVersion::Compare(const BundleVersion& other) const { if (&other == this) { // quicktest return 0; } if (this->undefined || other.undefined) throw std::logic_error("Cannot compare undefined version"); if (majorVersion < other.majorVersion) { return -1; } if (majorVersion == other.majorVersion) { if (minorVersion < other.minorVersion) { return -1; } if (minorVersion == other.minorVersion) { if (microVersion < other.microVersion) { return -1; } if (microVersion == other.microVersion) { return qualifier.compare(other.qualifier); } } } return 1; } std::ostream& operator<<(std::ostream& os, const BundleVersion& v) { return os << v.ToString(); } }
23.024648
80
0.649182
CMakeezer
d5365c85a6b5e1df62c2bd2017d064f6431c9e89
981
cpp
C++
droneLoggerROSModule/src/source/droneLoggerROSModuleNode.cpp
MorS25/cvg_quadrotor_swarm
da75d02049163cf65fd7305bc46a16359a851c7c
[ "BSD-3-Clause" ]
null
null
null
droneLoggerROSModule/src/source/droneLoggerROSModuleNode.cpp
MorS25/cvg_quadrotor_swarm
da75d02049163cf65fd7305bc46a16359a851c7c
[ "BSD-3-Clause" ]
null
null
null
droneLoggerROSModule/src/source/droneLoggerROSModuleNode.cpp
MorS25/cvg_quadrotor_swarm
da75d02049163cf65fd7305bc46a16359a851c7c
[ "BSD-3-Clause" ]
null
null
null
////////////////////////////////////////////////////// // droneLoggerROSModuleNode.cpp // // Created on: Dec 11, 2013 // Author: jespestana // // Last modification on: Dec 11, 2013 // Author: jespestana // ////////////////////////////////////////////////////// #include <iostream> #include "ros/ros.h" #include "droneloggerrosmodule.h" #include "communication_definition.h" int main(int argc,char **argv) { //Ros Init ros::init(argc, argv, MODULE_NAME_DRONE_LOGGER); ros::NodeHandle n; DroneLoggerROSModule drone_logger_ros_module(n); try { while(ros::ok()) { //Read messages ros::spinOnce(); //Run DroneLogger ROSModule if(drone_logger_ros_module.run()) { } //Sleep drone_logger_ros_module.sleep(); } } catch (std::exception &ex) { std::cout << "[ROSNODE] Exception :" << ex.what() << std::endl; } return 1; }
23.926829
71
0.510703
MorS25
d5370e59cd62fb16f9a94f3f6fa995657d4429df
100,992
hpp
C++
include/blib/bun/impl/orm.hpp
sp-mishra/bun
b2a3601872bb13cb92c05368b625e3448513fb93
[ "BSD-3-Clause" ]
86
2016-05-17T08:22:35.000Z
2022-03-19T20:01:43.000Z
include/blib/bun/impl/orm.hpp
sp-mishra/bun
b2a3601872bb13cb92c05368b625e3448513fb93
[ "BSD-3-Clause" ]
22
2016-04-30T20:07:02.000Z
2020-06-07T15:23:02.000Z
include/blib/bun/impl/orm.hpp
sp-mishra/bun
b2a3601872bb13cb92c05368b625e3448513fb93
[ "BSD-3-Clause" ]
23
2016-05-18T16:50:28.000Z
2022-03-19T20:01:57.000Z
#pragma once /////////////////////////////////////////////////////////////////////////////// /// @file Bun.hpp /// @author BrainlessLabs /// @version 0.3 /// @brief The include file for Bun ORM. This file includes all the source /// to make the class/struct persist in sqlite. Users need to include /// only this file. /////////////////////////////////////////////////////////////////////////////// #include <string> #include <memory> #include <set> #include <type_traits> #include <cstdint> #include <cstddef> #include <memory> #include <bitset> #include <third_party/fmt/format.hpp> #include <third_party/rapidjson/rapidjson.h> #include <third_party/rapidjson/document.h> #include <third_party/json/json.hpp> #include <boost/mpl/bool.hpp> #include <boost/preprocessor.hpp> #include <boost/fusion/sequence.hpp> #include <boost/fusion/include/sequence.hpp> #include <boost/fusion/adapted/struct/adapt_struct.hpp> #include <boost/fusion/include/adapt_struct.hpp> #include <boost/fusion/algorithm/iteration/for_each.hpp> #include <boost/fusion/include/for_each.hpp> #include <boost/fusion/support/pair.hpp> #include <boost/fusion/include/pair.hpp> #include <boost/fusion/include/algorithm.hpp> #include <boost/fusion/include/filter_if.hpp> #include <boost/fusion/include/copy.hpp> #include <boost/preprocessor/tuple/rem.hpp> #include <boost/iterator/iterator_facade.hpp> #include <boost/proto/proto.hpp> #include <soci/error.h> #include "blib/utils/MD5.hpp" #include "blib/bun/impl/DbBackend.hpp" #include "blib/bun/impl/DbLogger.hpp" #include "blib/bun/impl/SimpleOID.hpp" #include "blib/bun/impl/CppTypeToSQLString.hpp" /////////////////////////////////////////////////////////////////////////////// /// @basic Basic Persistance Start /// @details We will be using the Bun class for all the examples and /// understanding /// struct Bun { /// std::string bun_name, /// float sugar_quantity; /// float flour_quantity; /// float milk_quantity; /// float yeast_quantity; /// float butter_quantity; /// int bun_length; /// }; /////////////////////////////////////////////////////////////////////////////// /// @brief Make this 0 if no log is needed, else make it 1 #define QUERY_LOG_ON 1 /// @brief Log the query #define QUERY_LOG(log_string) BOOST_PP_EXPR_IF(QUERY_LOG_ON, l().info(log_string)) /// @brief Macro to output comments #define BLIB_MACRO_COMMENTS_ENABLED 0 #define BLIB_MACRO_COMMENTS_IF(a) BOOST_PP_EXPR_IF(BLIB_MACRO_COMMENTS_ENABLED, a) /// @brief createSchema Helper Macros /// @details We need to pass only the data members as a tuple to this macro /// @param ELEMS_TUP = (bun_name, sugar_quantity, flour_quantity, milk_quantity, yeast_quantity, butter_quantity, bun_length) /// @brief Expands the class members for CREATE TABLE //#define EXPAND_CLASS_MEMBERS_createSchema_I(z, n, ELEMS_TUP) ", " BOOST_STRINGIZE(BOOST_PP_TUPLE_ELEM(n, ELEMS_TUP)) " {}" //#define EXPAND_CLASS_MEMBERS_createSchema(ELEMS_TUP) BOOST_PP_REPEAT(BOOST_PP_TUPLE_SIZE(ELEMS_TUP), EXPAND_CLASS_MEMBERS_createSchema_I, ELEMS_TUP) namespace blib { namespace bun { template<typename T> struct PersistantNativeTypes { using ValueType = T; using DbFriendlyValueType = typename blib::bun::__private::ConvertCPPTypeToSOCISupportType<ValueType>::type; using SelfType = PersistantNativeTypes<ValueType>; DbFriendlyValueType val; PersistantNativeTypes() : val() {} PersistantNativeTypes(PersistantNativeTypes const& other) : val(other.val) {} PersistantNativeTypes(ValueType const other) : val(other) {} SelfType& operator=(SelfType const& other) { val = other.val; } SelfType& operator=(ValueType const& other) { val = other; } template<typename O> SelfType& operator=(O const& other) { val = blib::bun::__private::convertToSOCISupportedType<O>(other); } }; } } namespace blib { namespace bun { ///////////////////////////////////////////////// /// @class IsPersistant /// @brief If IsPersistant<Class>::value == true then Class can be persisted. /// Specialize this class for all the class which can be persistent. ///////////////////////////////////////////////// template<typename T> struct IsPersistant : boost::mpl::bool_<std::is_fundamental<T>::value || std::is_arithmetic<T>::value || std::is_floating_point<T>::value> { }; template<> struct IsPersistant<std::string> : boost::mpl::bool_<true> { }; namespace __private { ///////////////////////////////////////////////// /// @fn to_valid_query_string /// @param val /// @brief Helper class to persist any primitive types. ///////////////////////////////////////////////// template<typename T> inline auto to_valid_query_string(T const& val) -> T const& { T const& ret = val; return ret; } inline auto to_valid_query_string(std::string const& val, std::string const sym = "\"") -> std::string { const std::string ret_str = sym + val + sym; return ret_str; } inline auto to_valid_query_string(const char* val, std::string const sym = "\"") -> std::string { const std::string ret_str = sym + std::string(val) + sym; return ret_str; } /// @fn tojson_string /// @brief Convert into a json representable key value template<typename T> inline auto tojson_string(T const& value)->T { return value; } inline auto tojson_string(std::string const& value)->std::string { const std::string quote("\""); const std::string ret = quote + value + quote; return ret; } /// @fn to_json /// @brief Convert to json template<typename T> inline auto to_json(T const& value) -> std::string { //static_assert(blib::bun::IsPersistant<T>::value, "Cannot convert to json. Specialization for to_json conversion does not exist"); const std::string ret = fmt::format("{}", value); return ret; } template<typename T> inline void from_json(std::string const& json_string, T const& obj) { } } } } namespace blib { namespace bun { namespace __private { template<typename T> struct ConfigurationOptions { inline static std::set<std::string>& unique_constraint_set() { static std::set<std::string> constraint_set; return constraint_set; } }; ///////////////////////////////////////////////// /// @class IsComposite /// @brief True if the element is a class/struct that can be persisted ///////////////////////////////////////////////// template<typename T> struct IsComposite : boost::mpl::bool_<false> { }; template< class T > struct remove_cvref { typedef std::remove_cv_t<std::remove_reference_t<T>> type; }; ///////////////////////////////////////////////// /// @class StripQualifiersAndMakePointer /// @brief String all the qualifiers like const, volatile, removes reference and adds a pointer. ///////////////////////////////////////////////// template<typename T> struct StripQualifiersAndMakePointer { using type = typename std::add_pointer<typename remove_cvref<T>::type>::type; }; ///////////////////////////////////////////////// /// @class TypeMetaData /// @brief Contains meta data that will be usieful to get type /// inferences for a certain type. ///////////////////////////////////////////////// template<typename T> struct TypeMetaData { using MT = boost::fusion::vector<void>; static std::string const& class_name(); boost::fusion::vector<boost::fusion::pair<void, std::string>> const& tuple_type_pair(); }; ///////////////////////////////////////////////// /// @class SqlString /// @brief Generates the SQL strings in the class /// @details Any Sql string has to be part of this class /// This class should provide a way for other classess to /// customize the string. So the strings constructed in this /// class is are flexible. ///////////////////////////////////////////////// template<typename T> struct SqlString { private: struct SelectRows { private: std::string& sql; public: SelectRows(std::string& sql) : sql(sql) {} template <typename O> void operator()(O const& x) const { sql += "," + x.second; } }; struct CreateTable { private: std::string& sql; public: CreateTable(std::string& sql) : sql(sql) {} template <typename O> void operator()(O const& x) const { using ObjType = typename std::remove_const<typename std::remove_pointer<typename O::first_type>::type>::type; static const std::string composite_type = blib::bun::cppTypeEnumToDbTypeString<DbTypes::kComposite>(); std::string type = blib::bun::cppTypeToDbTypeString<typename blib::bun::__private::ConvertCPPTypeToSOCISupportType<ObjType>::type>(); // If the type is of an object type then we will use VARCHAR to store the hash value if (composite_type == type) { type = "VARCHAR"; } sql += "," + x.second + " " + type; } }; struct UpdateRow { private: std::string& sql; public: UpdateRow(std::string& sql) : sql(sql) {} template <typename O> void operator()(O const& x) const { if (!sql.empty()) { sql += ","; } sql += x.second + " = :" + x.second; } }; struct InsertRowNames { private: std::string& sql; public: InsertRowNames(std::string& sql) : sql(sql) {} template <typename O> void operator()(O const& x) const { sql += ", " + x.second; } }; struct InsertRowVal { private: std::string& sql; public: InsertRowVal(std::string& sql) : sql(sql) {} template <typename O> void operator()(O const& x) const { sql += " , :" + x.second; } }; public: /// @fn create_table_sql /// @brief Create table sql inline static std::string const& create_table_sql() { static const auto vecs = TypeMetaData<T>::tuple_type_pair(); static std::string sql; if (sql.empty()) { sql = "CREATE TABLE IF NOT EXISTS \"{}\" (oid VARCHAR PRIMARY KEY, oid_ref VARCHAR, parent_table_reference VARCHAR, parent_column_name VARCHAR"; boost::fusion::for_each(vecs, SqlString<T>::CreateTable(sql)); const auto& unique_constraint_set = ConfigurationOptions<T>::unique_constraint_set(); if (!unique_constraint_set.empty()) { std::string unique_str = ", CONSTRAINT \"unique_constraint_" + TypeMetaData<T>::class_name() + "\" UNIQUE ("; bool include_comma = false; for (const auto& elem : unique_constraint_set) { if (include_comma) { unique_str += ","; } else { include_comma = true; } unique_str += elem; } unique_str += ")"; sql += unique_str; } sql += ")"; } return sql; } /// @fn drop_table_sql /// @brief Drop table sql inline static std::string const& drop_table_sql() { static const std::string sql = "DROP TABLE IF EXISTS \"{}\"";; return sql; } /// @fn delete_row_condition_sql /// @brief Delete row sql with some condition /// @details This is useful for deleting child rows inline static std::string const& delete_row_condition_sql() { static const std::string sql = "DELETE FROM \"{}\" WHERE {}"; return sql; } /// @fn delete_row_sql /// @brief Delete a row inline static std::string const& delete_row_sql() { static const std::string sql = "DELETE FROM \"{}\" WHERE oid = :oid"; return sql; } /// @fn insert_row_sql /// @brief Insert row sql inline static std::string const& insert_row_sql() { static const auto vecs = TypeMetaData<T>::tuple_type_pair(); static std::string sql; if (sql.empty()) { sql = "INSERT INTO \"{}\" (oid, oid_ref, parent_table_reference, parent_column_name"; boost::fusion::for_each(vecs, SqlString<T>::InsertRowNames(sql)); sql += ") VALUES ({}, {}, {}, {}"; boost::fusion::for_each(vecs, SqlString<T>::InsertRowVal(sql)); sql += ")"; } return sql; } /// @fn update_row_sql /// @brief Update row sql inline static std::string const& update_row_sql() { static const auto vecs = TypeMetaData<T>::tuple_type_pair(); static std::string sql; if (sql.empty()) { sql = "UPDATE \"{}\" SET oid_ref = {}, parent_table_reference = {}, parent_column_name = {},"; std::string sql1; boost::fusion::for_each(vecs, SqlString<T>::UpdateRow(sql1)); sql += sql1 + " WHERE oid = {}"; } return sql; } /// @fn select_rows_sql /// @brief Select row sql inline static std::string const& select_rows_sql() { //static const auto vecs = TypeMetaData<T>::tuple_type_pair(); static const std::string sql = "SELECT * FROM \"{}\" "; return sql; } /// @fn select_all_oid_sql /// @brief Select Oids sql inline static std::string const& select_all_oid_sql() { static const std::string sql = "SELECT oid FROM \"{}\""; return sql; } }; ///////////////////////////////////////////////// /// @class SimpleObjHolder /// @brief A simple holder for objects. /// To be used for the from_base and to_base conversion. /// To be used for the orm object mapping ///////////////////////////////////////////////// template<typename T> struct SimpleObjHolder { T* obj_ptr; blib::bun::SimpleOID const& oid; SimpleObjHolder(T* obj_ptr_in, blib::bun::SimpleOID const& oid_in) :obj_ptr(obj_ptr_in), oid(oid_in) {} ~SimpleObjHolder() { obj_ptr = nullptr; } }; ///////////////////////////////////////////////// /// @class PRefHelper /// @brief Helper class for the persistent framework. /// This class is specialized to persist objects. ///////////////////////////////////////////////// template<typename T> struct QueryHelper { /// @fn createSchema /// @brief Create Schema inline static void createSchema() { const static std::string sql = fmt::format(SqlString<T>::create_table_sql(), TypeMetaData<T>::class_name()); QUERY_LOG(sql); try { blib::bun::__private::DbBackend<>::i().session() << sql; } catch (std::exception const & e) { l().error("createSchema: {} ", e.what()); } } /// @fn deleteSchema /// @brief Delete schema inline static void deleteSchema() { const static std::string sql = fmt::format(SqlString<T>::drop_table_sql(), TypeMetaData<T>::class_name()); QUERY_LOG(sql); try { blib::bun::__private::DbBackend<>::i().session() << sql; } catch (std::exception const & e) { l().error("deleteSchema(): {} ", e.what()); } } /// @fn persistObj /// @param obj This is the object that needs to be persisted /// @brief Persist an object inline static SimpleOID persistObj(T *obj, const SimpleOID& oid_ref = SimpleOID(), std::string const& parent_table_reference = std::string(), std::string const& parent_column_name = std::string()) { blib::bun::SimpleOID oid; oid.populate(); const static std::string& class_name = TypeMetaData<T>::class_name(); const std::string sql = fmt::format(SqlString<T>::insert_row_sql(), class_name, to_valid_query_string(oid.to_string(), "'"), to_valid_query_string(oid_ref.to_string(), "'"), to_valid_query_string(parent_table_reference, std::string("'")), to_valid_query_string(parent_column_name, std::string("'"))); SimpleObjHolder<T> obj_holder(obj, oid); QUERY_LOG(sql); try { blib::bun::__private::DbBackend<>::i().session() << sql, soci::use(obj_holder); } catch (std::exception const& e) { l().error("persistObj(): {} ", e.what()); } return oid; } /// @fn updateObj /// @param obj This is the object that needs to be updated /// @param oid the oid that needs to be updated /// @brief Persist an object. inline static void updateObj(T * obj, SimpleOID const& oid, const SimpleOID& oid_ref = SimpleOID(), std::string const& parent_table_reference = std::string(), std::string const& parent_column_name = std::string()) { static const std::string& class_name = TypeMetaData<T>::class_name(); const std::string sql = fmt::format(SqlString<T>::update_row_sql(), class_name, to_valid_query_string(oid_ref.to_string(), "'"), to_valid_query_string(parent_table_reference, std::string("'")), to_valid_query_string(parent_column_name, std::string("'")), to_valid_query_string(oid.to_string(), "'")); SimpleObjHolder<T> obj_holder(obj, oid); QUERY_LOG(sql); try { blib::bun::__private::DbBackend<>::i().session() << sql, soci::use(obj_holder); } catch (std::exception const& e) { l().error("updateObj(): {} ", e.what()); } } /// @class DeleteObjects /// @brief Helper class to delete the objects of the enclosed scope too. struct DeleteObjects { private: SimpleOID const& _oid; public: DeleteObjects(SimpleOID const& oid) :_oid(oid) {} template <typename O> void operator()(O const& /*x*/) const { QueryHelper<O>::deleteObjWithParentInfo(_oid); } }; /// @fn deleteObj /// @param oid The object associated with this oid needs to be deleted. /// @param obj The object that needs to be deleted /// @brief The object associated with this oid needs to be deleted. inline static void deleteObj(SimpleOID const& oid, T* obj = nullptr) { static const std::string& class_name = TypeMetaData<T>::class_name(); const static std::string sql = fmt::format(SqlString<T>::delete_row_sql(), class_name); QUERY_LOG(sql); try { if (obj != nullptr) { // Delete all the nested objects. boost::fusion::for_each(boost::fusion::filter_if<blib::bun::__private::IsComposite<boost::mpl::_>>(*obj), DeleteObjects(oid)); } blib::bun::__private::DbBackend<>::i().session() << sql, soci::use(oid.to_string()); } catch (std::exception const & e) { l().error("deleteObj(): {} ", e.what()); } } /// @fn deleteObjWithParentInfo /// @param oid_ref /// @param parent_table_reference /// @param parent_column_name /// @brief The object associated with this oid needs to be deleted. inline static void deleteObjWithParentInfo( const SimpleOID& oid_ref, std::string const& parent_table_reference = std::string(), std::string const& parent_column_name = std::string()) { static const std::string& class_name = TypeMetaData<T>::class_name(); std::string where_clause = fmt::format("oid_ref = {}", to_valid_query_string(oid_ref.to_string(), "'")); if (!parent_table_reference.empty()) { where_clause += fmt::format(" AND parent_table_reference = {}", to_valid_query_string(parent_table_reference, "'")); } if (!parent_column_name.empty()) { where_clause += fmt::format(" AND parent_column_name = {}", to_valid_query_string(parent_column_name, "'")); } const std::string sql = fmt::format(SqlString<T>::delete_row_condition_sql(), class_name, where_clause); QUERY_LOG(sql); try { blib::bun::__private::DbBackend<>::i().session() << sql; } catch (std::exception const& e) { l().error("deleteObjWithParentInfo({}): {} ", where_clause, e.what()); } } /// @fn getObj /// @param oid The oid for the object /// @brief The object with the particular oid will be returned. inline static std::unique_ptr<T> getObj(SimpleOID const & oid) { static const std::string& class_name = TypeMetaData<T>::class_name(); const std::string sql = fmt::format(SqlString<T>::select_rows_sql() + " WHERE oid = {}", class_name, to_valid_query_string(oid.to_string(), "'")); QUERY_LOG(sql); std::unique_ptr <T> obj = std::make_unique<T>(); SimpleObjHolder<T> obj_holder(obj.get(), oid); try { blib::bun::__private::DbBackend<>::i().session() << sql, soci::into(obj_holder); } catch (std::exception const& e) { l().error("getObj(): {} ", e.what()); } return std::move(obj); } /// @fn md5 /// @param oid The oid for the object /// @brief Returns the md5 of the object inline static std::string md5(T const& obj, SimpleOID const & oid) { const std::string json = QueryHelper<T>::objToJson(obj); const static std::string& class_name = TypeMetaData<T>::class_name(); const std::string str = "{" + fmt::format("'oid': '{}', 'class_name': '{}', 'json': '{}'", oid.to_string(), class_name, json) + "}"; const std::string md5 = blib::md5(str); return md5; } /// @fn objToString /// @param oid The oid for the object /// @param obj The object which we need to create to string /// @brief Converts the object to a string representation and /// returns the string representation. inline static std::string objToString(T const& obj) { return QueryHelper<T>::objToJson(obj); } /// @class ToJson /// @brief Helper class to convert an object into a json representation. struct ToJson { private: std::string& _str; const std::vector<std::string>& _member_names; int _count; bool _apply_comma; template<typename IT, bool IsCompositeType> struct _ToJsonImpl { static void impl(IT const& obj, const std::string& obj_name, bool const apply_comma, std::string& str) { const std::string comma = apply_comma ? "," : ""; str += fmt::format("{}\"{}\": {}", comma, obj_name, tojson_string(obj)); } }; template<typename IT> struct _ToJsonImpl<IT, true> { static void impl(IT const& obj, const std::string& obj_name, bool const apply_comma, std::string& str) { const std::string comma = apply_comma ? "," : ""; str += fmt::format("{}\"{}\":{}", comma, obj_name, to_json<IT>(obj)); } }; public: ToJson(std::string & str) : _str(str), _member_names(TypeMetaData<T>::member_names()), _count(2), _apply_comma(false) { } template <typename O> void operator()(O const& x) const { const std::string member_name = _member_names.at(const_cast<ToJson*>(this)->_count++); ToJson::_ToJsonImpl<O, IsComposite<O>::value>::impl(x, member_name, _apply_comma, _str); const_cast<ToJson*>(this)->_apply_comma = true; } }; /// @fn objToJson /// @param oid The oid for the object /// @param obj The object which we need to create to string /// @brief Converts the object to a json representation and /// returns the json representation as a string /// @return JSON representation inline static std::string objToJson(T const& obj) { std::string str; boost::fusion::for_each(obj, QueryHelper<T>::ToJson(str)); const std::string ret_string = "{" + str + "}"; return ret_string; } struct FromJson { private: rapidjson::Value const& _document; std::vector<std::string> const& _member_names; int _count; private: template<typename CppType> static CppType jsonTypeToCppType(rapidjson::Value const& val); template<typename JT, typename std::enable_if<std::is_same<JT, int>::value>::type> static int jsonTypeToCppType(rapidjson::Value const& val) { return val.GetInt(); } template<typename JT, typename std::enable_if<std::is_same<JT, std::int64_t>::value>::type> static std::int64_t jsonTypeToCppType(rapidjson::Value const& val) { return val.GetInt64(); } template<typename JT, typename std::enable_if<std::is_same<JT, unsigned int>::value>::type> static unsigned int jsonTypeToCppType(rapidjson::Value const& val) { return val.GetUint(); } template<typename JT, typename std::enable_if<std::is_same<JT, std::uint64_t>::value>::type> static std::uint64_t jsonTypeToCppType(rapidjson::Value const& val) { return val.GetUint64(); } template<typename JT, typename std::enable_if<std::is_same<JT, bool>::value>::type> static bool jsonTypeToCppType(rapidjson::Value const& val) { return val.GetBool(); } template<typename JT, typename std::enable_if<std::is_same<JT, double>::value>::type> static double jsonTypeToCppType(rapidjson::Value const& val) { return val.GetDouble(); } template<typename JT, typename std::enable_if<std::is_same<JT, float>::value>::type> static float jsonTypeToCppType(rapidjson::Value const& val) { return val.GetFloat(); } template<typename JT, typename std::enable_if<std::is_same<JT, std::string>::value>::type> static std::string jsonTypeToCppType(rapidjson::Value const& val) { return val.GetString(); } template<typename IT, bool isComplex> struct _FromJson { static void impl(IT& field, std::string const& field_name, rapidjson::Value const& doc) { field = jsonTypeToCppType<IT>(doc.FindMember(field_name.c_str())->value); } }; template<typename IT> struct _FromJson<IT, true> { static void impl(IT& field, std::string const& field_name, rapidjson::Value const& doc) { QueryHelper<IT>::jsonToObject(doc.FindMember(field_name.c_str())->value, field); } }; public: FromJson(rapidjson::Value const& document):_document(document), _member_names(TypeMetaData<T>::member_names()), _count(2){} template <typename O> void operator()(O& x) const { const std::string member_name = _member_names.at(const_cast<FromJson*>(this)->_count++); FromJson::_FromJson<O, IsComposite<O>::value>::impl(x, member_name, _document); } }; /// @fn jsonToObject /// @brief This function converts inline static void jsonToObject(rapidjson::Value const& json, T& obj) { QueryHelper<T>::FromJson fromJson(json); boost::fusion::for_each(obj, fromJson); } template<typename TA, bool IsComposite> struct GetAllObjectsImpl { inline static void impl(TA& x, const soci::row& row, const std::string& member_name, const std::string& /*oid_ref*/) { x = row.get<typename ConvertCPPTypeToSOCISupportType<TA>::type>(member_name); } }; template<typename TA> struct GetAllObjectsImpl<TA, true> { inline static void impl(TA& x, const soci::row& row, const std::string& member_name, const std::string& oid_ref) { const std::string sql = fmt::format("oid_ref = {} AND parent_column_name = {}", to_valid_query_string(oid_ref, "'"), to_valid_query_string(member_name, "'")); using ObjectRetType = std::pair<std::unique_ptr <TA>, SimpleOID>; std::vector<ObjectRetType> objs = QueryHelper<TA>::getAllObjectsWithQuery(sql); if (objs.empty()) { l().error("GetAllObjectsImpl() for member name:{} has no elements ", member_name); } else { ObjectRetType& obj = objs.at(0); boost::fusion::copy(*obj.first, x); //x; } } }; struct GetAllObjects { private: const soci::row& _row; const std::string& _oid_ref; const std::vector<std::string>& _member_names; int _count; public: GetAllObjects(const soci::row& row, const std::string& oid_ref) :_row(row), _oid_ref(oid_ref), _member_names(TypeMetaData<T>::member_names()), _count(2) { } template <typename O> void operator()(O& x) const { const std::string& member_name = _member_names.at(const_cast<GetAllObjects*>(this)->_count++); GetAllObjectsImpl<O, IsComposite<O>::value>::impl(x, _row, member_name, _oid_ref); //x = _row.get<ConvertCPPTypeToSOCISupportType<O>::type>(_member_names.at(const_cast<GetAllObjects*>(this)->_count++)); } }; /// @fn getAllObjectsWithQuery /// @param in_query Queries for which the objects will be returned. /// @brief The function will get all the objects that match the passed query /// @details https://www.citusdata.com/blog/2016/03/30/five-ways-to-paginate/ /// Limit and Offset have its merits and demerits. Follow the page to learn them /// We will be using Limit and Offset to start with the query building inline static std::vector<std::pair<std::unique_ptr <T>, SimpleOID>> getAllObjectsWithQuery( const std::string& in_query = std::string(), const std::size_t limit = 0, const std::size_t offset = 0) { std::vector<std::pair<std::unique_ptr <T>, SimpleOID>> ret_values; const std::string& class_name = TypeMetaData<T>::class_name(); const static std::string select_sql = fmt::format(SqlString<T>::select_rows_sql(), class_name) + "{} {}"; const std::string where_clasue = in_query.empty() ? "" : "WHERE " + in_query + " ORDER BY 'oid'"; const std::string limit_clause = fmt::format(" LIMIT {} ", limit); const std::string limit_offset_clause = limit ? limit_clause + fmt::format(" OFFSET {} ", offset) : ""; const std::string sql = fmt::format(select_sql, where_clasue, limit_offset_clause); QUERY_LOG(sql); try { // Fetch the results as rowset soci::rowset<soci::row> rows = (DbBackend<>::i().session().prepare << sql); for (soci::rowset<soci::row>::const_iterator row_itr = rows.begin(); row_itr != rows.end(); ++row_itr) { auto const& row = *row_itr; std::pair<std::unique_ptr <T>, SimpleOID> pair; pair.second = row.get<std::string>("oid"); pair.first = std::make_unique<T>(); T& obj = *pair.first; boost::fusion::for_each(obj, QueryHelper<T>::GetAllObjects(row, pair.second.to_string())); ret_values.emplace_back(pair.first.release(), pair.second); } } catch (std::exception const & e) { l().error("getAllObjectsWithQuery({}): {} ", in_query, e.what()); } return std::move(ret_values); } /// @fn getAllNestedObjectssWithQuery /// @param in_query Queries for which the objects will be returned. /// @brief Get all the oids with that match the query. inline static std::vector<std::pair<std::unique_ptr <T>, SimpleOID>> getAllNestedObjectssWithQuery(std::string const in_query = std::string(), const SimpleOID& oid_ref = SimpleOID(), std::string const& parent_table_reference = std::string(), std::string const& parent_column_name = std::string()) { const std::string query = fmt::format("{} AND oid_ref = {} AND parent_table_reference = {} AND parent_column_name = {}", to_valid_query_string(oid_ref.to_string(), "'"), to_valid_query_string(parent_table_reference, "'"), to_valid_query_string(parent_column_name, "'")); QUERY_LOG(query); return QueryHelper<T>::getAllObjectsWithQuery(query); } /// @fn getAllOids /// @brief Get all the oids inline static std::vector<SimpleOID> getAllOids() { const std::vector<SimpleOID> oids = QueryHelper<T>::getAllOidsWithQuery(); return oids; } /// @fn getAllOidsWithQuery /// @param in_query Queries for which the objects will be returned. /// @brief Get all the oids with that match the query. inline static std::vector<SimpleOID> getAllOidsWithQuery( std::string const in_query = std::string(), const std::size_t limit = 0, const std::size_t offset = 0) { std::vector<SimpleOID> oids; const static std::string& class_name = TypeMetaData<T>::class_name(); const static std::string select_oid_sql = fmt::format(SqlString<T>::select_all_oid_sql(), class_name) + " {} ORDER BY oid {}"; const std::string where_clasue = in_query.empty() ? "" : "WHERE " + in_query; const std::string limit_query = limit && offset ? "" : fmt::format("LIMIT {} OFFSET {}", limit, offset); const std::string sql = fmt::format(select_oid_sql, where_clasue, limit_query); QUERY_LOG(sql); try { const soci::rowset<soci::row> rows = (blib::bun::__private::DbBackend<>::i().session().prepare << sql); for (auto row_itr = rows.begin(); row_itr != rows.end(); ++row_itr) { auto const& row = *row_itr; oids.emplace_back(row.get<std::string>("oid")); } } catch (std::exception const & e) { l().error("getAllOidsWithQuery({}): {} ", in_query, e.what()); } return oids; } }; } } } /// ======================PRef Class Start======================== namespace blib { namespace bun { ///////////////////////////////////////////////// /// @class PRef /// @brief The persistent reference holder. /// @details This is the primary object holder. /// Anything assigned to this can be stored in the database. ///////////////////////////////////////////////// template<typename T> class PRef { private: /// @typedef OidType = SimpleOID using OidType = SimpleOID; /// @var std::unique_ptr<T> _obj /// @brief Stores the object. The unique pointer is specialized /// for that object type. std::unique_ptr<T> _obj; /// @var std::string _md5 /// @brief Holds the MD5 sum of this object. std::string _md5; public: using ObjType = T; typedef PRef<T> SelfType; /// @var OidType oid /// @brief Holds the OID for this object. /// Each object will have an unique OID. /// This will distinguish them from other object. OidType oid; using ByteArray = std::vector<std::uint8_t>; public: PRef() noexcept : _obj(), _md5(), oid() {} PRef(PRef const &in_other) : oid(in_other.oid) { load(oid); } PRef(PRef &in_other) : _obj(in_other._obj.release()), _md5(in_other._md5), oid(in_other.oid) { } PRef(ObjType *in_obj) : _obj(in_obj) {} PRef(OidType const &in_oid) : oid(in_oid) { load(oid); } PRef(OidType const &in_oid, ObjType *in_obj) : oid(in_oid), _obj(in_obj) {} /// @fn reset /// @brief Resets the current PRef and assigns another object to it. /// @param in_obj The other object to assign it to. void reset(ObjType *in_obj) { _obj.reset(in_obj); oid.clear(); _md5.clear(); } /// @fn release /// @brief Reset the PRef to hold nothing. /// The oid is set to 0 and the object released. ObjType *release() { oid.clear(); _md5.clear(); return _obj.release(); } ~PRef() {} auto operator*()->decltype(*_obj) { return *_obj; } T *operator->() { return _obj.get(); } /// @fn dirty /// @brief Returns true if the object is changed from last commit /// else false. /// @details The MD5 of the object is taken from the last commit. /// If the MD5 are different then it returns true else /// it returns false. bool dirty() { const auto md5 = blib::bun::__private::QueryHelper<ObjType>::md5(*_obj.get(), oid); // If the md5 dont match then there is a change in the objects state. return md5 != _md5 ? true : false; } /// @fn persist /// @brief Commits the object in database /// @details Commits the object in database and also updates the /// MD5 of the object. If this function is not called /// the object is not going to be updated in database. /// @return OidType Returns the OID of the persisted object. OidType persist() { try { if (_md5.empty()) { oid = blib::bun::__private::QueryHelper<ObjType>::persistObj(_obj.get()); } else { blib::bun::__private::QueryHelper<ObjType>::updateObj(_obj.get(), oid); } _md5 = blib::bun::__private::QueryHelper<ObjType>::md5(*_obj.get(), oid); } catch (std::exception const & e) { blib::bun::l().error(fmt::format("Exception while persisting: {}", e.what())); } catch (...) { blib::bun::l().error(fmt::format("Unknown Exception while persisting: {}")); } return oid; } /// @fn save /// @brief Does same as persist. Calls persist internally. OidType save() { return persist(); } /// @fn del /// @brief Delets the persistent object. /// Clears the MD5 and the flags. void del() { blib::bun::__private::QueryHelper<ObjType>::deleteObj(oid, _obj.get()); _md5.clear(); oid.clear(); } PRef& operator=(ObjType *in_obj) { reset(in_obj); return *this; } PRef& operator=(PRef& in_other) { copyFrom(in_other); return *this; } /*PRef& operator=(PRef const& in_other) { in_other.copyToOther(*this); return *this; }*/ bool operator==(PRef const &in_other) const { return oid == in_other.oid; } bool operator!=(PRef const &in_other) const { return oid != in_other.oid; } /// @fn toJson /// @brief Returns a JSON representation of the object. std::string toJson() const { return blib::bun::__private::QueryHelper<ObjType>::objToJson(*_obj.get()); } /// @fn fromJson /// @brief Creates the object from the given json string void fromJson(const std::string& json) { rapidjson::Document document; document.Parse(json.c_str()); _obj = std::make_unique<ObjType>(); blib::bun::__private::QueryHelper<ObjType>::jsonToObject(document, *_obj.get()); } ByteArray toMesssagepack() const { const std::string json_str = toJson(); const auto json_obj = nlohmann::json::parse(json_str); return nlohmann::json::to_msgpack(json_obj); } void fromMessagepack(ByteArray const& messagePack) { const auto json = nlohmann::json::from_msgpack(messagePack); const std::string json_str = json.dump(); fromJson(json_str); } private: void copyToOther(PRef& in_other) { in_other.oid = oid; in_other._obj.reset(const_cast<SelfType*>(this)->_obj.release()); in_other._md5 = _md5; } /// @fn oad(OidType const &in_oid) /// @brief Loads an object from Database. /// @param in_oid A valid OID for the object. void load(OidType const &in_oid) { oid = in_oid; _obj = blib::bun::__private::QueryHelper<ObjType>::getObj(oid); _md5 = blib::bun::__private::QueryHelper<ObjType>::md5(*_obj.get(), oid); } /// @fn copyFrom(PRef &in_other) /// @brief Create a exact clone of another PRef void copyFrom(PRef& in_other) { oid = in_other.oid; _md5 = in_other._md5; _obj.reset(in_other._obj.release()); } }; } } /// ======================Global Functions Start======================== namespace blib { namespace bun { ///////////////////////////////////////////////// /// @brief Helper class for the persistent framework. /// This class is specialized to persist objects. ///////////////////////////////////////////////// /// @fn createSchema /// @brief Create the schema for the object template<typename T> inline static void createSchema() { soci::transaction t(blib::bun::__private::DbBackend<>::i().session()); blib::bun::__private::QueryHelper<T>::createSchema(); t.commit(); } /// @fn deleteSchema /// @brief Delete the schema for the object template<typename T> inline static void deleteSchema() { soci::transaction t(blib::bun::__private::DbBackend<>::i().session()); blib::bun::__private::QueryHelper<T>::deleteSchema(); t.commit(); } /// @fn getAllOids /// @brief Get all the oids as a vector template<typename T> inline static std::vector <SimpleOID> getAllOids() { soci::transaction t(blib::bun::__private::DbBackend<>::i().session()); const std::vector<SimpleOID> oids = blib::bun::__private::QueryHelper<T>::getAllOids(); t.commit(); return oids; } /// @fn getAllObjWithQuery /// @brief Get all the objects as PRef that satisfy the query template<typename T> inline static std::vector <PRef<T>> getAllObjWithQuery( std::string const &in_query, const std::size_t limit = 0, const std::size_t offset = 0) { soci::transaction t(blib::bun::__private::DbBackend<>::i().session()); std::vector<std::pair<std::unique_ptr <T>, SimpleOID>> values = blib::bun::__private::QueryHelper<T>::getAllObjectsWithQuery(in_query, limit, offset); std::vector <PRef<T>> ret_vals; for (auto& value : values) { ret_vals.emplace_back(value.second, value.first.release()); } t.commit(); return std::move(ret_vals); } /// @fn getAllObjects /// @brief Get all the objects as PRef template<typename T> inline static std::vector <PRef<T>> getAllObjects() { //soci::transaction t(blib::bun::__private::DbBackend<>::i().session()); return getAllObjWithQuery<T>(std::string()); //t.commit(); } /// @fn connect /// @brief Connect with the proper connection strings template<typename DbType = blib::bun::__private::DbGenericType> inline bool connect(std::string const& connection_string) { const auto ret = blib::bun::__private::DbBackend<blib::bun::__private::DbGenericType>::i().connect(connection_string); return ret; } /// @fn generateMetaData /// @brief Generate the metadata needed for various functionalities of Bun to work. inline bool generateMetaData() { return true; } } } /// ======================Fetch results and iterator helper Start======================== namespace blib { namespace bun { namespace __private { /// @class FetchResultsForQuery /// @brief This class fetches the data from the database. template<typename T> class FetchResultsForQuery { public: using ObjPRefVecType = decltype(blib::bun::getAllObjWithQuery<T>("")); //using ObjPRefType = typename ObjPRefVecType::value_type; using ObjPRefType = ::blib::bun::PRef<T>; private: /// @var _query /// @brief The sql query generated std::string _query; /// @var _objects /// @brief The object cache. The objects at this current instance ObjPRefVecType _objects; /// @var _page_start /// @brief The pagination std::size_t _offset; /// @var _progress /// @brief How much the page should progress const std::size_t _limit; /// @var _cur_itr /// @brief The current iterator, that holds the current value typename ObjPRefVecType::iterator _cur_itr; /// @var _has_next /// @brief True if there is a next element and false if there is no element bool _has_next; static const std::size_t _initial_offset = 0; static const std::size_t _initial_limit = 1000; private: /// @fn populateObjectsFromDb /// @brief Fills the _objects with object from database. Resets the _offset to the next value and sets _has_next to true. void populateObjectsFromDb() { _objects = blib::bun::getAllObjWithQuery<T>(_query, _limit, _offset); if(!_objects.empty()) { _cur_itr = _objects.begin(); _offset += _limit; _has_next = true; } } bool isEmpty() const { bool ret = false; if(_query.empty() || _objects.empty() || _offset == _initial_offset || _limit == _initial_limit || _cur_itr == _objects.end() || _has_next == false) { ret = true; } return ret; } void progressNext() { if (_objects.end() == _cur_itr) { populateObjects(); } else{ ++_cur_itr; } if(_objects.end() == _cur_itr) { _has_next = false; } } void populateObjects() { populateObjectsFromDb(); } public: /// @fn This is the default constructor. This does not set any values as such as the query is not set yet. FetchResultsForQuery() noexcept : _offset(_initial_offset), _limit(_initial_limit), _cur_itr(_objects.end()), _has_next(false){} FetchResultsForQuery(std::string& query): _query(query), _offset(_initial_offset), _limit(_initial_limit), _cur_itr(), _has_next(false) { populateObjects(); } FetchResultsForQuery(FetchResultsForQuery& in_other) : _query(in_other._query), _objects(in_other._objects), _offset(in_other._offset), _limit(in_other._limit), _cur_itr(_objects.begin()), _has_next(in_other._has_next) {} FetchResultsForQuery& operator=(FetchResultsForQuery const& in_other) { _objects = in_other._objects; _offset = in_other._offset; _limit = in_other._limit; _cur_itr = _objects.begin(); _has_next = in_other._has_next; return *this; } bool operator==(FetchResultsForQuery const& in_other) const { bool is_same = false; if(_objects == in_other._objects && _offset == in_other._offset && _limit == in_other._limit && _cur_itr == in_other._cur_itr && in_other._has_next == _has_next) { is_same = true; } return is_same; } std::string const& query() const { return _query; } bool ok() const{ return !isEmpty() || _cur_itr != _objects.end(); } /// @fn reset /// @brief resets the query and all the objects fetched void reset(const std::string& query) { _query = query; _offset = _initial_offset; _limit = _initial_limit; _objects.clear(); _cur_itr = _objects.end(); _has_next = false; populateObjects(); } /// @fn hasNext /// @brief returns true if there are still objects in database /// else it returns false bool hasNext() const { return _has_next; } /// @fn next /// @brief Returns the next element in the database /// @return The PRef value if the object is present or an empty PRef ObjPRefType& next() { static ObjPRefType null_ref; ObjPRefType& ret = hasNext() ? *_cur_itr : null_ref; progressNext(); return ret; } /// @fn current /// @brief Returns the current object /// /// @return The PRef value if the object is present or an empty PRef ObjPRefType& current() const { static ObjPRefType null_ref; return ok() ? *_cur_itr : null_ref;; } /// @fn objects /// @brief Gets all the objects in the database. Should be used cautiously auto objects()->ObjPRefVecType& { _objects = blib::bun::getAllObjWithQuery<T>(_query); return _objects; } }; } template<typename ValueType/*, typename PRefType=blib::bun::PRef<ValueType>*/> class ObjectIterator : public boost::iterator_facade< ObjectIterator<ValueType>, blib::bun::PRef<ValueType>/*PRefType*/, boost::forward_traversal_tag > { public: using SelfType = ObjectIterator<ValueType>; using FetchResultType = blib::bun::__private::FetchResultsForQuery<ValueType>; using PRef = blib::bun::PRef<ValueType>; private: friend class boost::iterator_core_access; FetchResultType _fetch_result; public: ObjectIterator() noexcept = default; ObjectIterator(std::string& query_string) : _fetch_result(query_string) { } ObjectIterator(ObjectIterator& in_other) : _fetch_result(in_other._fetch_result) { } bool operator!=(ObjectIterator const& in_other) const{ return !equal(in_other); } bool operator==(ObjectIterator const& in_other) const{ return equal(in_other); } private: void increment() { _fetch_result.next(); } /// @todo Chack why the boost operator doesnt work only with this function in place. bool equal(ObjectIterator const& in_other) const { return _fetch_result.hasNext() == in_other._fetch_result.hasNext(); } PRef& dereference() const { return _fetch_result.current(); } }; } } /// ======================Fetch results and iterator helper End======================== /// ======================Query Start======================== /// @brief The query templates starts here /// @details This block of code refpresents the grammar and the structure of the /// query elements. namespace blib { namespace bun { /// @class Configuration terminal struct UniqueConstraint {}; namespace query { namespace __private { template<std::uint32_t I> struct QueryVariablePlaceholderIndex : std::integral_constant <std::uint32_t, I> { QueryVariablePlaceholderIndex() noexcept {} }; /// @brief Grammar for the query Start struct PlaceHoldersTerminals : boost::proto::or_ < boost::proto::terminal<QueryVariablePlaceholderIndex<0>>, boost::proto::terminal<QueryVariablePlaceholderIndex<1>>, boost::proto::terminal<QueryVariablePlaceholderIndex<2>>, boost::proto::terminal<QueryVariablePlaceholderIndex<3>>, boost::proto::terminal<QueryVariablePlaceholderIndex<4>>, boost::proto::terminal<QueryVariablePlaceholderIndex<5>>, boost::proto::terminal<QueryVariablePlaceholderIndex<6>>, boost::proto::terminal<QueryVariablePlaceholderIndex<7>>, boost::proto::terminal<QueryVariablePlaceholderIndex<8>>, boost::proto::or_< boost::proto::terminal<QueryVariablePlaceholderIndex<9>>, boost::proto::terminal<QueryVariablePlaceholderIndex<10>>, boost::proto::terminal<QueryVariablePlaceholderIndex<11>>, boost::proto::terminal<QueryVariablePlaceholderIndex<12>>, boost::proto::terminal<QueryVariablePlaceholderIndex<13>>, boost::proto::terminal<QueryVariablePlaceholderIndex<14>>, boost::proto::terminal<QueryVariablePlaceholderIndex<15>>, boost::proto::terminal<QueryVariablePlaceholderIndex<16>>, boost::proto::terminal<QueryVariablePlaceholderIndex<17>> > > { }; struct QueryLiteralTerminals : boost::proto::or_< boost::proto::terminal<boost::proto::convertible_to<int>>, boost::proto::terminal<boost::proto::convertible_to<unsigned int>>, boost::proto::terminal<boost::proto::convertible_to<char>>, boost::proto::terminal<boost::proto::convertible_to<unsigned char>>, boost::proto::terminal<boost::proto::convertible_to<float>>, boost::proto::terminal<boost::proto::convertible_to<double>>, boost::proto::terminal<boost::proto::convertible_to<bool>>, boost::proto::terminal<boost::proto::convertible_to<std::string>> > { }; /// @class ConfigurationTerminals /// @brief Terminal for configuration struct ConfigurationTerminals : boost::proto::or_< boost::proto::terminal<blib::bun::UniqueConstraint> > {}; struct AllTerminals : boost::proto::or_< PlaceHoldersTerminals, QueryLiteralTerminals > { }; /// @brief Configuration struct ConfigUniqueKeyGrammer : boost::proto::or_< boost::proto::assign<AllTerminals, ConfigurationTerminals> > { }; struct GreaterSymbols : boost::proto::or_< boost::proto::greater<AllTerminals, AllTerminals>, boost::proto::greater_equal<AllTerminals, AllTerminals> > { }; struct LessSymbols : boost::proto::or_< boost::proto::less<AllTerminals, AllTerminals>, boost::proto::less_equal<AllTerminals, AllTerminals> > { }; struct EqualSymbols : boost::proto::or_< boost::proto::equal_to<AllTerminals, AllTerminals>, boost::proto::not_equal_to<AllTerminals, AllTerminals> > { }; struct BunQueryGrammar : boost::proto::or_< AllTerminals, GreaterSymbols, LessSymbols, EqualSymbols, ConfigUniqueKeyGrammer, boost::proto::logical_and<BunQueryGrammar, BunQueryGrammar>, boost::proto::logical_or<BunQueryGrammar, BunQueryGrammar> > { }; // Grammar for the query End /// @fn mapping(const std::uint32_t in_index) /// @brief Gets the type element at position passed in by index /// { /// static const std::vector<std::string> ret = { "name", "age", "height" }; /// return ret.at( in_index ); /// } template<typename T> inline std::string const& mapping(const std::size_t in_index) { static const auto vals = blib::bun::__private::TypeMetaData<T>::member_names(); return vals.at(in_index + 2); // member_names start from oid_high and oid_low } /// @class TypesUsed /// @brief boost::mpl::vector<decltype(test::Person::name), decltype(test::Person::age), decltype(test::Person::height)>; template<typename T> struct TypesUsed { using Type = void; }; /// @class FromInternals /// @brief Helper class to be used in From query template<typename T> struct FromInternals { using TypesUsed = typename TypesUsed<T>::Type; /// @class BunQueryFilterContex /// @brief The context for filter queries in SQL struct BunQueryFilterContex : boost::proto::callable_context<BunQueryFilterContex> { typedef std::string result_type; /// @fn BunQueryFilterContex /// @brief default constructor BunQueryFilterContex() noexcept {} /// @fn operator() /// @param The terminal tag /// @param the terminal name /// @brief returns valid terminal name template<typename E> result_type operator ()(boost::proto::tag::terminal, E in_term) const { const auto ret = std::to_string(blib::bun::__private::to_valid_query_string(in_term)); return ret; } /// @fn operator() /// @param The terminal tag /// @param the terminal terminal name /// @brief returns valid terminal name result_type operator ()(boost::proto::tag::terminal, std::string& in_term) const { const auto ret = blib::bun::__private::to_valid_query_string(in_term, std::string("'")); return ret; } /// @fn operator() /// @param The terminal tag /// @param the terminal name /// @brief returns valid terminal name. Overloaded for character result_type operator ()(boost::proto::tag::terminal, char const* in_term) const { std::string str = std::string(in_term); const auto ret = blib::bun::__private::to_valid_query_string(str, std::string("'")); return ret; } /// @fn operator() /// @param The terminal tag /// @param The index of the variable for lookup /// @brief returns the name from the mapping template<std::uint32_t I> result_type operator()(boost::proto::tag::terminal, bun::query::__private::QueryVariablePlaceholderIndex<I> /*in_term*/) const { const auto ret = mapping<T>(I); return ret; } /// @fn operator() /// @param Logical /// @param left param /// @param right param /// @brief The query with the params template<typename L, typename R> result_type operator()(boost::proto::tag::logical_and, L const& in_l, R const& in_r) const { static const std::string operator_name = " AND "; auto ctx = *this; const auto left_string = boost::proto::eval(in_l, ctx); const auto right_string = boost::proto::eval(in_r, ctx); const std::string ret = left_string + operator_name + right_string; return ret; } template<typename L, typename R> result_type operator()(boost::proto::tag::logical_or, L const& in_l, R const& in_r) const { static const std::string operator_name = " OR "; auto ctx = *this; const auto left_string = boost::proto::eval(in_l, ctx); const auto right_string = boost::proto::eval(in_r, ctx); const std::string ret = left_string + operator_name + right_string; return ret; } template<typename L, typename R> result_type operator()(boost::proto::tag::less, L const& in_l, R const& in_r) const { static const std::string operator_name = " < "; auto ctx = *this; const auto left_string = boost::proto::eval(in_l, ctx); const auto right_string = boost::proto::eval(in_r, ctx); const std::string ret = left_string + operator_name + right_string; return ret; } template<typename L, typename R> result_type operator()(boost::proto::tag::less_equal, L const& in_l, R const& in_r) const { static const std::string operator_name = " <= "; auto ctx = *this; const auto left_string = boost::proto::eval(in_l, ctx); const auto right_string = boost::proto::eval(in_r, ctx); const std::string ret = left_string + operator_name + right_string; return ret; } template<typename L, typename R> result_type operator()(boost::proto::tag::greater, L const& in_l, R const& in_r) const { static const std::string operator_name = " > "; auto ctx = *this; const auto left_string = boost::proto::eval(in_l, ctx); const auto right_string = boost::proto::eval(in_r, ctx); const std::string ret = left_string + operator_name + right_string; return ret; } template<typename L, typename R> result_type operator()(boost::proto::tag::greater_equal, L const& in_l, R const& in_r) const { static const std::string operator_name = " >= "; auto ctx = *this; const auto left_string = boost::proto::eval(in_l, ctx); const auto right_string = boost::proto::eval(in_r, ctx); const std::string ret = left_string + operator_name + right_string; return ret; } template<typename L, typename R> result_type operator()(boost::proto::tag::equal_to, L const& in_l, R const& in_r) const { static const std::string operator_name = " = "; auto ctx = *this; const auto left_string = boost::proto::eval(in_l, ctx); const auto right_string = boost::proto::eval(in_r, ctx); const std::string ret = left_string + operator_name + right_string; return ret; } template<typename L, typename R> result_type operator()(boost::proto::tag::not_equal_to, L const& in_l, R const& in_r) const { static const std::string operator_name = " != "; auto ctx = *this; const auto left_string = boost::proto::eval(in_l, ctx); const auto right_string = boost::proto::eval(in_r, ctx); const std::string ret = left_string + operator_name + right_string; return ret; } template<typename TerminalType, typename L, typename R> result_type operator()(TerminalType, L const& /*in_l*/, R const& /*in_r*/) const { //static_assert(false, "Operator not supported in Bun"); const std::string ret = "Operator not supported in Bun"; return ret; } template<typename TerminalType, typename L> result_type operator()(TerminalType, L const& /*in_l*/) const { //static_assert(false, "Operator not supported in Bun"); const std::string ret = "Operator not supported in Bun"; return ret; } }; }; } /// @brief Fields for query. This is a unknown namespace. namespace { /// @class F /// @brief This class represents the details of the query /// @details This class is specialized in the /// SPECIALIZE_BUN_HELPER for each specialized class. template<typename T> struct F; } ///////////////////////////////////////////////// /// @brief From class for query. ///////////////////////////////////////////////// template<typename T> struct From { public: using ObjPRefVecType = typename blib::bun::__private::FetchResultsForQuery<T>::ObjPRefVecType; using ObjPRefType = typename blib::bun::__private::FetchResultsForQuery<T>::ObjPRefType; using ObjectIteratorType = blib::bun::ObjectIterator<T>; private: /// @var _query /// @brief The sql query generated std::string _query; blib::bun::__private::FetchResultsForQuery<T> _from_query; std::unique_ptr<ObjectIteratorType> _itr; private: template<typename ExpressionType> std::string eval(ExpressionType const& in_expr) { typename __private::FromInternals<T>::BunQueryFilterContex ctx; const std::string ret = boost::proto::eval(in_expr, ctx); return ret; } static std::string const& className() { static const auto table_name = blib::bun::__private::TypeMetaData<T>::class_name(); return table_name; } /// @fn append_query /// @param in_expr The query expression /// @param and_query if the value is true then the query is an and query, if and_query is false its an or query /// @brief Generates the query string template<typename ExpressionType> From& append_query(ExpressionType const& in_expr, const bool and_query = true) { static_assert(boost::proto::matches<ExpressionType, __private::BunQueryGrammar>::value, "Syntax error in Bun Query"); const std::string query_string = eval(in_expr); const std::string and_or_str = and_query ? " AND " : " OR "; const std::string add_string = _query.empty() ? "" : and_or_str; _query += add_string + query_string; return *this; } public: From() noexcept :_from_query(_query), _itr(nullptr){} From(From& in_other) :_query(in_other._query), _from_query(in_other._query), _itr(nullptr){} template<typename ExpressionType> From& And(ExpressionType const& in_expr) { return append_query(in_expr); } template<typename ExpressionType> From& Or(ExpressionType const& in_expr) { return append_query(in_expr, false); } template<typename ExpressionType> From& where(ExpressionType const& in_expr) { return append_query(in_expr); } template<typename ExpressionType> From& operator()(ExpressionType const& in_expr) { return append_query(in_expr); } bool hasNext() { return _from_query.hasNext(); } auto next()->ObjPRefType { return _from_query.next(); } std::string const& query() const { //l().info(_query); return _query; } /// @fn objects /// @brief Gets all the objects auto objects()->ObjPRefVecType& { return _from_query.objects(); } ObjectIteratorType& begin() { _itr = std::make_unique<ObjectIteratorType>(_query); return *_itr; } ObjectIteratorType& end() const { static std::unique_ptr<ObjectIteratorType> end_itr = std::make_unique<ObjectIteratorType>(); return *end_itr; } }; template<typename ExpressionType> struct IsValidQuery : std::integral_constant<bool, boost::proto::matches<ExpressionType, __private::BunQueryGrammar>::value> { }; } } } /// ======================Query End======================== /// ======================Configuration Start======================== namespace blib { namespace bun { namespace __private { /// @class UniqueConstraint /// @brief Helper class to be used to add template<typename T> struct UniqueConstraintInternal { //using TypesUsed = typename TypesUsed<T>::Type; /// @class BunConstraintContex /// @brief The context for Unique Constraint struct BunConstraintContex : boost::proto::callable_context<BunConstraintContex> { using result_type = std::string; /// @fn BunConstraintContex /// @brief default constructor BunConstraintContex() {} /// @fn operator() /// @param The terminal tag /// @param the terminal name /// @brief returns valid terminal name /*template<typename E> result_type operator ()(boost::proto::tag::terminal, E in_term) const { const auto ret = std::to_string(blib::bun::__private::to_valid_query_string(in_term)); return ret; }*/ /// @fn operator() /// @param The terminal tag /// @param the terminal terminal name /// @brief returns valid terminal name result_type operator ()(boost::proto::tag::terminal, std::string& in_term) const { const auto ret = blib::bun::__private::to_valid_query_string(in_term, std::string("'")); return ret; } /// @fn operator() /// @param The terminal tag /// @param the terminal name /// @brief returns valid terminal name. Overloaded for character result_type operator ()(boost::proto::tag::terminal, char const* in_term) const { std::string str = std::string(in_term); const auto ret = blib::bun::__private::to_valid_query_string(str, std::string("'")); return ret; } /// @fn operator() /// @param The terminal tag /// @param The index of the variable for lookup /// @brief returns the name from the mapping template<std::uint32_t I> result_type operator()(boost::proto::tag::terminal, ::blib::bun::query::__private::QueryVariablePlaceholderIndex<I> /*in_term*/) const { const result_type ret = ::blib::bun::query::__private::mapping<T>(I); return ret; } result_type operator()(boost::proto::tag::terminal, blib::bun::UniqueConstraint& /*in_term*/) const { static const result_type ret = "UNIQUE"; return ret; } template<typename L, typename R> result_type operator()(boost::proto::tag::assign, L const& in_l, R const& /*in_r*/) const { auto ctx = *this; const auto left_string = boost::proto::eval(in_l, ctx); //const auto right_string = boost::proto::eval(in_r, ctx); ConfigurationOptions<T>::unique_constraint_set().insert(left_string); const result_type ret = left_string; return ret; } }; }; } // __private ///////////////////////////////////////////////// /// @brief Cinfiguration class. ///////////////////////////////////////////////// template<typename T> struct Configuration { private: template<typename ExpressionType> std::string eval(ExpressionType const& in_expr) { typename __private::UniqueConstraintInternal<T>::BunConstraintContex ctx; const std::string ret = boost::proto::eval(in_expr, ctx); return ret; } static std::string const& className() { static const auto table_name = blib::bun::__private::TypeMetaData<T>::class_name(); return table_name; } public: Configuration() = default; template<typename ExpressionType> Configuration& set(ExpressionType const& in_expr) { static_assert(boost::proto::matches<ExpressionType, blib::bun::query::__private::BunQueryGrammar>::value, "Syntax error in Bun Configuration Expression"); const std::string query_string = eval(in_expr); return *this; } template<typename ExpressionType> Configuration& operator()(ExpressionType const& in_expr) { return set(in_expr); } std::set<std::string> const& uniques() const { return bun::__private::ConfigurationOptions<T>::unique_constraint_set(); } }; namespace { static blib::bun::UniqueConstraint unique_constraint; } } } /// ======================Configuration End======================== /// @brief Transaction namespace blib { namespace bun { /// @class Transaction /// @brief The class that handles transaction /// @details The transaction class is a wrapper around the transaction /// of SOCI. This supports all the methods of the soci::transaction class. class Transaction { private: soci::transaction _t; public: Transaction() noexcept :_t(blib::bun::__private::DbBackend<>::i().session()) { } ~Transaction() { _t.~transaction(); } void commit() { _t.commit(); } void rollback() { _t.rollback(); } }; } } /// @brief SOCI conversion helpers namespace blib { namespace bun { namespace __private { /// @class type_conversion /// @brief partial specialization to support regular objects T /// @details template<typename T> struct type_conversion { public: using ObjType = T; private: struct FromBase { private: soci::values const& _val; std::uint_fast32_t _count; public: FromBase(soci::values const& val) :_val(val), _count(2) {} template<typename O> void operator()(O& x) const { const std::string obj_name = TypeMetaData<ObjType>::member_names().at(const_cast<FromBase*>(this)->_count++); x = _val.get<typename ConvertCPPTypeToSOCISupportType<typename std::remove_reference<O>::type>::type>(obj_name); } }; public: inline static void from_base(soci::values const& v, soci::indicator, ObjType& obj) { //boost::fusion::for_each(obj, FromBase(v)); } private: struct ToBase { private: soci::values& _val; std::uint_fast32_t _count; public: ToBase(soci::values& val) :_val(val), _count(2) {} template<typename O> void operator()(O const& x) const { const std::string obj_name = TypeMetaData<ObjType>::member_names().at(const_cast<ToBase*>(this)->_count++); const_cast<ToBase*>(this)->_val.set(obj_name, x); } }; public: inline static void to_base(ObjType const& obj, soci::values& v, soci::indicator& ind) { //boost::fusion::for_each(obj, ToBase(v)); } }; /// @class type_conversion /// @brief partial specialization to support SimpleObjHolder<T> /// @details template<typename T> struct type_conversion<SimpleObjHolder<T>> { using ObjectHolderType = SimpleObjHolder<T>; using ObjType = T; private: template<typename O, bool IsComposite = false> struct FromBaseOperation { inline static void execute(O& x, const std::string& obj_name, soci::values const& val, const blib::bun::SimpleOID& /*parent_oid*/) { x = val.get<typename ConvertCPPTypeToSOCISupportType<typename std::remove_reference<O>::type>::type>(obj_name); } }; template<typename O> struct FromBaseOperation<O, true> { inline static void execute(O& x, const std::string& obj_name, soci::values const& val, const blib::bun::SimpleOID& parent_oid) { const blib::bun::SimpleOID& oid_ref = parent_oid; const std::string& parent_table_reference = TypeMetaData<ObjType>::class_name(); // TODO using RetType = std::vector<std::pair<std::unique_ptr <O>, SimpleOID>>; const RetType values = blib::bun::__private::QueryHelper<O>::getAllNestedObjectssWithQuery("", oid_ref, parent_table_reference, obj_name); if (!values.empty()) { x = *values.at(0).first; } else { l().error("FromBaseOperation::execute: Could not fetch object values"); } } }; struct FromBase { private: soci::values const& _val; const blib::bun::SimpleOID& _oid; std::uint16_t _count; soci::indicator& _ind; public: FromBase(soci::values const& val, blib::bun::SimpleOID const& oid, soci::indicator& ind) :_val(val), _oid(oid), _count(2), _ind(ind) {} template<typename O> void operator()(O& x) const { const std::string obj_name = TypeMetaData<ObjType>::member_names().at(const_cast<FromBase*>(this)->_count++); FromBaseOperation<O, IsComposite<O>::value>::execute(x, obj_name, _val, _oid); } }; public: /// @fn from_base Setting the values in the object /// @brief This will take the database value and put it in the object. Database -> Object inline static void from_base(soci::values const& v, soci::indicator ind, ObjectHolderType& obj_holder) { ObjType& obj = *(obj_holder.obj_ptr); const blib::bun::SimpleOID& oid = obj_holder.oid; boost::fusion::for_each(obj, FromBase(v, oid, ind)); } private: template<typename O, bool IsComposite = false> struct ToBaseOperation { inline static void execute(O& x, const std::string& obj_name, soci::values& val, const blib::bun::SimpleOID& parent_oid, soci::indicator& ind) { val.set<typename ConvertCPPTypeToSOCISupportType<typename std::remove_reference<O>::type>::type>(obj_name, x, ind); } }; template<typename O> struct ToBaseOperation<O, true> { inline static void execute(O& x, const std::string& obj_name, soci::values& val, const blib::bun::SimpleOID& parent_oid, soci::indicator& ind) { const blib::bun::SimpleOID& oid_ref = parent_oid; const std::string& parent_table_reference = TypeMetaData<ObjType>::class_name(); const std::string& parent_column_name = obj_name; // Do not delete if parent oid is nill. If parent // oid is nill then this object is not yet persisted. if (oid_ref.empty() != 0) { // Delete everything before inserting. There is no // update essentially. Just delete and insert of any nested objects. QueryHelper<O>::deleteObj(oid_ref, &x); } // Get the oid of the nested object after persisting it const blib::bun::SimpleOID oid = QueryHelper<O>::persistObj(&x, oid_ref, parent_table_reference, parent_column_name); // Get the json representation of the nested object and store it in the parent object const std::string oids = oid.to_json(); // TODO : Fix this. This has the context of current query execution. Needs to set the value in parent. val.set<typename ConvertCPPTypeToSOCISupportType<std::string>::type>(obj_name, oids, ind); } }; struct ToBase { private: soci::values& _val; const blib::bun::SimpleOID& _oid; std::uint_fast32_t _count; soci::indicator& _ind; public: ToBase(soci::values& val, blib::bun::SimpleOID const& oid, soci::indicator& ind) :_val(val), _oid(oid), _count(2), _ind(ind) {} template<typename O> void operator()(O& x) const { const std::string obj_name = TypeMetaData<ObjType>::member_names().at(const_cast<ToBase*>(this)->_count++); ToBaseOperation<O, IsComposite<O>::value>::execute(x, obj_name, _val, _oid, _ind); } }; public: /// @fn to_base Setting the values in the database /// @brief This will take the object value and persist it in the database. Object -> Database inline static void to_base(ObjectHolderType& obj_holder, soci::values& v, soci::indicator& ind) { ObjType& obj = *(obj_holder.obj_ptr); const blib::bun::SimpleOID& oid = obj_holder.oid; boost::fusion::for_each(obj, ToBase(v, oid, ind)); } }; } } } namespace soci { /// @class type_conversion /// @brief SOCI class specialized to use SimpleObjHolder template<typename T> struct type_conversion<blib::bun::__private::SimpleObjHolder<T>> { using ObjectHolderType = blib::bun::__private::SimpleObjHolder<T>; using ObjType = T; typedef values base_type; /// @fn from_base /// @param soci::values const& v /// @param soci::indicator ind /// @param ObjectHolderType& obj_holder inline static void from_base(soci::values const& v, soci::indicator ind, ObjectHolderType& obj_holder) { blib::bun::__private::type_conversion<ObjectHolderType>::from_base(v, ind, obj_holder); } /// @fn to_base /// @param ObjectHolderType const& obj_holder /// @param soci::values& v /// @param soci::indicator& ind inline static void to_base(ObjectHolderType& obj_holder, soci::values& v, soci::indicator& ind) { const std::string oid = obj_holder.oid.to_string(); blib::bun::__private::type_conversion<ObjectHolderType>::to_base(obj_holder, v, ind); } }; } /////////////////////////////////////////////////////////////////////////////// /// Helper Macros Start /////////////////////////////////////////////////////////////////////////////// #define GENERATE_TupType_I(z, n, CLASS_ELEMS_TUP) BOOST_PP_IF(n, BOOST_PP_COMMA, BOOST_PP_EMPTY)() std::add_pointer<std::remove_reference<std::remove_cv<decltype(BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP) :: BOOST_PP_TUPLE_ELEM(BOOST_PP_ADD(1, n), CLASS_ELEMS_TUP))>::type>::type>::type #define GENERATE_TupType(CLASS_ELEMS_TUP) BOOST_PP_REPEAT(BOOST_PP_SUB(BOOST_PP_TUPLE_SIZE(CLASS_ELEMS_TUP), 1), GENERATE_TupType_I, CLASS_ELEMS_TUP) #define GENERATE_TupTypePair_I(z, n, CLASS_ELEMS_TUP) BOOST_PP_IF(n, BOOST_PP_COMMA, BOOST_PP_EMPTY)() boost::fusion::pair<blib::bun::__private::StripQualifiersAndMakePointer<decltype(BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP) :: BOOST_PP_TUPLE_ELEM(BOOST_PP_ADD(1, n), CLASS_ELEMS_TUP))>::type, std::string> #define GENERATE_TupTypePair(CLASS_ELEMS_TUP) BOOST_PP_REPEAT(BOOST_PP_SUB(BOOST_PP_TUPLE_SIZE(CLASS_ELEMS_TUP), 1), GENERATE_TupTypePair_I, CLASS_ELEMS_TUP) #define GENERATE_TupTypePairObj_I(z, n, CLASS_ELEMS_TUP) BOOST_PP_IF(n, BOOST_PP_COMMA, BOOST_PP_EMPTY)() boost::fusion::make_pair<blib::bun::__private::StripQualifiersAndMakePointer<decltype(BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP) :: BOOST_PP_TUPLE_ELEM(BOOST_PP_ADD(1, n), CLASS_ELEMS_TUP))>::type>(BOOST_STRINGIZE(BOOST_PP_TUPLE_ELEM(BOOST_PP_ADD(1, n), CLASS_ELEMS_TUP))) #define GENERATE_TupTypePairObj(CLASS_ELEMS_TUP) BOOST_PP_REPEAT(BOOST_PP_SUB(BOOST_PP_TUPLE_SIZE(CLASS_ELEMS_TUP), 1), GENERATE_TupTypePairObj_I, CLASS_ELEMS_TUP) #define EXPAND_member_names_I(z, n, ELEMS_TUP) ,BOOST_STRINGIZE(BOOST_PP_TUPLE_ELEM(n, ELEMS_TUP)) #define EXPAND_member_names(ELEMS_TUP) BOOST_PP_REPEAT(BOOST_PP_TUPLE_SIZE(ELEMS_TUP), EXPAND_member_names_I, ELEMS_TUP) /// @brief generate the query and query fields #define DEFINE_CLASS_STATIC_VARS_QUERY_I(z, n, CLASS_ELEMS_TUP) boost::proto::terminal<blib::bun::query::__private::QueryVariablePlaceholderIndex<n>>::type const F<BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP)>::BOOST_PP_TUPLE_ELEM(BOOST_PP_ADD(n, 1), CLASS_ELEMS_TUP); #define DEFINE_CLASS_STATIC_VARS_QUERY(CLASS_ELEMS_TUP) BOOST_PP_REPEAT(BOOST_PP_SUB(BOOST_PP_TUPLE_SIZE(CLASS_ELEMS_TUP), 1), DEFINE_CLASS_STATIC_VARS_QUERY_I, CLASS_ELEMS_TUP) #define GENERATE_CLASS_STATIC_VARS_QUERY_I(z, n, ELEMS_TUP) static boost::proto::terminal<blib::bun::query::__private::QueryVariablePlaceholderIndex<n>>::type const BOOST_PP_TUPLE_ELEM(n, ELEMS_TUP); #define GENERATE_CLASS_STATIC_VARS_QUERY(ELEMS_TUP) BOOST_PP_REPEAT(BOOST_PP_TUPLE_SIZE(ELEMS_TUP), GENERATE_CLASS_STATIC_VARS_QUERY_I, ELEMS_TUP) /////////////////////////////////////////////////////////////////////////////// /// Helper Macros End /////////////////////////////////////////////////////////////////////////////// /// SPECIALIZE_BUN_HELPER Start #define SPECIALIZE_BUN_HELPER(CLASS_ELEMS_TUP) BOOST_FUSION_ADAPT_STRUCT( BOOST_PP_TUPLE_REM_CTOR(CLASS_ELEMS_TUP) ) \ namespace blib{namespace bun{\ template<> struct IsPersistant<BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP)> : boost::mpl::bool_<true> {};\ template<>\ struct CppTypeToDbType<BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP)>{\ static const DbTypes ret = DbTypes::kComposite;\ };\ }}\ namespace blib{namespace bun{namespace __private{\ template<> struct IsComposite<BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP)> : boost::mpl::bool_<true> {};\ template<>\ struct TypeMetaData<BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP)>{\ using TupType = boost::fusion::vector<GENERATE_TupType(CLASS_ELEMS_TUP)>;\ using TupTypePairType = boost::fusion::vector<GENERATE_TupTypePair(CLASS_ELEMS_TUP)>;\ using T = BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP);\ inline static auto tuple_type_pair()->TupTypePairType const&{\ static const TupTypePairType t{GENERATE_TupTypePairObj(CLASS_ELEMS_TUP)};\ return t;\ }\ inline static std::string const& class_name(){\ static std::string const class_name = BOOST_STRINGIZE(BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP));\ return class_name;\ }\ inline static const std::vector<std::string>& member_names(){\ static const std::vector<std::string> names = {"oid_high", "oid_low" EXPAND_member_names(BOOST_PP_TUPLE_POP_FRONT( CLASS_ELEMS_TUP ))};\ return names;\ }\ };\ template<>\ inline auto to_json<BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP)>(BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP) const& value) -> std::string {\ return QueryHelper<BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP)>::objToJson(value);\ }\ }}}\ namespace blib{ namespace bun{ namespace query{\ namespace {\ template<>\ struct F<BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP)> {\ GENERATE_CLASS_STATIC_VARS_QUERY(BOOST_PP_TUPLE_POP_FRONT( CLASS_ELEMS_TUP ))\ };\ DEFINE_CLASS_STATIC_VARS_QUERY(CLASS_ELEMS_TUP)\ }\ }}}\ /// SPECIALIZE_BUN_HELPER End
45.718425
375
0.505901
sp-mishra
d53922d188feee012efef3416e355a3a58b26fdd
792
cpp
C++
src/taglib/TagLibUnity_mpeg.cpp
khanhas/nowplaying-node
6d4455d6ab196866ad409635f6db3fd15cc96251
[ "MIT" ]
14
2018-05-27T22:01:35.000Z
2022-03-05T19:05:33.000Z
src/taglib/TagLibUnity_mpeg.cpp
khanhas/nowplaying-node
6d4455d6ab196866ad409635f6db3fd15cc96251
[ "MIT" ]
null
null
null
src/taglib/TagLibUnity_mpeg.cpp
khanhas/nowplaying-node
6d4455d6ab196866ad409635f6db3fd15cc96251
[ "MIT" ]
5
2018-06-06T03:14:37.000Z
2021-10-11T17:52:29.000Z
/* Copyright (C) 2014 Rainmeter Project Developers * * This Source Code Form is subject to the terms of the GNU General Public * License; either version 2 of the License, or (at your option) any later * version. If a copy of the GPL was not distributed with this file, You can * obtain one at <https://www.gnu.org/licenses/gpl-2.0.html>. */ // TagLib unity build: This file includes several TagLib source files. By compiling all of them // together, the build performance is greatly increased. #pragma warning(push) #pragma warning(disable: 4244; disable: 4267) #include "mpeg\mpegfile.cpp" #include "mpeg\mpegheader.cpp" #include "mpeg\mpegproperties.cpp" #include "mpeg\xingheader.cpp" #include "mpeg\id3v1\id3v1genres.cpp" #include "mpeg\id3v1\id3v1tag.cpp" #pragma warning(pop)
34.434783
95
0.752525
khanhas
d53931a98fa933cdd46718843aaf4b5c3aed6cea
535
cpp
C++
2nd/204_count_primes.cpp
buptlxb/leetcode
b641419de040801c4f54618d7ee26edcf10ee53c
[ "BSD-3-Clause" ]
null
null
null
2nd/204_count_primes.cpp
buptlxb/leetcode
b641419de040801c4f54618d7ee26edcf10ee53c
[ "BSD-3-Clause" ]
null
null
null
2nd/204_count_primes.cpp
buptlxb/leetcode
b641419de040801c4f54618d7ee26edcf10ee53c
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: int countPrimes(int n) { if (n < 3) return 0; vector<bool> vec(n, true); for (int i = 2; i < n; ++i) { if (!vec[i]) continue; for (int j = 2*i; j < n; j += i) vec[j] = false; } return count(vec.begin()+2, vec.end(), true); } }; int main(void) { cout << Solution().countPrimes(1000) << endl; return 0; }
19.107143
53
0.472897
buptlxb
d53a10df498d4b2f887daf6a5b195a1ddb15f940
2,596
hpp
C++
tools/dump/switches.hpp
paulhuggett/pstore2
a0c663d10a2e2713fdf39ecdae1f9c1e96041f5c
[ "Apache-2.0" ]
11
2018-02-02T21:24:49.000Z
2020-12-11T04:06:03.000Z
tools/dump/switches.hpp
SNSystems/pstore
74e9dd960245d6bfc125af03ed964d8ad660a62d
[ "Apache-2.0" ]
63
2018-02-05T17:24:59.000Z
2022-03-22T17:26:28.000Z
tools/dump/switches.hpp
paulhuggett/pstore
067be94d87c87fce524c8d76c6f47c347d8f1853
[ "Apache-2.0" ]
5
2020-01-13T22:47:11.000Z
2021-05-14T09:31:15.000Z
//===- tools/dump/switches.hpp ----------------------------*- mode: C++ -*-===// //* _ _ _ * //* _____ _(_) |_ ___| |__ ___ ___ * //* / __\ \ /\ / / | __/ __| '_ \ / _ \/ __| * //* \__ \\ V V /| | || (__| | | | __/\__ \ * //* |___/ \_/\_/ |_|\__\___|_| |_|\___||___/ * //* * //===----------------------------------------------------------------------===// // // Part of the pstore project, under the Apache License v2.0 with LLVM Exceptions. // See https://github.com/SNSystems/pstore/blob/master/LICENSE.txt for license // information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// /// \file switches.hpp /// \brief Defines a structure which represents the dump tool's command-line switches. #ifndef PSTORE_DUMP_SWITCHES_HPP #define PSTORE_DUMP_SWITCHES_HPP #include <list> #include <string> #include <utility> #include "pstore/command_line/tchar.hpp" #include "pstore/config/config.hpp" #include "pstore/core/database.hpp" #include "pstore/core/index_types.hpp" struct switches { bool show_all = false; /// A list of the individual fragment digests from the command-line. std::list<pstore::index::digest> fragments; /// True if --all-fragments was specified on the command-line. bool show_all_fragments = false; /// A list containing compilations digests from the command-line. std::list<pstore::index::digest> compilations; /// True is --all-compilations was specified on the command-line. bool show_all_compilations = false; /// A list of the individual debug line header digests from the command-line. std::list<pstore::index::digest> debug_line_headers; /// True if --all-debug-line-headers was specified on the command-line. bool show_all_debug_line_headers = false; /// The target-triple to use for disassembly if one is not known. std::string triple; bool show_header = false; bool show_indices = false; bool show_log = false; bool show_shared = false; /// True if --names was specified. bool show_names = false; /// True if --paths was specified. bool show_paths = false; unsigned revision = pstore::head_revision; bool hex = false; bool expanded_addresses = false; bool no_times = false; bool no_disassembly = false; std::list<std::string> paths; }; std::pair<switches, int> get_switches (int argc, pstore::command_line::tchar * argv[]); #endif // PSTORE_DUMP_SWITCHES_HPP
36.56338
87
0.605547
paulhuggett
d53a3436a1ce275d1957fe3be24593e0daded105
609
cpp
C++
codeforces/259c.little-elephant-and-bits/259c.cpp
KayvanMazaheri/acm
aeb05074bc9b9c92f35b6a741183da09a08af85d
[ "MIT" ]
3
2018-01-19T14:09:23.000Z
2018-02-01T00:40:55.000Z
codeforces/259c.little-elephant-and-bits/259c.cpp
KayvanMazaheri/acm
aeb05074bc9b9c92f35b6a741183da09a08af85d
[ "MIT" ]
null
null
null
codeforces/259c.little-elephant-and-bits/259c.cpp
KayvanMazaheri/acm
aeb05074bc9b9c92f35b6a741183da09a08af85d
[ "MIT" ]
null
null
null
// K1 // :) #include <iostream> #include <fstream> #include <algorithm> #include <vector> #include <queue> #include <bitset> #include <string> #include <cmath> #include <iomanip> #include <set> #include <map> #define EPS 1e-8 #define PI 3.141592653589793 #define point pair <int , int> #define X first #define Y second #define FX(x) fixed << setprecision((x)) using namespace std; const int MAXN = 1e9; int main() { string s; cin >> s; int pos = s.find('0'); if (pos == string::npos) cout << s.substr(1) << endl; else cout << s.substr(0, pos) + s.substr(pos+1) << endl; return 0; return 0; }
15.225
53
0.646962
KayvanMazaheri
d53cb5b3dd09c3c05263a13ef12ed4944171b8cf
15,522
cc
C++
src/main/solverUtils.cc
trey0/zmdp
d07d4f92479b92a56f955d464837fcce89085ebf
[ "Apache-2.0" ]
39
2015-02-23T16:52:30.000Z
2022-01-26T09:08:24.000Z
src/main/solverUtils.cc
trey0/zmdp
d07d4f92479b92a56f955d464837fcce89085ebf
[ "Apache-2.0" ]
3
2016-09-06T00:34:27.000Z
2021-09-13T09:09:01.000Z
src/main/solverUtils.cc
trey0/zmdp
d07d4f92479b92a56f955d464837fcce89085ebf
[ "Apache-2.0" ]
11
2015-09-05T21:40:41.000Z
2020-10-21T07:33:36.000Z
/********** tell emacs we use -*- c++ -*- style comments ******************* Copyright (c) 2002-2005, Trey Smith. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ***************************************************************************/ /*************************************************************************** * INCLUDES ***************************************************************************/ #include "solverUtils.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fstream> #include <iostream> #include <string> #include "MatrixUtils.h" #include "zmdpCommonDefs.h" #include "zmdpCommonTime.h" using namespace std; using namespace MatrixUtils; extern void usage(const char *binaryName); namespace zmdp { /********************************************************************** * HELPER FUNCTIONS **********************************************************************/ static EnumEntry searchStrategyTableG[] = { {"frtdp", S_FRTDP}, {"hsvi", S_HSVI}, {"rtdp", S_RTDP}, {"lrtdp", S_LRTDP}, {"hdp", S_HDP}, {"script", S_SCRIPT}, {NULL, -1}}; static EnumEntry modelTypeTableG[] = {{"-", -1}, {"pomdp", T_POMDP}, {"mdp", T_MDP}, {"racetrack", T_RACETRACK}, {"custom", T_CUSTOM}, {NULL, -1}}; static EnumEntry lowerBoundRepresentationTableG[] = { {"-", -1}, {"point", V_POINT}, {"convex", V_MAXPLANES}, {NULL, -1}}; static EnumEntry upperBoundRepresentationTableG[] = { {"-", -1}, {"point", V_POINT}, {"sawtooth", V_SAWTOOTH}, {NULL, -1}}; static EnumEntry maintainLowerBoundTableG[] = { {"-", -1}, {"0", 0}, {"1", 1}, {NULL, -1}}; static EnumEntry runTimeActionSelectionTableG[] = { {"-", -1}, {"lower", 0}, {"upper", 1}, {NULL, -1}}; int getEnum(const std::string &key, EnumEntry *table, const char *opt) { EnumEntry *i; for (i = table; NULL != i->key; i++) { if (key == i->key) { return i->val; } } fprintf(stderr, "ERROR: invalid value %s for config field %s, expected one of ", key.c_str(), opt); for (i = table; NULL != i->key; i++) { fprintf(stderr, "'%s' ", i->key); } fprintf(stderr, "(-h for help)\n"); exit(EXIT_FAILURE); } bool endsWith(const std::string &s, const std::string &suffix) { if (s.size() < suffix.size()) return false; return (s.substr(s.size() - suffix.size()) == suffix); } /********************************************************************** * EXPORTED API **********************************************************************/ SolverParams::SolverParams(void) : binaryName(NULL), probName(NULL), usingBenchmarkFrontEnd(false) {} #define SU_GET_ENUM(FIELD) \ FIELD = getEnum(config.getString(#FIELD), FIELD##TableG, #FIELD); #define SU_GET_BOOL(FIELD) FIELD = config.getBool(#FIELD); #define SU_GET_DOUBLE(FIELD) FIELD = config.getDouble(#FIELD); #define SU_GET_STRING(FIELD) FIELD = config.getString(#FIELD).c_str(); #define SU_GET_INT(FIELD) FIELD = config.getInt(#FIELD); void SolverParams::setValues(const ZMDPConfig &config) { binaryName = config.getString("binaryName").c_str(); probName = config.getString("simulatorModel").c_str(); // set global debug level, used by parts of the codebase that do not // depend on ZMDPConfig zmdpDebugLevelG = config.getInt("debugLevel"); if (zmdpDebugLevelG >= 1) { cout << "[params begin]" << endl; config.writeToStream(cout); cout << "[params end]" << endl; } SU_GET_ENUM(searchStrategy); SU_GET_ENUM(modelType); SU_GET_ENUM(lowerBoundRepresentation); SU_GET_ENUM(upperBoundRepresentation); SU_GET_ENUM(maintainLowerBound); SU_GET_BOOL(maintainUpperBound); SU_GET_STRING(policyOutputFile); SU_GET_BOOL(useFastModelParser); SU_GET_DOUBLE(terminateRegretBound); SU_GET_DOUBLE(terminateWallclockSeconds); if (terminateWallclockSeconds <= 0.0) { terminateWallclockSeconds = 99e+20; } SU_GET_INT(maxHorizon); SU_GET_BOOL(useWeakUpperBoundHeuristic); SU_GET_ENUM(maintainLowerBound); useUpperBoundRunTimeActionSelection = getEnum(config.getString("runTimeActionSelection"), runTimeActionSelectionTableG, "runTimeActionSelection"); SU_GET_INT(evaluationTrialsPerEpoch); SU_GET_INT(evaluationMaxStepsPerTrial); SU_GET_DOUBLE(evaluationFirstEpochWallclockSeconds); SU_GET_DOUBLE(evaluationEpochsPerMagnitude); SU_GET_STRING(evaluationOutputFile); SU_GET_STRING(boundsOutputFile); SU_GET_STRING(simulationTraceOutputFile); // if the probName is NULL, we are not solving a planning problem // (e.g., we are running zmdpEvaluate). skip filling in missing // solver parameters. if (NULL != probName) { inferMissingValues(); } } void SolverParams::inferMissingValues(void) { // fill in default and inferred values if (-1 == modelType) { if (endsWith(probName, ".pomdp")) { if (zmdpDebugLevelG >= 1) { printf( "[params] inferred modelType='pomdp' from model filename " "extension\n"); } modelType = T_POMDP; } else if (endsWith(probName, ".mdp")) { if (zmdpDebugLevelG >= 1) { printf( "[params] inferred modelType='mdp' from model filename " "extension\n"); } modelType = T_MDP; } else if (endsWith(probName, ".racetrack")) { if (zmdpDebugLevelG >= 1) { printf( "[params] inferred modelType='racetrack' from model filename " "extension\n"); } modelType = T_RACETRACK; } else if (0 == strcmp(probName, "custom")) { if (zmdpDebugLevelG >= 1) { printf("[params] inferred modelType='custom' from model filename\n"); } modelType = T_CUSTOM; } else { fprintf(stderr, "ERROR: couldn't infer problem type from model filename %s (use " "-t option, -h for help)\n", probName); exit(EXIT_FAILURE); } } if (-1 == lowerBoundRepresentation) { if (T_POMDP == modelType) { lowerBoundRepresentation = V_MAXPLANES; if (zmdpDebugLevelG >= 1) { printf( "[params] selected lowerBoundRepresentation='maxPlanes' because " "modelType='pomdp'\n"); } } else { lowerBoundRepresentation = V_POINT; if (zmdpDebugLevelG >= 1) { printf( "[params] selected lowerBoundRepresentation='point' because " "model is an MDP\n"); } } } if (-1 == upperBoundRepresentation) { if (T_POMDP == modelType) { upperBoundRepresentation = V_SAWTOOTH; if (zmdpDebugLevelG >= 1) { printf( "[params] selected upperBoundRepresentation='sawtooth' because " "modelType='pomdp'\n"); } } else { upperBoundRepresentation = V_POINT; if (zmdpDebugLevelG >= 1) { printf( "[params] selected upperBoundRepresentation='point' because " "model is an MDP\n"); } } } // error check if (V_MAXPLANES == lowerBoundRepresentation && T_POMDP != modelType) { fprintf(stderr, "ERROR: lowerBoundRepresentation='maxPlanes' requires " "modelType='pomdp' (-h for help)\n"); exit(EXIT_FAILURE); } if (V_SAWTOOTH == upperBoundRepresentation && T_POMDP != modelType) { fprintf(stderr, "ERROR: upperBoundRepresentation='sawtooth' requires " "modelType='pomdp' (-h for help)\n"); exit(EXIT_FAILURE); } if (NULL != policyOutputFile && 0 == strcmp(policyOutputFile, "none")) { policyOutputFile = NULL; } if (NULL != policyOutputFile && 0 == strcmp(policyOutputFile, "-")) { if (usingBenchmarkFrontEnd) { policyOutputFile = NULL; if (zmdpDebugLevelG >= 1) { printf( "[params] selected policyOutputFile='none' because front end is " "zmdp benchmark\n"); } } else { policyOutputFile = "out.policy"; if (zmdpDebugLevelG >= 1) { printf( "[params] selected policyOutputFile='%s' because front end is " "zmdp solve\n", policyOutputFile); } } } } void constructSolverObjects(SolverObjects &obj, SolverParams &p, const ZMDPConfig &config) { switch (p.modelType) { case T_POMDP: obj.problem = new Pomdp(p.probName, &config); break; case T_MDP: obj.problem = new GenericDiscreteMDP(p.probName, &config); break; case T_RACETRACK: obj.problem = new RaceTrack(p.probName); break; case T_CUSTOM: obj.problem = new CustomMDP(config); break; default: assert(0); // never reach this point } obj.sim = new MDPSim(obj.problem); if (T_POMDP == p.modelType && obj.problem->getDiscount() >= 1.0 && -1 == p.maxHorizon) { cerr << "ERROR: with modelType='pomdp', you must have either discount < 1\n" << " or maxHorizon defined (i.e. non-negative) in order to generate " "initial\n" << " bounds (-h for help)" << endl; exit(EXIT_FAILURE); } bool lowerBoundRequired; bool upperBoundRequired; switch (p.searchStrategy) { case S_FRTDP: obj.solver = new FRTDP(); lowerBoundRequired = true; upperBoundRequired = true; break; case S_HSVI: obj.solver = new HSVI(); lowerBoundRequired = true; upperBoundRequired = true; break; case S_RTDP: obj.solver = new RTDP(); lowerBoundRequired = false; upperBoundRequired = true; break; case S_LRTDP: obj.solver = new LRTDP(); lowerBoundRequired = false; upperBoundRequired = true; break; case S_HDP: obj.solver = new HDP(); lowerBoundRequired = false; upperBoundRequired = true; break; case S_SCRIPT: obj.solver = new ScriptedUpdater(); lowerBoundRequired = false; upperBoundRequired = false; break; default: assert(0); // never reach this point } if (zmdpDebugLevelG >= 1) { printf( "[params] with requested searchStrategy, lowerBoundRequired=%d, " "upperBoundRequired=%d\n", lowerBoundRequired, upperBoundRequired); } switch (p.maintainLowerBound) { case -1: p.maintainLowerBound = lowerBoundRequired; if (zmdpDebugLevelG >= 1) { printf( "[params] selected maintainLowerBound=%d because " "lowerBoundRequired=%d\n", p.maintainLowerBound, lowerBoundRequired); } break; case 0: if (lowerBoundRequired) { fprintf(stderr, "ERROR: maintainLowerBound=0 is incompatible with " "searchStrategy='%s' (-h for help)\n", config.getString("searchStrategy").c_str()); exit(EXIT_FAILURE); } break; case 1: // keep current value break; default: assert(0); // never reach this point } if (!p.maintainUpperBound && upperBoundRequired) { fprintf(stderr, "ERROR: maintainUpperBound=0 is incompatible with " "searchStrategy='%s' (-h for help)\n", config.getString("searchStrategy").c_str()); exit(EXIT_FAILURE); } if (!(p.maintainLowerBound || p.maintainUpperBound)) { fprintf(stderr, "ERROR: at least one bound must be maintained, lower or " "upper (-h for help)\n"); exit(EXIT_FAILURE); } switch (p.useUpperBoundRunTimeActionSelection) { case -1: p.useUpperBoundRunTimeActionSelection = !p.maintainLowerBound; if (zmdpDebugLevelG >= 1) { printf( "[params] selected useUpperBoundRunTimeActionSelection=%d because " "maintainLowerBound=%d\n", p.useUpperBoundRunTimeActionSelection, p.maintainLowerBound); } break; case 0: if (!p.maintainLowerBound) { fprintf(stderr, "ERROR: runTimeActionSelection='lower' incompatible with " "maintainLowerBound=0 (-h for help)\n"); exit(EXIT_FAILURE); } break; case 1: if (!p.maintainUpperBound) { fprintf(stderr, "ERROR: runTimeActionSelection='upper' incompatible with " "maintainUpperBound=0 (-h for help)\n"); exit(EXIT_FAILURE); } break; default: assert(0); // never reach this point } if (NULL != p.policyOutputFile) { if (!(p.maintainLowerBound && (p.lowerBoundRepresentation == V_MAXPLANES))) { cerr << "WARNING: selected options indicate an output policy should be " "written, but\n" << " policy output is currently only supported when " "modelType='pomdp',\n" << " lowerBoundRepresentation='maxPlanes', and lower bound is " "maintained;\n" << " disabling policy output on this run" << endl; p.policyOutputFile = NULL; } } bool dualPointBounds = p.maintainLowerBound && p.maintainUpperBound && (V_POINT == p.lowerBoundRepresentation) && (V_POINT == p.upperBoundRepresentation); obj.bounds = new BoundPair(p.maintainLowerBound, p.maintainUpperBound, p.useUpperBoundRunTimeActionSelection, dualPointBounds); PointLowerBound *plb; MaxPlanesLowerBound *mlb; if (p.maintainLowerBound) { switch (p.lowerBoundRepresentation) { case V_POINT: plb = new PointLowerBound(obj.problem, &config, obj.bounds); plb->initBound = obj.problem->newLowerBound(&config); obj.bounds->lowerBound = plb; break; case V_MAXPLANES: mlb = new MaxPlanesLowerBound(obj.problem, &config); mlb->core = obj.bounds; obj.bounds->lowerBound = mlb; break; default: assert(0); // never reach this point } } PointUpperBound *pub; SawtoothUpperBound *sub; if (p.maintainUpperBound) { switch (p.upperBoundRepresentation) { case V_POINT: pub = new PointUpperBound(obj.problem, &config, obj.bounds); if (T_RACETRACK == p.modelType && !p.useWeakUpperBoundHeuristic) { // stronger upper bound strategy for racetrack MDP pub->initBound = new RelaxUBInitializer(obj.problem, &config); } else { // default upper bound strategy, depends on the MDP type pub->initBound = obj.problem->newUpperBound(&config); } obj.bounds->upperBound = pub; break; case V_SAWTOOTH: sub = new SawtoothUpperBound(obj.problem, &config); sub->core = obj.bounds; obj.bounds->upperBound = sub; break; default: assert(0); // never reach this point } } (reinterpret_cast<RTDPCore *>(obj.solver))->setBounds(obj.bounds); } }; // namespace zmdp
31.938272
80
0.593094
trey0
d53f772ff269353f3dc548dd8ac90dfaeda87871
16,127
cc
C++
src/mem/snoop_filter.cc
fei-shan/gem5-experiment
70781db30d42b1fe50e495bd04f7755a4b0e0e59
[ "BSD-3-Clause" ]
1
2022-03-20T23:23:41.000Z
2022-03-20T23:23:41.000Z
src/mem/snoop_filter.cc
fei-shan/gem5-experiment
70781db30d42b1fe50e495bd04f7755a4b0e0e59
[ "BSD-3-Clause" ]
1
2021-04-17T17:13:56.000Z
2021-04-17T17:13:56.000Z
src/mem/snoop_filter.cc
fei-shan/gem5-experiment
70781db30d42b1fe50e495bd04f7755a4b0e0e59
[ "BSD-3-Clause" ]
1
2021-09-12T02:45:38.000Z
2021-09-12T02:45:38.000Z
/* * Copyright (c) 2013-2017,2019 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * 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 holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @file * Implementation of a snoop filter. */ #include "mem/snoop_filter.hh" #include "base/logging.hh" #include "base/trace.hh" #include "debug/SnoopFilter.hh" #include "sim/system.hh" const int SnoopFilter::SNOOP_MASK_SIZE; void SnoopFilter::eraseIfNullEntry(SnoopFilterCache::iterator& sf_it) { SnoopItem& sf_item = sf_it->second; if ((sf_item.requested | sf_item.holder).none()) { cachedLocations.erase(sf_it); DPRINTF(SnoopFilter, "%s: Removed SF entry.\n", __func__); } } std::pair<SnoopFilter::SnoopList, Cycles> SnoopFilter::lookupRequest(const Packet* cpkt, const ResponsePort& cpu_side_port) { DPRINTF(SnoopFilter, "%s: src %s packet %s\n", __func__, cpu_side_port.name(), cpkt->print()); // check if the packet came from a cache bool allocate = !cpkt->req->isUncacheable() && cpu_side_port.isSnooping() && cpkt->fromCache(); Addr line_addr = cpkt->getBlockAddr(linesize); if (cpkt->isSecure()) { line_addr |= LineSecure; } SnoopMask req_port = portToMask(cpu_side_port); reqLookupResult.it = cachedLocations.find(line_addr); bool is_hit = (reqLookupResult.it != cachedLocations.end()); // If the snoop filter has no entry, and we should not allocate, // do not create a new snoop filter entry, simply return a NULL // portlist. if (!is_hit && !allocate) return snoopDown(lookupLatency); // If no hit in snoop filter create a new element and update iterator if (!is_hit) { reqLookupResult.it = cachedLocations.emplace(line_addr, SnoopItem()).first; } SnoopItem& sf_item = reqLookupResult.it->second; SnoopMask interested = sf_item.holder | sf_item.requested; // Store unmodified value of snoop filter item in temp storage in // case we need to revert because of a send retry in // updateRequest. reqLookupResult.retryItem = sf_item; stats.totRequests++; if (is_hit) { if (interested.count() == 1) stats.hitSingleRequests++; else stats.hitMultiRequests++; } DPRINTF(SnoopFilter, "%s: SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); // If we are not allocating, we are done if (!allocate) return snoopSelected(maskToPortList(interested & ~req_port), lookupLatency); if (cpkt->needsResponse()) { if (!cpkt->cacheResponding()) { // Max one request per address per port panic_if((sf_item.requested & req_port).any(), "double request :( SF value %x.%x\n", sf_item.requested, sf_item.holder); // Mark in-flight requests to distinguish later on sf_item.requested |= req_port; DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } else { // NOTE: The memInhibit might have been asserted by a cache closer // to the CPU, already -> the response will not be seen by this // filter -> we do not need to keep the in-flight request, but make // sure that we know that that cluster has a copy panic_if((sf_item.holder & req_port).none(), "Need to hold the value!"); DPRINTF(SnoopFilter, "%s: not marking request. SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } } else { // if (!cpkt->needsResponse()) assert(cpkt->isEviction()); // make sure that the sender actually had the line panic_if((sf_item.holder & req_port).none(), "requestor %x is not a " \ "holder :( SF value %x.%x\n", req_port, sf_item.requested, sf_item.holder); // CleanEvicts and Writebacks -> the sender and all caches above // it may not have the line anymore. if (!cpkt->isBlockCached()) { sf_item.holder &= ~req_port; DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } } return snoopSelected(maskToPortList(interested & ~req_port), lookupLatency); } void SnoopFilter::finishRequest(bool will_retry, Addr addr, bool is_secure) { if (reqLookupResult.it != cachedLocations.end()) { // since we rely on the caller, do a basic check to ensure // that finishRequest is being called following lookupRequest Addr line_addr = (addr & ~(Addr(linesize - 1))); if (is_secure) { line_addr |= LineSecure; } assert(reqLookupResult.it->first == line_addr); if (will_retry) { SnoopItem retry_item = reqLookupResult.retryItem; // Undo any changes made in lookupRequest to the snoop filter // entry if the request will come again. retryItem holds // the previous value of the snoopfilter entry. reqLookupResult.it->second = retry_item; DPRINTF(SnoopFilter, "%s: restored SF value %x.%x\n", __func__, retry_item.requested, retry_item.holder); } eraseIfNullEntry(reqLookupResult.it); } } std::pair<SnoopFilter::SnoopList, Cycles> SnoopFilter::lookupSnoop(const Packet* cpkt) { DPRINTF(SnoopFilter, "%s: packet %s\n", __func__, cpkt->print()); assert(cpkt->isRequest()); Addr line_addr = cpkt->getBlockAddr(linesize); if (cpkt->isSecure()) { line_addr |= LineSecure; } auto sf_it = cachedLocations.find(line_addr); bool is_hit = (sf_it != cachedLocations.end()); panic_if(!is_hit && (cachedLocations.size() >= maxEntryCount), "snoop filter exceeded capacity of %d cache blocks\n", maxEntryCount); // If the snoop filter has no entry, simply return a NULL // portlist, there is no point creating an entry only to remove it // later if (!is_hit) return snoopDown(lookupLatency); SnoopItem& sf_item = sf_it->second; SnoopMask interested = (sf_item.holder | sf_item.requested); stats.totSnoops++; if (interested.count() == 1) stats.hitSingleSnoops++; else stats.hitMultiSnoops++; // ReadEx and Writes require both invalidation and exlusivity, while reads // require neither. Writebacks on the other hand require exclusivity but // not the invalidation. Previously Writebacks did not generate upward // snoops so this was never an issue. Now that Writebacks generate snoops // we need a special case for Writebacks. Additionally cache maintenance // operations can generate snoops as they clean and/or invalidate all // caches down to the specified point of reference. assert(cpkt->isWriteback() || cpkt->req->isUncacheable() || (cpkt->isInvalidate() == cpkt->needsWritable()) || cpkt->req->isCacheMaintenance()); if (cpkt->isInvalidate() && sf_item.requested.none()) { // Early clear of the holder, if no other request is currently going on // @todo: This should possibly be updated even though we do not filter // upward snoops DPRINTF(SnoopFilter, "%s: old SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); sf_item.holder = 0; DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); eraseIfNullEntry(sf_it); } return snoopSelected(maskToPortList(interested), lookupLatency); } void SnoopFilter::updateSnoopResponse(const Packet* cpkt, const ResponsePort& rsp_port, const ResponsePort& req_port) { DPRINTF(SnoopFilter, "%s: rsp %s req %s packet %s\n", __func__, rsp_port.name(), req_port.name(), cpkt->print()); assert(cpkt->isResponse()); assert(cpkt->cacheResponding()); // if this snoop response is due to an uncacheable request, or is // being turned into a normal response, there is nothing more to // do if (cpkt->req->isUncacheable() || !req_port.isSnooping()) { return; } Addr line_addr = cpkt->getBlockAddr(linesize); if (cpkt->isSecure()) { line_addr |= LineSecure; } SnoopMask rsp_mask = portToMask(rsp_port); SnoopMask req_mask = portToMask(req_port); SnoopItem& sf_item = cachedLocations[line_addr]; DPRINTF(SnoopFilter, "%s: old SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); // The source should have the line panic_if((sf_item.holder & rsp_mask).none(), "SF value %x.%x does not have the line\n", sf_item.requested, sf_item.holder); // The destination should have had a request in panic_if((sf_item.requested & req_mask).none(), "SF value %x.%x missing "\ "the original request\n", sf_item.requested, sf_item.holder); // If the snoop response has no sharers the line is passed in // Modified state, and we know that there are no other copies, or // they will all be invalidated imminently if (!cpkt->hasSharers()) { DPRINTF(SnoopFilter, "%s: dropping %x because non-shared snoop " "response SF val: %x.%x\n", __func__, rsp_mask, sf_item.requested, sf_item.holder); sf_item.holder = 0; } assert(!cpkt->isWriteback()); // @todo Deal with invalidating responses sf_item.holder |= req_mask; sf_item.requested &= ~req_mask; assert((sf_item.requested | sf_item.holder).any()); DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } void SnoopFilter::updateSnoopForward(const Packet* cpkt, const ResponsePort& rsp_port, const RequestPort& req_port) { DPRINTF(SnoopFilter, "%s: rsp %s req %s packet %s\n", __func__, rsp_port.name(), req_port.name(), cpkt->print()); assert(cpkt->isResponse()); assert(cpkt->cacheResponding()); Addr line_addr = cpkt->getBlockAddr(linesize); if (cpkt->isSecure()) { line_addr |= LineSecure; } auto sf_it = cachedLocations.find(line_addr); bool is_hit = sf_it != cachedLocations.end(); // Nothing to do if it is not a hit if (!is_hit) return; // If the snoop response has no sharers the line is passed in // Modified state, and we know that there are no other copies, or // they will all be invalidated imminently if (!cpkt->hasSharers()) { SnoopItem& sf_item = sf_it->second; DPRINTF(SnoopFilter, "%s: old SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); sf_item.holder = 0; DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); eraseIfNullEntry(sf_it); } } void SnoopFilter::updateResponse(const Packet* cpkt, const ResponsePort& cpu_side_port) { DPRINTF(SnoopFilter, "%s: src %s packet %s\n", __func__, cpu_side_port.name(), cpkt->print()); assert(cpkt->isResponse()); // we only allocate if the packet actually came from a cache, but // start by checking if the port is snooping if (cpkt->req->isUncacheable() || !cpu_side_port.isSnooping()) return; // next check if we actually allocated an entry Addr line_addr = cpkt->getBlockAddr(linesize); if (cpkt->isSecure()) { line_addr |= LineSecure; } auto sf_it = cachedLocations.find(line_addr); if (sf_it == cachedLocations.end()) return; SnoopMask response_mask = portToMask(cpu_side_port); SnoopItem& sf_item = sf_it->second; DPRINTF(SnoopFilter, "%s: old SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); // Make sure we have seen the actual request, too panic_if((sf_item.requested & response_mask).none(), "SF value %x.%x missing request bit\n", sf_item.requested, sf_item.holder); sf_item.requested &= ~response_mask; // Update the residency of the cache line. if (cpkt->req->isCacheMaintenance()) { // A cache clean response does not carry any data so it // shouldn't change the holders, unless it is invalidating. if (cpkt->isInvalidate()) { sf_item.holder &= ~response_mask; } eraseIfNullEntry(sf_it); } else { // Any other response implies that a cache above will have the // block. sf_item.holder |= response_mask; assert((sf_item.holder | sf_item.requested).any()); } DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } SnoopFilter::SnoopFilterStats::SnoopFilterStats(Stats::Group *parent) : Stats::Group(parent), ADD_STAT(totRequests, UNIT_COUNT, "Total number of requests made to the snoop filter."), ADD_STAT(hitSingleRequests, UNIT_COUNT, "Number of requests hitting in the snoop filter with a single " "holder of the requested data."), ADD_STAT(hitMultiRequests, UNIT_COUNT, "Number of requests hitting in the snoop filter with multiple " "(>1) holders of the requested data."), ADD_STAT(totSnoops, UNIT_COUNT, "Total number of snoops made to the snoop filter."), ADD_STAT(hitSingleSnoops, UNIT_COUNT, "Number of snoops hitting in the snoop filter with a single " "holder of the requested data."), ADD_STAT(hitMultiSnoops, UNIT_COUNT, "Number of snoops hitting in the snoop filter with multiple " "(>1) holders of the requested data.") {} void SnoopFilter::regStats() { SimObject::regStats(); }
38.860241
80
0.644075
fei-shan
d54054a788b27283e72ebd6635c129fe46dae05b
548
cpp
C++
core/src/Platform/MiniAudio/MiniAudio.cpp
BryceStandley/TNAH
909ba9cf9f04632a3b518646c3af39752bd9d407
[ "MIT" ]
1
2021-11-08T09:44:40.000Z
2021-11-08T09:44:40.000Z
core/src/Platform/MiniAudio/MiniAudio.cpp
BryceStandley/TNAH
909ba9cf9f04632a3b518646c3af39752bd9d407
[ "MIT" ]
null
null
null
core/src/Platform/MiniAudio/MiniAudio.cpp
BryceStandley/TNAH
909ba9cf9f04632a3b518646c3af39752bd9d407
[ "MIT" ]
null
null
null
#include "tnahpch.h" #include "MiniAudio.h" namespace tnah { bool MiniAudio::SetListener(TransformComponent &transforms) const { return false; } bool MiniAudio::AddAudioSource(AudioSourceComponent &sound) { return false; } bool MiniAudio::UpdateAudioSource(AudioSourceComponent &sound) { return false; } void MiniAudio::OnUpdate() { } void MiniAudio::UpdateSound(AudioSourceComponent &sound, TransformComponent &transforms) { } bool MiniAudio::Active() const { return false; } void MiniAudio::Clear() { } }
13.047619
89
0.717153
BryceStandley
d54067c388a2f93e63e5d860debc17ed9f6bc03d
4,770
cpp
C++
world/source/Memberships.cpp
prolog/shadow-of-the-wyrm
a1312c3e9bb74473f73c4e7639e8bd537f10b488
[ "MIT" ]
60
2019-08-21T04:08:41.000Z
2022-03-10T13:48:04.000Z
world/source/Memberships.cpp
prolog/shadow-of-the-wyrm
a1312c3e9bb74473f73c4e7639e8bd537f10b488
[ "MIT" ]
3
2021-03-18T15:11:14.000Z
2021-10-20T12:13:07.000Z
world/source/Memberships.cpp
prolog/shadow-of-the-wyrm
a1312c3e9bb74473f73c4e7639e8bd537f10b488
[ "MIT" ]
8
2019-11-16T06:29:05.000Z
2022-01-23T17:33:43.000Z
#include "Memberships.hpp" #include "CreatureFeatures.hpp" #include "MembershipTextKeys.hpp" #include "Serialize.hpp" using namespace std; // Memberships bool Memberships::operator==(const Memberships& m) const { bool result = true; result = result && memberships == m.memberships; return result; } bool Memberships::add_membership(const string& id, const Membership& m) { set<string> exclusions = get_excluded_memberships(); if (exclusions.find(id) == exclusions.end()) { memberships[id] = m; return true; } return false; } bool Memberships::remove_membership(const string& id) { auto m_it = memberships.find(id); if (m_it != memberships.end()) { memberships.erase(m_it); return true; } return false; } bool Memberships::has_membership(const string& id) { auto m_it = memberships.find(id); return (m_it != memberships.end()); } map<string, Membership> Memberships::get_memberships() const { return memberships; } set<string> Memberships::get_excluded_memberships() const { set<string> excl; for (auto m_pair : memberships) { set<string> cur_excl = m_pair.second.get_excluded_memberships(); excl.insert(cur_excl.begin(), cur_excl.end()); } return excl; } ClassIdentifier Memberships::internal_class_identifier() const { return ClassIdentifier::CLASS_ID_MEMBERSHIPS; } bool Memberships::serialize(ostream& stream) const { Serialize::write_size_t(stream, memberships.size()); for (const auto& m_pair : memberships) { Serialize::write_string(stream, m_pair.first); m_pair.second.serialize(stream); } return true; } bool Memberships::deserialize(istream& stream) { size_t m_size = 0; Serialize::read_size_t(stream, m_size); for (size_t i = 0; i < m_size; i++) { string membership_id; Serialize::read_string(stream, membership_id); Membership m; m.deserialize(stream); memberships[membership_id] = m; } return true; } // Individual Membership Membership::Membership() { } Membership::Membership(const string& new_membership_id, const string& new_desc_sid, const set<string>& new_excluded_memberships) : membership_id(new_membership_id), description_sid(new_desc_sid), excluded_memberships(new_excluded_memberships) { } bool Membership::operator==(const Membership& m) const { bool result = true; result = result && (membership_id == m.membership_id); result = result && (description_sid == m.description_sid); result = result && (this->excluded_memberships == m.excluded_memberships); return result; } bool Membership::is_null() const { return membership_id.empty(); } void Membership::set_membership_id(const string& new_membership_id) { membership_id = new_membership_id; } string Membership::get_membership_id() const { return membership_id; } void Membership::set_description_sid(const string& new_description_sid) { description_sid = new_description_sid; } string Membership::get_description_sid() const { return description_sid; } void Membership::add_excluded_membership(const string& excl) { excluded_memberships.insert(excl); } void Membership::remove_excluded_membership(const string& excl) { auto e_it = excluded_memberships.find(excl); if (e_it != excluded_memberships.end()) { excluded_memberships.erase(e_it); } } void Membership::set_excluded_memberships(const set<string>& new_excluded_memberships) { excluded_memberships = new_excluded_memberships; } set<string> Membership::get_excluded_memberships() const { return excluded_memberships; } ClassIdentifier Membership::internal_class_identifier() const { return ClassIdentifier::CLASS_ID_MEMBERSHIP; } bool Membership::serialize(ostream& stream) const { Serialize::write_string(stream, membership_id); Serialize::write_string(stream, description_sid); Serialize::write_string_set(stream, excluded_memberships); return true; } bool Membership::deserialize(istream& stream) { Serialize::read_string(stream, membership_id); Serialize::read_string(stream, description_sid); Serialize::read_string_set(stream, excluded_memberships); return true; } Membership MembershipFactory::create_holy_champion() { Membership m(MembershipID::MEMBERSHIP_ID_HOLY_CHAMPION, MembershipTextKeys::MEMBERSHIP_CHAMPION, {}); return m; } Membership MembershipFactory::create_fallen_champion() { Membership m(MembershipID::MEMBERSHIP_ID_FALLEN_CHAMPION, MembershipTextKeys::MEMBERSHIP_FALLEN_CHAMPION, {}); return m; } #ifdef UNIT_TESTS #include "unit_tests/Memberships_test.cpp" #endif
22.083333
129
0.716981
prolog
d540889433fb259bb6338c0478e03cbd118239ce
2,546
hpp
C++
OcularCore/include/Resources/ResourceDetails.hpp
ssell/OcularEngine
c80cc4fcdb7dd7ce48d3af330bd33d05312076b1
[ "Apache-2.0" ]
8
2017-01-27T01:06:06.000Z
2020-11-05T20:23:19.000Z
OcularCore/include/Resources/ResourceDetails.hpp
ssell/OcularEngine
c80cc4fcdb7dd7ce48d3af330bd33d05312076b1
[ "Apache-2.0" ]
39
2016-06-03T02:00:36.000Z
2017-03-19T17:47:39.000Z
OcularCore/include/Resources/ResourceDetails.hpp
ssell/OcularEngine
c80cc4fcdb7dd7ce48d3af330bd33d05312076b1
[ "Apache-2.0" ]
4
2019-05-22T09:13:36.000Z
2020-12-01T03:17:45.000Z
/** * Copyright 2014-2017 Steven T Sell (ssell@vertexfragment.com) * * 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. */ #pragma once #ifndef __H__OCULAR_RESOURCES_RESOURCE_DETAILS__H__ #define __H__OCULAR_RESOURCES_RESOURCE_DETAILS__H__ #include "Resource.hpp" #include <memory> //------------------------------------------------------------------------------------------ /** * \addtogroup Ocular * @{ */ namespace Ocular { /** * \addtogroup Core * @{ */ namespace Core { class ResourceManager; /** * \class ResourceDetails * \brief Maintains a resource and usage details. */ class ResourceDetails { friend class ResourceManager; public: ResourceDetails(Resource* resource, ResourceType type = ResourceType::Undefined); ~ResourceDetails(); /** * */ Resource* getResource(); /** * */ Resource* getResourceUntracked() const; /** * */ uint64_t getTimeOfLastRequest() const; /** * */ unsigned getNumberOfRequests() const; /** * */ uint64_t getSize() const; /** * */ ResourceType getType() const; /** * */ void reset(); protected: Resource* m_Resource; ResourceType m_Type; /// Secondary copy of ResourceType. Mainly used when identifying subresources of MultiResource instances. uint64_t m_LastRequest; /// In NS unsigned m_NumberOfRequests; private: }; } /** * @} End of Doxygen Groups */ } /** * @} End of Doxygen Groups */ //------------------------------------------------------------------------------------------ #endif
23.357798
142
0.501964
ssell
d5421111c38bc93789c9f630947f17728a966993
70,130
cpp
C++
HotPatcher/Source/HotPatcherRuntime/Private/FlibPatchParserHelper.cpp
roy5931/HotPatcher
925b2ba574dea912041990c0f5541dfc4a6067ca
[ "MIT" ]
null
null
null
HotPatcher/Source/HotPatcherRuntime/Private/FlibPatchParserHelper.cpp
roy5931/HotPatcher
925b2ba574dea912041990c0f5541dfc4a6067ca
[ "MIT" ]
null
null
null
HotPatcher/Source/HotPatcherRuntime/Private/FlibPatchParserHelper.cpp
roy5931/HotPatcher
925b2ba574dea912041990c0f5541dfc4a6067ca
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. // project header #include "FlibPatchParserHelper.h" #include "FlibAssetManageHelper.h" #include "BaseTypes/AssetManager/FFileArrayDirectoryVisitor.hpp" #include "FlibAssetManageHelper.h" #include "FlibAssetManageHelper.h" #include "HotPatcherLog.h" #include "CreatePatch/FExportPatchSettings.h" #include "DependenciesParser/FDefaultAssetDependenciesParser.h" #include "DependenciesParser/FOldAssetDependenciesParser.h" // engine header #include "Misc/App.h" #include "Misc/SecureHash.h" #include "Kismet/KismetSystemLibrary.h" #include "Kismet/KismetStringLibrary.h" #include "Interfaces/IPluginManager.h" #include "Serialization/JsonSerializer.h" #include "HAL/FileManager.h" #include "Engine/EngineTypes.h" #include "JsonObjectConverter.h" #include "AssetRegistryState.h" #include "CreatePatch/TimeRecorder.h" #include "Misc/Paths.h" #include "Kismet/KismetStringLibrary.h" #include "Serialization/LargeMemoryReader.h" TArray<FString> UFlibPatchParserHelper::GetAvailableMaps(FString GameName, bool IncludeEngineMaps, bool IncludePluginMaps, bool Sorted) { const FString WildCard = FString::Printf(TEXT("*%s"), *FPackageName::GetMapPackageExtension()); TArray<FString> AllMaps; TMap<FString,FString> AllEnableModules; UFlibAssetManageHelper::GetAllEnabledModuleName(AllEnableModules); auto ScanMapsByModuleName = [WildCard,&AllMaps](const FString& InModuleBaseDir) { TArray<FString> OutMaps; FString ModuleContentAbsPath= FPaths::ConvertRelativePathToFull(FPaths::Combine(*InModuleBaseDir, TEXT("Content"))); IFileManager::Get().FindFilesRecursive(OutMaps, *ModuleContentAbsPath, *WildCard, true, false); for (const auto& MapPath : OutMaps) { AllMaps.Add(FPaths::GetBaseFilename(MapPath)); } }; ScanMapsByModuleName(AllEnableModules[TEXT("Game")]); if (IncludeEngineMaps) { ScanMapsByModuleName(AllEnableModules[TEXT("Engine")]); } if (IncludePluginMaps) { TArray<FString> AllModuleNames; AllEnableModules.GetKeys(AllModuleNames); for (const auto& ModuleName : AllModuleNames) { if (!ModuleName.Equals(TEXT("Game")) && !ModuleName.Equals(TEXT("Engine"))) { ScanMapsByModuleName(AllEnableModules[ModuleName]); } } } if (Sorted) { AllMaps.Sort(); } return AllMaps; } FString UFlibPatchParserHelper::GetProjectName() { return FApp::GetProjectName(); } FString UFlibPatchParserHelper::GetProjectFilePath() { FString ProjectFilePath; { FString ProjectPath = UKismetSystemLibrary::GetProjectDirectory(); FString ProjectName = FString(FApp::GetProjectName()).Append(TEXT(".uproject")); ProjectFilePath = FPaths::Combine(ProjectPath, ProjectName); } return ProjectFilePath; } bool UFlibPatchParserHelper::DiffVersionAssets( const FAssetDependenciesInfo& InNewVersion, const FAssetDependenciesInfo& InBaseVersion, FAssetDependenciesInfo& OutAddAsset, FAssetDependenciesInfo& OutModifyAsset, FAssetDependenciesInfo& OutDeleteAsset ) { FAssetDependenciesInfo result; TArray<FString> AddAsset; TArray<FString> ModifyAsset; TArray<FString> DeleteAsset; { TArray<FString> InNewAssetModuleKeyList; InNewVersion.AssetsDependenciesMap.GetKeys(InNewAssetModuleKeyList); TArray<FString> InBaseAssetModuleKeysList; InBaseVersion.AssetsDependenciesMap.GetKeys(InBaseAssetModuleKeysList); // Parser Add new asset for (const auto& NewVersionAssetModule : InNewAssetModuleKeyList) { // is a new mdoule? if (!InBaseAssetModuleKeysList.Contains(NewVersionAssetModule)) { OutAddAsset.AssetsDependenciesMap.Add(NewVersionAssetModule, *InNewVersion.AssetsDependenciesMap.Find(NewVersionAssetModule)); continue; } { TArray<FString> NewVersionDependAssetsList; InNewVersion.AssetsDependenciesMap.Find(NewVersionAssetModule)->AssetDependencyDetails.GetKeys(NewVersionDependAssetsList); TArray<FString> BaseVersionDependAssetsList; InBaseVersion.AssetsDependenciesMap.Find(NewVersionAssetModule)->AssetDependencyDetails.GetKeys(BaseVersionDependAssetsList); const TMap<FString,FAssetDetail>& NewVersionAssetModuleDetail = InNewVersion.AssetsDependenciesMap.Find(NewVersionAssetModule)->AssetDependencyDetails; TArray<FString> CurrentModuleAssetList; NewVersionAssetModuleDetail.GetKeys(CurrentModuleAssetList); // add to TArray<FString> for (const auto& NewAssetItem : CurrentModuleAssetList) { if (!BaseVersionDependAssetsList.Contains(NewAssetItem)) { FString BelongModuneName = UFlibAssetManageHelper::GetAssetBelongModuleName(NewAssetItem); if (!OutAddAsset.AssetsDependenciesMap.Contains(BelongModuneName)) { OutAddAsset.AssetsDependenciesMap.Add(BelongModuneName, FAssetDependenciesDetail{ BelongModuneName,TMap<FString,FAssetDetail>{} }); } TMap<FString, FAssetDetail>& CurrentModuleAssetDetails = OutAddAsset.AssetsDependenciesMap.Find(BelongModuneName)->AssetDependencyDetails; CurrentModuleAssetDetails.Add(NewAssetItem, *NewVersionAssetModuleDetail.Find(NewAssetItem)); } } } } // Parser Modify Asset for (const auto& BaseVersionAssetModule : InBaseAssetModuleKeysList) { const FAssetDependenciesDetail& BaseVersionModuleAssetsDetail = *InBaseVersion.AssetsDependenciesMap.Find(BaseVersionAssetModule); const FAssetDependenciesDetail& NewVersionModuleAssetsDetail = *InNewVersion.AssetsDependenciesMap.Find(BaseVersionAssetModule); if (InNewVersion.AssetsDependenciesMap.Contains(BaseVersionAssetModule)) { TArray<FString> BeseVersionCurrentModuleAssetListKeys; BaseVersionModuleAssetsDetail.AssetDependencyDetails.GetKeys(BeseVersionCurrentModuleAssetListKeys); for (const auto& AssetItem : BeseVersionCurrentModuleAssetListKeys) { const FAssetDetail* BaseVersionAssetDetail = BaseVersionModuleAssetsDetail.AssetDependencyDetails.Find(AssetItem); const FAssetDetail* NewVersionAssetDetail = NewVersionModuleAssetsDetail.AssetDependencyDetails.Find(AssetItem); if (!NewVersionAssetDetail) { if (!OutDeleteAsset.AssetsDependenciesMap.Contains(BaseVersionAssetModule)) { OutDeleteAsset.AssetsDependenciesMap.Add(BaseVersionAssetModule, FAssetDependenciesDetail{ BaseVersionAssetModule,TMap<FString,FAssetDetail>{} }); } OutDeleteAsset.AssetsDependenciesMap.Find(BaseVersionAssetModule)->AssetDependencyDetails.Add(AssetItem, *BaseVersionAssetDetail); continue; } if (!(*NewVersionAssetDetail == *BaseVersionAssetDetail)) { UE_LOG(LogHotPatcher,Display,TEXT("Modify Asset: %s"),*AssetItem); if (!OutModifyAsset.AssetsDependenciesMap.Contains(BaseVersionAssetModule)) { OutModifyAsset.AssetsDependenciesMap.Add(BaseVersionAssetModule, FAssetDependenciesDetail{ BaseVersionAssetModule,TMap<FString,FAssetDetail>{} }); } OutModifyAsset.AssetsDependenciesMap.Find(BaseVersionAssetModule)->AssetDependencyDetails.Add(AssetItem, *NewVersionAssetDetail); } } } } } return true; } bool UFlibPatchParserHelper::DiffVersionAllPlatformExFiles( const FHotPatcherVersion& InBaseVersion,const FHotPatcherVersion& InNewVersion, TMap<ETargetPlatform, FPatchVersionExternDiff>& OutDiff) { OutDiff.Empty(); auto ParserDiffPlatformExFileLambda = [](const FPlatformExternFiles& InBase,const FPlatformExternFiles& InNew,ETargetPlatform Platform)->FPatchVersionExternDiff { FPatchVersionExternDiff result; result.Platform = Platform; auto ParserAddFiles = [](const TArray<FExternFileInfo>& InBase,const TArray<FExternFileInfo>& InNew,TArray<FExternFileInfo>& Out) { for (const auto& NewVersionFile : InNew) { if (!InBase.Contains(NewVersionFile)) { Out.AddUnique(NewVersionFile); } } }; // Parser Add Files ParserAddFiles(InBase.ExternFiles, InNew.ExternFiles, result.AddExternalFiles); // Parser delete Files ParserAddFiles(InNew.ExternFiles, InBase.ExternFiles, result.DeleteExternalFiles); auto ParserModifyFiles = [](const FPlatformExternFiles& InBase,const FPlatformExternFiles& InNew,TArray<FExternFileInfo>& Out) { for (const auto& NewVersionFile : InNew.ExternFiles) { // UE_LOG(LogHotPatcher, Log, TEXT("check file %s."), *NewVersionFile); if (InBase.ExternFiles.Contains(NewVersionFile)) { uint32 BaseFileIndex = InBase.ExternFiles.Find(NewVersionFile); bool bIsSame = (NewVersionFile.FileHash == InBase.ExternFiles[BaseFileIndex].FileHash); if (!bIsSame) { // UE_LOG(LogHotPatcher, Log, TEXT("%s is not same."), *NewVersionFile.MountPath); Out.Add(NewVersionFile); }else { // UE_LOG(LogHotPatcher, Log, TEXT("%s is same."), *NewVersionFile.MountPath); } } else { // UE_LOG(LogHotPatcher, Log, TEXT("base version not contains %s."), *NewVersionFile.MountPath); } } }; // Parser modify Files ParserModifyFiles(InBase,InNew,result.ModifyExternalFiles); return result; }; TArray<ETargetPlatform> NewPlatformKeys; TArray<ETargetPlatform> BasePlatformKeys; InNewVersion.PlatformAssets.GetKeys(NewPlatformKeys); InBaseVersion.PlatformAssets.GetKeys(BasePlatformKeys); // ADD for(const auto& Platform:NewPlatformKeys) { if(InBaseVersion.PlatformAssets.Contains(Platform)) { OutDiff.Add(Platform,ParserDiffPlatformExFileLambda( UFlibPatchParserHelper::GetAllExFilesByPlatform(InBaseVersion.PlatformAssets[Platform],false), UFlibPatchParserHelper::GetAllExFilesByPlatform(InNewVersion.PlatformAssets[Platform]), Platform )); } else { FPlatformExternFiles EmptyBase; EmptyBase.Platform = Platform; OutDiff.Add(Platform,ParserDiffPlatformExFileLambda( EmptyBase, UFlibPatchParserHelper::GetAllExFilesByPlatform(InNewVersion.PlatformAssets[Platform],true), Platform )); } } // Delete for(const auto& Platform:BasePlatformKeys) { if(!InNewVersion.PlatformAssets.Contains(Platform)) { FPlatformExternFiles EmptyNew; EmptyNew.Platform = Platform; OutDiff.Add(Platform,ParserDiffPlatformExFileLambda( UFlibPatchParserHelper::GetAllExFilesByPlatform(InBaseVersion.PlatformAssets[Platform]), EmptyNew, Platform )); } } return true; } FPlatformExternFiles UFlibPatchParserHelper::GetAllExFilesByPlatform( const FPlatformExternAssets& InPlatformConf,bool InGeneratedHash) { FPlatformExternFiles result; result.ExternFiles = UFlibPatchParserHelper::ParserExDirectoryAsExFiles(InPlatformConf.AddExternDirectoryToPak); for (auto& ExFile : InPlatformConf.AddExternFileToPak) { // ignore FPaths::FileExists(ExFile.FilePath.FilePath) if (!ExFile.FilePath.FilePath.IsEmpty() && !result.ExternFiles.Contains(ExFile)) { FExternFileInfo CurrentFile = ExFile; CurrentFile.FilePath.FilePath = UFlibPatchParserHelper::ReplaceMarkPath(ExFile.FilePath.FilePath); result.ExternFiles.Add(CurrentFile); } } if (InGeneratedHash) { for (auto& ExFile : result.ExternFiles) { ExFile.GenerateFileHash(); } } return result; } bool UFlibPatchParserHelper::GetPakFileInfo(const FString& InFile, FPakFileInfo& OutFileInfo) { bool bRunStatus = false; if (FPaths::FileExists(InFile)) { FString PathPart; FString FileNamePart; FString ExtensionPart; FPaths::Split(InFile, PathPart, FileNamePart, ExtensionPart); FMD5Hash CurrentPakHash = FMD5Hash::HashFile(*InFile); OutFileInfo.FileName = FString::Printf(TEXT("%s.%s"),*FileNamePart,*ExtensionPart); OutFileInfo.Hash = LexToString(CurrentPakHash); OutFileInfo.FileSize = IFileManager::Get().FileSize(*InFile); bRunStatus = true; } return bRunStatus; } TArray<FString> UFlibPatchParserHelper::GetCookedGlobalShaderCacheFiles(const FString& InProjectDir, const FString& InPlatformName) { TArray<FString> Resault; // if (UFlibAssetManageHelper::IsValidPlatform(InPlatformName)) { FString CookedEngineFolder = FPaths::Combine(InProjectDir,TEXT("Saved/Cooked"),InPlatformName,TEXT("Engine")); if (FPaths::DirectoryExists(CookedEngineFolder)) { TArray<FString> FoundGlobalShaderCacheFiles; IFileManager::Get().FindFiles(FoundGlobalShaderCacheFiles, *CookedEngineFolder, TEXT("bin")); for (const auto& GlobalShaderCache : FoundGlobalShaderCacheFiles) { Resault.AddUnique(FPaths::Combine(CookedEngineFolder, GlobalShaderCache)); } } } return Resault; } bool UFlibPatchParserHelper::GetCookedAssetRegistryFiles(const FString& InProjectAbsDir,const FString& InProjectName, const FString& InPlatformName, FString& OutFiles) { bool bRunStatus = false; // if (UFlibAssetManageHelper::IsValidPlatform(InPlatformName)) { FString CookedPAssetRegistryFile = FPaths::Combine(InProjectAbsDir, TEXT("Saved/Cooked"), InPlatformName, InProjectName,TEXT("AssetRegistry.bin")); if (FPaths::FileExists(CookedPAssetRegistryFile)) { bRunStatus = true; OutFiles = CookedPAssetRegistryFile; } } return bRunStatus; } bool UFlibPatchParserHelper::GetCookedShaderBytecodeFiles(const FString& InProjectAbsDir, const FString& InProjectName, const FString& InPlatformName, bool InGalobalBytecode, bool InProjectBytecode, TArray<FString>& OutFiles) { bool bRunStatus = false; OutFiles.Reset(); // if (UFlibAssetManageHelper::IsValidPlatform(InPlatformName)) { FString CookedContentDir = FPaths::Combine(InProjectAbsDir, TEXT("Saved/Cooked"), InPlatformName, InProjectName, TEXT("Content")); if (FPaths::DirectoryExists(CookedContentDir)) { TArray<FString> ShaderbytecodeFiles; IFileManager::Get().FindFiles(ShaderbytecodeFiles, *CookedContentDir, TEXT("ushaderbytecode")); for (const auto& ShaderByteCodeFile : ShaderbytecodeFiles) { if (InGalobalBytecode && ShaderByteCodeFile.Contains(TEXT("Global"))) { OutFiles.AddUnique(FPaths::Combine(CookedContentDir, ShaderByteCodeFile)); } if (InProjectBytecode && ShaderByteCodeFile.Contains(InProjectName)) { OutFiles.AddUnique(FPaths::Combine(CookedContentDir, ShaderByteCodeFile)); } } bRunStatus = !!ShaderbytecodeFiles.Num(); } } return bRunStatus; } TArray<FString> UFlibPatchParserHelper::GetProjectIniFiles(const FString& InProjectDir, const FString& InPlatformName) { FString ConfigFolder = FPaths::Combine(InProjectDir, TEXT("Config")); return UFlibPatchParserHelper::GetIniConfigs(ConfigFolder,InPlatformName); } bool UFlibPatchParserHelper::ConvIniFilesToPakCommands( const FString& InEngineAbsDir, const FString& InProjectAbsDir, const FString& InProjectName, // const TArray<FString>& InPakOptions, const TArray<FString>& InIniFiles, TArray<FString>& OutCommands, TFunction<void(const FPakCommand&)> InReceiveCommand ) { OutCommands.Reset(); bool bRunStatus = false; if (!FPaths::DirectoryExists(InProjectAbsDir) || !FPaths::DirectoryExists(InEngineAbsDir)) return false; FString UProjectFile = FPaths::Combine(InProjectAbsDir, InProjectName + TEXT(".uproject")); if (!FPaths::FileExists(UProjectFile)) return false; for (const auto& IniFile : InIniFiles) { bool bIsInProjectIni = false; if (IniFile.Contains(InProjectAbsDir)) { bIsInProjectIni = true; } { FString IniAbsDir; FString IniFileName; FString IniExtention; FPaths::Split(IniFile, IniAbsDir, IniFileName, IniExtention); FString RelativePath; if (bIsInProjectIni) { RelativePath = FString::Printf( TEXT("../../../%s/"), *InProjectName ); FString RelativeToProjectDir = UKismetStringLibrary::GetSubstring(IniAbsDir, InProjectAbsDir.Len(), IniAbsDir.Len() - InProjectAbsDir.Len()); RelativePath = FPaths::Combine(RelativePath, RelativeToProjectDir); } else { RelativePath = FString::Printf( TEXT("../../../Engine/") ); FString RelativeToEngineDir = UKismetStringLibrary::GetSubstring(IniAbsDir, InEngineAbsDir.Len(), IniAbsDir.Len() - InEngineAbsDir.Len()); RelativePath = FPaths::Combine(RelativePath, RelativeToEngineDir); } FString IniFileNameWithExten = FString::Printf(TEXT("%s.%s"),*IniFileName,*IniExtention); FString CookedIniRelativePath = FPaths::Combine(RelativePath, IniFileNameWithExten); FString CookCommand = FString::Printf( TEXT("\"%s\" \"%s\""), *IniFile, *CookedIniRelativePath ); FPakCommand CurrentPakCommand; CurrentPakCommand.PakCommands = TArray<FString>{ CookCommand }; CurrentPakCommand.MountPath = CookedIniRelativePath; CurrentPakCommand.AssetPackage = UFlibPatchParserHelper::MountPathToRelativePath(CurrentPakCommand.MountPath); InReceiveCommand(CurrentPakCommand); OutCommands.AddUnique(CookCommand); bRunStatus = true; } } return bRunStatus; } bool UFlibPatchParserHelper::ConvNotAssetFileToPakCommand( const FString& InProjectDir, const FString& InPlatformName, // const TArray<FString>& InPakOptions, const FString& InCookedFile, FString& OutCommand, TFunction<void(const FPakCommand&)> InReceiveCommand ) { bool bRunStatus = false; if (FPaths::FileExists(InCookedFile)) { FString CookPlatformAbsPath = FPaths::Combine(InProjectDir, TEXT("Saved/Cooked"), InPlatformName); FString RelativePath = UKismetStringLibrary::GetSubstring(InCookedFile, CookPlatformAbsPath.Len() + 1, InCookedFile.Len() - CookPlatformAbsPath.Len()); FString AssetFileRelativeCookPath = FString::Printf( TEXT("../../../%s"), *RelativePath ); OutCommand = FString::Printf( TEXT("\"%s\" \"%s\""), *InCookedFile, *AssetFileRelativeCookPath ); FPakCommand CurrentPakCommand; CurrentPakCommand.PakCommands = TArray<FString>{ OutCommand }; CurrentPakCommand.MountPath = AssetFileRelativeCookPath; CurrentPakCommand.AssetPackage = UFlibPatchParserHelper::MountPathToRelativePath(CurrentPakCommand.MountPath); InReceiveCommand(CurrentPakCommand); bRunStatus = true; } return bRunStatus; } bool UFlibPatchParserHelper::ConvNotAssetFileToExFile(const FString& InProjectDir, const FString& InPlatformName, const FString& InCookedFile, FExternFileInfo& OutExFile) { bool bRunStatus = false; if (FPaths::FileExists(InCookedFile)) { FString CookPlatformAbsPath = FPaths::Combine(InProjectDir, TEXT("Saved/Cooked"), InPlatformName); FString RelativePath = UKismetStringLibrary::GetSubstring(InCookedFile, CookPlatformAbsPath.Len() + 1, InCookedFile.Len() - CookPlatformAbsPath.Len()); FString AssetFileRelativeCookPath = FString::Printf( TEXT("../../../%s"), *RelativePath ); OutExFile.FilePath.FilePath = InCookedFile; OutExFile.MountPath = AssetFileRelativeCookPath; OutExFile.GetFileHash(); bRunStatus = true; } return bRunStatus; } FString UFlibPatchParserHelper::HashStringWithSHA1(const FString &InString) { FSHAHash StringHash; FSHA1::HashBuffer(TCHAR_TO_ANSI(*InString), InString.Len(), StringHash.Hash); return StringHash.ToString(); } TArray<FString> UFlibPatchParserHelper::GetIniConfigs(const FString& InSearchDir, const FString& InPlatformName) { TArray<FString> Result; const FString SearchConfigAbsDir = FPaths::ConvertRelativePathToFull(InSearchDir); if (FPaths::DirectoryExists(SearchConfigAbsDir)) { FFileArrayDirectoryVisitor Visitor; IFileManager::Get().IterateDirectory(*SearchConfigAbsDir, Visitor); for (const auto& IniFile : Visitor.Files) { if (!FPaths::GetCleanFilename(IniFile).Contains(TEXT("Editor"))) { Result.Add(IniFile); } } int32 PlatformNameBeginIndex = SearchConfigAbsDir.Len() + 1; for (const auto& PlatformIniDirectory : Visitor.Directories) { FString DirectoryName = UKismetStringLibrary::GetSubstring(PlatformIniDirectory, PlatformNameBeginIndex, PlatformIniDirectory.Len() - PlatformNameBeginIndex); if (InPlatformName.Contains(DirectoryName)) { FFileArrayDirectoryVisitor PlatformVisitor; IFileManager::Get().IterateDirectory(*PlatformIniDirectory, PlatformVisitor); for (const auto& PlatformIni : PlatformVisitor.Files) { Result.Add(PlatformIni); } } } } return Result; } TArray<FString> UFlibPatchParserHelper::GetEngineConfigs(const FString& InPlatformName) { return UFlibPatchParserHelper::GetIniConfigs(FPaths::EngineConfigDir() , InPlatformName); } TArray<FString> UFlibPatchParserHelper::GetEnabledPluginConfigs(const FString& InPlatformName) { TArray<FString> result; TArray<TSharedRef<IPlugin>> AllEnablePlugins = IPluginManager::Get().GetEnabledPlugins(); for (const auto& Plugin : AllEnablePlugins) { FString PluginAbsPath; if (UFlibAssetManageHelper::GetPluginModuleAbsDir(Plugin->GetName(), PluginAbsPath)) { FString PluginIniPath = FPaths::Combine(PluginAbsPath, TEXT("Config")); result.Append(UFlibPatchParserHelper::GetIniConfigs(PluginIniPath, InPlatformName)); } } return result; } TArray<FExternFileInfo> UFlibPatchParserHelper::ParserExDirectoryAsExFiles(const TArray<FExternDirectoryInfo>& InExternDirectorys) { TArray<FExternFileInfo> result; if (!InExternDirectorys.Num()) return result; for (const auto& DirectoryItem : InExternDirectorys) { if(DirectoryItem.DirectoryPath.Path.IsEmpty()) continue; FString DirAbsPath = UFlibPatchParserHelper::ReplaceMarkPath(DirectoryItem.DirectoryPath.Path); //FPaths::ConvertRelativePathToFull(DirectoryItem.DirectoryPath.Path); FPaths::MakeStandardFilename(DirAbsPath); if (!DirAbsPath.IsEmpty() && FPaths::DirectoryExists(DirAbsPath)) { TArray<FString> DirectoryAllFiles; if (UFlibAssetManageHelper::FindFilesRecursive(DirAbsPath, DirectoryAllFiles, true)) { int32 ParentDirectoryIndex = DirAbsPath.Len(); for (const auto& File : DirectoryAllFiles) { FString RelativeParentPath = UKismetStringLibrary::GetSubstring(File, ParentDirectoryIndex, File.Len() - ParentDirectoryIndex); FString RelativeMountPointPath = FPaths::Combine(DirectoryItem.MountPoint, RelativeParentPath); FPaths::MakeStandardFilename(RelativeMountPointPath); FExternFileInfo CurrentFile; CurrentFile.FilePath.FilePath = File; CurrentFile.MountPath = RelativeMountPointPath; if (!result.Contains(CurrentFile)) result.Add(CurrentFile); } } } } return result; } TArray<FAssetDetail> UFlibPatchParserHelper::ParserExFilesInfoAsAssetDetailInfo(const TArray<FExternFileInfo>& InExFiles) { TArray<FAssetDetail> result; for (auto& File : InExFiles) { FAssetDetail CurrentFile; CurrentFile.AssetType = TEXT("ExternalFile"); CurrentFile.PackagePath = FName(*File.MountPath); //CurrentFile.mGuid = File.GetFileHash(); result.Add(CurrentFile); } return result; } TArray<FString> UFlibPatchParserHelper::GetIniFilesByPakInternalInfo(const FPakInternalInfo& InPakInternalInfo, const FString& PlatformName) { TArray<FString> Inis; if (InPakInternalInfo.bIncludeEngineIni) { Inis.Append(UFlibPatchParserHelper::GetEngineConfigs(PlatformName)); } if (InPakInternalInfo.bIncludePluginIni) { Inis.Append(UFlibPatchParserHelper::GetEnabledPluginConfigs(PlatformName)); } if (InPakInternalInfo.bIncludeProjectIni) { Inis.Append(UFlibPatchParserHelper::GetProjectIniFiles(FPaths::ProjectDir(), PlatformName)); } return Inis; } TArray<FString> UFlibPatchParserHelper::GetCookedFilesByPakInternalInfo(const FPakInternalInfo& InPakInternalInfo, const FString& PlatformName) { TArray<FString> SearchAssetList; FString ProjectAbsDir = FPaths::ConvertRelativePathToFull(FPaths::ProjectDir()); FString ProjectName = UFlibPatchParserHelper::GetProjectName(); if (InPakInternalInfo.bIncludeAssetRegistry) { FString AssetRegistryCookCommand; if (UFlibPatchParserHelper::GetCookedAssetRegistryFiles(ProjectAbsDir, UFlibPatchParserHelper::GetProjectName(), PlatformName, AssetRegistryCookCommand)) { SearchAssetList.AddUnique(AssetRegistryCookCommand); } } if (InPakInternalInfo.bIncludeGlobalShaderCache) { TArray<FString> GlobalShaderCacheList = UFlibPatchParserHelper::GetCookedGlobalShaderCacheFiles(ProjectAbsDir, PlatformName); if (!!GlobalShaderCacheList.Num()) { SearchAssetList.Append(GlobalShaderCacheList); } } if (InPakInternalInfo.bIncludeShaderBytecode) { TArray<FString> ShaderByteCodeFiles; if (UFlibPatchParserHelper::GetCookedShaderBytecodeFiles(ProjectAbsDir, ProjectName, PlatformName, true, true, ShaderByteCodeFiles) && !!ShaderByteCodeFiles.Num() ) { SearchAssetList.Append(ShaderByteCodeFiles); } } return SearchAssetList; } TArray<FExternFileInfo> UFlibPatchParserHelper::GetInternalFilesAsExFiles(const FPakInternalInfo& InPakInternalInfo, const FString& InPlatformName) { TArray<FExternFileInfo> resultFiles; TArray<FString> AllNeedPakInternalCookedFiles; FString ProjectAbsDir = FPaths::ConvertRelativePathToFull(FPaths::ProjectDir()); AllNeedPakInternalCookedFiles.Append(UFlibPatchParserHelper::GetCookedFilesByPakInternalInfo(InPakInternalInfo, InPlatformName)); for (const auto& File : AllNeedPakInternalCookedFiles) { FExternFileInfo CurrentFile; UFlibPatchParserHelper::ConvNotAssetFileToExFile(ProjectAbsDir,InPlatformName, File, CurrentFile); resultFiles.Add(CurrentFile); } return resultFiles; } TArray<FString> UFlibPatchParserHelper::GetPakCommandsFromInternalInfo( const FPakInternalInfo& InPakInternalInfo, const FString& PlatformName, // const TArray<FString>& InPakOptions, TFunction<void(const FPakCommand&)> InReceiveCommand ) { TArray<FString> OutPakCommands; TArray<FString> AllNeedPakInternalCookedFiles; FString ProjectAbsDir = FPaths::ConvertRelativePathToFull(FPaths::ProjectDir()); AllNeedPakInternalCookedFiles.Append(UFlibPatchParserHelper::GetCookedFilesByPakInternalInfo(InPakInternalInfo, PlatformName)); // combine as cook commands for (const auto& AssetFile : AllNeedPakInternalCookedFiles) { FString CurrentCommand; if (UFlibPatchParserHelper::ConvNotAssetFileToPakCommand(ProjectAbsDir, PlatformName ,/*InPakOptions,*/ AssetFile, CurrentCommand, InReceiveCommand)) { OutPakCommands.AddUnique(CurrentCommand); } } FString EngineAbsDir = FPaths::ConvertRelativePathToFull(FPaths::EngineDir()); auto CombineInPakCommands = [&OutPakCommands, &ProjectAbsDir, &EngineAbsDir, &PlatformName, /*&InPakOptions,*/&InReceiveCommand](const TArray<FString>& IniFiles) { TArray<FString> result; TArray<FString> IniPakCommmands; UFlibPatchParserHelper::ConvIniFilesToPakCommands( EngineAbsDir, ProjectAbsDir, UFlibPatchParserHelper::GetProjectName(), // InPakOptions, IniFiles, IniPakCommmands, InReceiveCommand ); if (!!IniPakCommmands.Num()) { OutPakCommands.Append(IniPakCommmands); } }; TArray<FString> AllNeedPakIniFiles = UFlibPatchParserHelper::GetIniFilesByPakInternalInfo(InPakInternalInfo, PlatformName); CombineInPakCommands(AllNeedPakIniFiles); return OutPakCommands; } FChunkInfo UFlibPatchParserHelper::CombineChunkInfo(const FChunkInfo& R, const FChunkInfo& L) { FChunkInfo result = R; result.ChunkName = FString::Printf(TEXT("%s_%s"), *R.ChunkName, *L.ChunkName); result.AssetIncludeFilters.Append(L.AssetIncludeFilters); result.AssetIgnoreFilters.Append(L.AssetIgnoreFilters); result.bAnalysisFilterDependencies = L.bAnalysisFilterDependencies || R.bAnalysisFilterDependencies; result.IncludeSpecifyAssets.Append(L.IncludeSpecifyAssets); // result.AddExternDirectoryToPak.Append(L.AddExternDirectoryToPak); // result.AddExternFileToPak.Append(L.AddExternFileToPak); for(const auto& LChunkPlatform:L.AddExternAssetsToPlatform) { int32 FoundIndex = result.AddExternAssetsToPlatform.Find(LChunkPlatform); if(FoundIndex!=INDEX_NONE) { result.AddExternAssetsToPlatform[FoundIndex].AddExternDirectoryToPak.Append(LChunkPlatform.AddExternDirectoryToPak); result.AddExternAssetsToPlatform[FoundIndex].AddExternFileToPak.Append(LChunkPlatform.AddExternFileToPak); } else { result.AddExternAssetsToPlatform.Add(LChunkPlatform); } } #define COMBINE_INTERNAL_FILES(InResult,Left,Right,PropertyName)\ InResult.InternalFiles.PropertyName = Left.InternalFiles.PropertyName || Right.InternalFiles.PropertyName; COMBINE_INTERNAL_FILES(result, L, R, bIncludeAssetRegistry); COMBINE_INTERNAL_FILES(result, L, R, bIncludeGlobalShaderCache); COMBINE_INTERNAL_FILES(result, L, R, bIncludeShaderBytecode); COMBINE_INTERNAL_FILES(result, L, R, bIncludeEngineIni); COMBINE_INTERNAL_FILES(result, L, R, bIncludePluginIni); COMBINE_INTERNAL_FILES(result, L, R, bIncludeProjectIni); return result; } FChunkInfo UFlibPatchParserHelper::CombineChunkInfos(const TArray<FChunkInfo>& Chunks) { FChunkInfo result; for (const auto& Chunk : Chunks) { result = UFlibPatchParserHelper::CombineChunkInfo(result, Chunk); } return result; } TArray<FString> UFlibPatchParserHelper::GetDirectoryPaths(const TArray<FDirectoryPath>& InDirectoryPath) { TArray<FString> Result; for (const auto& Filter : InDirectoryPath) { if (!Filter.Path.IsEmpty()) { FString Path = Filter.Path; if(Path.StartsWith(TEXT("/All/"))) { Path.RemoveFromStart(TEXT("/All")); } Result.AddUnique(Path); } } return Result; } TMap<ETargetPlatform,FPlatformExternFiles> UFlibPatchParserHelper::GetAllPlatformExternFilesFromChunk(const FChunkInfo& InChunk, bool bCalcHash) { TMap<ETargetPlatform,FPlatformExternFiles> result; auto ParserAllFileAndDirs = [](const FPlatformExternAssets& InPlatformInfo,bool bCalcHash=true)->FPlatformExternFiles { FPlatformExternFiles result; result.Platform = InPlatformInfo.TargetPlatform; result.ExternFiles = InPlatformInfo.AddExternFileToPak; for (auto& ExFile : InPlatformInfo.AddExternFileToPak) { if (!result.ExternFiles.Contains(ExFile)) { result.ExternFiles.Add(ExFile); } } if (bCalcHash) { for (auto& ExFile : result.ExternFiles) { ExFile.GenerateFileHash(); } } return result; }; for(const auto& Platform:InChunk.AddExternAssetsToPlatform) { result.Add(Platform.TargetPlatform,ParserAllFileAndDirs(Platform)); } return result; } FChunkAssetDescribe UFlibPatchParserHelper::CollectFChunkAssetsDescribeByChunk( const FPatchVersionDiff& DiffInfo, const FChunkInfo& Chunk, TArray<ETargetPlatform> Platforms ) { FChunkAssetDescribe ChunkAssetDescribe; // Collect Chunk Assets { auto GetAssetFilterPaths = [](const TArray<FDirectoryPath>& InFilters)->TArray<FString> { TArray<FString> Result; for (const auto& Filter : InFilters) { if (!Filter.Path.IsEmpty()) { FString FinalFilter = Filter.Path; if(!Filter.Path.EndsWith(TEXT("/"))) { FinalFilter = FString::Printf(TEXT("%s/"),*FinalFilter); } Result.AddUnique(FinalFilter); } } return Result; }; FAssetDependenciesInfo SpecifyDependAssets; FAssetDependenciesParser Parser; FAssetDependencies Conf; Conf.InIncludeSpecifyAsset = Chunk.IncludeSpecifyAssets; Parser.Parse(Conf); TSet<FName> AssetLongPackageNames = Parser.GetrParseResults(); TArray<FString> AssetFilterPaths = GetAssetFilterPaths(Chunk.AssetIncludeFilters); // AssetFilterPaths.Append(GetSpecifyAssets(Chunk.IncludeSpecifyAssets)); // AssetFilterPaths.Append(SpecifyDependAssets.GetAssetLongPackageNames()); for(FName LongPackageName:AssetLongPackageNames) { if(LongPackageName.IsNone()) continue; AssetFilterPaths.AddUnique(LongPackageName.ToString()); } const FAssetDependenciesInfo& AddAssetsRef = DiffInfo.AssetDiffInfo.AddAssetDependInfo; const FAssetDependenciesInfo& ModifyAssetsRef = DiffInfo.AssetDiffInfo.ModifyAssetDependInfo; auto CollectChunkAssets = [](const FAssetDependenciesInfo& SearchBase, const TArray<FString>& SearchFilters)->FAssetDependenciesInfo { FAssetDependenciesInfo ResultAssetDependInfos; for (const auto& SearchItem : SearchFilters) { if (SearchItem.IsEmpty()) continue; FString SearchModuleName; int32 findedPos = SearchItem.Find(TEXT("/"), ESearchCase::IgnoreCase, ESearchDir::FromStart, 1); if (findedPos != INDEX_NONE) { SearchModuleName = UKismetStringLibrary::GetSubstring(SearchItem, 1, findedPos - 1); } else { SearchModuleName = UKismetStringLibrary::GetSubstring(SearchItem, 1, SearchItem.Len() - 1); } if (!SearchModuleName.IsEmpty() && (SearchBase.AssetsDependenciesMap.Contains(SearchModuleName))) { if (!ResultAssetDependInfos.AssetsDependenciesMap.Contains(SearchModuleName)) ResultAssetDependInfos.AssetsDependenciesMap.Add(SearchModuleName, FAssetDependenciesDetail(SearchModuleName, TMap<FString, FAssetDetail>{})); const FAssetDependenciesDetail& SearchBaseModule = *SearchBase.AssetsDependenciesMap.Find(SearchModuleName); TArray<FString> AllAssetKeys; SearchBaseModule.AssetDependencyDetails.GetKeys(AllAssetKeys); for (const auto& KeyItem : AllAssetKeys) { if (KeyItem.StartsWith(SearchItem)) { FAssetDetail FindedAsset = *SearchBaseModule.AssetDependencyDetails.Find(KeyItem); if (!ResultAssetDependInfos.AssetsDependenciesMap.Find(SearchModuleName)->AssetDependencyDetails.Contains(KeyItem)) { ResultAssetDependInfos.AssetsDependenciesMap.Find(SearchModuleName)->AssetDependencyDetails.Add(KeyItem, FindedAsset); } } } } } return ResultAssetDependInfos; }; ChunkAssetDescribe.AddAssets = CollectChunkAssets(AddAssetsRef, AssetFilterPaths); ChunkAssetDescribe.ModifyAssets = CollectChunkAssets(ModifyAssetsRef, AssetFilterPaths); ChunkAssetDescribe.Assets = UFlibAssetManageHelper::CombineAssetDependencies(ChunkAssetDescribe.AddAssets, ChunkAssetDescribe.ModifyAssets); } auto CoolectPlatformExFiles = [](const FPatchVersionDiff& DiffInfo,const auto& Chunk,ETargetPlatform Platform)->TArray<FExternFileInfo> { // Collect Extern Files TArray<FExternFileInfo> AllFiles; TSet<FString> AllSearchFileFilter; { for(int32 PlatformIndex=0;PlatformIndex<Chunk.AddExternAssetsToPlatform.Num();++PlatformIndex) { if(Chunk.AddExternAssetsToPlatform[PlatformIndex].TargetPlatform == Platform) { for (const auto& Directory : Chunk.AddExternAssetsToPlatform[PlatformIndex].AddExternDirectoryToPak) { if (!Directory.DirectoryPath.Path.IsEmpty()) AllSearchFileFilter.Add(UFlibPatchParserHelper::ReplaceMarkPath(Directory.DirectoryPath.Path)); } for (const auto& File : Chunk.AddExternAssetsToPlatform[PlatformIndex].AddExternFileToPak) { AllSearchFileFilter.Add(UFlibPatchParserHelper::ReplaceMarkPath(File.FilePath.FilePath)); } } } } TArray<FExternFileInfo> AddFilesRef; TArray<FExternFileInfo> ModifyFilesRef; if(DiffInfo.PlatformExternDiffInfo.Contains(Platform)) { AddFilesRef = DiffInfo.PlatformExternDiffInfo.Find(Platform)->AddExternalFiles; ModifyFilesRef = DiffInfo.PlatformExternDiffInfo.Find(Platform)->ModifyExternalFiles; } // TArray<FString> auto CollectExtenFilesLambda = [&AllFiles](const TArray<FExternFileInfo>& SearchBase, const TSet<FString>& Filters,EPatchAssetType Type) { for (const auto& Filter : Filters) { for (const auto& SearchItem : SearchBase) { if (SearchItem.FilePath.FilePath.StartsWith(Filter)) { FExternFileInfo FileItem = SearchItem; FileItem.Type = Type; AllFiles.Add(FileItem); } } } }; CollectExtenFilesLambda(AddFilesRef, AllSearchFileFilter,EPatchAssetType::NEW); CollectExtenFilesLambda(ModifyFilesRef, AllSearchFileFilter,EPatchAssetType::MODIFY); return AllFiles; }; for(auto Platform:Platforms) { FPlatformExternFiles PlatformFiles; PlatformFiles.Platform = Platform; PlatformFiles.ExternFiles = CoolectPlatformExFiles(DiffInfo,Chunk,Platform); ChunkAssetDescribe.AllPlatformExFiles.Add(Platform,PlatformFiles); } ChunkAssetDescribe.InternalFiles = Chunk.InternalFiles; return ChunkAssetDescribe; } TArray<FString> UFlibPatchParserHelper::CollectPakCommandsStringsByChunk( const FPatchVersionDiff& DiffInfo, const FChunkInfo& Chunk, const FString& PlatformName, // const TArray<FString>& PakOptions, const FExportPatchSettings* PatcheSettings ) { TArray<FString> ChunkPakCommands; { TArray<FPakCommand> ChunkPakCommands_r = UFlibPatchParserHelper::CollectPakCommandByChunk(DiffInfo, Chunk, PlatformName,/* PakOptions,*/PatcheSettings); for (const auto& PakCommand : ChunkPakCommands_r) { ChunkPakCommands.Append(PakCommand.GetPakCommands()); } } return ChunkPakCommands; } TArray<FPakCommand> UFlibPatchParserHelper::CollectPakCommandByChunk( const FPatchVersionDiff& DiffInfo, const FChunkInfo& Chunk, const FString& PlatformName, // const TArray<FString>& PakOptions, const FExportPatchSettings* PatcheSettings ) { auto CollectPakCommandsByChunkLambda = [PatcheSettings](const FPatchVersionDiff& DiffInfo, const FChunkInfo& Chunk, const FString& PlatformName/*, const TArray<FString>& PakOptions*/)->TArray<FPakCommand> { ETargetPlatform Platform; THotPatcherTemplateHelper::GetEnumValueByName(PlatformName,Platform); TArray<ETargetPlatform> CollectPlatforms = {ETargetPlatform::AllPlatforms}; CollectPlatforms.AddUnique(Platform); FChunkAssetDescribe ChunkAssetsDescrible = UFlibPatchParserHelper::CollectFChunkAssetsDescribeByChunk(DiffInfo, Chunk ,CollectPlatforms); TArray<FPakCommand> PakCommands; bool bIoStore =false; bool bAllowBulkDataInIoStore = false; #if ENGINE_MAJOR_VERSION > 4 ||ENGINE_MINOR_VERSION > 25 if(PatcheSettings) { bIoStore = PatcheSettings->GetIoStoreSettings().bIoStore; bAllowBulkDataInIoStore = PatcheSettings->GetIoStoreSettings().bAllowBulkDataInIoStore; } #endif auto IsIoStoreAssetsLambda = [bIoStore,bAllowBulkDataInIoStore](const FString& InAbsAssets)->bool { bool Matched = false; if(bIoStore) { TArray<FString> IoStoreExterns = {TEXT(".uasset"),TEXT(".umap")}; if(bAllowBulkDataInIoStore) { IoStoreExterns.Add(TEXT(".ubulk")); IoStoreExterns.Add(TEXT(".uptnl")); } // bool bIoStoreMatched = false; for(const auto& IoStoreExrern:IoStoreExterns) { if(InAbsAssets.EndsWith(IoStoreExrern)) { Matched = true; break; } } } return Matched; }; // Collect Chunk Assets { struct PakCommandReceiver { PakCommandReceiver(TArray<FPakCommand>& InPakCommandsRef,EPatchAssetType InType):PakCommands(InPakCommandsRef),Type(InType){} void operator()(const TArray<FString>& InPakCommand,const TArray<FString>& InIoStoreCommand, const FString& InMountPath,const FString& InLongPackageName) { FPakCommand CurrentPakCommand; CurrentPakCommand.PakCommands = InPakCommand; CurrentPakCommand.IoStoreCommands = InIoStoreCommand; CurrentPakCommand.MountPath = InMountPath; CurrentPakCommand.AssetPackage = InLongPackageName; CurrentPakCommand.Type = Type; PakCommands.Add(CurrentPakCommand); } TArray<FPakCommand>& PakCommands; EPatchAssetType Type; }; // auto ReceivePakCommandAssetLambda = [&PakCommands](const TArray<FString>& InPakCommand,const TArray<FString>& InIoStoreCommand, const FString& InMountPath,const FString& InLongPackageName) // { // // }; PakCommandReceiver AddReceiver(PakCommands,EPatchAssetType::NEW); PakCommandReceiver ModifyReceiver(PakCommands,EPatchAssetType::MODIFY); FString ProjectDir = FPaths::ConvertRelativePathToFull(FPaths::ProjectDir()); TArray<FString> AssetsPakCommands; UFlibAssetManageHelper::MakePakCommandFromAssetDependencies( ProjectDir, PlatformName, ChunkAssetsDescrible.AddAssets, // PakOptions, AssetsPakCommands, AddReceiver, IsIoStoreAssetsLambda ); AssetsPakCommands.Empty(); UFlibAssetManageHelper::MakePakCommandFromAssetDependencies( ProjectDir, PlatformName, ChunkAssetsDescrible.ModifyAssets, // PakOptions, AssetsPakCommands, ModifyReceiver, IsIoStoreAssetsLambda ); } // Collect Extern Files for(const auto& PlatformItenm:CollectPlatforms) { for (const auto& CollectFile : ChunkAssetsDescrible.AllPlatformExFiles[PlatformItenm].ExternFiles) { FPakCommand CurrentPakCommand; CurrentPakCommand.MountPath = CollectFile.MountPath; CurrentPakCommand.AssetPackage = UFlibPatchParserHelper::MountPathToRelativePath(CurrentPakCommand.MountPath); // FString PakOptionsStr; // for (const auto& Param : PakOptions) // { // FString FileExtension = FPaths::GetExtension(CollectFile.FilePath.FilePath,false); // if(IgnoreCompressFormats.Contains(FileExtension) && Param.Equals(TEXT("-compress"),ESearchCase::IgnoreCase)) // { // continue; // } // PakOptionsStr += TEXT(" ") + Param; // } CurrentPakCommand.PakCommands = TArray<FString>{ FString::Printf(TEXT("\"%s\" \"%s\""), *CollectFile.FilePath.FilePath, *CollectFile.MountPath/*,*PakOptionsStr*/) }; CurrentPakCommand.Type = CollectFile.Type; PakCommands.Add(CurrentPakCommand); } } // internal files // TArray<FString> NotCompressOptions = PakOptions; // if(NotCompressOptions.Contains(TEXT("-compress"))) // NotCompressOptions.Remove(TEXT("-compress")); auto ReceivePakCommandExFilesLambda = [&PakCommands](const FPakCommand& InCommand){ PakCommands.Emplace(InCommand); }; UFlibPatchParserHelper::GetPakCommandsFromInternalInfo(ChunkAssetsDescrible.InternalFiles, PlatformName,/* NotCompressOptions,*/ ReceivePakCommandExFilesLambda); return PakCommands; }; return CollectPakCommandsByChunkLambda(DiffInfo, Chunk, PlatformName/*, PakOptions*/); } FHotPatcherVersion UFlibPatchParserHelper::ExportReleaseVersionInfo( const FString& InVersionId, const FString& InBaseVersion, const FString& InDate, const TArray<FString>& InIncludeFilter, const TArray<FString>& InIgnoreFilter, const TArray<FString>& ForceSkipContents, const TArray<UClass*>& ForceSkipClasses, const TArray<EAssetRegistryDependencyTypeEx>& AssetRegistryDependencyTypes, const TArray<FPatcherSpecifyAsset>& InIncludeSpecifyAsset, const TArray<FPlatformExternAssets>& AddToPlatformExFiles, bool InIncludeHasRefAssetsOnly, bool bInAnalysisFilterDependencies ) { SCOPED_NAMED_EVENT_TEXT("ExportReleaseVersionInfo",FColor::Red); FHotPatcherVersion ExportVersion; { ExportVersion.VersionId = InVersionId; ExportVersion.Date = InDate; ExportVersion.BaseVersionId = InBaseVersion; } // add Include Filter { TArray<FString> AllIncludeFilter; for (const auto& Filter : InIncludeFilter) { AllIncludeFilter.AddUnique(Filter); ExportVersion.IncludeFilter.AddUnique(Filter); } } // add Ignore Filter { TArray<FString> AllIgnoreFilter; for (const auto& Filter : InIgnoreFilter) { AllIgnoreFilter.AddUnique(Filter); ExportVersion.IgnoreFilter.AddUnique(Filter); } } ExportVersion.bIncludeHasRefAssetsOnly = InIncludeHasRefAssetsOnly; ExportVersion.IncludeSpecifyAssets = InIncludeSpecifyAsset; // for (const auto& File : InAllExternFiles) // { // if (!ExportVersion.ExternalFiles.Contains(File.FilePath.FilePath)) // { // ExportVersion.ExternalFiles.Add(File.MountPath, File); // } // } TSet<FName> IgnoreTypes = { TEXT("EditorUtilityBlueprint") }; for(auto Class:ForceSkipClasses) { IgnoreTypes.Add(*Class->GetName()); } FAssetDependencies AssetConfig; AssetConfig.IncludeFilters = ExportVersion.IncludeFilter; AssetConfig.IgnoreFilters = ExportVersion.IgnoreFilter; AssetConfig.AssetRegistryDependencyTypes = AssetRegistryDependencyTypes; AssetConfig.InIncludeSpecifyAsset = InIncludeSpecifyAsset; AssetConfig.ForceSkipContents = ForceSkipContents; AssetConfig.bRedirector = true; AssetConfig.AnalysicFilterDependencies = bInAnalysisFilterDependencies; AssetConfig.IncludeHasRefAssetsOnly = InIncludeHasRefAssetsOnly; AssetConfig.IgnoreAseetTypes = IgnoreTypes; { SCOPED_NAMED_EVENT_TEXT("parser all uasset dependencies(optimized)",FColor::Red); FAssetDependenciesParser Parser; Parser.Parse(AssetConfig); UE_LOG(LogHotPatcher,Display,TEXT("FAssetDependenciteParser Asset Num (Optimized) %d"),Parser.GetrParseResults().Num()); { SCOPED_NAMED_EVENT_TEXT("combine all assets to FAssetDependenciesInfo",FColor::Red); for(FName LongPackageName:Parser.GetrParseResults()) { if(LongPackageName.IsNone()) continue; FAssetDetail CurrentDetail; if(UFlibAssetManageHelper::GetSpecifyAssetDetail(LongPackageName.ToString(),CurrentDetail)) { ExportVersion.AssetInfo.AddAssetsDetail(CurrentDetail); } } } } // { // SCOPED_NAMED_EVENT_TEXT("parser all uasset dependencies(Old)",FColor::Red); // FOldAssetDependenciesParser Parser; // Parser.Parse(AssetConfig); // // { // SCOPED_NAMED_EVENT_TEXT("calac all uasset num (old)",FColor::Red); // TArray<FAssetDetail> AssetDetails; // UFlibAssetManageHelper::GetAssetDetailsByAssetDependenciesInfo(Parser.GetrParseResults(),AssetDetails); // UE_LOG(LogHotPatcher,Display,TEXT("FAssetDependenciteParser Asset Num (old) %d"),AssetDetails.Num()); // } // // ExportVersion.AssetInfo = Parser.GetrParseResults(); // } { SCOPED_NAMED_EVENT_TEXT("ExportReleaseVersionInfo parser external files",FColor::Red); for(const auto& PlatformExInfo:AddToPlatformExFiles) { FPlatformExternFiles PlatformFileInfo = UFlibPatchParserHelper::GetAllExFilesByPlatform(PlatformExInfo); FPlatformExternAssets PlatformExternAssets; PlatformExternAssets.TargetPlatform = PlatformExInfo.TargetPlatform; PlatformExternAssets.AddExternFileToPak = PlatformFileInfo.ExternFiles; ExportVersion.PlatformAssets.Add(PlatformExInfo.TargetPlatform,PlatformExternAssets); } } return ExportVersion; } FHotPatcherVersion UFlibPatchParserHelper::ExportReleaseVersionInfoByChunk( const FString& InVersionId, const FString& InBaseVersion, const FString& InDate, const FChunkInfo& InChunkInfo, bool InIncludeHasRefAssetsOnly /*= false */, bool bInAnalysisFilterDependencies /* = true*/) { TArray<FString> AllSkipContents;; if(InChunkInfo.bForceSkipContent) { AllSkipContents.Append(UFlibAssetManageHelper::DirectoryPathsToStrings(InChunkInfo.ForceSkipContentRules)); AllSkipContents.Append(UFlibAssetManageHelper::SoftObjectPathsToStrings(InChunkInfo.ForceSkipAssets)); } return UFlibPatchParserHelper::ExportReleaseVersionInfo( InVersionId, InBaseVersion, InDate, UFlibPatchParserHelper::GetDirectoryPaths(InChunkInfo.AssetIncludeFilters), UFlibPatchParserHelper::GetDirectoryPaths(InChunkInfo.AssetIgnoreFilters), AllSkipContents, InChunkInfo.ForceSkipClasses, InChunkInfo.AssetRegistryDependencyTypes, InChunkInfo.IncludeSpecifyAssets, InChunkInfo.AddExternAssetsToPlatform, InIncludeHasRefAssetsOnly, bInAnalysisFilterDependencies ); } TArray<FString> UFlibPatchParserHelper::GetPakCommandStrByCommands(const TArray<FPakCommand>& PakCommands,const TArray<FReplaceText>& InReplaceTexts,bool bIoStore) { TArray<FString> ResultPakCommands; { for (const auto& PakCommand : PakCommands) { const TArray<FString>& PakCommandOriginTexts = bIoStore?PakCommand.GetIoStoreCommands():PakCommand.GetPakCommands(); if (!!InReplaceTexts.Num()) { for (const auto& PakCommandOriginText : PakCommandOriginTexts) { FString PakCommandTargetText = PakCommandOriginText; for (const auto& ReplaceText : InReplaceTexts) { ESearchCase::Type SearchCaseMode = ReplaceText.SearchCase == ESearchCaseMode::CaseSensitive ? ESearchCase::CaseSensitive : ESearchCase::IgnoreCase; PakCommandTargetText = PakCommandTargetText.Replace(*ReplaceText.From, *ReplaceText.To, SearchCaseMode); } ResultPakCommands.Add(PakCommandTargetText); } } else { ResultPakCommands.Append(PakCommandOriginTexts); } } } return ResultPakCommands; } // FHotPatcherAssetDependency UFlibPatchParserHelper::GetAssetRelatedInfo( // const FAssetDetail& InAsset, // const TArray<EAssetRegistryDependencyTypeEx>& AssetRegistryDependencyTypes, // TMap<FString, FAssetDependenciesInfo>& ScanedCaches // ) // { // FHotPatcherAssetDependency Dependency; // Dependency.Asset = InAsset; // FString LongPackageName = UFlibAssetManageHelper::PackagePathToLongPackageName(InAsset.PackagePath.ToString()); // // { // TArray<EAssetRegistryDependencyType::Type> SearchAssetDepTypes; // for (const auto& Type : AssetRegistryDependencyTypes) // { // SearchAssetDepTypes.AddUnique(UFlibAssetManageHelper::ConvAssetRegistryDependencyToInternal(Type)); // } // // UFlibAssetManageHelper::GetAssetDependency(LongPackageName, AssetRegistryDependencyTypes,Dependency.AssetDependency, ScanedCaches,false); // UFlibAssetManageHelper::GetAssetReference(InAsset, SearchAssetDepTypes, Dependency.AssetReference); // // } // // return Dependency; // } // // TArray<FHotPatcherAssetDependency> UFlibPatchParserHelper::GetAssetsRelatedInfo( // const TArray<FAssetDetail>& InAssets, // const TArray<EAssetRegistryDependencyTypeEx>& AssetRegistryDependencyTypes, // TMap<FString, FAssetDependenciesInfo>& ScanedCaches // ) // { // TArray<FHotPatcherAssetDependency> AssetsDependency; // // for (const auto& Asset : InAssets) // { // AssetsDependency.Add(UFlibPatchParserHelper::GetAssetRelatedInfo(Asset, AssetRegistryDependencyTypes,ScanedCaches)); // } // return AssetsDependency; // } // // TArray<FHotPatcherAssetDependency> UFlibPatchParserHelper::GetAssetsRelatedInfoByFAssetDependencies( // const FAssetDependenciesInfo& InAssetsDependencies, // const TArray<EAssetRegistryDependencyTypeEx>& AssetRegistryDependencyTypes, // TMap<FString, FAssetDependenciesInfo>& ScanedCaches // ) // { // const TArray<FAssetDetail>& AssetsDetail = InAssetsDependencies.GetAssetDetails(); // return UFlibPatchParserHelper::GetAssetsRelatedInfo(AssetsDetail, AssetRegistryDependencyTypes,ScanedCaches); // } bool UFlibPatchParserHelper::GetCookProcCommandParams(const FCookerConfig& InConfig, FString& OutParams) { FString FinalParams; FinalParams.Append(FString::Printf(TEXT("\"%s\" "), *InConfig.ProjectPath)); FinalParams.Append(FString::Printf(TEXT("%s "), *InConfig.EngineParams)); auto CombineParamsLambda = [&FinalParams,&InConfig](const FString& InName, const TArray<FString>& InArray) { if(!InArray.Num()) return; FinalParams.Append(InName); for (int32 Index = 0; Index < InArray.Num(); ++Index) { FinalParams.Append(InArray[Index]); if (!(Index == InArray.Num() - 1)) { FinalParams.Append(TEXT("+")); } } FinalParams.Append(TEXT(" ")); }; CombineParamsLambda(TEXT("-targetplatform="), InConfig.CookPlatforms); CombineParamsLambda(TEXT("-Map="), InConfig.CookMaps); for (const auto& CookFilter : InConfig.CookFilter) { FString FilterFullPath; if (UFlibAssetManageHelper::ConvRelativeDirToAbsDir(CookFilter, FilterFullPath)) { if (FPaths::DirectoryExists(FilterFullPath)) { FinalParams.Append(FString::Printf(TEXT("-COOKDIR=\"%s\" "), *FilterFullPath)); } } } for (const auto& Option : InConfig.CookSettings) { FinalParams.Append(TEXT("-") + Option + TEXT(" ")); } FinalParams.Append(InConfig.Options); OutParams = FinalParams; return true; } void UFlibPatchParserHelper::ExcludeContentForVersionDiff(FPatchVersionDiff& VersionDiff,const TArray<FString>& ExcludeRules) { UFlibAssetManageHelper::ExcludeContentForAssetDependenciesDetail(VersionDiff.AssetDiffInfo.AddAssetDependInfo,ExcludeRules); UFlibAssetManageHelper::ExcludeContentForAssetDependenciesDetail(VersionDiff.AssetDiffInfo.ModifyAssetDependInfo,ExcludeRules); UFlibAssetManageHelper::ExcludeContentForAssetDependenciesDetail(VersionDiff.AssetDiffInfo.DeleteAssetDependInfo,ExcludeRules); } FString UFlibPatchParserHelper::MountPathToRelativePath(const FString& InMountPath) { FString Path; FString filename; FString RelativePath; #define RELATIVE_STR_LENGTH 9 if (InMountPath.StartsWith("../../../")) { RelativePath = UKismetStringLibrary::GetSubstring(InMountPath, RELATIVE_STR_LENGTH, InMountPath.Len() - RELATIVE_STR_LENGTH); } FString extersion; FPaths::Split(RelativePath, Path, filename, extersion); return Path/filename; } #define ENGINEDIR_MARK TEXT("[ENGINEDIR]/") #define ENGINE_CONTENT_DIR_MARK TEXT("[ENGINE_CONTENT_DIR]/") #define PROJECTDIR_MARK TEXT("[PROJECTDIR]/") #define PROJECT_CONTENT_DIR_MARK TEXT("[PROJECT_CONTENT_DIR]/") #define PROJECT_SAVED_DIR_MARK TEXT("[PROJECT_SAVED_DIR]/") #define PROJECT_CONFIG_DIR_MARK TEXT("[PROJECT_CONFIG_DIR]/") TMap<FString, FString> UFlibPatchParserHelper::GetReplacePathMarkMap() { static TMap<FString,FString> MarkMap; static bool bInited = false; if(!bInited) { MarkMap.Add(ENGINEDIR_MARK,FPaths::EngineDir()); MarkMap.Add(ENGINE_CONTENT_DIR_MARK,FPaths::EngineContentDir()); MarkMap.Add(PROJECTDIR_MARK,FPaths::ProjectDir()); MarkMap.Add(PROJECT_CONTENT_DIR_MARK,FPaths::ProjectContentDir()); MarkMap.Add(PROJECT_SAVED_DIR_MARK,FPaths::ProjectSavedDir()); MarkMap.Add(PROJECT_CONFIG_DIR_MARK,FPaths::ProjectConfigDir()); bInited = true; } return MarkMap; } FString UFlibPatchParserHelper::ReplaceMark(const FString& Src) { TMap<FString,FString> MarkMap = UFlibPatchParserHelper::GetReplacePathMarkMap(); auto ReplaceStringMark = [&MarkMap](const FString& OriginDir)->FString { TArray<FString> MarkKeys; MarkMap.GetKeys(MarkKeys); FString result = OriginDir; for(const auto& Key:MarkKeys) { if(OriginDir.StartsWith(Key)) { result = OriginDir; result.RemoveFromStart(Key,ESearchCase::IgnoreCase); result = FPaths::Combine(MarkMap[Key],result); break; } } return result; }; return ReplaceStringMark(Src); } FString UFlibPatchParserHelper::ReplaceMarkPath(const FString& Src) { FString result = UFlibPatchParserHelper::ReplaceMark(Src); FPaths::MakeStandardFilename(result); result = FPaths::ConvertRelativePathToFull(result); return result; } void UFlibPatchParserHelper::ReplacePatherSettingProjectDir(TArray<FPlatformExternAssets>& PlatformAssets) { for(auto& ExPlatform:PlatformAssets) { for(auto& ExFile:ExPlatform.AddExternFileToPak) { ExFile.FilePath.FilePath = UFlibPatchParserHelper::ReplaceMarkPath(ExFile.FilePath.FilePath); } for(auto& ExDir:ExPlatform.AddExternDirectoryToPak) { ExDir.DirectoryPath.Path = UFlibPatchParserHelper::ReplaceMarkPath(ExDir.DirectoryPath.Path); } } } TArray<FString> UFlibPatchParserHelper::GetUnCookUassetExtensions() { TArray<FString> UAssetFormats = { TEXT(".uasset"),TEXT(".umap")}; return UAssetFormats; } TArray<FString> UFlibPatchParserHelper::GetCookedUassetExtensions() { TArray<FString> UAssetFormats = { TEXT(".uasset"),TEXT(".ubulk"),TEXT(".uexp"),TEXT(".umap"),TEXT(".ufont") }; return UAssetFormats; } bool UFlibPatchParserHelper::IsCookedUassetExtensions(const FString& InAsset) { return UFlibPatchParserHelper::MatchStrInArray(InAsset,UFlibPatchParserHelper::GetCookedUassetExtensions()); } bool UFlibPatchParserHelper::IsUnCookUassetExtension(const FString& InAsset) { return UFlibPatchParserHelper::MatchStrInArray(InAsset,UFlibPatchParserHelper::GetUnCookUassetExtensions()); } bool UFlibPatchParserHelper::MatchStrInArray(const FString& InStr, const TArray<FString>& InArray) { bool bResult = false; for (const auto& Format:InArray) { if (InStr.Contains(Format)) { bResult = true; break; } } return bResult; } FString UFlibPatchParserHelper::LoadAESKeyStringFromCryptoFile(const FString& InCryptoJson) { FString result; if(FPaths::FileExists(InCryptoJson)) { FString Content; FFileHelper::LoadFileToString(Content,*InCryptoJson); if (!Content.IsEmpty()) { TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(Content); TSharedPtr<FJsonObject> DeserializeJsonObject; if (FJsonSerializer::Deserialize(JsonReader, DeserializeJsonObject)) { const TSharedPtr<FJsonObject>* EncryptionKeyObject; DeserializeJsonObject->TryGetObjectField(TEXT("EncryptionKey"),EncryptionKeyObject); if(EncryptionKeyObject->IsValid()) { FString Key; EncryptionKeyObject->Get()->TryGetStringField(TEXT("Key"),Key); if(!Key.IsEmpty()) { result = Key; } } } } } return result; } FAES::FAESKey UFlibPatchParserHelper::LoadAESKeyFromCryptoFile(const FString& InCryptoJson) { FAES::FAESKey AESKey; FString AESKeyString = UFlibPatchParserHelper::LoadAESKeyStringFromCryptoFile(InCryptoJson); if(!AESKeyString.IsEmpty()) { TArray<uint8> DecodedBuffer; if (!FBase64::Decode(AESKeyString, DecodedBuffer)) { FMemory::Memcpy(AESKey.Key, DecodedBuffer.GetData(), 32); } } return AESKey; } FString UFlibPatchParserHelper::AssetMountPathToAbs(const FString& InAssetMountPath) { FString result; // ../../../Engine/xxx to ENGINE/ FString Dest = InAssetMountPath; while(Dest.StartsWith(TEXT("../"))) { Dest.RemoveFromStart(TEXT("../")); } if(Dest.StartsWith(TEXT("Engine"))) { Dest.RemoveFromStart(TEXT("Engine/")); result = FPaths::Combine(FPaths::EngineDir(),Dest); } if(Dest.StartsWith(FApp::GetProjectName())) { Dest.RemoveFromStart(FString::Printf(TEXT("%s/"),FApp::GetProjectName())); result = FPaths::Combine(FPaths::ProjectDir(),Dest); } FPaths::NormalizeFilename(result); return FPaths::ConvertRelativePathToFull(result); } FString UFlibPatchParserHelper::UAssetMountPathToPackagePath(const FString& InAssetMountPath) { TMap<FString, FString> ReceiveModuleMap; UFlibAssetManageHelper::GetAllEnabledModuleName(ReceiveModuleMap); FString LongPackageName = InAssetMountPath; LongPackageName.RemoveFromStart(TEXT("../../..")); for(const auto& UnCookAssetExtension:UFlibPatchParserHelper::GetUnCookUassetExtensions()) { LongPackageName.RemoveFromEnd(UnCookAssetExtension); } // LongPackageName = LongPackageName.Replace(TEXT("/Content"), TEXT("")); FString ModuleName = LongPackageName; { ModuleName.RemoveAt(0); int32 Index; if (ModuleName.FindChar('/', Index)) { ModuleName = ModuleName.Left(Index); } } if (ModuleName.Equals(FApp::GetProjectName())) { LongPackageName.RemoveFromStart(TEXT("/") + ModuleName); LongPackageName = TEXT("/Game") + LongPackageName; } if (LongPackageName.Contains(TEXT("/Plugins/"))) { TArray<FString> ModuleKeys; ReceiveModuleMap.GetKeys(ModuleKeys); TArray<FString> IgnoreModules = { TEXT("Game"),TEXT("Engine") }; for (const auto& IgnoreModule : IgnoreModules) { ModuleKeys.Remove(IgnoreModule); } for (const auto& Module : ModuleKeys) { FString FindStr = TEXT("/") + Module + TEXT("/"); if (LongPackageName.Contains(FindStr,ESearchCase::IgnoreCase)) { int32 PluginModuleIndex = LongPackageName.Find(FindStr,ESearchCase::IgnoreCase,ESearchDir::FromEnd); LongPackageName = LongPackageName.Right(LongPackageName.Len()- PluginModuleIndex-FindStr.Len()); LongPackageName = TEXT("/") + Module + TEXT("/") + LongPackageName; break; } } } int32 ContentPoint = LongPackageName.Find(TEXT("/Content")); if(ContentPoint != INDEX_NONE) { LongPackageName = FPaths::Combine(LongPackageName.Left(ContentPoint), LongPackageName.Right(LongPackageName.Len() - ContentPoint - 8)); } FString LongPackagePath = UFlibAssetManageHelper::LongPackageNameToPackagePath(LongPackageName); return LongPackagePath; } bool UFlibPatchParserHelper::GetPluginPakPathByName(const FString& PluginName,FString& uPluginAbsPath,FString& uPluginMountPath) { bool bStatus = false; TSharedPtr<IPlugin> FoundPlugin = IPluginManager::Get().FindPlugin(PluginName); FString uPluginFileAbsPath; FString uPluginFileMountPath; if(FoundPlugin.IsValid()) { uPluginFileAbsPath = FPaths::ConvertRelativePathToFull(FPaths::Combine(FoundPlugin->GetBaseDir(),FString::Printf(TEXT("%s.uplugin"),*FoundPlugin->GetName()))); FPaths::NormalizeFilename(uPluginFileAbsPath); uPluginFileMountPath = uPluginFileAbsPath; if(FPaths::FileExists(uPluginFileAbsPath)) { FString EnginePluginPath = FPaths::ConvertRelativePathToFull(FPaths::EnginePluginsDir()); FString ProjectPluginPath = FPaths::ConvertRelativePathToFull(FPaths::ProjectPluginsDir()); if(uPluginFileMountPath.StartsWith(EnginePluginPath)) { uPluginFileMountPath.RemoveFromStart(EnginePluginPath); uPluginFileMountPath = FString::Printf(TEXT("../../../Engine/Plugins/%s"),*uPluginFileMountPath); } if(uPluginFileMountPath.StartsWith(ProjectPluginPath)) { uPluginFileMountPath.RemoveFromStart(ProjectPluginPath); uPluginFileMountPath = FString::Printf(TEXT("../../../%s/Plugins/%s"),FApp::GetProjectName(),*uPluginFileMountPath); } uPluginAbsPath = uPluginFileAbsPath; uPluginMountPath = uPluginFileMountPath; bStatus = true; } } return bStatus; } FString UFlibPatchParserHelper::GetPluginMountPoint(const FString& PluginName) { FString uPluginAbsPath; FString uPluginMountPath; if(UFlibPatchParserHelper::GetPluginPakPathByName(PluginName,uPluginAbsPath,uPluginMountPath)) { uPluginMountPath.RemoveFromEnd(FString::Printf(TEXT("/%s.uplugin"),*PluginName)); } return uPluginMountPath; } FString UFlibPatchParserHelper::ParserMountPointRegular(const FString& Src) { FString result; if(Src.MatchesWildcard(FString::Printf(TEXT("*%s*"),AS_PROJECTDIR_MARK))) { result = Src.Replace(AS_PROJECTDIR_MARK,*FString::Printf(TEXT("../../../%s"),FApp::GetProjectName())); } if(Src.MatchesWildcard(FString::Printf(TEXT("*%s*"),AS_PLUGINDIR_MARK))) { int32 index = Src.Find(AS_PLUGINDIR_MARK); index += strlen(TCHAR_TO_ANSI(AS_PLUGINDIR_MARK)); int32 BeginIndex = index + 1; int32 EndIndex; Src.FindLastChar(']',EndIndex); FString PluginName = UKismetStringLibrary::GetSubstring(Src,BeginIndex,EndIndex-BeginIndex); result = Src.Replace(AS_PLUGINDIR_MARK,TEXT("")); result = result.Replace(*FString::Printf(TEXT("[%s]"),*PluginName),*UFlibPatchParserHelper::GetPluginMountPoint(PluginName)); } return result; } void UFlibPatchParserHelper::ReloadShaderbytecode() { UFlibPakHelper::ReloadShaderbytecode(); } bool UFlibPatchParserHelper::LoadShaderbytecode(const FString& LibraryName, const FString& LibraryDir) { return UFlibPakHelper::LoadShaderbytecode(LibraryName,LibraryDir); } void UFlibPatchParserHelper::CloseShaderbytecode(const FString& LibraryName) { UFlibPakHelper::CloseShaderbytecode(LibraryName); } #define ENCRYPT_KEY_NAME TEXT("EncryptionKey") #define ENCRYPT_PAK_INI_FILES_NAME TEXT("bEncryptPakIniFiles") #define ENCRYPT_PAK_INDEX_NAME TEXT("bEncryptPakIndex") #define ENCRYPT_UASSET_FILES_NAME TEXT("bEncryptUAssetFiles") #define ENCRYPT_ALL_ASSET_FILES_NAME TEXT("bEncryptAllAssetFiles") #define SIGNING_PAK_SIGNING_NAME TEXT("bEnablePakSigning") #define SIGNING_MODULES_NAME TEXT("SigningModulus") #define SIGNING_PUBLIC_EXPONENT_NAME TEXT("SigningPublicExponent") #define SIGNING_PRIVATE_EXPONENT_NAME TEXT("SigningPrivateExponent") FPakEncryptionKeys UFlibPatchParserHelper::GetCryptoByProjectSettings() { FPakEncryptionKeys result; result.EncryptionKey.Name = TEXT("Embedded"); result.EncryptionKey.Guid = FGuid::NewGuid().ToString(); UClass* Class = FindObject<UClass>(ANY_PACKAGE, TEXT("/Script/CryptoKeys.CryptoKeysSettings"), true); if(Class) { FString AESKey; for(TFieldIterator<FProperty> PropertyIter(Class);PropertyIter;++PropertyIter) { FProperty* PropertyIns = *PropertyIter; UE_LOG(LogTemp,Log,TEXT("%s"),*PropertyIns->GetName()); if(PropertyIns->GetName().Equals(ENCRYPT_KEY_NAME)) { result.EncryptionKey.Key = *PropertyIns->ContainerPtrToValuePtr<FString>(Class->GetDefaultObject()); } if(PropertyIns->GetName().Equals(ENCRYPT_PAK_INI_FILES_NAME)) { result.bEnablePakIniEncryption = *PropertyIns->ContainerPtrToValuePtr<bool>(Class->GetDefaultObject()); } if(PropertyIns->GetName().Equals(ENCRYPT_PAK_INDEX_NAME)) { result.bEnablePakIndexEncryption = *PropertyIns->ContainerPtrToValuePtr<bool>(Class->GetDefaultObject()); } if(PropertyIns->GetName().Equals(ENCRYPT_UASSET_FILES_NAME)) { result.bEnablePakUAssetEncryption = *PropertyIns->ContainerPtrToValuePtr<bool>(Class->GetDefaultObject()); } if(PropertyIns->GetName().Equals(ENCRYPT_ALL_ASSET_FILES_NAME)) { result.bEnablePakFullAssetEncryption = *PropertyIns->ContainerPtrToValuePtr<bool>(Class->GetDefaultObject()); } // SIGN if(PropertyIns->GetName().Equals(SIGNING_PAK_SIGNING_NAME)) { result.bEnablePakSigning = *PropertyIns->ContainerPtrToValuePtr<bool>(Class->GetDefaultObject()); } if(PropertyIns->GetName().Equals(SIGNING_PUBLIC_EXPONENT_NAME)) { result.SigningKey.PublicKey.Exponent = *PropertyIns->ContainerPtrToValuePtr<FString>(Class->GetDefaultObject()); } if(PropertyIns->GetName().Equals(SIGNING_MODULES_NAME)) { result.SigningKey.PublicKey.Modulus = *PropertyIns->ContainerPtrToValuePtr<FString>(Class->GetDefaultObject()); result.SigningKey.PrivateKey.Modulus = result.SigningKey.PublicKey.Modulus; } if(PropertyIns->GetName().Equals(SIGNING_PRIVATE_EXPONENT_NAME)) { result.SigningKey.PrivateKey.Exponent = *PropertyIns->ContainerPtrToValuePtr<FString>(Class->GetDefaultObject()); } } } return result; } FEncryptSetting UFlibPatchParserHelper::GetCryptoSettingsByJson(const FString& CryptoJson) { FEncryptSetting result; FArchive* File = IFileManager::Get().CreateFileReader(*CryptoJson); TSharedPtr<FJsonObject> RootObject; TSharedRef<TJsonReader<char>> Reader = TJsonReaderFactory<char>::Create(File); if (FJsonSerializer::Deserialize(Reader, RootObject)) { result.bSign = RootObject->GetBoolField(TEXT("bEnablePakSigning")); result.bEncryptIndex = RootObject->GetBoolField(TEXT("bEnablePakIndexEncryption")); result.bEncryptIniFiles = RootObject->GetBoolField(TEXT("bEnablePakIniEncryption")); result.bEncryptUAssetFiles = RootObject->GetBoolField(TEXT("bEnablePakUAssetEncryption")); result.bEncryptAllAssetFiles = RootObject->GetBoolField(TEXT("bEnablePakFullAssetEncryption")); } return result; } FEncryptSetting UFlibPatchParserHelper::GetCryptoSettingByPakEncryptSettings(const FPakEncryptSettings& Config) { FEncryptSetting EncryptSettings; if(Config.bUseDefaultCryptoIni) { FPakEncryptionKeys ProjectCrypt = UFlibPatchParserHelper::GetCryptoByProjectSettings(); EncryptSettings.bEncryptIniFiles = ProjectCrypt.bEnablePakIniEncryption; EncryptSettings.bEncryptUAssetFiles = ProjectCrypt.bEnablePakUAssetEncryption; EncryptSettings.bEncryptAllAssetFiles = ProjectCrypt.bEnablePakFullAssetEncryption; EncryptSettings.bEncryptIndex = ProjectCrypt.bEnablePakIndexEncryption; EncryptSettings.bSign = ProjectCrypt.bEnablePakSigning; } else { FString CryptoKeyFile = FPaths::ConvertRelativePathToFull(Config.CryptoKeys.FilePath); if(FPaths::FileExists(CryptoKeyFile)) { FEncryptSetting CryptoJsonSettings = UFlibPatchParserHelper::GetCryptoSettingsByJson(CryptoKeyFile); EncryptSettings.bEncryptIniFiles = CryptoJsonSettings.bEncryptIniFiles; EncryptSettings.bEncryptUAssetFiles = CryptoJsonSettings.bEncryptUAssetFiles; EncryptSettings.bEncryptAllAssetFiles = CryptoJsonSettings.bEncryptAllAssetFiles; EncryptSettings.bSign = CryptoJsonSettings.bSign; EncryptSettings.bEncryptIndex = CryptoJsonSettings.bEncryptIndex; } } return EncryptSettings; } bool UFlibPatchParserHelper::SerializePakEncryptionKeyToFile(const FPakEncryptionKeys& PakEncryptionKeys, const FString& ToFile) { FString KeyInfo; THotPatcherTemplateHelper::TSerializeStructAsJsonString(PakEncryptionKeys,KeyInfo); return UFlibAssetManageHelper::SaveStringToFile(ToFile, KeyInfo); } TArray<FDirectoryPath> UFlibPatchParserHelper::GetDefaultForceSkipContentDir() { TArray<FDirectoryPath> result; TArray<FString> DefaultSkipEditorContentRules = {TEXT("/Engine/Editor"),TEXT("/Engine/VREditor")}; for(const auto& Ruls:DefaultSkipEditorContentRules) { FDirectoryPath PathIns; PathIns.Path = Ruls; result.Add(PathIns); } return result; }
35.082541
226
0.749423
roy5931
d5471f18a30f29d8c7084ce6a0cad491124e082c
8,225
inl
C++
unit_tests/api/cl_enqueue_image_tests.inl
FelipeMLopez/compute-runtime
3e3d2d3b3ac9129b1ee9c4251a2586fef0b300b8
[ "MIT" ]
3
2019-09-20T23:26:36.000Z
2019-10-03T17:44:12.000Z
unit_tests/api/cl_enqueue_image_tests.inl
FelipeMLopez/compute-runtime
3e3d2d3b3ac9129b1ee9c4251a2586fef0b300b8
[ "MIT" ]
1
2019-09-17T08:06:24.000Z
2019-09-17T08:06:24.000Z
unit_tests/api/cl_enqueue_image_tests.inl
FelipeMLopez/compute-runtime
3e3d2d3b3ac9129b1ee9c4251a2586fef0b300b8
[ "MIT" ]
3
2019-05-16T07:22:51.000Z
2019-11-11T03:05:32.000Z
/* * Copyright (C) 2018-2019 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "test.h" #include "unit_tests/fixtures/image_fixture.h" #include "unit_tests/mocks/mock_buffer.h" #include "unit_tests/mocks/mock_command_queue.h" #include "unit_tests/mocks/mock_context.h" #include <functional> using namespace NEO; using ImageEnqueueCall = std::function<void(MockCommandQueue *, Image *, size_t *, size_t *, int32_t &)>; struct ValidateRegionAndOriginTests : public ::testing::TestWithParam<ImageEnqueueCall> { void SetUp() override { context.reset(new MockContext()); cmdQ.reset(new MockCommandQueue(context.get(), context->getDevice(0), 0)); } static void readImage(MockCommandQueue *cmdQ, Image *image, size_t *origin, size_t *region, int32_t &retVal) { uint32_t tempPtr; retVal = clEnqueueReadImage(cmdQ, image, CL_TRUE, origin, region, 0, 0, &tempPtr, 0, nullptr, nullptr); } static void writeImage(MockCommandQueue *cmdQ, Image *image, size_t *origin, size_t *region, int32_t &retVal) { uint32_t tempPtr; retVal = clEnqueueWriteImage(cmdQ, image, CL_TRUE, origin, region, 0, 0, &tempPtr, 0, nullptr, nullptr); } static void fillImage(MockCommandQueue *cmdQ, Image *image, size_t *origin, size_t *region, int32_t &retVal) { uint32_t fill_color[4] = {0xaaaaaaaa, 0xbbbbbbbb, 0xcccccccc, 0xdddddddd}; retVal = clEnqueueFillImage(cmdQ, image, fill_color, origin, region, 0, nullptr, nullptr); } static void copyImageWithCorrectSrc(MockCommandQueue *cmdQ, Image *dstImage, size_t *dstOrigin, size_t *region, int32_t &retVal) { std::unique_ptr<Image> srcImage(ImageHelper<Image3dDefaults>::create(&cmdQ->getContext())); size_t srcOrigin[3] = {0, 0, 0}; retVal = clEnqueueCopyImage(cmdQ, srcImage.get(), dstImage, srcOrigin, dstOrigin, region, 0, nullptr, nullptr); } static void copyImageWithCorrectDst(MockCommandQueue *cmdQ, Image *srcImage, size_t *srcOrigin, size_t *region, int32_t &retVal) { std::unique_ptr<Image> dstImage(ImageHelper<Image3dDefaults>::create(&cmdQ->getContext())); size_t dstOrigin[3] = {0, 0, 0}; retVal = clEnqueueCopyImage(cmdQ, srcImage, dstImage.get(), srcOrigin, dstOrigin, region, 0, nullptr, nullptr); } static void copyImageToBuffer(MockCommandQueue *cmdQ, Image *image, size_t *origin, size_t *region, int32_t &retVal) { MockBuffer buffer; retVal = clEnqueueCopyImageToBuffer(cmdQ, image, &buffer, origin, region, 0, 0, nullptr, nullptr); } static void copyBufferToImage(MockCommandQueue *cmdQ, Image *image, size_t *origin, size_t *region, int32_t &retVal) { MockBuffer buffer; retVal = clEnqueueCopyBufferToImage(cmdQ, &buffer, image, 0, origin, region, 0, nullptr, nullptr); } static void mapImage(MockCommandQueue *cmdQ, Image *image, size_t *origin, size_t *region, int32_t &retVal) { clEnqueueMapImage(cmdQ, image, CL_TRUE, CL_MAP_READ, origin, region, nullptr, nullptr, 0, nullptr, nullptr, &retVal); } std::unique_ptr<MockContext> context; std::unique_ptr<MockCommandQueue> cmdQ; cl_int retVal = CL_SUCCESS; }; TEST_P(ValidateRegionAndOriginTests, givenAnyZeroRegionParamWhenEnqueueCalledThenReturnError) { std::unique_ptr<Image> image(ImageHelper<Image3dDefaults>::create(context.get())); EXPECT_NE(nullptr, image.get()); size_t origin[3] = {0, 0, 0}; std::array<size_t, 3> region = {{0, 1, 1}}; GetParam()(cmdQ.get(), image.get(), origin, &region[0], retVal); EXPECT_EQ(CL_INVALID_VALUE, retVal); region = {{1, 0, 1}}; GetParam()(cmdQ.get(), image.get(), origin, &region[0], retVal); EXPECT_EQ(CL_INVALID_VALUE, retVal); region = {{1, 1, 0}}; GetParam()(cmdQ.get(), image.get(), origin, &region[0], retVal); EXPECT_EQ(CL_INVALID_VALUE, retVal); region = {{0, 0, 0}}; GetParam()(cmdQ.get(), image.get(), origin, &region[0], retVal); EXPECT_EQ(CL_INVALID_VALUE, retVal); } TEST_P(ValidateRegionAndOriginTests, givenSecondOriginCoordinateAndNotAllowedImgTypeWhenEnqueueCalledThenReturnError) { size_t region[3] = {1, 1, 1}; size_t origin[3] = {0, 1, 0}; std::unique_ptr<Image> image(ImageHelper<Image1dDefaults>::create(context.get())); GetParam()(cmdQ.get(), image.get(), origin, &region[0], retVal); EXPECT_EQ(CL_INVALID_VALUE, retVal); auto image1dBufferDesc = Image1dDefaults::imageDesc; image1dBufferDesc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; image.reset(ImageHelper<Image1dDefaults>::create(context.get(), &image1dBufferDesc)); GetParam()(cmdQ.get(), image.get(), origin, &region[0], retVal); EXPECT_EQ(CL_INVALID_VALUE, retVal); } TEST_P(ValidateRegionAndOriginTests, givenThirdOriginCoordinateAndNotAllowedImgTypeWhenEnqueueCalledThenReturnError) { size_t region[3] = {1, 1, 1}; size_t origin[3] = {0, 0, 1}; std::unique_ptr<Image> image(ImageHelper<Image1dDefaults>::create(context.get())); GetParam()(cmdQ.get(), image.get(), origin, &region[0], retVal); EXPECT_EQ(CL_INVALID_VALUE, retVal); image.reset(ImageHelper<Image2dDefaults>::create(context.get())); GetParam()(cmdQ.get(), image.get(), origin, &region[0], retVal); EXPECT_EQ(CL_INVALID_VALUE, retVal); image.reset(ImageHelper<Image1dArrayDefaults>::create(context.get())); GetParam()(cmdQ.get(), image.get(), origin, &region[0], retVal); EXPECT_EQ(CL_INVALID_VALUE, retVal); auto image1dBufferDesc = Image1dDefaults::imageDesc; image1dBufferDesc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; image.reset(ImageHelper<Image1dDefaults>::create(context.get(), &image1dBufferDesc)); GetParam()(cmdQ.get(), image.get(), origin, &region[0], retVal); EXPECT_EQ(CL_INVALID_VALUE, retVal); } TEST_P(ValidateRegionAndOriginTests, givenSecondRegionCoordinateAndNotAllowedImgTypeWhenEnqueueCalledThenReturnError) { size_t region[3] = {1, 2, 1}; size_t origin[3] = {0, 0, 0}; std::unique_ptr<Image> image(ImageHelper<Image1dDefaults>::create(context.get())); GetParam()(cmdQ.get(), image.get(), origin, &region[0], retVal); EXPECT_EQ(CL_INVALID_VALUE, retVal); auto image1dBufferDesc = Image1dDefaults::imageDesc; image1dBufferDesc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; image.reset(ImageHelper<Image1dDefaults>::create(context.get(), &image1dBufferDesc)); GetParam()(cmdQ.get(), image.get(), origin, &region[0], retVal); EXPECT_EQ(CL_INVALID_VALUE, retVal); } TEST_P(ValidateRegionAndOriginTests, givenThirdRegionnCoordinateAndNotAllowedImgTypeWhenEnqueueCalledThenReturnError) { size_t region[3] = {1, 1, 2}; size_t origin[3] = {0, 0, 0}; std::unique_ptr<Image> image(ImageHelper<Image1dDefaults>::create(context.get())); GetParam()(cmdQ.get(), image.get(), origin, &region[0], retVal); EXPECT_EQ(CL_INVALID_VALUE, retVal); image.reset(ImageHelper<Image2dDefaults>::create(context.get())); GetParam()(cmdQ.get(), image.get(), origin, &region[0], retVal); EXPECT_EQ(CL_INVALID_VALUE, retVal); image.reset(ImageHelper<Image1dArrayDefaults>::create(context.get())); GetParam()(cmdQ.get(), image.get(), origin, &region[0], retVal); EXPECT_EQ(CL_INVALID_VALUE, retVal); auto image1dBufferDesc = Image1dDefaults::imageDesc; image1dBufferDesc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; image.reset(ImageHelper<Image1dDefaults>::create(context.get(), &image1dBufferDesc)); GetParam()(cmdQ.get(), image.get(), origin, &region[0], retVal); EXPECT_EQ(CL_INVALID_VALUE, retVal); } ImageEnqueueCall enqueueFunctions[8] = { &ValidateRegionAndOriginTests::readImage, &ValidateRegionAndOriginTests::writeImage, &ValidateRegionAndOriginTests::fillImage, &ValidateRegionAndOriginTests::copyImageWithCorrectSrc, &ValidateRegionAndOriginTests::copyImageWithCorrectDst, &ValidateRegionAndOriginTests::copyImageToBuffer, &ValidateRegionAndOriginTests::copyBufferToImage, &ValidateRegionAndOriginTests::mapImage, }; INSTANTIATE_TEST_CASE_P( ValidateRegionAndOriginTests, ValidateRegionAndOriginTests, ::testing::ValuesIn(enqueueFunctions));
44.22043
134
0.717568
FelipeMLopez
d54878115d668fe93b900e80ce96b14dbf318a3d
1,500
hpp
C++
gamedata/AreaSize_Data.hpp
rigertd/LegacyMUD
cf351cca466158f0682f6c877b88d5c2eb59e240
[ "BSD-3-Clause" ]
1
2021-04-24T06:01:57.000Z
2021-04-24T06:01:57.000Z
gamedata/AreaSize_Data.hpp
rigertd/LegacyMUD
cf351cca466158f0682f6c877b88d5c2eb59e240
[ "BSD-3-Clause" ]
null
null
null
gamedata/AreaSize_Data.hpp
rigertd/LegacyMUD
cf351cca466158f0682f6c877b88d5c2eb59e240
[ "BSD-3-Clause" ]
null
null
null
/*! \file AreaSize_Data.hpp \author Keith Adkins \created 3/3/2017 \modified 3/3/2017 \course CS467, Winter 2017 \details Declaration file for the AreaSize_Data class. Functions are provided to convert between string and enum values. This class should not be instantiated. */ #ifndef LEGACYMUD_AREA_SIZE_DATA_HPP #define LEGACYMUD_AREA_SIZE_DATA_HPP #include <string> #include <AreaSize.hpp> namespace legacymud { namespace gamedata { /*! \brief Area Size Data class for legacyMUD. */ class AreaSize_Data { public: /*! \brief AreaSize_Data class default constructor. */ AreaSize_Data() { } /*! \brief AreaSize_Data class destructor. */ ~AreaSize_Data(){ } /*! \brief Converts an AreaSize enum to a string for saving data \param[in] sizeEnum enum value of area size \post Returns a string of area size. */ static std::string enumToString(engine::AreaSize sizeEnum); /*! \brief Converts an area size string to an enum for loading data \param[in] sizeStr area size string \post Returns an AreaSize enum */ static engine::AreaSize stringToEnum(std::string sizeStr); }; }} #endif
25
91
0.551333
rigertd
d5490b226194b0cbf2c20c9bcaa0928e907c96e1
9,078
cpp
C++
src/adera/Machines/RCSController.cpp
TheOpenSpaceProgram/osp-magnum
c34b2e27a5ab5efe1270838991d908ecef4d7612
[ "MIT" ]
70
2020-01-27T22:16:36.000Z
2022-03-31T01:29:22.000Z
src/adera/Machines/RCSController.cpp
TheOpenSpaceProgram/osp-magnum
c34b2e27a5ab5efe1270838991d908ecef4d7612
[ "MIT" ]
107
2020-09-21T04:26:49.000Z
2022-03-26T05:57:15.000Z
src/adera/Machines/RCSController.cpp
TheOpenSpaceProgram/osp-magnum
c34b2e27a5ab5efe1270838991d908ecef4d7612
[ "MIT" ]
12
2020-09-27T20:32:51.000Z
2022-03-23T15:14:36.000Z
/** * Open Space Program * Copyright © 2019-2020 Open Space Program Project * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "RCSController.h" // IWYU pragma: associated #include <osp/Active/basic.h> // for ACompTransform #include <osp/Active/SysWire.h> // for ACompWire, ACtxWireNodes #include <osp/Active/physics.h> #include <osp/Active/SysSignal.h> // for Signal<>::NodeState, SysSignal #include <osp/Active/SysPhysics.h> #include <osp/Active/SysVehicle.h> #include <osp/Active/machines.h> // for ACompMachines #include <osp/Active/activetypes.h> // for ActiveEnt, ActiveReg_t #include <osp/Resource/machines.h> #include <osp/Resource/Resource.h> // for DependRes #include <osp/Resource/blueprints.h> // for BlueprintMachine, BlueprintV... #include <osp/Resource/PrototypePart.h> // for NodeMap_t #include <osp/types.h> // for Vector3, Matrix4 #include <vector> // for std::vector #include <iterator> // for std::begin, std::end #include <algorithm> // for std::clamp, std::sort #include <functional> // for std::negate // IWYU pragma: no_include "adera/wiretypes.h" // IWYU pragma: no_include <cstddef> // IWYU pragma: no_include <stdint.h> // IWYU pragma: no_include <type_traits> #if 0 namespace osp { class Package; } namespace osp { struct Path; } using osp::active::ActiveScene; using osp::active::ActiveEnt; using osp::active::ACompMachines; using osp::active::ACompPhysDynamic; using osp::active::ACompTransform; using osp::active::SysPhysics; using osp::active::MCompWirePanel; using osp::active::ACtxWireNodes; using osp::active::ACompWire; using osp::active::SysWire; using osp::active::SysSignal; using osp::active::WireNode; using osp::active::WirePort; using osp::active::UpdNodes_t; using osp::nodeindex_t; using osp::BlueprintMachine; using osp::Package; using osp::DependRes; using osp::Path; using osp::machine_id_t; using osp::NodeMap_t; using osp::Matrix4; using osp::Vector3; namespace adera::active::machines { float SysMCompRCSController::thruster_influence(Vector3 posOset, Vector3 direction, Vector3 cmdTransl, Vector3 cmdRot) { // Thrust is applied in opposite direction of thruster nozzle direction Vector3 thrust = std::negate{}(direction.normalized()); float rotInfluence = 0.0f; if (cmdRot.length() > 0.0f) { Vector3 torque = Magnum::Math::cross(posOset, thrust).normalized(); rotInfluence = Magnum::Math::dot(torque, cmdRot.normalized()); } float translInfluence = 0.0f; if (cmdTransl.length() > 0.0f) { translInfluence = Magnum::Math::dot(thrust, cmdTransl.normalized()); } // Total component of thrust in direction of command float total = rotInfluence + translInfluence; if (total < .01f) { /* Ignore small contributions from imprecision * Real thrusters can't throttle this deep anyways, so if their * contribution is this small, it'd be a waste of fuel to fire them. */ return 0.0f; } /* Compute thruster throttle output demanded by current command. * In the future, it would be neat to implement PWM so that unthrottlable * thrusters would pulse on and off in order to deliver reduced thrust */ return std::clamp(rotInfluence + translInfluence, 0.0f, 1.0f); } void SysMCompRCSController::update_construct(ActiveScene &rScene) { auto view = rScene.get_registry() .view<osp::active::ACompVehicle, osp::active::ACompVehicleInConstruction>(); machine_id_t const id = osp::mach_id<MCompRCSController>(); for (auto [vehEnt, rVeh, rVehConstr] : view.each()) { // Check if the vehicle blueprint might store MCompRCSControllers if (rVehConstr.m_blueprint->m_machines.size() <= id) { continue; } // Initialize all MCompRCSControllers in the vehicle for (BlueprintMachine &mach : rVehConstr.m_blueprint->m_machines[id]) { // Get part ActiveEnt partEnt = rVeh.m_parts[mach.m_partIndex]; // Get machine entity previously reserved by SysVehicle auto& machines = rScene.reg_get<ACompMachines>(partEnt); ActiveEnt machEnt = machines.m_machines[mach.m_protoMachineIndex]; rScene.reg_emplace<MCompRCSController>(machEnt); } } } void SysMCompRCSController::update_calculate(ActiveScene& rScene) { using adera::wire::Percent; using adera::wire::AttitudeControl; ACtxWireNodes<Percent> &rNodesPercent = SysWire::nodes<Percent>(rScene); std::vector<ActiveEnt>& rToUpdate = SysWire::to_update<MCompRCSController>(rScene); UpdNodes_t<Percent> updPercent; for (ActiveEnt ent : rToUpdate) { float influence = 0.0f; auto const *pPanelAtCtrl = rScene.get_registry() .try_get< MCompWirePanel<AttitudeControl> >(ent); if (pPanelAtCtrl != nullptr) { WirePort<AttitudeControl> const *pPortCommand = pPanelAtCtrl->port(MCompRCSController::smc_wiCommandOrient); // Read AttitudeControl Command Input if (pPortCommand != nullptr) { auto const &nodesAttCtrl = rScene.reg_get< ACtxWireNodes<AttitudeControl> >( rScene.hier_get_root()); WireNode<AttitudeControl> const &nodeCommand = nodesAttCtrl.get_node(pPortCommand->m_nodeIndex); // Get rigidbody ancestor and its transformation component auto const *pRbAncestor = SysPhysics::try_get_or_find_rigidbody_ancestor( rScene, ent); auto const &rDyn = rScene.reg_get<ACompPhysDynamic>( pRbAncestor->m_ancestor); Matrix4 transform = pRbAncestor->m_relTransform; // TODO: RCS translation is not currently implemented, only // rotation Vector3 commandTransl = Vector3{0.0f}; Vector3 commandRot = nodeCommand.m_state.m_attitude; Vector3 thrusterPos = transform.translation() - rDyn.m_centerOfMassOffset; Vector3 thrusterDir = transform.rotation() * Vector3{0.0f, 0.0f, 1.0f}; if ((commandRot.length() > 0.0f) || (commandTransl.length() > 0.0f)) { influence = thruster_influence(thrusterPos, thrusterDir, commandTransl, commandRot); } } } auto const *pPanelPercent = rScene.get_registry() .try_get< MCompWirePanel<Percent> >(ent); if (pPanelPercent != nullptr) { WirePort<Percent> const *pPortThrottle = pPanelPercent->port(MCompRCSController::m_woThrottle); // Write to throttle output if (pPortThrottle != nullptr) { WireNode<Percent> const &nodeThrottle = rNodesPercent.get_node(pPortThrottle->m_nodeIndex); // Write possibly new throttle value to node SysSignal<Percent>::signal_assign( rScene, {influence}, nodeThrottle, pPortThrottle->m_nodeIndex, updPercent); } } } // Request to update any wire nodes if they were modified if (!updPercent.empty()) { std::sort(std::begin(updPercent), std::end(updPercent)); rNodesPercent.update_write(updPercent); rScene.reg_get<ACompWire>(rScene.hier_get_root()).request_update(); } } } // namespace adera::active::machines #endif
35.740157
83
0.633289
TheOpenSpaceProgram
d54bee1991842c09805289de2c6c5715a06252ef
2,129
cpp
C++
src/net_types.cpp
republic-productions/finalcoin
7c0f335ded1e5c662034c822ca2c474b8e62778f
[ "MIT" ]
null
null
null
src/net_types.cpp
republic-productions/finalcoin
7c0f335ded1e5c662034c822ca2c474b8e62778f
[ "MIT" ]
null
null
null
src/net_types.cpp
republic-productions/finalcoin
7c0f335ded1e5c662034c822ca2c474b8e62778f
[ "MIT" ]
null
null
null
// Copyright (c) 2021 The Finalcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <net_types.h> #include <netaddress.h> #include <netbase.h> #include <univalue.h> CBanEntry::CBanEntry(const UniValue& json) : nVersion(json["version"].get_int()), nCreateTime(json["ban_created"].get_int64()), nBanUntil(json["banned_until"].get_int64()) { } UniValue CBanEntry::ToJson() const { UniValue json(UniValue::VOBJ); json.pushKV("version", nVersion); json.pushKV("ban_created", nCreateTime); json.pushKV("banned_until", nBanUntil); return json; } static const char* BANMAN_JSON_ADDR_KEY = "address"; /** * Convert a `banmap_t` object to a JSON array. * @param[in] bans Bans list to convert. * @return a JSON array, similar to the one returned by the `listbanned` RPC. Suitable for * passing to `BanMapFromJson()`. */ UniValue BanMapToJson(const banmap_t& bans) { UniValue bans_json(UniValue::VARR); for (const auto& it : bans) { const auto& address = it.first; const auto& ban_entry = it.second; UniValue j = ban_entry.ToJson(); j.pushKV(BANMAN_JSON_ADDR_KEY, address.ToString()); bans_json.push_back(j); } return bans_json; } /** * Convert a JSON array to a `banmap_t` object. * @param[in] bans_json JSON to convert, must be as returned by `BanMapToJson()`. * @param[out] bans Bans list to create from the JSON. * @throws std::runtime_error if the JSON does not have the expected fields or they contain * unparsable values. */ void BanMapFromJson(const UniValue& bans_json, banmap_t& bans) { for (const auto& ban_entry_json : bans_json.getValues()) { CSubNet subnet; const auto& subnet_str = ban_entry_json[BANMAN_JSON_ADDR_KEY].get_str(); if (!LookupSubNet(subnet_str, subnet)) { throw std::runtime_error( strprintf("Cannot parse banned address or subnet: %s", subnet_str)); } bans.insert_or_assign(subnet, CBanEntry{ban_entry_json}); } }
32.257576
91
0.687647
republic-productions
d54d403b78e659a3739eab8938d2a195f9e540d4
2,058
hpp
C++
include/burst/iterator/detail/uniform_range_tuple_please.hpp
izvolov/thrust
399e12eed54131d731c4c5ef40512b17107bca56
[ "BSL-1.0" ]
85
2015-11-25T14:05:42.000Z
2021-11-15T11:47:19.000Z
include/burst/iterator/detail/uniform_range_tuple_please.hpp
izvolov/burst
399e12eed54131d731c4c5ef40512b17107bca56
[ "BSL-1.0" ]
147
2015-01-11T08:36:53.000Z
2021-11-04T09:03:36.000Z
include/burst/iterator/detail/uniform_range_tuple_please.hpp
izvolov/thrust
399e12eed54131d731c4c5ef40512b17107bca56
[ "BSL-1.0" ]
6
2016-06-02T17:28:26.000Z
2020-04-05T11:16:16.000Z
#ifndef BURST__ITERATOR__DETAIL__UNIFORM_RANGE_TUPLE_PLEASE_HPP #define BURST__ITERATOR__DETAIL__UNIFORM_RANGE_TUPLE_PLEASE_HPP #include <burst/range/variant_range.hpp> #include <burst/tuple/by_all.hpp> #include <burst/type_traits/are_same.hpp> #include <tuple> #include <type_traits> #include <utility> namespace burst { namespace detail { /*! \brief Перегрузка для случая, когда все переданные диапазоны имеют один и тот же тип \see uniform_range_tuple_please */ template <typename... Ranges> auto uniform_range_tuple_please_impl (std::tuple<Ranges &...> ranges, std::true_type) { static_assert(are_same_v<Ranges...>, ""); return ranges; } /*! \brief Перегрузка для случая, когда переданные диапазоны разнотипны \see uniform_range_tuple_please */ template <typename... Ranges> auto uniform_range_tuple_please_impl (std::tuple<Ranges &...> ranges, std::false_type) { static_assert(not are_same_v<Ranges...>, ""); const auto to_variant_range = [] (auto & r) {return variant_range<Ranges...>(r.begin(), r.end());}; return by_all(to_variant_range, std::move(ranges)); } /*! \brief Сделать из кортежа возможно разнотипных диапазонов кортеж заведомо однотипных диапазонов \returns Если диапазоны изначально однотипны, то возвращается изначальный кортеж, в противном случае создаётся кортеж, в котором каждый из диапазонов приведён к boost::any_range. \see are_same */ template <typename... Ranges> auto uniform_range_tuple_please (std::tuple<Ranges &...> ranges) { return uniform_range_tuple_please_impl(ranges, are_same<Ranges...>{}); } } } #endif // BURST__ITERATOR__DETAIL__UNIFORM_RANGE_TUPLE_PLEASE_HPP
31.181818
94
0.614674
izvolov
d551110a940f8c29cf31fc3cc91bb3168d0afe81
3,940
cpp
C++
Foundation/testsuite/src/LineEndingConverterTest.cpp
e0861280/poco
961ca3e246f55646ab6e101e35e3ec0db359360f
[ "BSL-1.0" ]
null
null
null
Foundation/testsuite/src/LineEndingConverterTest.cpp
e0861280/poco
961ca3e246f55646ab6e101e35e3ec0db359360f
[ "BSL-1.0" ]
null
null
null
Foundation/testsuite/src/LineEndingConverterTest.cpp
e0861280/poco
961ca3e246f55646ab6e101e35e3ec0db359360f
[ "BSL-1.0" ]
1
2019-10-21T03:40:54.000Z
2019-10-21T03:40:54.000Z
// // LineEndingConverterTest.cpp // // $Id: //poco/1.4/Foundation/testsuite/src/LineEndingConverterTest.cpp#1 $ // // Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #include "LineEndingConverterTest.h" #include "Poco/CppUnit/TestCaller.h" #include "Poco/CppUnit/TestSuite.h" #include "Poco/LineEndingConverter.h" #include "Poco/StreamCopier.h" #include <sstream> using Poco::LineEnding; using Poco::InputLineEndingConverter; using Poco::OutputLineEndingConverter; using Poco::StreamCopier; LineEndingConverterTest::LineEndingConverterTest(const std::string& rName): CppUnit::TestCase(rName) { } LineEndingConverterTest::~LineEndingConverterTest() { } void LineEndingConverterTest::testInputDosToUnix() { std::istringstream input("line1\r\nline2\r\nline3\r\n"); std::ostringstream output; InputLineEndingConverter conv(input, LineEnding::NEWLINE_LF); StreamCopier::copyStream(conv, output); std::string result = output.str(); assert (result == "line1\nline2\nline3\n"); } void LineEndingConverterTest::testInputUnixToDos() { std::istringstream input("line1\nline2\nline3\n"); std::ostringstream output; InputLineEndingConverter conv(input, LineEnding::NEWLINE_CRLF); StreamCopier::copyStream(conv, output); std::string result = output.str(); assert (result == "line1\r\nline2\r\nline3\r\n"); } void LineEndingConverterTest::testInputMacToUnix() { std::istringstream input("line1\rline2\rline3\r"); std::ostringstream output; InputLineEndingConverter conv(input, LineEnding::NEWLINE_LF); StreamCopier::copyStream(conv, output); std::string result = output.str(); assert (result == "line1\nline2\nline3\n"); } void LineEndingConverterTest::testInputRemove() { std::istringstream input("line1\r\nline2\rline3\n"); std::ostringstream output; InputLineEndingConverter conv(input, ""); StreamCopier::copyStream(conv, output); std::string result = output.str(); assert (result == "line1line2line3"); } void LineEndingConverterTest::testOutputDosToUnix() { std::ostringstream output; OutputLineEndingConverter conv(output, LineEnding::NEWLINE_LF); conv << "line1\r\nline2\r\nline3\r\n" << std::flush; std::string result = output.str(); assert (result == "line1\nline2\nline3\n"); } void LineEndingConverterTest::testOutputUnixToDos() { std::ostringstream output; OutputLineEndingConverter conv(output, LineEnding::NEWLINE_CRLF); conv << "line1\nline2\nline3\n" << std::flush; std::string result = output.str(); assert (result == "line1\r\nline2\r\nline3\r\n"); } void LineEndingConverterTest::testOutputMacToUnix() { std::ostringstream output; OutputLineEndingConverter conv(output, LineEnding::NEWLINE_LF); conv << "line1\rline2\rline3\r" << std::flush; std::string result = output.str(); assert (result == "line1\nline2\nline3\n"); } void LineEndingConverterTest::testOutputRemove() { std::ostringstream output; OutputLineEndingConverter conv(output, ""); conv << "line1\r\nline2\rline3\n" << std::flush; std::string result = output.str(); assert (result == "line1line2line3"); } void LineEndingConverterTest::setUp() { } void LineEndingConverterTest::tearDown() { } CppUnit::Test* LineEndingConverterTest::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("LineEndingConverterTest"); CppUnit_addTest(pSuite, LineEndingConverterTest, testInputDosToUnix); CppUnit_addTest(pSuite, LineEndingConverterTest, testInputUnixToDos); CppUnit_addTest(pSuite, LineEndingConverterTest, testInputMacToUnix); CppUnit_addTest(pSuite, LineEndingConverterTest, testInputRemove); CppUnit_addTest(pSuite, LineEndingConverterTest, testOutputDosToUnix); CppUnit_addTest(pSuite, LineEndingConverterTest, testOutputUnixToDos); CppUnit_addTest(pSuite, LineEndingConverterTest, testOutputMacToUnix); CppUnit_addTest(pSuite, LineEndingConverterTest, testOutputRemove); return pSuite; }
26.986301
100
0.768528
e0861280
d553fdd4494a551c82bb840cca6d211cdcb19797
65,143
cpp
C++
wpilibc/Athena/src/CANTalon.cpp
flamingchickens1540/wpilib-mirror
58a82be5baaf0248ce3161804c9743724f165479
[ "BSD-3-Clause" ]
null
null
null
wpilibc/Athena/src/CANTalon.cpp
flamingchickens1540/wpilib-mirror
58a82be5baaf0248ce3161804c9743724f165479
[ "BSD-3-Clause" ]
null
null
null
wpilibc/Athena/src/CANTalon.cpp
flamingchickens1540/wpilib-mirror
58a82be5baaf0248ce3161804c9743724f165479
[ "BSD-3-Clause" ]
null
null
null
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2014-2016. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include "CANTalon.h" #include "WPIErrors.h" #include <unistd.h> // usleep #include <sstream> #include "LiveWindow/LiveWindow.h" /** * Number of adc engineering units per 0 to 3.3V sweep. * This is necessary for scaling Analog Position in rotations/RPM. */ const double kNativeAdcUnitsPerRotation = 1024.0; /** * Number of pulse width engineering units per full rotation. * This is necessary for scaling Pulse Width Decoded Position in rotations/RPM. */ const double kNativePwdUnitsPerRotation = 4096.0; /** * Number of minutes per 100ms unit. Useful for scaling velocities * measured by Talon's 100ms timebase to rotations per minute. */ const double kMinutesPer100msUnit = 1.0/600.0; /** * Constructor for the CANTalon device. * @param deviceNumber The CAN ID of the Talon SRX */ CANTalon::CANTalon(int deviceNumber) : m_deviceNumber(deviceNumber), m_impl(new CanTalonSRX(deviceNumber)), m_safetyHelper(new MotorSafetyHelper(this)) { ApplyControlMode(m_controlMode); m_impl->SetProfileSlotSelect(m_profile); m_isInverted = false; LiveWindow::GetInstance()->AddActuator("CANTalon", m_deviceNumber, this); } /** * Constructor for the CANTalon device. * @param deviceNumber The CAN ID of the Talon SRX * @param controlPeriodMs The period in ms to send the CAN control frame. * Period is bounded to [1ms,95ms]. */ CANTalon::CANTalon(int deviceNumber, int controlPeriodMs) : m_deviceNumber(deviceNumber), m_impl(new CanTalonSRX(deviceNumber,controlPeriodMs)), m_safetyHelper(new MotorSafetyHelper(this)) { ApplyControlMode(m_controlMode); m_impl->SetProfileSlotSelect(m_profile); LiveWindow::GetInstance()->AddActuator("CANTalon", m_deviceNumber, this); } CANTalon::~CANTalon() { if (m_table != nullptr) m_table->RemoveTableListener(this); if (m_hasBeenMoved) return; Disable(); } /** * Write out the PID value as seen in the PIDOutput base object. * * @deprecated Call Set instead. * * @param output Write out the PercentVbus value as was computed by the * PIDController */ void CANTalon::PIDWrite(float output) { if (GetControlMode() == kPercentVbus) { Set(output); } else { wpi_setWPIErrorWithContext(IncompatibleMode, "PID only supported in PercentVbus mode"); } } /** * Retrieve the current sensor value. Equivalent to Get(). * * @return The current sensor value of the Talon. */ double CANTalon::PIDGet() { return Get(); } /** * Gets the current status of the Talon (usually a sensor value). * * In Current mode: returns output current. * In Speed mode: returns current speed. * In Position mode: returns current sensor position. * In PercentVbus and Follower modes: returns current applied throttle. * * @return The current sensor value of the Talon. */ float CANTalon::Get() const { int value; switch (m_controlMode) { case kVoltage: return GetOutputVoltage(); case kCurrent: return GetOutputCurrent(); case kSpeed: m_impl->GetSensorVelocity(value); return ScaleNativeUnitsToRpm(m_feedbackDevice, value); case kPosition: m_impl->GetSensorPosition(value); return ScaleNativeUnitsToRotations(m_feedbackDevice, value); case kPercentVbus: case kFollower: default: m_impl->GetAppliedThrottle(value); return (float)value / 1023.0; } } /** * Sets the appropriate output on the talon, depending on the mode. * * In PercentVbus, the output is between -1.0 and 1.0, with 0.0 as stopped. * In Voltage mode, output value is in volts. * In Current mode, output value is in amperes. * In Speed mode, output value is in position change / 10ms. * In Position mode, output value is in encoder ticks or an analog value, * depending on the sensor. * In Follower mode, the output value is the integer device ID of the talon to * duplicate. * * @param outputValue The setpoint value, as described above. * @see SelectProfileSlot to choose between the two sets of gains. */ void CANTalon::Set(float value, uint8_t syncGroup) { /* feed safety helper since caller just updated our output */ m_safetyHelper->Feed(); if (m_controlEnabled) { m_setPoint = value; /* cache set point for GetSetpoint() */ CTR_Code status = CTR_OKAY; switch (m_controlMode) { case CANSpeedController::kPercentVbus: { m_impl->Set(m_isInverted ? -value : value); status = CTR_OKAY; } break; case CANSpeedController::kFollower: { status = m_impl->SetDemand((int)value); } break; case CANSpeedController::kVoltage: { // Voltage is an 8.8 fixed point number. int volts = int((m_isInverted ? -value : value) * 256); status = m_impl->SetDemand(volts); } break; case CANSpeedController::kSpeed: /* if the caller has provided scaling info, apply it */ status = m_impl->SetDemand(ScaleVelocityToNativeUnits(m_feedbackDevice, m_isInverted ? -value : value)); break; case CANSpeedController::kPosition: status = m_impl->SetDemand(ScaleRotationsToNativeUnits(m_feedbackDevice, value)); break; case CANSpeedController::kCurrent: { double milliamperes = (m_isInverted ? -value : value) * 1000.0; /* mA*/ status = m_impl->SetDemand(milliamperes); } break; case CANSpeedController::kMotionProfile: { status = m_impl->SetDemand((int)value); } break; default: wpi_setWPIErrorWithContext( IncompatibleMode, "The CAN Talon does not support this control mode."); break; } if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } status = m_impl->SetModeSelect(m_sendMode); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } } /** * Sets the setpoint to value. Equivalent to Set(). */ void CANTalon::SetSetpoint(float value) { Set(value); } /** * Resets the integral term and disables the controller. */ void CANTalon::Reset() { ClearIaccum(); Disable(); } /** * Disables control of the talon, causing the motor to brake or coast * depending on its mode (see the Talon SRX Software Reference manual * for more information). */ void CANTalon::Disable() { m_impl->SetModeSelect((int)CANTalon::kDisabled); m_controlEnabled = false; } /** * Enables control of the Talon, allowing the motor to move. */ void CANTalon::EnableControl() { SetControlMode(m_controlMode); m_controlEnabled = true; } /** * Enables control of the Talon, allowing the motor to move. */ void CANTalon::Enable() { EnableControl(); } /** * @return Whether the Talon is currently enabled. */ bool CANTalon::IsControlEnabled() const { return m_controlEnabled; } /** * @return Whether the Talon is currently enabled. */ bool CANTalon::IsEnabled() const { return IsControlEnabled(); } /** * @param p Proportional constant to use in PID loop. * @see SelectProfileSlot to choose between the two sets of gains. */ void CANTalon::SetP(double p) { CTR_Code status = m_impl->SetPgain(m_profile, p); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * Set the integration constant of the currently selected profile. * * @param i Integration constant for the currently selected PID profile. * @see SelectProfileSlot to choose between the two sets of gains. */ void CANTalon::SetI(double i) { CTR_Code status = m_impl->SetIgain(m_profile, i); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * Set the derivative constant of the currently selected profile. * * @param d Derivative constant for the currently selected PID profile. * @see SelectProfileSlot to choose between the two sets of gains. */ void CANTalon::SetD(double d) { CTR_Code status = m_impl->SetDgain(m_profile, d); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * Set the feedforward value of the currently selected profile. * * @param f Feedforward constant for the currently selected PID profile. * @see SelectProfileSlot to choose between the two sets of gains. */ void CANTalon::SetF(double f) { CTR_Code status = m_impl->SetFgain(m_profile, f); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * Set the Izone to a nonzero value to auto clear the integral accumulator * when the absolute value of CloseLoopError exceeds Izone. * * @see SelectProfileSlot to choose between the two sets of gains. */ void CANTalon::SetIzone(unsigned iz) { CTR_Code status = m_impl->SetIzone(m_profile, iz); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * SRX has two available slots for PID. * @param slotIdx one or zero depending on which slot caller wants. */ void CANTalon::SelectProfileSlot(int slotIdx) { m_profile = (slotIdx == 0) ? 0 : 1; /* only get two slots for now */ CTR_Code status = m_impl->SetProfileSlotSelect(m_profile); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * Sets control values for closed loop control. * * @param p Proportional constant. * @param i Integration constant. * @param d Differential constant. * This function does not modify F-gain. Considerable passing a zero for f * using * the four-parameter function. */ void CANTalon::SetPID(double p, double i, double d) { SetP(p); SetI(i); SetD(d); } /** * Sets control values for closed loop control. * * @param p Proportional constant. * @param i Integration constant. * @param d Differential constant. * @param f Feedforward constant. */ void CANTalon::SetPID(double p, double i, double d, double f) { SetP(p); SetI(i); SetD(d); SetF(f); } /** * Select the feedback device to use in closed-loop */ void CANTalon::SetFeedbackDevice(FeedbackDevice feedbackDevice) { /* save the selection so that future setters/getters know which scalars to apply */ m_feedbackDevice = feedbackDevice; /* pass feedback to actual CAN frame */ CTR_Code status = m_impl->SetFeedbackDeviceSelect((int)feedbackDevice); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * Select the feedback device to use in closed-loop */ void CANTalon::SetStatusFrameRateMs(StatusFrameRate stateFrame, int periodMs) { CTR_Code status = m_impl->SetStatusFrameRate((int)stateFrame, periodMs); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * Get the current proportional constant. * * @return double proportional constant for current profile. * @see SelectProfileSlot to choose between the two sets of gains. */ double CANTalon::GetP() const { CanTalonSRX::param_t param = m_profile ? CanTalonSRX::eProfileParamSlot1_P : CanTalonSRX::eProfileParamSlot0_P; // Update the info in m_impl. CTR_Code status = m_impl->RequestParam(param); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } usleep(kDelayForSolicitedSignalsUs); /* small yield for getting response */ double p; status = m_impl->GetPgain(m_profile, p); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } return p; } /** * TODO documentation (see CANJaguar.cpp) * @see SelectProfileSlot to choose between the two sets of gains. */ double CANTalon::GetI() const { CanTalonSRX::param_t param = m_profile ? CanTalonSRX::eProfileParamSlot1_I : CanTalonSRX::eProfileParamSlot0_I; // Update the info in m_impl. CTR_Code status = m_impl->RequestParam(param); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } usleep(kDelayForSolicitedSignalsUs); /* small yield for getting response */ double i; status = m_impl->GetIgain(m_profile, i); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } return i; } /** * TODO documentation (see CANJaguar.cpp) * @see SelectProfileSlot to choose between the two sets of gains. */ double CANTalon::GetD() const { CanTalonSRX::param_t param = m_profile ? CanTalonSRX::eProfileParamSlot1_D : CanTalonSRX::eProfileParamSlot0_D; // Update the info in m_impl. CTR_Code status = m_impl->RequestParam(param); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } usleep(kDelayForSolicitedSignalsUs); /* small yield for getting response */ double d; status = m_impl->GetDgain(m_profile, d); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } return d; } /** * * @see SelectProfileSlot to choose between the two sets of gains. */ double CANTalon::GetF() const { CanTalonSRX::param_t param = m_profile ? CanTalonSRX::eProfileParamSlot1_F : CanTalonSRX::eProfileParamSlot0_F; // Update the info in m_impl. CTR_Code status = m_impl->RequestParam(param); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } usleep(kDelayForSolicitedSignalsUs); /* small yield for getting response */ double f; status = m_impl->GetFgain(m_profile, f); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } return f; } /** * @see SelectProfileSlot to choose between the two sets of gains. */ int CANTalon::GetIzone() const { CanTalonSRX::param_t param = m_profile ? CanTalonSRX::eProfileParamSlot1_IZone : CanTalonSRX::eProfileParamSlot0_IZone; // Update the info in m_impl. CTR_Code status = m_impl->RequestParam(param); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } usleep(kDelayForSolicitedSignalsUs); int iz; status = m_impl->GetIzone(m_profile, iz); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } return iz; } /** * @return the current setpoint; ie, whatever was last passed to Set(). */ double CANTalon::GetSetpoint() const { return m_setPoint; } /** * Returns the voltage coming in from the battery. * * @return The input voltage in volts. */ float CANTalon::GetBusVoltage() const { double voltage; CTR_Code status = m_impl->GetBatteryV(voltage); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } return voltage; } /** * @return The voltage being output by the Talon, in Volts. */ float CANTalon::GetOutputVoltage() const { int throttle11; CTR_Code status = m_impl->GetAppliedThrottle(throttle11); float voltage = GetBusVoltage() * (float(throttle11) / 1023.0); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } return voltage; } /** * Returns the current going through the Talon, in Amperes. */ float CANTalon::GetOutputCurrent() const { double current; CTR_Code status = m_impl->GetCurrent(current); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } return current; } /** * Returns temperature of Talon, in degrees Celsius. */ float CANTalon::GetTemperature() const { double temp; CTR_Code status = m_impl->GetTemp(temp); if (temp != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } return temp; } /** * Set the position value of the selected sensor. This is useful for zero-ing * quadrature encoders. * Continuous sensors (like analog encoderes) can also partially be set (the * portion of the postion based on overflows). */ void CANTalon::SetPosition(double pos) { int32_t nativePos = ScaleRotationsToNativeUnits(m_feedbackDevice, pos); CTR_Code status = m_impl->SetSensorPosition(nativePos); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * TODO documentation (see CANJaguar.cpp) * * @return The position of the sensor currently providing feedback. * When using analog sensors, 0 units corresponds to 0V, 1023 * units corresponds to 3.3V * When using an analog encoder (wrapping around 1023 => 0 is * possible) the units are still 3.3V per 1023 units. * When using quadrature, each unit is a quadrature edge (4X) * mode. */ double CANTalon::GetPosition() const { int32_t position; CTR_Code status = m_impl->GetSensorPosition(position); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } return ScaleNativeUnitsToRotations(m_feedbackDevice, position); } /** * If sensor and motor are out of phase, sensor can be inverted * (position and velocity multiplied by -1). * @see GetPosition and @see GetSpeed. */ void CANTalon::SetSensorDirection(bool reverseSensor) { CTR_Code status = m_impl->SetRevFeedbackSensor(reverseSensor ? 1 : 0); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * Flips the sign (multiplies by negative one) the throttle values going into * the motor on the talon in closed loop modes. Typically the application * should use SetSensorDirection to keep sensor and motor in phase. * @see SetSensorDirection * However this routine is helpful for reversing the motor direction * when Talon is in slave mode, or when using a single-direction position * sensor in a closed-loop mode. * * @param reverseOutput True if motor output should be flipped; False if not. */ void CANTalon::SetClosedLoopOutputDirection(bool reverseOutput) { CTR_Code status = m_impl->SetRevMotDuringCloseLoopEn(reverseOutput ? 1 : 0); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * Returns the current error in the controller. * * @return the difference between the setpoint and the sensor value. */ int CANTalon::GetClosedLoopError() const { int error; /* retrieve the closed loop error in native units */ CTR_Code status = m_impl->GetCloseLoopErr(error); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } return error; } /** * Set the allowable closed loop error. * @param allowableCloseLoopError allowable closed loop error for selected profile. * mA for Curent closed loop. * Talon Native Units for position and velocity. */ void CANTalon::SetAllowableClosedLoopErr(uint32_t allowableCloseLoopError) { /* grab param enum */ CanTalonSRX::param_t param; if (m_profile == 1) { param = CanTalonSRX::eProfileParamSlot1_AllowableClosedLoopErr; } else { param = CanTalonSRX::eProfileParamSlot0_AllowableClosedLoopErr; } /* send allowable close loop er in native units */ ConfigSetParameter(param, allowableCloseLoopError); } /** * TODO documentation (see CANJaguar.cpp) * * @returns The speed of the sensor currently providing feedback. * * The speed units will be in the sensor's native ticks per 100ms. * * For analog sensors, 3.3V corresponds to 1023 units. * So a speed of 200 equates to ~0.645 dV per 100ms or 6.451 dV per * second. * If this is an analog encoder, that likely means 1.9548 rotations * per sec. * For quadrature encoders, each unit corresponds a quadrature edge (4X). * So a 250 count encoder will produce 1000 edge events per * rotation. * An example speed of 200 would then equate to 20% of a rotation * per 100ms, * or 10 rotations per second. */ double CANTalon::GetSpeed() const { int32_t speed; CTR_Code status = m_impl->GetSensorVelocity(speed); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } return ScaleNativeUnitsToRpm(m_feedbackDevice, speed); } /** * Get the position of whatever is in the analog pin of the Talon, regardless of * whether it is actually being used for feedback. * * @returns The 24bit analog value. The bottom ten bits is the ADC (0 - 1023) * on the analog pin of the Talon. * The upper 14 bits tracks the overflows and * underflows (continuous sensor). */ int CANTalon::GetAnalogIn() const { int position; CTR_Code status = m_impl->GetAnalogInWithOv(position); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } return position; } void CANTalon::SetAnalogPosition(int newPosition) { CTR_Code status = m_impl->SetParam(CanTalonSRX::eAinPosition, newPosition); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * Get the position of whatever is in the analog pin of the Talon, regardless of * whether it is actually being used for feedback. * * @returns The ADC (0 - 1023) on analog pin of the Talon. */ int CANTalon::GetAnalogInRaw() const { return GetAnalogIn() & 0x3FF; } /** * Get the position of whatever is in the analog pin of the Talon, regardless of * whether it is actually being used for feedback. * * @returns The value (0 - 1023) on the analog pin of the Talon. */ int CANTalon::GetAnalogInVel() const { int vel; CTR_Code status = m_impl->GetAnalogInVel(vel); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } return vel; } /** * Get the position of whatever is in the analog pin of the Talon, regardless of * whether it is actually being used for feedback. * * @returns The value (0 - 1023) on the analog pin of the Talon. */ int CANTalon::GetEncPosition() const { int position; CTR_Code status = m_impl->GetEncPosition(position); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } return position; } void CANTalon::SetEncPosition(int newPosition) { CTR_Code status = m_impl->SetParam(CanTalonSRX::eEncPosition, newPosition); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * Get the position of whatever is in the analog pin of the Talon, regardless of * whether it is actually being used for feedback. * * @returns The value (0 - 1023) on the analog pin of the Talon. */ int CANTalon::GetEncVel() const { int vel; CTR_Code status = m_impl->GetEncVel(vel); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } return vel; } int CANTalon::GetPulseWidthPosition() const { int param; CTR_Code status = m_impl->GetPulseWidthPosition(param); if (status != CTR_OKAY) wpi_setErrorWithContext(status, getHALErrorMessage(status)); return param; } void CANTalon::SetPulseWidthPosition(int newPosition) { CTR_Code status = m_impl->SetParam(CanTalonSRX::ePwdPosition, newPosition); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } int CANTalon::GetPulseWidthVelocity()const { int param; CTR_Code status = m_impl->GetPulseWidthVelocity(param); if (status != CTR_OKAY) wpi_setErrorWithContext(status, getHALErrorMessage(status)); return param; } int CANTalon::GetPulseWidthRiseToFallUs()const { int param; CTR_Code status = m_impl->GetPulseWidthRiseToFallUs(param); if (status != CTR_OKAY) wpi_setErrorWithContext(status, getHALErrorMessage(status)); return param; } int CANTalon::GetPulseWidthRiseToRiseUs()const { int param; CTR_Code status = m_impl->GetPulseWidthRiseToRiseUs(param); if (status != CTR_OKAY) wpi_setErrorWithContext(status, getHALErrorMessage(status)); return param; } /** * @param which feedback sensor to check it if is connected. * @return status of caller's specified sensor type. */ CANTalon::FeedbackDeviceStatus CANTalon::IsSensorPresent(FeedbackDevice feedbackDevice)const { FeedbackDeviceStatus retval = FeedbackStatusUnknown; int param; /* detecting sensor health depends on which sensor caller cares about */ switch (feedbackDevice) { case QuadEncoder: case AnalogPot: case AnalogEncoder: case EncRising: case EncFalling: /* no real good way to tell if these sensor are actually present so return status unknown. */ break; case PulseWidth: case CtreMagEncoder_Relative: case CtreMagEncoder_Absolute: /* all of these require pulse width signal to be present. */ CTR_Code status = m_impl->IsPulseWidthSensorPresent(param); if (status != CTR_OKAY) { /* we're not getting status info, signal unknown status */ } else { /* param is updated */ if (param) { /* pulse signal is present, sensor must be working since it always generates a pulse waveform.*/ retval = FeedbackStatusPresent; } else { /* no pulse present, sensor disconnected */ retval = FeedbackStatusNotPresent; } } break; } return retval; } /** * @return IO level of QUADA pin. */ int CANTalon::GetPinStateQuadA() const { int retval; CTR_Code status = m_impl->GetQuadApin(retval); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } return retval; } /** * @return IO level of QUADB pin. */ int CANTalon::GetPinStateQuadB() const { int retval; CTR_Code status = m_impl->GetQuadBpin(retval); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } return retval; } /** * @return IO level of QUAD Index pin. */ int CANTalon::GetPinStateQuadIdx() const { int retval; CTR_Code status = m_impl->GetQuadIdxpin(retval); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } return retval; } /** * @return '1' iff forward limit switch is closed, 0 iff switch is open. * This function works regardless if limit switch feature is enabled. */ int CANTalon::IsFwdLimitSwitchClosed() const { int retval; CTR_Code status = m_impl->GetLimitSwitchClosedFor( retval); /* rename this func, '1' => open, '0' => closed */ if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } return retval ? 0 : 1; } /** * @return '1' iff reverse limit switch is closed, 0 iff switch is open. * This function works regardless if limit switch feature is enabled. */ int CANTalon::IsRevLimitSwitchClosed() const { int retval; CTR_Code status = m_impl->GetLimitSwitchClosedRev( retval); /* rename this func, '1' => open, '0' => closed */ if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } return retval ? 0 : 1; } /* * Simple accessor for tracked rise eventso index pin. * @return number of rising edges on idx pin. */ int CANTalon::GetNumberOfQuadIdxRises() const { int rises; CTR_Code status = m_impl->GetEncIndexRiseEvents( rises); /* rename this func, '1' => open, '0' => closed */ if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } return rises; } /* * @param rises integral value to set into index-rises register. Great way to * zero the index count. */ void CANTalon::SetNumberOfQuadIdxRises(int rises) { CTR_Code status = m_impl->SetParam( CanTalonSRX::eEncIndexRiseEvents, rises); /* rename this func, '1' => open, '0' => closed */ if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * TODO documentation (see CANJaguar.cpp) */ bool CANTalon::GetForwardLimitOK() const { int limSwit = 0; int softLim = 0; CTR_Code status = CTR_OKAY; status = m_impl->GetFault_ForSoftLim(softLim); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } status = m_impl->GetFault_ForLim(limSwit); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /* If either fault is asserted, signal caller we are disabled (with false?) */ return (softLim | limSwit) ? false : true; } /** * TODO documentation (see CANJaguar.cpp) */ bool CANTalon::GetReverseLimitOK() const { int limSwit = 0; int softLim = 0; CTR_Code status = CTR_OKAY; status = m_impl->GetFault_RevSoftLim(softLim); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } status = m_impl->GetFault_RevLim(limSwit); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /* If either fault is asserted, signal caller we are disabled (with false?) */ return (softLim | limSwit) ? false : true; } /** * TODO documentation (see CANJaguar.cpp) */ uint16_t CANTalon::GetFaults() const { uint16_t retval = 0; int val; CTR_Code status = CTR_OKAY; /* temperature */ val = 0; status = m_impl->GetFault_OverTemp(val); if (status != CTR_OKAY) wpi_setErrorWithContext(status, getHALErrorMessage(status)); retval |= (val) ? CANSpeedController::kTemperatureFault : 0; /* voltage */ val = 0; status = m_impl->GetFault_UnderVoltage(val); if (status != CTR_OKAY) wpi_setErrorWithContext(status, getHALErrorMessage(status)); retval |= (val) ? CANSpeedController::kBusVoltageFault : 0; /* fwd-limit-switch */ val = 0; status = m_impl->GetFault_ForLim(val); if (status != CTR_OKAY) wpi_setErrorWithContext(status, getHALErrorMessage(status)); retval |= (val) ? CANSpeedController::kFwdLimitSwitch : 0; /* rev-limit-switch */ val = 0; status = m_impl->GetFault_RevLim(val); if (status != CTR_OKAY) wpi_setErrorWithContext(status, getHALErrorMessage(status)); retval |= (val) ? CANSpeedController::kRevLimitSwitch : 0; /* fwd-soft-limit */ val = 0; status = m_impl->GetFault_ForSoftLim(val); if (status != CTR_OKAY) wpi_setErrorWithContext(status, getHALErrorMessage(status)); retval |= (val) ? CANSpeedController::kFwdSoftLimit : 0; /* rev-soft-limit */ val = 0; status = m_impl->GetFault_RevSoftLim(val); if (status != CTR_OKAY) wpi_setErrorWithContext(status, getHALErrorMessage(status)); retval |= (val) ? CANSpeedController::kRevSoftLimit : 0; return retval; } uint16_t CANTalon::GetStickyFaults() const { uint16_t retval = 0; int val; CTR_Code status = CTR_OKAY; /* temperature */ val = 0; status = m_impl->GetStckyFault_OverTemp(val); if (status != CTR_OKAY) wpi_setErrorWithContext(status, getHALErrorMessage(status)); retval |= (val) ? CANSpeedController::kTemperatureFault : 0; /* voltage */ val = 0; status = m_impl->GetStckyFault_UnderVoltage(val); if (status != CTR_OKAY) wpi_setErrorWithContext(status, getHALErrorMessage(status)); retval |= (val) ? CANSpeedController::kBusVoltageFault : 0; /* fwd-limit-switch */ val = 0; status = m_impl->GetStckyFault_ForLim(val); if (status != CTR_OKAY) wpi_setErrorWithContext(status, getHALErrorMessage(status)); retval |= (val) ? CANSpeedController::kFwdLimitSwitch : 0; /* rev-limit-switch */ val = 0; status = m_impl->GetStckyFault_RevLim(val); if (status != CTR_OKAY) wpi_setErrorWithContext(status, getHALErrorMessage(status)); retval |= (val) ? CANSpeedController::kRevLimitSwitch : 0; /* fwd-soft-limit */ val = 0; status = m_impl->GetStckyFault_ForSoftLim(val); if (status != CTR_OKAY) wpi_setErrorWithContext(status, getHALErrorMessage(status)); retval |= (val) ? CANSpeedController::kFwdSoftLimit : 0; /* rev-soft-limit */ val = 0; status = m_impl->GetStckyFault_RevSoftLim(val); if (status != CTR_OKAY) wpi_setErrorWithContext(status, getHALErrorMessage(status)); retval |= (val) ? CANSpeedController::kRevSoftLimit : 0; return retval; } void CANTalon::ClearStickyFaults() { CTR_Code status = m_impl->ClearStickyFaults(); wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Set the maximum voltage change rate. This ramp rate is in affect regardless * of which control mode * the TALON is in. * * When in PercentVbus or Voltage output mode, the rate at which the voltage * changes can * be limited to reduce current spikes. Set this to 0.0 to disable rate * limiting. * * @param rampRate The maximum rate of voltage change in Percent Voltage mode in * V/s. */ void CANTalon::SetVoltageRampRate(double rampRate) { /* Caller is expressing ramp as Voltage per sec, assuming 12V is full. Talon's throttle ramp is in dThrot/d10ms. 1023 is full fwd, -1023 is full rev. */ double rampRatedThrotPer10ms = (rampRate * 1023.0 / 12.0) / 100; CTR_Code status = m_impl->SetRampThrottle((int)rampRatedThrotPer10ms); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } void CANTalon::SetVoltageCompensationRampRate(double rampRate) { /* when in voltage compensation mode, the voltage compensation rate directly caps the change in target voltage */ CTR_Code status = CTR_OKAY; status = m_impl->SetVoltageCompensationRate(rampRate / 1000); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * Sets a voltage change rate that applies only when a close loop contorl mode * is enabled. * This allows close loop specific ramp behavior. * * @param rampRate The maximum rate of voltage change in Percent Voltage mode in * V/s. */ void CANTalon::SetCloseLoopRampRate(double rampRate) { CTR_Code status = m_impl->SetCloseLoopRampRate( m_profile, rampRate * 1023.0 / 12.0 / 1000.0); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * @return The version of the firmware running on the Talon */ uint32_t CANTalon::GetFirmwareVersion() const { int firmwareVersion; CTR_Code status = m_impl->RequestParam(CanTalonSRX::eFirmVers); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } usleep(kDelayForSolicitedSignalsUs); status = m_impl->GetParamResponseInt32(CanTalonSRX::eFirmVers, firmwareVersion); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /* only sent once on boot */ // CTR_Code status = m_impl->GetFirmVers(firmwareVersion); // if (status != CTR_OKAY) { // wpi_setErrorWithContext(status, getHALErrorMessage(status)); //} return firmwareVersion; } /** * @return The accumulator for I gain. */ int CANTalon::GetIaccum() const { CTR_Code status = m_impl->RequestParam(CanTalonSRX::ePidIaccum); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } usleep(kDelayForSolicitedSignalsUs); /* small yield for getting response */ int iaccum; status = m_impl->GetParamResponseInt32(CanTalonSRX::ePidIaccum, iaccum); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } return iaccum; } /** * Clear the accumulator for I gain. */ void CANTalon::ClearIaccum() { CTR_Code status = m_impl->SetParam(CanTalonSRX::ePidIaccum, 0); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * TODO documentation (see CANJaguar.cpp) */ void CANTalon::ConfigNeutralMode(NeutralMode mode) { CTR_Code status = CTR_OKAY; switch (mode) { default: case kNeutralMode_Jumper: /* use default setting in flash based on webdash/BrakeCal button selection */ status = m_impl->SetOverrideBrakeType( CanTalonSRX::kBrakeOverride_UseDefaultsFromFlash); break; case kNeutralMode_Brake: status = m_impl->SetOverrideBrakeType( CanTalonSRX::kBrakeOverride_OverrideBrake); break; case kNeutralMode_Coast: status = m_impl->SetOverrideBrakeType( CanTalonSRX::kBrakeOverride_OverrideCoast); break; } if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * @return nonzero if brake is enabled during neutral. Zero if coast is enabled * during neutral. */ int CANTalon::GetBrakeEnableDuringNeutral() const { int brakeEn = 0; CTR_Code status = m_impl->GetBrakeIsEnabled(brakeEn); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } return brakeEn; } /** * Configure how many codes per revolution are generated by your encoder. * * @param codesPerRev The number of counts per revolution. */ void CANTalon::ConfigEncoderCodesPerRev(uint16_t codesPerRev) { /* first save the scalar so that all getters/setter work as the user expects */ m_codesPerRev = codesPerRev; /* next send the scalar to the Talon over CAN. This is so that the Talon can report it to whoever needs it, like the webdash. Don't bother checking the return, this is only for instrumentation and is not necessary for Talon functionality. */ (void)m_impl->SetParam(CanTalonSRX::eNumberEncoderCPR, m_codesPerRev); } /** * Configure the number of turns on the potentiometer. * * @param turns The number of turns of the potentiometer. */ void CANTalon::ConfigPotentiometerTurns(uint16_t turns) { /* first save the scalar so that all getters/setter work as the user expects */ m_numPotTurns = turns; /* next send the scalar to the Talon over CAN. This is so that the Talon can report it to whoever needs it, like the webdash. Don't bother checking the return, this is only for instrumentation and is not necessary for Talon functionality. */ (void)m_impl->SetParam(CanTalonSRX::eNumberPotTurns, m_numPotTurns); } /** * @deprecated not implemented */ void CANTalon::ConfigSoftPositionLimits(double forwardLimitPosition, double reverseLimitPosition) { ConfigLimitMode(kLimitMode_SoftPositionLimits); ConfigForwardLimit(forwardLimitPosition); ConfigReverseLimit(reverseLimitPosition); } /** * TODO documentation (see CANJaguar.cpp) */ void CANTalon::DisableSoftPositionLimits() { ConfigLimitMode(kLimitMode_SwitchInputsOnly); } /** * TODO documentation (see CANJaguar.cpp) * Configures the soft limit enable (wear leveled persistent memory). * Also sets the limit switch overrides. */ void CANTalon::ConfigLimitMode(LimitMode mode) { CTR_Code status = CTR_OKAY; switch (mode) { case kLimitMode_SwitchInputsOnly: /** Only use switches for limits */ /* turn OFF both limits. SRX has individual enables and polarity for each * limit switch.*/ status = m_impl->SetForwardSoftEnable(false); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } status = m_impl->SetReverseSoftEnable(false); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /* override enable the limit switches, this circumvents the webdash */ status = m_impl->SetOverrideLimitSwitchEn( CanTalonSRX::kLimitSwitchOverride_EnableFwd_EnableRev); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } break; case kLimitMode_SoftPositionLimits: /** Use both switches and soft limits */ /* turn on both limits. SRX has individual enables and polarity for each * limit switch.*/ status = m_impl->SetForwardSoftEnable(true); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } status = m_impl->SetReverseSoftEnable(true); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /* override enable the limit switches, this circumvents the webdash */ status = m_impl->SetOverrideLimitSwitchEn( CanTalonSRX::kLimitSwitchOverride_EnableFwd_EnableRev); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } break; case kLimitMode_SrxDisableSwitchInputs: /** disable both limit switches and soft limits */ /* turn on both limits. SRX has individual enables and polarity for each * limit switch.*/ status = m_impl->SetForwardSoftEnable(false); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } status = m_impl->SetReverseSoftEnable(false); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /* override enable the limit switches, this circumvents the webdash */ status = m_impl->SetOverrideLimitSwitchEn( CanTalonSRX::kLimitSwitchOverride_DisableFwd_DisableRev); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } break; } } /** * TODO documentation (see CANJaguar.cpp) */ void CANTalon::ConfigForwardLimit(double forwardLimitPosition) { CTR_Code status = CTR_OKAY; int32_t nativeLimitPos = ScaleRotationsToNativeUnits(m_feedbackDevice, forwardLimitPosition); status = m_impl->SetForwardSoftLimit(nativeLimitPos); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * Change the fwd limit switch setting to normally open or closed. * Talon will disable momentarilly if the Talon's current setting * is dissimilar to the caller's requested setting. * * Since Talon saves setting to flash this should only affect * a given Talon initially during robot install. * * @param normallyOpen true for normally open. false for normally closed. */ void CANTalon::ConfigFwdLimitSwitchNormallyOpen(bool normallyOpen) { CTR_Code status = m_impl->SetParam(CanTalonSRX::eOnBoot_LimitSwitch_Forward_NormallyClosed, normallyOpen ? 0 : 1); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * Change the rev limit switch setting to normally open or closed. * Talon will disable momentarilly if the Talon's current setting * is dissimilar to the caller's requested setting. * * Since Talon saves setting to flash this should only affect * a given Talon initially during robot install. * * @param normallyOpen true for normally open. false for normally closed. */ void CANTalon::ConfigRevLimitSwitchNormallyOpen(bool normallyOpen) { CTR_Code status = m_impl->SetParam(CanTalonSRX::eOnBoot_LimitSwitch_Reverse_NormallyClosed, normallyOpen ? 0 : 1); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * TODO documentation (see CANJaguar.cpp) */ void CANTalon::ConfigReverseLimit(double reverseLimitPosition) { CTR_Code status = CTR_OKAY; int32_t nativeLimitPos = ScaleRotationsToNativeUnits(m_feedbackDevice, reverseLimitPosition); status = m_impl->SetReverseSoftLimit(nativeLimitPos); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * TODO documentation (see CANJaguar.cpp) */ void CANTalon::ConfigMaxOutputVoltage(double voltage) { /* config peak throttle when in closed-loop mode in the fwd and rev direction. */ ConfigPeakOutputVoltage(voltage, -voltage); } void CANTalon::ConfigPeakOutputVoltage(double forwardVoltage,double reverseVoltage) { /* bounds checking */ if (forwardVoltage > 12) forwardVoltage = 12; else if (forwardVoltage < 0) forwardVoltage = 0; if (reverseVoltage > 0) reverseVoltage = 0; else if (reverseVoltage < -12) reverseVoltage = -12; /* config calls */ ConfigSetParameter(CanTalonSRX::ePeakPosOutput, 1023 * forwardVoltage / 12.0); ConfigSetParameter(CanTalonSRX::ePeakNegOutput, 1023 * reverseVoltage / 12.0); } void CANTalon::ConfigNominalOutputVoltage(double forwardVoltage,double reverseVoltage) { /* bounds checking */ if (forwardVoltage > 12) forwardVoltage = 12; else if (forwardVoltage < 0) forwardVoltage = 0; if (reverseVoltage > 0) reverseVoltage = 0; else if (reverseVoltage < -12) reverseVoltage = -12; /* config calls */ ConfigSetParameter(CanTalonSRX::eNominalPosOutput,1023*forwardVoltage/12.0); ConfigSetParameter(CanTalonSRX::eNominalNegOutput,1023*reverseVoltage/12.0); } /** * General set frame. Since the parameter is a general integral type, this can * be used for testing future features. */ void CANTalon::ConfigSetParameter(uint32_t paramEnum, double value) { CTR_Code status; /* config peak throttle when in closed-loop mode in the positive direction. */ status = m_impl->SetParam((CanTalonSRX::param_t)paramEnum,value); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * General get frame. Since the parameter is a general integral type, this can * be used for testing future features. */ bool CANTalon::GetParameter(uint32_t paramEnum, double & dvalue) const { bool retval = true; /* send the request frame */ CTR_Code status = m_impl->RequestParam((CanTalonSRX::param_t)paramEnum); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); retval = false; } /* small yield for getting response */ usleep(kDelayForSolicitedSignalsUs); /* get the last received update */ status = m_impl->GetParamResponse((CanTalonSRX::param_t)paramEnum, dvalue); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); retval = false; } return retval; } /** * TODO documentation (see CANJaguar.cpp) */ void CANTalon::ConfigFaultTime(float faultTime) { /* SRX does not have fault time. SRX motor drive is only disabled for soft * limits and limit-switch faults. */ wpi_setWPIErrorWithContext(IncompatibleMode, "Fault Time not supported."); } /** * Fixup the sendMode so Set() serializes the correct demand value. * Also fills the modeSelecet in the control frame to disabled. * @param mode Control mode to ultimately enter once user calls Set(). * @see Set() */ void CANTalon::ApplyControlMode(CANSpeedController::ControlMode mode) { m_controlMode = mode; HALReport(HALUsageReporting::kResourceType_CANTalonSRX, m_deviceNumber + 1, mode); switch (mode) { case kPercentVbus: m_sendMode = kThrottle; break; case kCurrent: m_sendMode = kCurrentMode; break; case kSpeed: m_sendMode = kSpeedMode; break; case kPosition: m_sendMode = kPositionMode; break; case kVoltage: m_sendMode = kVoltageMode; break; case kFollower: m_sendMode = kFollowerMode; break; case kMotionProfile: m_sendMode = kMotionProfileMode; break; } // Keep the talon disabled until Set() is called. CTR_Code status = m_impl->SetModeSelect((int)kDisabled); if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * TODO documentation (see CANJaguar.cpp) */ void CANTalon::SetControlMode(CANSpeedController::ControlMode mode) { if (m_controlMode == mode) { /* we already are in this mode, don't perform disable workaround */ } else { ApplyControlMode(mode); } } /** * TODO documentation (see CANJaguar.cpp) */ CANSpeedController::ControlMode CANTalon::GetControlMode() const { return m_controlMode; } void CANTalon::SetExpiration(float timeout) { m_safetyHelper->SetExpiration(timeout); } float CANTalon::GetExpiration() const { return m_safetyHelper->GetExpiration(); } bool CANTalon::IsAlive() const { return m_safetyHelper->IsAlive(); } bool CANTalon::IsSafetyEnabled() const { return m_safetyHelper->IsSafetyEnabled(); } void CANTalon::SetSafetyEnabled(bool enabled) { m_safetyHelper->SetSafetyEnabled(enabled); } void CANTalon::GetDescription(std::ostringstream& desc) const { desc << "CANTalon ID " << m_deviceNumber; } /** * @param devToLookup FeedbackDevice to lookup the scalar for. Because Talon * allows multiple sensors to be attached simultaneously, caller must * specify which sensor to lookup. * @return The number of native Talon units per rotation of the selected sensor. * Zero if the necessary sensor information is not available. * @see ConfigEncoderCodesPerRev * @see ConfigPotentiometerTurns */ double CANTalon::GetNativeUnitsPerRotationScalar(FeedbackDevice devToLookup)const { bool scalingAvail = false; CTR_Code status = CTR_OKAY; double retval = 0; switch (devToLookup) { case QuadEncoder: { /* When caller wants to lookup Quadrature, the QEI may be in 1x if the selected feedback is edge counter. * Additionally if the quadrature source is the CTRE Mag encoder, then the CPR is known. * This is nice in that the calling app does not require knowing the CPR at all. * So do both checks here. */ int32_t qeiPulsePerCount = 4; /* default to 4x */ switch (m_feedbackDevice) { case CtreMagEncoder_Relative: case CtreMagEncoder_Absolute: /* we assume the quadrature signal comes from the MagEnc, of which we know the CPR already */ retval = kNativePwdUnitsPerRotation; scalingAvail = true; break; case EncRising: /* Talon's QEI is setup for 1x, so perform 1x math */ case EncFalling: qeiPulsePerCount = 1; break; case QuadEncoder: /* Talon's QEI is 4x */ default: /* pulse width and everything else, assume its regular quad use. */ break; } if (scalingAvail) { /* already deduced the scalar above, we're done. */ } else { /* we couldn't deduce the scalar just based on the selection */ if (0 == m_codesPerRev) { /* caller has never set the CPR. Most likely caller is just using engineering units so fall to the bottom of this func.*/ } else { /* Talon expects PPR units */ retval = qeiPulsePerCount * m_codesPerRev; scalingAvail = true; } } } break; case EncRising: case EncFalling: if (0 == m_codesPerRev) { /* caller has never set the CPR. Most likely caller is just using engineering units so fall to the bottom of this func.*/ } else { /* Talon expects PPR units */ retval = 1 * m_codesPerRev; scalingAvail = true; } break; case AnalogPot: case AnalogEncoder: if (0 == m_numPotTurns) { /* caller has never set the CPR. Most likely caller is just using engineering units so fall to the bottom of this func.*/ } else { retval = (double)kNativeAdcUnitsPerRotation / m_numPotTurns; scalingAvail = true; } break; case CtreMagEncoder_Relative: case CtreMagEncoder_Absolute: case PulseWidth: retval = kNativePwdUnitsPerRotation; scalingAvail = true; break; } /* handle any detected errors */ if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /* if scaling information is not possible, signal caller by returning zero */ if (false == scalingAvail) retval = 0; return retval; } /** * @param fullRotations double precision value representing number of rotations of selected feedback sensor. * If user has never called the config routine for the selected sensor, then the caller * is likely passing rotations in engineering units already, in which case it is returned * as is. * @see ConfigPotentiometerTurns * @see ConfigEncoderCodesPerRev * @return fullRotations in native engineering units of the Talon SRX firmware. */ int32_t CANTalon::ScaleRotationsToNativeUnits(FeedbackDevice devToLookup,double fullRotations)const { /* first assume we don't have config info, prep the default return */ int32_t retval = (int32_t)fullRotations; /* retrieve scaling info */ double scalar = GetNativeUnitsPerRotationScalar(devToLookup); /* apply scalar if its available */ if (scalar > 0) retval = (int32_t)(fullRotations*scalar); return retval; } /** * @param rpm double precision value representing number of rotations per minute of selected feedback sensor. * If user has never called the config routine for the selected sensor, then the caller * is likely passing rotations in engineering units already, in which case it is returned * as is. * @see ConfigPotentiometerTurns * @see ConfigEncoderCodesPerRev * @return sensor velocity in native engineering units of the Talon SRX firmware. */ int32_t CANTalon::ScaleVelocityToNativeUnits(FeedbackDevice devToLookup,double rpm)const { /* first assume we don't have config info, prep the default return */ int32_t retval = (int32_t)rpm; /* retrieve scaling info */ double scalar = GetNativeUnitsPerRotationScalar(devToLookup); /* apply scalar if its available */ if (scalar > 0) retval = (int32_t)(rpm * kMinutesPer100msUnit * scalar); return retval; } /** * @param nativePos integral position of the feedback sensor in native Talon SRX units. * If user has never called the config routine for the selected sensor, then the return * will be in TALON SRX units as well to match the behavior in the 2015 season. * @see ConfigPotentiometerTurns * @see ConfigEncoderCodesPerRev * @return double precision number of rotations, unless config was never performed. */ double CANTalon::ScaleNativeUnitsToRotations(FeedbackDevice devToLookup,int32_t nativePos)const { /* first assume we don't have config info, prep the default return */ double retval = (double)nativePos; /* retrieve scaling info */ double scalar = GetNativeUnitsPerRotationScalar(devToLookup); /* apply scalar if its available */ if (scalar > 0) retval = ((double)nativePos) / scalar; return retval; } /** * @param nativeVel integral velocity of the feedback sensor in native Talon SRX units. * If user has never called the config routine for the selected sensor, then the return * will be in TALON SRX units as well to match the behavior in the 2015 season. * @see ConfigPotentiometerTurns * @see ConfigEncoderCodesPerRev * @return double precision of sensor velocity in RPM, unless config was never performed. */ double CANTalon::ScaleNativeUnitsToRpm(FeedbackDevice devToLookup, int32_t nativeVel)const { /* first assume we don't have config info, prep the default return */ double retval = (double)nativeVel; /* retrieve scaling info */ double scalar = GetNativeUnitsPerRotationScalar(devToLookup); /* apply scalar if its available */ if (scalar > 0) retval = (double)(nativeVel) / (scalar*kMinutesPer100msUnit); return retval; } /** * Enables Talon SRX to automatically zero the Sensor Position whenever an * edge is detected on the index signal. * @param enable boolean input, pass true to enable feature or false to disable. * @param risingEdge boolean input, pass true to clear the position on rising edge, * pass false to clear the position on falling edge. */ void CANTalon::EnableZeroSensorPositionOnIndex(bool enable, bool risingEdge) { if (enable) { /* enable the feature, update the edge polarity first to ensure it is correct before the feature is enabled. */ ConfigSetParameter(CanTalonSRX::eQuadIdxPolarity,risingEdge ? 1 : 0); ConfigSetParameter(CanTalonSRX::eClearPositionOnIdx,1); } else { /* disable the feature first, then update the edge polarity. */ ConfigSetParameter(CanTalonSRX::eClearPositionOnIdx,0); ConfigSetParameter(CanTalonSRX::eQuadIdxPolarity,risingEdge ? 1 : 0); } } /** * Calling application can opt to speed up the handshaking between the robot API and the Talon to increase the * download rate of the Talon's Motion Profile. Ideally the period should be no more than half the period * of a trajectory point. */ void CANTalon::ChangeMotionControlFramePeriod(int periodMs) { m_impl->ChangeMotionControlFramePeriod(periodMs); } /** * Clear the buffered motion profile in both Talon RAM (bottom), and in the API (top). * Be sure to check GetMotionProfileStatus() to know when the buffer is actually cleared. */ void CANTalon::ClearMotionProfileTrajectories() { m_impl->ClearMotionProfileTrajectories(); } /** * Retrieve just the buffer count for the api-level (top) buffer. * This routine performs no CAN or data structure lookups, so its fast and ideal * if caller needs to quickly poll the progress of trajectory points being emptied * into Talon's RAM. Otherwise just use GetMotionProfileStatus. * @return number of trajectory points in the top buffer. */ int CANTalon::GetMotionProfileTopLevelBufferCount() { return m_impl->GetMotionProfileTopLevelBufferCount(); } /** * Push another trajectory point into the top level buffer (which is emptied into * the Talon's bottom buffer as room allows). * @param trajPt the trajectory point to insert into buffer. * @return true if trajectory point push ok. CTR_BufferFull if buffer is full * due to kMotionProfileTopBufferCapacity. */ bool CANTalon::PushMotionProfileTrajectory(const TrajectoryPoint & trajPt) { /* convert positiona and velocity to native units */ int32_t targPos = ScaleRotationsToNativeUnits(m_feedbackDevice, trajPt.position); int32_t targVel = ScaleVelocityToNativeUnits(m_feedbackDevice, trajPt.velocity); /* bounds check signals that require it */ uint32_t profileSlotSelect = (trajPt.profileSlotSelect) ? 1 : 0; uint8_t timeDurMs = (trajPt.timeDurMs >= 255) ? 255 : trajPt.timeDurMs; /* cap time to 255ms */ /* send it to the top level buffer */ CTR_Code status = m_impl->PushMotionProfileTrajectory(targPos, targVel, profileSlotSelect, timeDurMs, trajPt.velocityOnly, trajPt.isLastPoint, trajPt.zeroPos); return (status == CTR_OKAY) ? true : false; } /** * @return true if api-level (top) buffer is full. */ bool CANTalon::IsMotionProfileTopLevelBufferFull() { return m_impl->IsMotionProfileTopLevelBufferFull(); } /** * This must be called periodically to funnel the trajectory points from the API's top level buffer to * the Talon's bottom level buffer. Recommendation is to call this twice as fast as the executation rate of the motion profile. * So if MP is running with 20ms trajectory points, try calling this routine every 10ms. All motion profile functions are thread-safe * through the use of a mutex, so there is no harm in having the caller utilize threading. */ void CANTalon::ProcessMotionProfileBuffer() { m_impl->ProcessMotionProfileBuffer(); } /** * Retrieve all status information. * Since this all comes from one CAN frame, its ideal to have one routine to retrieve the frame once and decode everything. * @param [out] motionProfileStatus contains all progress information on the currently running MP. */ void CANTalon::GetMotionProfileStatus(MotionProfileStatus & motionProfileStatus) { uint32_t flags; uint32_t profileSlotSelect; int32_t targPos, targVel; uint32_t topBufferRem, topBufferCnt, btmBufferCnt; uint32_t outputEnable; /* retrieve all motion profile signals from status frame */ CTR_Code status = m_impl->GetMotionProfileStatus(flags, profileSlotSelect, targPos, targVel, topBufferRem, topBufferCnt, btmBufferCnt, outputEnable); /* completely update the caller's structure */ motionProfileStatus.topBufferRem = topBufferRem; motionProfileStatus.topBufferCnt = topBufferCnt; motionProfileStatus.btmBufferCnt = btmBufferCnt; motionProfileStatus.hasUnderrun = (flags & CanTalonSRX::kMotionProfileFlag_HasUnderrun) ? true :false; motionProfileStatus.isUnderrun = (flags & CanTalonSRX::kMotionProfileFlag_IsUnderrun) ? true :false; motionProfileStatus.activePointValid = (flags & CanTalonSRX::kMotionProfileFlag_ActTraj_IsValid) ? true :false; motionProfileStatus.activePoint.isLastPoint = (flags & CanTalonSRX::kMotionProfileFlag_ActTraj_IsLast) ? true :false; motionProfileStatus.activePoint.velocityOnly = (flags & CanTalonSRX::kMotionProfileFlag_ActTraj_VelOnly) ? true :false; motionProfileStatus.activePoint.position = ScaleNativeUnitsToRotations(m_feedbackDevice, targPos); motionProfileStatus.activePoint.velocity = ScaleNativeUnitsToRpm(m_feedbackDevice, targVel); motionProfileStatus.activePoint.profileSlotSelect = profileSlotSelect; switch(outputEnable){ case CanTalonSRX::kMotionProf_Disabled: motionProfileStatus.outputEnable = SetValueMotionProfileDisable; break; case CanTalonSRX::kMotionProf_Enable: motionProfileStatus.outputEnable = SetValueMotionProfileEnable; break; case CanTalonSRX::kMotionProf_Hold: motionProfileStatus.outputEnable = SetValueMotionProfileHold; break; default: motionProfileStatus.outputEnable = SetValueMotionProfileDisable; break; } motionProfileStatus.activePoint.zeroPos = false; /* this signal is only used sending pts to Talon */ motionProfileStatus.activePoint.timeDurMs = 0; /* this signal is only used sending pts to Talon */ if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } } /** * Clear the hasUnderrun flag in Talon's Motion Profile Executer when MPE is ready for another point, * but the low level buffer is empty. * * Once the Motion Profile Executer sets the hasUnderrun flag, it stays set until * Robot Application clears it with this routine, which ensures Robot Application * gets a chance to instrument or react. Caller could also check the isUnderrun flag * which automatically clears when fault condition is removed. */ void CANTalon::ClearMotionProfileHasUnderrun() { ConfigSetParameter(CanTalonSRX::eMotionProfileHasUnderrunErr, 0); } /** * Common interface for inverting direction of a speed controller. * Only works in PercentVbus, speed, and Voltage modes. * @param isInverted The state of inversion, true is inverted. */ void CANTalon::SetInverted(bool isInverted) { m_isInverted = isInverted; } /** * Common interface for the inverting direction of a speed controller. * * @return isInverted The state of inversion, true is inverted. * */ bool CANTalon::GetInverted() const { return m_isInverted; } /** * Common interface for stopping the motor * Part of the MotorSafety interface * * @deprecated Call Disable instead. */ void CANTalon::StopMotor() { Disable(); } void CANTalon::ValueChanged(ITable* source, llvm::StringRef key, std::shared_ptr<nt::Value> value, bool isNew) { if(key == "Mode" && value->IsDouble()) SetControlMode(static_cast<CANSpeedController::ControlMode>(value->GetDouble())); if(key == "p" && value->IsDouble()) SetP(value->GetDouble()); if(key == "i" && value->IsDouble()) SetI(value->GetDouble()); if(key == "d" && value->IsDouble()) SetD(value->GetDouble()); if(key == "f" && value->IsDouble()) SetF(value->GetDouble()); if(key == "Enabled" && value->IsBoolean()) { if (value->GetBoolean()) { Enable(); } else { Disable(); } } if(key == "Value" && value->IsDouble()) Set(value->GetDouble()); } bool CANTalon::IsModePID(CANSpeedController::ControlMode mode) const { return mode == kCurrent || mode == kSpeed || mode == kPosition; } void CANTalon::UpdateTable() { if (m_table != nullptr) { m_table->PutString("~TYPE~", "CANSpeedController"); m_table->PutString("Type", "CANTalon"); m_table->PutNumber("Mode", m_controlMode); m_table->PutNumber("p", GetP()); m_table->PutNumber("i", GetI()); m_table->PutNumber("d", GetD()); m_table->PutNumber("f", GetF()); m_table->PutBoolean("Enabled", IsControlEnabled()); m_table->PutNumber("Value", Get()); } } void CANTalon::StartLiveWindowMode() { if (m_table != nullptr) { m_table->AddTableListener(this, true); } } void CANTalon::StopLiveWindowMode() { if (m_table != nullptr) { m_table->RemoveTableListener(this); } } std::string CANTalon::GetSmartDashboardType() const { return "CANSpeedController"; } void CANTalon::InitTable(std::shared_ptr<ITable> subTable) { m_table = subTable; UpdateTable(); } std::shared_ptr<ITable> CANTalon::GetTable() const { return m_table; }
34.430761
161
0.707152
flamingchickens1540
d55869b798943dce25938c135d640bf7c08d4d80
10,545
cpp
C++
PhysX_3.4/Samples/SampleFramework/framework/src/SampleCommandLine.cpp
DoubleTT-Changan/0715
acbd071531ca4f3e2a82525b92f60824178c39fa
[ "Unlicense" ]
null
null
null
PhysX_3.4/Samples/SampleFramework/framework/src/SampleCommandLine.cpp
DoubleTT-Changan/0715
acbd071531ca4f3e2a82525b92f60824178c39fa
[ "Unlicense" ]
null
null
null
PhysX_3.4/Samples/SampleFramework/framework/src/SampleCommandLine.cpp
DoubleTT-Changan/0715
acbd071531ca4f3e2a82525b92f60824178c39fa
[ "Unlicense" ]
null
null
null
// // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2019 NVIDIA Corporation. All rights reserved. #include "FrameworkFoundation.h" #include <SampleCommandLine.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include "PxTkFile.h" #include "foundation/PxAssert.h" #ifdef WIN32 #include <windows.h> #elif defined(ANDROID) typedef int errno_t; #endif #include "PsString.h" using namespace SampleFramework; namespace Ps = physx::shdfnd; static char **CommandLineToArgvA(const char *cmdLine, unsigned int &_argc) { char **argv = 0; char *_argv = 0; unsigned int len = 0; unsigned int argc = 0; char a = 0; unsigned int i = 0; unsigned int j = 0; bool in_QM = false; bool in_TEXT = false; bool in_SPACE = true; len = (unsigned int)strlen(cmdLine); i = ((len+2)/2)*sizeof(char*) + sizeof(char*); argv = (char **)malloc(i + (len+2)*sizeof(char)); _argv = (char *)(((char *)argv)+i); argv[0] = _argv; i = 0; a = cmdLine[i]; while(a) { if(in_QM) { if(a == '\"') { in_QM = false; } else { _argv[j] = a; j++; } } else { switch(a) { case '\"': in_QM = true; in_TEXT = true; if(in_SPACE) { argv[argc] = _argv+j; argc++; } in_SPACE = false; break; case ' ': case '\t': case '\n': case '\r': if(in_TEXT) { _argv[j] = '\0'; j++; } in_TEXT = false; in_SPACE = true; break; default: in_TEXT = true; if(in_SPACE) { argv[argc] = _argv+j; argc++; } _argv[j] = a; j++; in_SPACE = false; break; } } i++; a = cmdLine[i]; } _argv[j] = '\0'; argv[argc] = 0; _argc = argc; return argv; } static bool isSwitchChar(char c) { return (c == '-' || c == '/'); } namespace { void operationOK(int e) { PX_UNUSED(e); PX_ASSERT(0 == e); } const char * const * getCommandLineArgumentsFromFile(unsigned int & argc, const char * programName, const char * commandLineFilePath) { const char * const * argv = NULL; argc = 0; PX_ASSERT(NULL != programName); PX_ASSERT(NULL != commandLineFilePath); if(NULL != programName && NULL != commandLineFilePath) { File* commandLineFile = NULL; operationOK(PxToolkit::fopen_s(&commandLineFile, commandLineFilePath, "r")); if(NULL != commandLineFile) { operationOK(fseek(commandLineFile, 0, SEEK_END)); const unsigned int commandLineFileCount = static_cast<unsigned int>(ftell(commandLineFile)); rewind(commandLineFile); const unsigned int bufferCount = static_cast<unsigned int>(::strlen(programName)) + 1 + commandLineFileCount + 1; if(bufferCount > 0) { char * argsOwn = static_cast<char*>(::malloc(bufferCount)); Ps::strlcpy(argsOwn, bufferCount, programName); Ps::strlcat(argsOwn, bufferCount, " "); const unsigned int offset = static_cast<unsigned int>(::strlen(argsOwn)); PX_ASSERT((bufferCount - offset - 1) == commandLineFileCount); if(NULL != fgets(argsOwn + offset, bufferCount - offset, commandLineFile)) { argv = CommandLineToArgvA(argsOwn, argc); } ::free(argsOwn); argsOwn = NULL; } operationOK(fclose(commandLineFile)); commandLineFile = NULL; } } return argv; } } //namespace nameless SampleCommandLine::SampleCommandLine(unsigned int argc, const char * const * argv, const char * commandLineFilePathFallback) :m_argc(0) ,m_argv(NULL) ,m_freeme(NULL) ,m_argUsed(NULL) { //initially, set to use inherent command line arguments PX_ASSERT((0 != argc) && (NULL != argv) && "This class assumes argument 0 is always the executable path!"); m_argc = argc; m_argv = argv; //finalize init initCommon(commandLineFilePathFallback); } SampleCommandLine::SampleCommandLine(const char * args, const char * commandLineFilePathFallback) :m_argc(0) ,m_argv(NULL) ,m_freeme(NULL) ,m_argUsed(NULL) { //initially, set to use inherent command line arguments unsigned int argc = 0; const char * const * argvOwning = NULL; argvOwning = CommandLineToArgvA(args, argc); PX_ASSERT((0 != argc) && (NULL != argvOwning) && "This class assumes argument 0 is always the executable path!"); m_argc = argc; m_argv = argvOwning; m_freeme = const_cast<void *>(static_cast<const void *>(argvOwning)); argvOwning = NULL; //finalize init initCommon(commandLineFilePathFallback); } SampleCommandLine::~SampleCommandLine(void) { if(m_freeme) { free(m_freeme); m_freeme = NULL; } if(m_argUsed) { delete[] m_argUsed; m_argUsed = NULL; } } void SampleCommandLine::initCommon(const char * commandLineFilePathFallback) { //if available, set to use command line arguments from file const bool tryUseCommandLineArgumentsFromFile = ((1 == m_argc) && (NULL != commandLineFilePathFallback)); if(tryUseCommandLineArgumentsFromFile) { unsigned int argcFile = 0; const char * const * argvFileOwn = NULL; argvFileOwn = getCommandLineArgumentsFromFile(argcFile, m_argv[0], commandLineFilePathFallback); if((0 != argcFile) && (NULL != argvFileOwn)) { if(NULL != m_freeme) { ::free(m_freeme); m_freeme = NULL; } m_argc = argcFile; m_argv = argvFileOwn; m_freeme = const_cast<void *>(static_cast<const void *>(argvFileOwn)); argvFileOwn = NULL; } } //for tracking use-status of arguments if((0 != m_argc) && (NULL != m_argv)) { m_argUsed = new bool[m_argc]; for(unsigned int i = 0; i < m_argc; i++) { m_argUsed[i] = false; } } } unsigned int SampleCommandLine::getNumArgs(void) const { return(m_argc); } const char * SampleCommandLine::getProgramName(void) const { return(m_argv[0]); } unsigned int SampleCommandLine::unusedArgsBufSize(void) const { unsigned int bufLen = 0; for(unsigned int i = 1; i < m_argc; i++) { if((!m_argUsed[i]) && isSwitchChar(m_argv[i][0])) { bufLen += (unsigned int) strlen(m_argv[i]) + 1; // + 1 is for the space between unused args } } if(bufLen != 0) { bufLen++; // if there are unused args add a space for the '\0' char. } return(bufLen); } const char* SampleCommandLine::getUnusedArgs(char *buf, unsigned int bufSize) const { if(bufSize != 0) { buf[0] = '\0'; for(unsigned int i = 1; i < m_argc; i++) { if((!m_argUsed[i]) && isSwitchChar(m_argv[i][0])) { Ps::strlcat(buf, bufSize, m_argv[i]); Ps::strlcat(buf, bufSize, " "); } } } return(buf); } //! has a given command-line switch? // e.g. s=="foo" checks for -foo bool SampleCommandLine::hasSwitch(const char *s, unsigned int argNum) const { bool has = false; PX_ASSERT(*s); if(*s) { unsigned int n = (unsigned int) strlen(s); unsigned int firstArg; unsigned int lastArg; if(argNum != invalidArgNum) { firstArg = argNum; lastArg = argNum; } else { firstArg = 1; lastArg = (m_argc > 1) ? (m_argc - 1) : 0; } for(unsigned int i=firstArg; i<=lastArg; i++) { const char *arg = m_argv[i]; // allow switches of '/', '-', and double character versions of both. if( (isSwitchChar(*arg) && !Ps::strnicmp(arg+1, s, n) && ((arg[n+1]=='\0')||(arg[n+1]=='='))) || (isSwitchChar(*(arg+1)) && !Ps::strnicmp(arg+2, s, n) && ((arg[n+2]=='\0')||(arg[n+2]=='='))) ) { m_argUsed[i] = true; has = true; break; } } } return has; } //! gets the value of a switch... // e.g. s="foo" returns "bar" if '-foo=bar' is in the commandline. const char *SampleCommandLine::getValue(const char *s, unsigned int argNum) const { const char *value = 0; PX_ASSERT(*s); if(*s) { unsigned int firstArg; unsigned int lastArg; if(argNum != invalidArgNum) { firstArg = argNum; lastArg = argNum; } else { firstArg = 1; lastArg = m_argc - 1; } for(unsigned int i=firstArg; i<=lastArg; i++) { const char *arg = m_argv[i]; if(isSwitchChar(*arg)) { arg++; if(isSwitchChar(*arg)) // is it a double dash arg? '--' { arg++; } const char *st=s; for(; *st && *arg && toupper(*st)==toupper(*arg) && *arg!='='; st++,arg++) { } if(!*st && *arg=='=') { m_argUsed[i] = true; value = arg+1; break; } if(!*st && !*arg && ((i+1)<m_argc) && (!isSwitchChar(*m_argv[i+1]))) { m_argUsed[i] = true; value = m_argv[i+1]; break; } } } } return value; } //! if the first argument is the given command. bool SampleCommandLine::isCommand(const char *s) const { bool has = false; const char *command = getCommand(); if(command && !Ps::stricmp(command, s)) { has = true; } return has; } //! get the first argument assuming it isn't a switch. // e.g. for the command-line "myapp.exe editor -foo" it will return "editor". const char *SampleCommandLine::getCommand(void) const { const char *command = 0; if(m_argc > 1 && !isSwitchChar(*m_argv[1])) { command = m_argv[1]; } return command; } //! whether or not an argument has been read already bool SampleCommandLine::isUsed(unsigned int argNum) const { return argNum < m_argc ? m_argUsed[argNum] : false; }
24.69555
133
0.646088
DoubleTT-Changan
d55892c4dbdc01267c7edf9e587294e5ec8e2bc9
28,540
cpp
C++
src/solver/SolverNLOptGenericGeometric.cpp
nsomani/constraint-controller-library
5452b32c5b3cc4c602fb7b700bee5c950a9e0541
[ "BSD-2-Clause" ]
3
2016-10-31T08:51:09.000Z
2020-09-08T15:37:41.000Z
src/solver/SolverNLOptGenericGeometric.cpp
nsomani/constraint-controller-library
5452b32c5b3cc4c602fb7b700bee5c950a9e0541
[ "BSD-2-Clause" ]
2
2016-10-11T05:52:00.000Z
2016-12-21T15:38:08.000Z
src/solver/SolverNLOptGenericGeometric.cpp
nsomani/constraint-controller-library
5452b32c5b3cc4c602fb7b700bee5c950a9e0541
[ "BSD-2-Clause" ]
null
null
null
// //Copyright (c) 2016, Nikhil Somani //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. // //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 "SolverNLOptGenericGeometric.h" Eigen::MatrixXd SolverNLOptGenericGeometricAA::calculateNumericalDerivativeGeometric(Constraint *&constraint, Eigen::VectorXd X_iter, Eigen::VectorXd X_current) { Eigen::MatrixXd J; J.resize(constraint->getNumConstraints(),7); Eigen::VectorXd val_minus, val_plus; Eigen::VectorXd X_minus; Eigen::VectorXd X_plus; Eigen::VectorXd dX_minus; Eigen::VectorXd dX_plus; dX_minus.resize(X_iter.size()); dX_plus.resize(X_iter.size()); double eps = 1e-4; for(std::size_t dx_id = 0;dx_id < 7;++dx_id) { X_minus = X_iter; X_plus = X_iter; X_minus(dx_id) -= eps; X_plus(dx_id) += eps; X_minus.segment(3,3).normalize(); X_plus.segment(3,3).normalize(); for(std::size_t pose_id = 0;pose_id < X_iter.size()/7;++pose_id) { dX_minus.segment(pose_id*7,7) = getDelta(X_minus.segment(pose_id*7,7), X_current.segment(pose_id*7,7)); dX_plus.segment(pose_id*7,7) = getDelta(X_plus.segment(pose_id*7,7), X_current.segment(pose_id*7,7)); } val_minus = ((OperationalPositionConstraint*)constraint)->calculateConstraintValueAA(dX_minus); val_plus = ((OperationalPositionConstraint*)constraint)->calculateConstraintValueAA(dX_plus); J.block(0,dx_id,constraint->getNumConstraints(),1) = (val_plus-val_minus)/(2.0*eps); } return J; } double SolverNLOptGenericGeometricAA::optimization_function_operational(const std::vector<double> &x, std::vector<double> &grad, void *data) { SolverNLOptGenericGeometricAA* solver = (SolverNLOptGenericGeometricAA*) data; Eigen::VectorXd X_iter = Eigen::VectorXd::Map(x.data(), x.size()); Eigen::VectorXd val; val.resize(solver->num_variables_/7); for(std::size_t pose_id = 0;pose_id < solver->num_variables_/7;++pose_id) { val(pose_id) = distanceTTSS(transformFromVector(X_iter.segment(7*pose_id, 7)), transformFromVector(solver->X_current_.segment(7*pose_id, 7))); } if (!grad.empty()) { Eigen::VectorXd dX_minus, dX_plus; dX_minus.resize(7); dX_plus.resize(7); for(std::size_t pose_id = 0;pose_id < solver->num_variables_/7;++pose_id) { double eps = 1e-4; for(std::size_t dx_id = 0;dx_id < 7;++dx_id) { dX_minus = X_iter.segment(7*pose_id, 7); dX_plus = X_iter.segment(7*pose_id, 7); dX_minus(dx_id) -= eps; dX_plus(dx_id) += eps; dX_minus.segment(3,3).normalize(); dX_plus.segment(3,3).normalize(); double val_minus = distanceTTSS(transformFromVector(dX_minus.segment(7*pose_id, 7)), transformFromVector(solver->X_current_.segment(7*pose_id, 7))); double val_plus = distanceTTSS(transformFromVector(dX_plus.segment(7*pose_id, 7)), transformFromVector(solver->X_current_.segment(7*pose_id, 7))); grad[pose_id*7+dx_id] = (val_plus*val_plus-val_minus*val_minus)/(2.0*eps); } } } return val.dot(val); } void SolverNLOptGenericGeometricAA::nonlinear_inequality_constraints_operational(uint m, double* result, uint n, const double* x, double *grad, void* data) { SolverNLOptGenericGeometricAA* solver = (SolverNLOptGenericGeometricAA*) data; Eigen::VectorXd X_iter = Eigen::VectorXd::Map(x, n); std::size_t constraint_dim = 0; for(std::size_t constraint_id = 0;constraint_id < solver->constraints_.size();++constraint_id) { Eigen::VectorXd g_constraint; Eigen::MatrixXd g_constraint_derivative; Eigen::VectorXd lb; Eigen::VectorXd ub; if(solver->constraints_[constraint_id]->constraint_space == Constraint::Operational) { Eigen::VectorXd X_delta; if(solver->constraints_[constraint_id]->fixed_shape_id != solver->fixed_shape_id) { X_delta.resize(14); X_delta.segment(0,7) = getDelta(X_iter.segment(solver->constraints_[constraint_id]->constrained_shape_id*7,7), solver->X_current_.segment(solver->constraints_[constraint_id]->constrained_shape_id*7,7)); X_delta.segment(7,7) = getDelta(X_iter.segment(solver->constraints_[constraint_id]->fixed_shape_id*7,7), solver->X_current_.segment(solver->constraints_[constraint_id]->fixed_shape_id*7,7)); } else { X_delta.resize(7); X_delta = getDelta(X_iter.segment(solver->constraints_[constraint_id]->constrained_shape_id*7,7), solver->X_current_.segment(solver->constraints_[constraint_id]->constrained_shape_id*7,7)); // std::cout << X_delta.transpose() << std::endl; } g_constraint = ((OperationalPositionConstraint*)solver->constraints_[constraint_id])->calculateConstraintValueAA(X_delta); lb = solver->constraints_[constraint_id]->getLowerBounds(); ub = solver->constraints_[constraint_id]->getUpperBounds(); } if (grad != NULL) { if(solver->constraints_[constraint_id]->constraint_space == Constraint::Operational) { Eigen::VectorXd X_delta; if(solver->constraints_[constraint_id]->fixed_shape_id != solver->fixed_shape_id) { X_delta.resize(14); X_delta.segment(0,7) = getDelta(X_iter.segment(solver->constraints_[constraint_id]->constrained_shape_id*7,7), solver->X_current_.segment(solver->constraints_[constraint_id]->constrained_shape_id*7,7)); X_delta.segment(7,7) = getDelta(X_iter.segment(solver->constraints_[constraint_id]->fixed_shape_id*7,7), solver->X_current_.segment(solver->constraints_[constraint_id]->fixed_shape_id*7,7)); } else { X_delta.resize(7); X_delta = getDelta(X_iter.segment(solver->constraints_[constraint_id]->constrained_shape_id*7,7), solver->X_current_.segment(solver->constraints_[constraint_id]->constrained_shape_id*7,7)); } #ifdef NUMERICAL_DIFF g_constraint_derivative = solver->calculateNumericalDerivativeGeometric(solver->constraints_[constraint_id], X_iter, solver->X_current_); #else g_constraint_derivative = solver->constraints_[constraint_id]->calculateConstraintDerivative(X_delta); #endif } } for(std::size_t constraint_i_dim = 0;constraint_i_dim < g_constraint.size();++constraint_i_dim, ++constraint_dim) { result[2*constraint_dim] = g_constraint[constraint_i_dim]-ub(constraint_i_dim); result[2*constraint_dim+1] = -1*g_constraint[constraint_i_dim]+lb(constraint_i_dim); if (grad != NULL) { for(std::size_t variable_id = 0;variable_id < solver->num_variables_;++variable_id) { grad[(2*constraint_dim)*solver->num_variables_+variable_id] = 0; grad[(2*constraint_dim+1)*solver->num_variables_+variable_id] = 0; } for(std::size_t variable_id = 0;variable_id < 7;++variable_id) { grad[(2*constraint_dim)*solver->num_variables_+solver->constraints_[constraint_id]->constrained_shape_id*7+variable_id] = g_constraint_derivative(constraint_i_dim, variable_id); grad[(2*constraint_dim+1)*solver->num_variables_+solver->constraints_[constraint_id]->constrained_shape_id*7+variable_id] = -1*g_constraint_derivative(constraint_i_dim, variable_id); } } } } for(std::size_t pose_id = 0;pose_id < solver->num_variables_/7;++pose_id) { result[2*constraint_dim+2*pose_id] = (X_iter.segment(7*pose_id+3,3)).squaredNorm()-1; result[2*constraint_dim+2*pose_id+1] = -1*(X_iter.segment(7*pose_id+3,3)).squaredNorm()+1; if (grad != NULL) { grad[(2*constraint_dim+2*pose_id)*solver->num_variables_+0] = 0; grad[(2*constraint_dim+2*pose_id)*solver->num_variables_+1] = 0; grad[(2*constraint_dim+2*pose_id)*solver->num_variables_+2] = 0; grad[(2*constraint_dim+2*pose_id)*solver->num_variables_+3] = 2*X_iter(7*pose_id+3); grad[(2*constraint_dim+2*pose_id)*solver->num_variables_+4] = 2*X_iter(7*pose_id+4); grad[(2*constraint_dim+2*pose_id)*solver->num_variables_+5] = 2*X_iter(7*pose_id+5); grad[(2*constraint_dim+2*pose_id)*solver->num_variables_+6] = 0; grad[(2*constraint_dim+2*pose_id+1)*solver->num_variables_+0] = 0; grad[(2*constraint_dim+2*pose_id+1)*solver->num_variables_+1] = 0; grad[(2*constraint_dim+2*pose_id+1)*solver->num_variables_+2] = 0; grad[(2*constraint_dim+2*pose_id+1)*solver->num_variables_+3] = -2*X_iter(7*pose_id+3); grad[(2*constraint_dim+2*pose_id+1)*solver->num_variables_+4] = -2*X_iter(7*pose_id+4); grad[(2*constraint_dim+2*pose_id+1)*solver->num_variables_+5] = -2*X_iter(7*pose_id+5); grad[(2*constraint_dim+2*pose_id+1)*solver->num_variables_+6] = 0; } } } SolverNLOptGenericGeometricAA::SolverNLOptGenericGeometricAA(std::vector<Constraint *> &constraints, Eigen::VectorXd &X_current): constraints_(constraints), X_current_(X_current), fixed_shape_id(-1) { num_variables_ = X_current.size(); opt_ = new nlopt::opt(nlopt::LN_COBYLA, num_variables_); } Eigen::VectorXd SolverNLOptGenericGeometricAA::solve() { opt_->set_min_objective(SolverNLOptGenericGeometricAA::optimization_function_operational, this); std::vector<double> tolerances; for(std::size_t constraint_id = 0;constraint_id < constraints_.size();++constraint_id) { for(std::size_t constraint_i_dim = 0;constraint_i_dim < constraints_[constraint_id]->getNumConstraints();++constraint_i_dim) { tolerances.push_back(solver_params_.constraint_tol_); tolerances.push_back(solver_params_.constraint_tol_); } } for(std::size_t pose_id = 0;pose_id < num_variables_/7;++pose_id) { tolerances.push_back(solver_params_.constraint_tol_); tolerances.push_back(solver_params_.constraint_tol_); } std::vector<double> ub_vec, lb_vec; for(std::size_t pose_id = 0;pose_id < num_variables_/7;++pose_id) { for(std::size_t var_id = 0;var_id < 6;++var_id) { lb_vec.push_back(-1.0); ub_vec.push_back(1.0); } lb_vec.push_back(0); ub_vec.push_back(M_PI); } opt_->set_lower_bounds(lb_vec); opt_->set_upper_bounds(ub_vec); // opt_->set_stopval(solver_params_.stopval_); opt_->set_xtol_abs(solver_params_.x_tol_); opt_->set_maxtime(solver_params_.max_time_); opt_->add_inequality_mconstraint(SolverNLOptGenericGeometricAA::nonlinear_inequality_constraints_operational, this, tolerances); std::vector<double> x; x.resize(num_variables_); for(std::size_t variable_id = 0;variable_id < num_variables_;++variable_id) { // x[variable_id] = X_current_(variable_id); x[variable_id] += ((rand()%1000 - 500)/10000.0); } for(std::size_t pose_id = 0;pose_id < num_variables_/7;++pose_id) { double norm = std::sqrt(x[pose_id*7+3]*x[pose_id*7+3]+x[pose_id*7+4]*x[pose_id*7+4]+x[pose_id*7+5]*x[pose_id*7+5]); x[pose_id*7+3] /= norm; x[pose_id*7+4] /= norm; x[pose_id*7+5] /= norm; } double f_val = 0; try { nlopt::result res = opt_->optimize(x, f_val); std::cout << "optimization result:" << res << std::endl; } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } Eigen::VectorXd optimal_value = Eigen::VectorXd::Map(x.data(), x.size()); // std::cout << "optimal value: " << optimal_value.transpose() << std::endl; return optimal_value; } double SolverNLOptGenericGeometric::optimization_function_operational(const std::vector<double> &x, std::vector<double> &grad, void *data) { SolverNLOptGenericGeometric* solver = (SolverNLOptGenericGeometric*) data; Eigen::VectorXd X_iter = Eigen::VectorXd::Map(x.data(), x.size()); Eigen::VectorXd val; val.resize(solver->num_variables_/7); for(std::size_t pose_id = 0;pose_id < solver->num_variables_/7;++pose_id) { val(pose_id) = distanceTTSS(transformFromQuaternion(X_iter.segment(7*pose_id, 7)), transformFromQuaternion(solver->X_current_.segment(7*pose_id, 7))); } if (!grad.empty()) { Eigen::VectorXd dX_minus, dX_plus; dX_minus.resize(7); dX_plus.resize(7); for(std::size_t pose_id = 0;pose_id < solver->num_variables_/7;++pose_id) { double eps = 1e-6; for(std::size_t dx_id = 0;dx_id < 7;++dx_id) { dX_minus = X_iter.segment(7*pose_id, 7); dX_plus = X_iter.segment(7*pose_id, 7); dX_minus(dx_id) -= eps; dX_plus(dx_id) += eps; dX_minus.segment(3,4).normalize(); dX_plus.segment(3,4).normalize(); double val_minus = distanceTTSS(transformFromQuaternion(dX_minus.segment(7*pose_id, 7)), transformFromQuaternion(solver->X_current_.segment(7*pose_id, 7))); double val_plus = distanceTTSS(transformFromQuaternion(dX_plus.segment(7*pose_id, 7)), transformFromQuaternion(solver->X_current_.segment(7*pose_id, 7))); grad[pose_id*7+dx_id] = (val_plus*val_plus-val_minus*val_minus)/(2.0*eps); } } } return val.dot(val); } void SolverNLOptGenericGeometric::nonlinear_inequality_constraints_operational(uint m, double *result, uint n, const double *x, double *grad, void *data) { SolverNLOptGenericGeometric* solver = (SolverNLOptGenericGeometric*) data; Eigen::VectorXd X_iter = Eigen::VectorXd::Map(x, n); std::size_t constraint_dim = 0; for(std::size_t constraint_id = 0;constraint_id < solver->constraints_.size();++constraint_id) { Eigen::VectorXd g_constraint; Eigen::MatrixXd g_constraint_derivative; Eigen::VectorXd lb; Eigen::VectorXd ub; if(solver->constraints_[constraint_id]->constraint_space == Constraint::Operational) { Eigen::VectorXd X_delta; if(solver->constraints_[constraint_id]->fixed_shape_id != solver->fixed_shape_id) { X_delta.resize(14); X_delta.segment(0,7) = getDeltaQuaternion(X_iter.segment(solver->pose_vec_map[solver->constraints_[constraint_id]->constrained_shape_id]*7,7), solver->X_current_.segment(solver->pose_vec_map[solver->constraints_[constraint_id]->constrained_shape_id]*7,7)); X_delta.segment(7,7) = getDeltaQuaternion(X_iter.segment(solver->pose_vec_map[solver->constraints_[constraint_id]->fixed_shape_id]*7,7), solver->X_current_.segment(solver->pose_vec_map[solver->constraints_[constraint_id]->fixed_shape_id]*7,7)); } else { X_delta.resize(7); X_delta = getDeltaQuaternion(X_iter.segment(solver->pose_vec_map[solver->constraints_[constraint_id]->constrained_shape_id]*7,7), solver->X_current_.segment(solver->pose_vec_map[solver->constraints_[constraint_id]->constrained_shape_id]*7,7)); } g_constraint = solver->constraints_[constraint_id]->calculateConstraintValue(X_delta); lb = solver->constraints_[constraint_id]->getLowerBounds(); ub = solver->constraints_[constraint_id]->getUpperBounds(); } if (grad != NULL) { if(solver->constraints_[constraint_id]->constraint_space == Constraint::Operational) { // Eigen::VectorXd X_delta; // if(solver->constraints_[constraint_id]->fixed_shape_id != solver->fixed_shape_id) // { // X_delta.resize(14); // X_delta.segment(0,7) = getDeltaQuaternion(X_iter.segment(solver->pose_vec_map[solver->constraints_[constraint_id]->constrained_shape_id]*7,7), solver->X_current_.segment(solver->pose_vec_map[solver->constraints_[constraint_id]->constrained_shape_id]*7,7)); // X_delta.segment(7,7) = getDeltaQuaternion(X_iter.segment(solver->pose_vec_map[solver->constraints_[constraint_id]->fixed_shape_id]*7,7), solver->X_current_.segment(solver->pose_vec_map[solver->constraints_[constraint_id]->fixed_shape_id]*7,7)); // } // else // { // X_delta.resize(7); // X_delta = getDeltaQuaternion(X_iter.segment(solver->pose_vec_map[solver->constraints_[constraint_id]->constrained_shape_id]*7,7), solver->X_current_.segment(solver->pose_vec_map[solver->constraints_[constraint_id]->constrained_shape_id]*7,7)); // } #ifdef NUMERICAL_DIFF g_constraint_derivative = solver->calculateNumericalDerivativeGeometric(solver->constraints_[constraint_id], X_iter, solver->X_current_); #else g_constraint_derivative = solver->constraints_[constraint_id]->calculateConstraintDerivative(X_delta); #endif } } for(std::size_t constraint_i_dim = 0;constraint_i_dim < g_constraint.size();++constraint_i_dim, ++constraint_dim) { result[2*constraint_dim] = g_constraint[constraint_i_dim]-ub(constraint_i_dim); result[2*constraint_dim+1] = -1*g_constraint[constraint_i_dim]+lb(constraint_i_dim); if (grad != NULL) { // for(std::size_t variable_id = 0;variable_id < solver->num_variables_;++variable_id) // { // grad[(2*constraint_dim)*solver->num_variables_+variable_id] = 0; // grad[(2*constraint_dim+1)*solver->num_variables_+variable_id] = 0; // } for(std::size_t variable_id = 0;variable_id < solver->num_variables_;++variable_id) { grad[(2*constraint_dim)*solver->num_variables_+variable_id] = g_constraint_derivative(constraint_i_dim, variable_id); grad[(2*constraint_dim+1)*solver->num_variables_+variable_id] = -1*g_constraint_derivative(constraint_i_dim, variable_id); } } } } for(std::size_t pose_id = 0;pose_id < solver->num_variables_/7;++pose_id) { result[2*constraint_dim+2*pose_id] = (X_iter.segment(7*pose_id+3,4)).squaredNorm()-1; result[2*constraint_dim+2*pose_id+1] = -1*(X_iter.segment(7*pose_id+3,4)).squaredNorm()+1; if (grad != NULL) { grad[(2*constraint_dim+2*pose_id)*solver->num_variables_+0] = 0; grad[(2*constraint_dim+2*pose_id)*solver->num_variables_+1] = 0; grad[(2*constraint_dim+2*pose_id)*solver->num_variables_+2] = 0; grad[(2*constraint_dim+2*pose_id)*solver->num_variables_+3] = 2*X_iter(7*pose_id+3); grad[(2*constraint_dim+2*pose_id)*solver->num_variables_+4] = 2*X_iter(7*pose_id+4); grad[(2*constraint_dim+2*pose_id)*solver->num_variables_+5] = 2*X_iter(7*pose_id+5); grad[(2*constraint_dim+2*pose_id)*solver->num_variables_+6] = 2*X_iter(7*pose_id+6); grad[(2*constraint_dim+2*pose_id+1)*solver->num_variables_+0] = 0; grad[(2*constraint_dim+2*pose_id+1)*solver->num_variables_+1] = 0; grad[(2*constraint_dim+2*pose_id+1)*solver->num_variables_+2] = 0; grad[(2*constraint_dim+2*pose_id+1)*solver->num_variables_+3] = -2*X_iter(7*pose_id+3); grad[(2*constraint_dim+2*pose_id+1)*solver->num_variables_+4] = -2*X_iter(7*pose_id+4); grad[(2*constraint_dim+2*pose_id+1)*solver->num_variables_+5] = -2*X_iter(7*pose_id+5); grad[(2*constraint_dim+2*pose_id+1)*solver->num_variables_+6] = -2*X_iter(7*pose_id+6); } } } SolverNLOptGenericGeometric::SolverNLOptGenericGeometric(std::vector<Constraint *> &constraints, Eigen::VectorXd &X_current): constraints_(constraints), X_current_(X_current), fixed_shape_id(0) { num_variables_ = X_current.size(); for(std::size_t pose_id = 0;pose_id < num_variables_/7;++pose_id) { pose_vec_map.insert(std::pair<int, int> (pose_id, pose_id)); } opt_ = new nlopt::opt(nlopt::LD_SLSQP, num_variables_); } Eigen::VectorXd SolverNLOptGenericGeometric::solve() { opt_->set_min_objective(SolverNLOptGenericGeometric::optimization_function_operational, this); std::vector<double> tolerances; for(std::size_t constraint_id = 0;constraint_id < constraints_.size();++constraint_id) { for(std::size_t constraint_i_dim = 0;constraint_i_dim < constraints_[constraint_id]->getNumConstraints();++constraint_i_dim) { tolerances.push_back(solver_params_.constraint_tol_); tolerances.push_back(solver_params_.constraint_tol_); } } for(std::size_t pose_id = 0;pose_id < num_variables_/7;++pose_id) { tolerances.push_back(solver_params_.constraint_tol_); tolerances.push_back(solver_params_.constraint_tol_); } std::vector<double> ub_vec, lb_vec; for(std::size_t pose_id = 0;pose_id < num_variables_/7;++pose_id) { for(std::size_t var_id = 0;var_id < 7;++var_id) { lb_vec.push_back(-1.0); ub_vec.push_back(1.0); } } opt_->set_lower_bounds(lb_vec); opt_->set_upper_bounds(ub_vec); opt_->set_stopval(solver_params_.stopval_); opt_->set_xtol_abs(solver_params_.x_tol_); opt_->set_maxtime(solver_params_.max_time_); opt_->add_inequality_mconstraint(SolverNLOptGenericGeometric::nonlinear_inequality_constraints_operational, this, tolerances); std::vector<double> x; x.resize(num_variables_); for(std::size_t variable_id = 0;variable_id < num_variables_;++variable_id) { // x[variable_id] = ((rand()%1000 - 500)/1000.0); x[variable_id] = X_current_(variable_id); } for(std::size_t pose_id = 0;pose_id < num_variables_/7;++pose_id) { double norm = std::sqrt(x[pose_id*7+3]*x[pose_id*7+3]+x[pose_id*7+4]*x[pose_id*7+4]+x[pose_id*7+5]*x[pose_id*7+5]+x[pose_id*7+6]*x[pose_id*7+6]); x[pose_id*7+3] /= norm; x[pose_id*7+4] /= norm; x[pose_id*7+5] /= norm; x[pose_id*7+6] /= norm; } double f_val = 0; try { nlopt::result res = opt_->optimize(x, f_val); std::cout << "optimization result:" << res << std::endl; } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } Eigen::VectorXd optimal_value = Eigen::VectorXd::Map(x.data(), x.size()); // std::cout << "optimal value: " << optimal_value.transpose() << std::endl; Eigen::VectorXd X_iter = optimal_value; for(std::size_t constraint_id = 0;constraint_id < constraints_.size();++constraint_id) { Eigen::VectorXd g_constraint; Eigen::VectorXd lb = constraints_[constraint_id]->getLowerBounds(); Eigen::VectorXd ub = constraints_[constraint_id]->getUpperBounds(); Eigen::VectorXd X_delta; if(constraints_[constraint_id]->fixed_shape_id != fixed_shape_id) { X_delta.resize(14); X_delta.segment(0,7) = getDeltaQuaternion(X_iter.segment(pose_vec_map[constraints_[constraint_id]->constrained_shape_id]*7,7), X_current_.segment(pose_vec_map[constraints_[constraint_id]->constrained_shape_id]*7,7)); X_delta.segment(7,7) = getDeltaQuaternion(X_iter.segment(pose_vec_map[constraints_[constraint_id]->fixed_shape_id]*7,7), X_current_.segment(pose_vec_map[constraints_[constraint_id]->fixed_shape_id]*7,7)); } else { X_delta.resize(7); X_delta = getDeltaQuaternion(X_iter.segment(pose_vec_map[constraints_[constraint_id]->constrained_shape_id]*7,7), X_current_.segment(pose_vec_map[constraints_[constraint_id]->constrained_shape_id]*7,7)); } g_constraint = constraints_[constraint_id]->calculateConstraintValue(X_delta); std::cout << constraints_[constraint_id]->constraint_name << ":" << lb.transpose() << " < " << g_constraint.transpose() << " < " << ub.transpose() << std::endl; } return optimal_value; } Eigen::MatrixXd SolverNLOptGenericGeometric::calculateNumericalDerivativeGeometric(Constraint *&constraint, Eigen::VectorXd X_iter, Eigen::VectorXd X_current) { Eigen::MatrixXd J; J.resize(constraint->getNumConstraints(), X_iter.size()); J.setZero(); Eigen::VectorXd val_minus, val_plus; Eigen::VectorXd X_minus; Eigen::VectorXd X_plus; Eigen::VectorXd dX_minus; Eigen::VectorXd dX_plus; double eps = 1e-6; for(std::size_t pose_id = 0;pose_id < X_iter.size()/7;++pose_id) { if(pose_id != pose_vec_map[constraint->constrained_shape_id] && pose_id != pose_vec_map[constraint->fixed_shape_id]) continue; for(std::size_t dx_id = 0;dx_id < 7;++dx_id) { X_minus = X_iter; X_plus = X_iter; X_minus(pose_id*7+dx_id) -= eps; X_plus(pose_id*7+dx_id) += eps; X_minus.segment(pose_id*7+3,4).normalize(); X_plus.segment(pose_id*7+3,4).normalize(); if(constraint->fixed_shape_id != fixed_shape_id) { dX_plus.resize(14); dX_plus.segment(0,7) = getDeltaQuaternion(X_plus.segment(pose_vec_map[constraint->constrained_shape_id]*7,7), X_current.segment(pose_vec_map[constraint->constrained_shape_id]*7,7)); dX_plus.segment(7,7) = getDeltaQuaternion(X_plus.segment(pose_vec_map[constraint->fixed_shape_id]*7,7), X_current.segment(pose_vec_map[constraint->fixed_shape_id]*7,7)); dX_minus.resize(14); dX_minus.segment(0,7) = getDeltaQuaternion(X_minus.segment(pose_vec_map[constraint->constrained_shape_id]*7,7), X_current.segment(pose_vec_map[constraint->constrained_shape_id]*7,7)); dX_minus.segment(7,7) = getDeltaQuaternion(X_minus.segment(pose_vec_map[constraint->fixed_shape_id]*7,7), X_current.segment(pose_vec_map[constraint->fixed_shape_id]*7,7)); } else { dX_plus.resize(7); dX_plus = getDeltaQuaternion(X_plus.segment(pose_vec_map[constraint->constrained_shape_id]*7,7), X_current.segment(pose_vec_map[constraint->constrained_shape_id]*7,7)); dX_minus.resize(7); dX_minus = getDeltaQuaternion(X_minus.segment(pose_vec_map[constraint->constrained_shape_id]*7,7), X_current.segment(pose_vec_map[constraint->constrained_shape_id]*7,7)); } val_minus = constraint->calculateConstraintValue(dX_minus); val_plus = constraint->calculateConstraintValue(dX_plus); J.block(0,pose_id*7+dx_id,constraint->getNumConstraints(),1) = (val_plus-val_minus)/(2.0*eps); } } return J; }
52.080292
278
0.659215
nsomani
d55929d6c571f2c6846b82bad79d8e4002112bbf
21,078
cpp
C++
deps/usr/src/libwav/libwav/PaTask.cpp
xia-lixun/Libaudio.jl
0e3b60d2d7c3e73f9741e7ab8721c213a9b4bf2d
[ "MIT" ]
4
2018-09-27T13:09:53.000Z
2022-02-14T12:25:29.000Z
deps/usr/src/libwav/libwav/PaTask.cpp
xia-lixun/Libaudio.jl
0e3b60d2d7c3e73f9741e7ab8721c213a9b4bf2d
[ "MIT" ]
null
null
null
deps/usr/src/libwav/libwav/PaTask.cpp
xia-lixun/Libaudio.jl
0e3b60d2d7c3e73f9741e7ab8721c213a9b4bf2d
[ "MIT" ]
null
null
null
/** @file PaTask.cpp @ingroup PaDynamic @brief Portaudio wrapper for dynamic languages: Julia/Matlab etc. @author Lixun Xia <lixun.xia2@harman.com> */ #include <cstdio> #include <cstdlib> #include <cmath> #include <string> #include <cassert> #include "./CsWav.h" #include "../include/portaudio.h" #include "../include/pa_asio.h" #include "./PaTask.h" #define FRAMES_PER_BUFFER (64) class PaPlayRecord { public: PaPlayRecord( std::string path_to_play, std::string path_to_record, size_t process_sample_rate, size_t channels, size_t bits_per_sample ) : stream(0), mic_cntframes(0), mic_dat(NULL), spk_frame(0) { //init playback wav source size_t head_bytes = spk_wav.ExtractMetaInfo(path_to_play.c_str()); spk_wav.PrintMetaInfo(); assert(spk_wav.GetSampleRate() == process_sample_rate); sample_rate = process_sample_rate; spk_totsps = spk_wav.GetFrameLength() * spk_wav.GetNumChannel(); spk_dat = spk_wav.GetFrameMatrix(path_to_play.c_str()); //init recording wav source bits_persample = bits_per_sample; path_written = path_to_record; mic_channels = channels; mic_totframes = spk_wav.GetFrameLength(); mic_dat = mic_wav.SetFrameMatrix(mic_totframes, mic_channels, sample_rate); assert(mic_dat != NULL); //log status string sprintf(message, "ctor ok"); } bool open(PaDeviceIndex index) { PaStreamParameters inputParameters; PaStreamParameters outputParameters; inputParameters.device = index; outputParameters.device = index; if (outputParameters.device == paNoDevice) return false; if (inputParameters.device == paNoDevice) return false; const PaDeviceInfo* pInfo = Pa_GetDeviceInfo(index); if (pInfo != 0) printf("Output device name: '%s'\r", pInfo->name); outputParameters.channelCount = (int)(spk_wav.GetNumChannel()); /* dependes on the wav file */ outputParameters.sampleFormat = paFloat32; /* CsWav will alway ensure 32 bit float format */ outputParameters.suggestedLatency = Pa_GetDeviceInfo(outputParameters.device)->defaultLowOutputLatency; outputParameters.hostApiSpecificStreamInfo = NULL; inputParameters.channelCount = (int)(mic_channels); /* dependes on the wav file */ inputParameters.sampleFormat = paFloat32; /* CsWav will alway ensure 32 bit float format */ inputParameters.suggestedLatency = Pa_GetDeviceInfo(inputParameters.device)->defaultLowOutputLatency; inputParameters.hostApiSpecificStreamInfo = NULL; //frames per buffer can also be "paFramesPerBufferUnspecified" //Using 'this' for userData so we can cast to PaPlay* in paCallback method if (paNoError != Pa_OpenStream(&stream, &inputParameters, &outputParameters, sample_rate, FRAMES_PER_BUFFER, paClipOff, &PaPlayRecord::paCallback, this)) return false; if (paNoError != Pa_SetStreamFinishedCallback(stream, &PaPlayRecord::paStreamFinished)) { Pa_CloseStream(stream); stream = 0; return false; } return true; } bool info() { if (stream == 0) return false; const PaStreamInfo * stream_info = Pa_GetStreamInfo(stream); printf("PaStreamInfo: struct version = %d\n", stream_info->structVersion); printf("PaStreamInfo: input latency = %f second\n", stream_info->inputLatency); printf("PaStreamInfo: output latency = %f second\n", stream_info->outputLatency); printf("PaStreamInfo: sample rate = %f sps\n", stream_info->sampleRate); return paNoError; } bool close() { if (stream == 0) return false; PaError err = Pa_CloseStream(stream); stream = 0; return (err == paNoError); } bool start() { if (stream == 0) return false; PaError err = Pa_StartStream(stream); return (err == paNoError); } bool pending() { if (stream == 0) return false; printf("\n"); while (Pa_IsStreamActive(stream)) { printf("\rcpu load:[%f], patime[%f]", cpuload, timebase); fflush(stdout); Pa_Sleep(250); } return paNoError; } bool stop() { if (stream == 0) return false; PaError err = Pa_StopStream(stream); return (err == paNoError); } size_t save() { size_t bytes_written = mic_wav.SaveFile(path_written.c_str(), bits_persample); return bytes_written; } volatile double cpuload; volatile PaTime timebase; private: /* The instance callback, where we have access to every method/variable in object of class PaPlay */ int paCallbackMethod( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags) { const float *in = (const float *)inputBuffer; float *out = (float*)outputBuffer; unsigned long i; (void)timeInfo; /* Prevent unused variable warnings. */ (void)statusFlags; for (i = 0; i < framesPerBuffer; i++) { memcpy(out, &spk_dat[spk_frame], spk_wav.GetNumChannel() * sizeof(float)); memcpy(mic_dat, in, mic_channels * sizeof(float)); out += ((int)(spk_wav.GetNumChannel())); spk_frame += (spk_wav.GetNumChannel()); in += ((int)mic_channels); mic_dat += ((int)mic_channels); mic_cntframes += 1; //for sentinel and verification only if (spk_frame >= spk_totsps) { assert(mic_cntframes == mic_totframes); memset(out, 0, (framesPerBuffer - i - 1) * (spk_wav.GetNumChannel()) * sizeof(float)); spk_frame = 0; mic_cntframes = 0; return paComplete; } } //update utility features cpuload = Pa_GetStreamCpuLoad(stream); timebase = Pa_GetStreamTime(stream); return paContinue; } /* This routine will be called by the PortAudio engine when audio is needed. ** It may called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ static int paCallback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void *userData) { /* Here we cast userData to PaPlay* type so we can call the instance method paCallbackMethod, we can do that since we called Pa_OpenStream with 'this' for userData */ return ((PaPlayRecord*)userData)->paCallbackMethod(inputBuffer, outputBuffer, framesPerBuffer, timeInfo, statusFlags); } void paStreamFinishedMethod() { printf("Stream Completed: %s\n", message); } /* * This routine is called by portaudio when playback is done. */ static void paStreamFinished(void* userData) { return ((PaPlayRecord*)userData)->paStreamFinishedMethod(); } //record std::string path_written; size_t bits_persample; CsWav mic_wav; float *mic_dat; size_t mic_channels; size_t mic_cntframes; size_t mic_totframes; size_t sample_rate; //play CsWav spk_wav; const float *spk_dat; size_t spk_frame; size_t spk_totsps; PaStream *stream; char message[20]; }; class PaRecord { public: PaRecord( std::string path_to_record, size_t process_sample_rate, size_t channels, double recording_time, size_t bits_per_sample ) : stream(0), mic_cntframes(0), mic_dat(NULL) { //init recording wav source bits_persample = bits_per_sample; path_written = path_to_record; mic_channels = channels; sample_rate = process_sample_rate; mic_totframes = (size_t)std::ceil(recording_time * (double)sample_rate); mic_dat = mic_wav.SetFrameMatrix(mic_totframes, mic_channels, sample_rate); assert(mic_dat != NULL); //log status string sprintf(message, "ctor ok"); } bool open(PaDeviceIndex index) { PaStreamParameters inputParameters; inputParameters.device = index; if (inputParameters.device == paNoDevice) return false; const PaDeviceInfo* pInfo = Pa_GetDeviceInfo(index); if (pInfo != 0) printf("Output device name: '%s'\r", pInfo->name); inputParameters.channelCount = (int)(mic_channels); /* dependes on the wav file */ inputParameters.sampleFormat = paFloat32; /* CsWav will alway ensure 32 bit float format */ inputParameters.suggestedLatency = Pa_GetDeviceInfo(inputParameters.device)->defaultLowOutputLatency; inputParameters.hostApiSpecificStreamInfo = NULL; //frames per buffer can also be "paFramesPerBufferUnspecified" //Using 'this' for userData so we can cast to PaPlay* in paCallback method if (paNoError != Pa_OpenStream(&stream, &inputParameters, NULL, sample_rate, FRAMES_PER_BUFFER, paClipOff, &PaRecord::paCallback, this)) return false; if (paNoError != Pa_SetStreamFinishedCallback(stream, &PaRecord::paStreamFinished)) { Pa_CloseStream(stream); stream = 0; return false; } return true; } bool info() { if (stream == 0) return false; const PaStreamInfo * stream_info = Pa_GetStreamInfo(stream); printf("PaStreamInfo: struct version = %d\n", stream_info->structVersion); printf("PaStreamInfo: input latency = %f second\n", stream_info->inputLatency); printf("PaStreamInfo: output latency = %f second\n", stream_info->outputLatency); printf("PaStreamInfo: sample rate = %f sps\n", stream_info->sampleRate); return paNoError; } bool close() { if (stream == 0) return false; PaError err = Pa_CloseStream(stream); stream = 0; return (err == paNoError); } bool start() { if (stream == 0) return false; PaError err = Pa_StartStream(stream); return (err == paNoError); } bool pending() { if (stream == 0) return false; printf("\n"); while (Pa_IsStreamActive(stream)) { printf("\rcpu load:[%f], patime[%f]", cpuload, timebase); fflush(stdout); Pa_Sleep(250); } return paNoError; } bool stop() { if (stream == 0) return false; PaError err = Pa_StopStream(stream); return (err == paNoError); } size_t save() { size_t bytes_written = mic_wav.SaveFile(path_written.c_str(), bits_persample); return bytes_written; } volatile double cpuload; volatile PaTime timebase; private: /* The instance callback, where we have access to every method/variable in object of class PaPlay */ int paCallbackMethod( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags) { const float *in = (const float *)inputBuffer; unsigned long i; (void)timeInfo; /* Prevent unused variable warnings. */ (void)statusFlags; (void)outputBuffer; for (i = 0; i < framesPerBuffer; i++) { memcpy(mic_dat, in, mic_channels * sizeof(float)); in += (int)mic_channels; mic_dat += (int)mic_channels; mic_cntframes += 1; if (mic_cntframes >= mic_totframes) { mic_cntframes = 0; return paComplete; } } //update utility features cpuload = Pa_GetStreamCpuLoad(stream); timebase = Pa_GetStreamTime(stream); return paContinue; } /* This routine will be called by the PortAudio engine when audio is needed. ** It may called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ static int paCallback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void *userData) { /* Here we cast userData to PaPlay* type so we can call the instance method paCallbackMethod, we can do that since we called Pa_OpenStream with 'this' for userData */ return ((PaRecord*)userData)->paCallbackMethod(inputBuffer, outputBuffer, framesPerBuffer, timeInfo, statusFlags); } void paStreamFinishedMethod() { printf("Stream Completed: %s\n", message); } /* * This routine is called by portaudio when playback is done. */ static void paStreamFinished(void* userData) { return ((PaRecord*)userData)->paStreamFinishedMethod(); } std::string path_written; size_t bits_persample; CsWav mic_wav; float *mic_dat; size_t mic_channels; size_t mic_cntframes; size_t mic_totframes; size_t sample_rate; PaStream *stream; char message[20]; }; class PaPlay { public: PaPlay( std::string path_to_play, size_t process_sample_rate //int * out_channel_select, //int out_channels ) : stream(0), spk_frame(0) { //init playback wav source size_t head_bytes = spk_wav.ExtractMetaInfo(path_to_play.c_str()); spk_wav.PrintMetaInfo(); assert(spk_wav.GetSampleRate() == process_sample_rate); sample_rate = process_sample_rate; spk_totsps = spk_wav.GetFrameLength() * spk_wav.GetNumChannel(); //load the playback data from the wav spk_dat = spk_wav.GetFrameMatrix(path_to_play.c_str()); //routing infomation //memcpy(outputChannelSelectors, out_channel_select, out_channels * sizeof(int)); //log status string sprintf( message, "ctor ok" ); } bool open(PaDeviceIndex index) { PaStreamParameters outputParameters; outputParameters.device = index; if (outputParameters.device == paNoDevice) return false; const PaDeviceInfo* pInfo = Pa_GetDeviceInfo(index); if (pInfo != 0) printf("Output device name: '%s'\r", pInfo->name); outputParameters.channelCount = (int)(spk_wav.GetNumChannel()); /* dependes on the wav file */ outputParameters.sampleFormat = paFloat32; /* CsWav will alway ensure 32 bit float format */ outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; outputParameters.hostApiSpecificStreamInfo = NULL; /* Use an ASIO specific structure. WARNING - this is not portable. */ //asioOutputInfo.size = sizeof(PaAsioStreamInfo); //asioOutputInfo.hostApiType = paASIO; //asioOutputInfo.version = 1; //asioOutputInfo.flags = paAsioUseChannelSelectors; ////outputChannelSelectors[0] = 1; /* skip channel 0 and use the second (right) ASIO device channel */ //asioOutputInfo.channelSelectors = outputChannelSelectors; //outputParameters.hostApiSpecificStreamInfo = &asioOutputInfo; //frames per buffer can also be "paFramesPerBufferUnspecified" //Using 'this' for userData so we can cast to PaPlay* in paCallback method if (paNoError != Pa_OpenStream(&stream, NULL, &outputParameters, sample_rate, FRAMES_PER_BUFFER, paClipOff, &PaPlay::paCallback, this)) return false; if (paNoError != Pa_SetStreamFinishedCallback(stream, &PaPlay::paStreamFinished)) { Pa_CloseStream( stream ); stream = 0; return false; } return true; } bool info() { if (stream == 0) return false; const PaStreamInfo * stream_info = Pa_GetStreamInfo(stream); printf("PaStreamInfo: struct version = %d\n", stream_info->structVersion); printf("PaStreamInfo: input latency = %f second\n", stream_info->inputLatency); printf("PaStreamInfo: output latency = %f second\n", stream_info->outputLatency); printf("PaStreamInfo: sample rate = %f sps\n", stream_info->sampleRate); return paNoError; } bool close() { if (stream == 0) return false; PaError err = Pa_CloseStream( stream ); stream = 0; return (err == paNoError); } bool start() { if (stream == 0) return false; PaError err = Pa_StartStream( stream ); return (err == paNoError); } bool pending() { if (stream == 0) return false; printf("\n"); while (Pa_IsStreamActive(stream)) { printf("\rcpu load:[%f], patime[%f]", cpuload, timebase); fflush(stdout); Pa_Sleep(250); } return paNoError; } bool stop() { if (stream == 0) return false; PaError err = Pa_StopStream( stream ); return (err == paNoError); } volatile double cpuload; volatile PaTime timebase; private: /* The instance callback, where we have access to every method/variable in object of class PaPlay */ int paCallbackMethod( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags) { float *out = (float*)outputBuffer; unsigned long i; (void) timeInfo; /* Prevent unused variable warnings. */ (void) statusFlags; (void) inputBuffer; for( i = 0; i < framesPerBuffer; i++ ) { memcpy(out, &spk_dat[spk_frame], spk_wav.GetNumChannel() * sizeof(float)); out += ((int)(spk_wav.GetNumChannel())); spk_frame += (spk_wav.GetNumChannel()); if (spk_frame >= spk_totsps) { memset(out, 0, (framesPerBuffer-i-1) * (spk_wav.GetNumChannel()) * sizeof(float)); spk_frame = 0; return paComplete; } } //update utility features cpuload = Pa_GetStreamCpuLoad(stream); timebase = Pa_GetStreamTime(stream); return paContinue; } /* This routine will be called by the PortAudio engine when audio is needed. ** It may called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ static int paCallback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void *userData ) { /* Here we cast userData to PaPlay* type so we can call the instance method paCallbackMethod, we can do that since we called Pa_OpenStream with 'this' for userData */ return ((PaPlay*)userData)->paCallbackMethod(inputBuffer, outputBuffer, framesPerBuffer, timeInfo, statusFlags); } void paStreamFinishedMethod() { printf( "Stream Completed: %s\n", message ); } /* * This routine is called by portaudio when playback is done. */ static void paStreamFinished(void* userData) { return ((PaPlay*)userData)->paStreamFinishedMethod(); } CsWav spk_wav; const float *spk_dat; size_t spk_frame; size_t spk_totsps; //PaAsioStreamInfo asioOutputInfo; //int outputChannelSelectors[MAX_SPEAKER_IO]; size_t sample_rate; PaStream *stream; char message[20]; }; class ScopedPaHandler { public: ScopedPaHandler() : _result(Pa_Initialize()) { } ~ScopedPaHandler() { if (_result == paNoError) Pa_Terminate(); } PaError result() const { return _result; } private: PaError _result; }; /*******************************************************************/ //int main(void); //int main(void) int playrecord(const char * path_play, const char * path_record, int sample_rate, int channels_record, int bits_record) { printf("PortAudio Test: I/O PaPlay and PaRecord. SR = %d, BufSize = %d\n", 48000, FRAMES_PER_BUFFER); std::string spath(path_play); std::string rpath(path_record); PaPlayRecord PaPlayRecord(spath, rpath, sample_rate, channels_record, bits_record); ScopedPaHandler paInit; if (paInit.result() != paNoError) goto error; if (PaPlayRecord.open(Pa_GetDefaultOutputDevice())) { PaPlayRecord.info(); if (PaPlayRecord.start()) { PaPlayRecord.pending(); PaPlayRecord.stop(); PaPlayRecord.save(); } PaPlayRecord.close(); } return paNoError; error: fprintf(stderr, "An error occured while using the portaudio stream\n"); fprintf(stderr, "Error number: %d\n", paInit.result()); fprintf(stderr, "Error message: %s\n", Pa_GetErrorText(paInit.result())); return 1; } int play(const char * path, int sample_rate) { printf("PortAudio Test: output PaPlay wave. SR = %d, BufSize = %d\n", 48000, FRAMES_PER_BUFFER); //PaPlay PaPlay("D:\\pa_stable_v190600_20161030\\PaDynamic\\8_Channel_ID.wav", 48000); std::string spath(path); PaPlay PaPlay(spath, sample_rate); ScopedPaHandler paInit; if( paInit.result() != paNoError ) goto error; if (PaPlay.open(Pa_GetDefaultOutputDevice())) { PaPlay.info(); if (PaPlay.start()) { PaPlay.pending(); PaPlay.stop(); } PaPlay.close(); } return paNoError; error: fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", paInit.result() ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( paInit.result() ) ); return 1; } int record(const char * path, int sample_rate, int channels, double duration, int bits) { printf("PortAudio Test: input PaRecord wave. SR = %d, BufSize = %d\n", 48000, FRAMES_PER_BUFFER); std::string rpath(path); PaRecord PaRecord(rpath, sample_rate, channels, duration, bits); ScopedPaHandler paInit; if (paInit.result() != paNoError) goto error; if (PaRecord.open(Pa_GetDefaultOutputDevice())) { PaRecord.info(); if (PaRecord.start()) { PaRecord.pending(); PaRecord.stop(); PaRecord.save(); } PaRecord.close(); } return paNoError; error: fprintf(stderr, "An error occured while using the portaudio stream\n"); fprintf(stderr, "Error number: %d\n", paInit.result()); fprintf(stderr, "Error message: %s\n", Pa_GetErrorText(paInit.result())); return 1; }
27.023077
155
0.691384
xia-lixun
d559b5cd6fef87a9e6b8f1d147e33a79f6724e0f
3,025
cpp
C++
Visual Mercutio/zModelWeb/PSS_PublishModelAttributesDialog.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
1
2022-01-31T06:24:24.000Z
2022-01-31T06:24:24.000Z
Visual Mercutio/zModelWeb/PSS_PublishModelAttributesDialog.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-04-11T15:50:42.000Z
2021-06-05T08:23:04.000Z
Visual Mercutio/zModelWeb/PSS_PublishModelAttributesDialog.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-01-08T00:55:18.000Z
2022-01-31T06:24:18.000Z
/**************************************************************************** * ==> PSS_PublishModelAttributesDialog ------------------------------------* **************************************************************************** * Description : Dialog box allowing to select the model attributes to * * publish * * Developer : Processsoft * ****************************************************************************/ #include "StdAfx.h" #include "PSS_PublishModelAttributesDialog.h" // processsoft #include "zBaseLib\PSS_MsgBox.h" #include "zProperty\PSS_PropertyAttributes.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif //--------------------------------------------------------------------------- // Message loop //--------------------------------------------------------------------------- BEGIN_MESSAGE_MAP(PSS_PublishModelAttributesDialog, PSS_WizardDialog) //{{AFX_MSG_MAP(PSS_PublishModelAttributesDialog) //}}AFX_MSG_MAP END_MESSAGE_MAP() //--------------------------------------------------------------------------- // PSS_PublishModelAttributesDialog //--------------------------------------------------------------------------- PSS_PublishModelAttributesDialog::PSS_PublishModelAttributesDialog(PSS_PropertyAttributes* pPropAttributes, PSS_Properties::IPropertySet* pPropSet, CWnd* pParent) : PSS_WizardDialog(PSS_PublishModelAttributesDialog::IDD, IDB_WZBMP1, 0, 0, IDS_PUBLISHMODELATTRIBUTES_S, IDS_PUBLISHMODELATTRIBUTES_T), m_pPropAttributes(pPropAttributes), m_pPropSet(pPropSet) {} //--------------------------------------------------------------------------- void PSS_PublishModelAttributesDialog::DoDataExchange(CDataExchange* pDX) { PSS_WizardDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(PSS_PublishModelAttributesDialog) DDX_Control(pDX, IDC_HTMLATTRIBUTE_TREE, m_Attributes); //}}AFX_DATA_MAP } //--------------------------------------------------------------------------- BOOL PSS_PublishModelAttributesDialog::OnInitDialog() { PSS_WizardDialog::OnInitDialog(); // initialize the attribute tree control m_Attributes.Initialize(m_pPropAttributes,m_pPropSet); // return TRUE unless the focus was set to a control. NOTE OCX property pages should return FALSE return TRUE; } //--------------------------------------------------------------------------- void PSS_PublishModelAttributesDialog::OnOK() { UpdateData(); m_Attributes.FillMatchingCheckedItems(); PSS_WizardDialog::OnOK(); } //---------------------------------------------------------------------------
41.438356
113
0.45157
Jeanmilost
d55b4373474c1e05d6c225ee76f3da0c0512a2a9
292
cpp
C++
src/cli/dmain.cpp
gasteve/bitcoin
b5e79be9e7612c31403a2231ba03850f495ea9c1
[ "MIT" ]
1
2017-05-18T17:12:00.000Z
2017-05-18T17:12:00.000Z
src/cli/dmain.cpp
gasteve/bitcoin
b5e79be9e7612c31403a2231ba03850f495ea9c1
[ "MIT" ]
null
null
null
src/cli/dmain.cpp
gasteve/bitcoin
b5e79be9e7612c31403a2231ba03850f495ea9c1
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////////////// // // Start bitcoind // #include "init.h" #include "util.h" int main(int argc, char* argv[]) { bool fRet = false; fRet = AppInit(argc, argv); if (fRet && fDaemon) return 0; return 1; }
15.368421
78
0.40411
gasteve
f65d0b82e98790b2167c2e146333049a0f240dbe
10,979
cpp
C++
src/qos/qos_event_manager.cpp
hsungyang/poseidonos
0f523b36ccf0d70726364395ea96ac6ae3b845c3
[ "BSD-3-Clause" ]
null
null
null
src/qos/qos_event_manager.cpp
hsungyang/poseidonos
0f523b36ccf0d70726364395ea96ac6ae3b845c3
[ "BSD-3-Clause" ]
null
null
null
src/qos/qos_event_manager.cpp
hsungyang/poseidonos
0f523b36ccf0d70726364395ea96ac6ae3b845c3
[ "BSD-3-Clause" ]
null
null
null
/* * BSD LICENSE * Copyright (c) 2021 Samsung Electronics Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Samsung Electronics Corporation nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "src/qos/qos_event_manager.h" #include "src/qos/io_queue.h" #include "src/qos/parameter_queue.h" #include "src/qos/qos_manager.h" #include "src/qos/rate_limit.h" #include "src/spdk_wrapper/event_framework_api.h" namespace pos { #define SEC_TO_USEC 1000000ULL /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ QosEventManager::QosEventManager(SpdkEnvCaller* spdkEnvCaller) : spdkEnvCaller(spdkEnvCaller) { for (uint32_t eventId = BackendEvent_Start; eventId < BackendEvent_Count; eventId++) { eventWeightWRR[eventId] = M_DEFAULT_WEIGHT; } for (uint32_t worker = 0; worker < MAX_IO_WORKER; worker++) { _EventParamterInit(worker); for (uint32_t eventId = BackendEvent_Start; eventId < BackendEvent_Count; eventId++) { pendingEventIO[worker][eventId] = 0; } } try { bwIopsRateLimit = new BwIopsRateLimit; parameterQueue = new ParameterQueue; ioQueue = new IoQueue<UbioSmartPtr>; } catch (std::bad_alloc& ex) { assert(0); } } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ QosEventManager::~QosEventManager(void) { delete bwIopsRateLimit; delete parameterQueue; delete ioQueue; if (spdkEnvCaller != nullptr) { delete spdkEnvCaller; } } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ bool QosEventManager::_RateLimit(uint32_t id, BackendEvent event) { return bwIopsRateLimit->IsLimitExceeded(id, event); } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ void QosEventManager::_UpdateRateLimit(uint32_t id, BackendEvent event, uint64_t size) { bwIopsRateLimit->UpdateRateLimit(id, event, size); } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ void QosEventManager::HandleEventUbioSubmission(SubmissionAdapter* ioSubmission, SubmissionNotifier* submissionNotifier, uint32_t id, UbioSmartPtr ubio) { int completionCount = 0; BackendEvent event = _IdentifyEventType(ubio); uint64_t currentBw = 0; if ((BackendEvent_Unknown == event) || (ubio->IsSyncMode() == true)) { completionCount = ioSubmission->Do(ubio); submissionNotifier->Do(completionCount); return; } currentBw = eventQosParam[id][event].currentBW; if ((0 == pendingEventIO[id][event]) && (false == _RateLimit(id, event))) { currentBw = currentBw + ubio->GetSize(); completionCount = ioSubmission->Do(ubio); submissionNotifier->Do(completionCount); _UpdateRateLimit(id, event, ubio->GetSize()); } else { pendingEventIO[id][event]++; _EnqueueEventUbio(id, event, ubio); while (!IsExitQosSet()) { if (_RateLimit(id, event) == true) { break; } UbioSmartPtr queuedUbio = nullptr; queuedUbio = _DequeueEventUbio(id, event); if (queuedUbio == nullptr) { break; } currentBw = currentBw + queuedUbio->GetSize(); pendingEventIO[id][event]--; completionCount = ioSubmission->Do(queuedUbio); submissionNotifier->Do(completionCount); _UpdateRateLimit(id, event, queuedUbio->GetSize()); } } eventQosParam[id][event].currentBW = currentBw; } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ UbioSmartPtr QosEventManager::_DequeueEventUbio(uint32_t id, uint32_t event) { return ioQueue->DequeueIo(id, event); } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ void QosEventManager::_EnqueueParams(uint32_t workerId, BackendEvent event, bw_iops_parameter& event_param) { parameterQueue->EnqueueParameter(workerId, event, event_param); } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ bw_iops_parameter QosEventManager::DequeueParams(uint32_t workerId, BackendEvent event) { return parameterQueue->DequeueParameter(workerId, event); } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ void QosEventManager::_EnqueueEventUbio(uint32_t id, BackendEvent event, UbioSmartPtr ubio) { ioQueue->EnqueueIo(id, event, ubio); } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ void QosEventManager::SetEventWeightWRR(BackendEvent eventId, int64_t weight) { eventWeightWRR[eventId] = weight; } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ int64_t QosEventManager::GetEventWeightWRR(BackendEvent eventId) { return eventWeightWRR[eventId]; } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ int64_t QosEventManager::GetDefaultEventWeightWRR(BackendEvent eventId) { return M_DEFAULT_WEIGHT; } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ void QosEventManager::_ResetRateLimit(uint32_t id, BackendEvent event) { bwIopsRateLimit->ResetRateLimit(id, event, 1, DEFAULT_MAX_BW_IOPS, DEFAULT_MAX_BW_IOPS); } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ int QosEventManager::IOWorkerPoller(uint32_t id, SubmissionAdapter* ioSubmission) { int32_t retVal = 0; uint64_t now = spdkEnvCaller->SpdkGetTicks(); int completions = 0; uint64_t currentBW = 0; struct poller_structure* param = &eventPollStructure[id]; uint32_t workerId = id; uint64_t next_tick = param->nextTimeStamp; uint32_t event = 0; if (now < next_tick) { return 0; } param->nextTimeStamp = now + param->qosTimeSlice; for (event = BackendEvent_Start; event < BackendEvent_End; event++) { eventQosParam[workerId][event].valid = M_VALID_ENTRY; _EnqueueParams(workerId, (BackendEvent)event, eventQosParam[workerId][event]); currentBW = 0; _ResetRateLimit(workerId, (BackendEvent)event); while (!IsExitQosSet()) { if (_RateLimit(workerId, (BackendEvent)event) == true) { break; } UbioSmartPtr queuedUbio = nullptr; queuedUbio = _DequeueEventUbio(workerId, event); if (queuedUbio == nullptr) { break; } currentBW = currentBW + queuedUbio->GetSize(); pendingEventIO[workerId][event]--; completions = ioSubmission->Do(queuedUbio); retVal += completions; _UpdateRateLimit(workerId, (BackendEvent)event, queuedUbio->GetSize()); } eventQosParam[workerId][event].currentBW = currentBW; } return retVal; } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ BackendEvent QosEventManager::_IdentifyEventType(UbioSmartPtr ubio) { return (ubio->GetEventType()); } /* --------------------------------------------------------------------------*/ /** * @Synopsis * * @Returns */ /* --------------------------------------------------------------------------*/ void QosEventManager::_EventParamterInit(uint32_t id) { eventPollStructure[id].qosTimeSlice = IBOF_QOS_TIMESLICE_IN_USEC * spdkEnvCaller->SpdkGetTicksHz() / SEC_TO_USEC; eventPollStructure[id].nextTimeStamp = spdkEnvCaller->SpdkGetTicks() + eventPollStructure[id].qosTimeSlice; eventPollStructure[id].id = id; } } // namespace pos
30.328729
117
0.510611
hsungyang
f66202ecd11b5626639569493a8afb3bab3f73c1
31,010
cpp
C++
tools/clang/tools/clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
guoyuqi020/TraceRecorder
d6a31ca49d26bfd3c58a92cbf1727db99901d335
[ "Apache-2.0" ]
250
2019-05-07T12:56:44.000Z
2022-03-10T15:52:06.000Z
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
procedural/checkedc_binaries_ubuntu_16_04_from_12_Oct_2021
ad4e8b01121fbfb40d81ee798480add7dc93f0bf
[ "BSD-Source-Code" ]
410
2019-06-06T20:52:32.000Z
2022-01-18T14:21:48.000Z
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
procedural/checkedc_binaries_ubuntu_16_04_from_12_Oct_2021
ad4e8b01121fbfb40d81ee798480add7dc93f0bf
[ "BSD-Source-Code" ]
50
2019-05-10T21:12:24.000Z
2022-01-21T06:39:47.000Z
// Remove UNSUPPORTED for powerpc64le when the problem introduced by // r288563 is resolved. // UNSUPPORTED: powerpc64le // RUN: %check_clang_tidy %s readability-identifier-naming %t -- \ // RUN: -config='{CheckOptions: [ \ // RUN: {key: readability-identifier-naming.AbstractClassCase, value: CamelCase}, \ // RUN: {key: readability-identifier-naming.AbstractClassPrefix, value: 'A'}, \ // RUN: {key: readability-identifier-naming.ClassCase, value: CamelCase}, \ // RUN: {key: readability-identifier-naming.ClassPrefix, value: 'C'}, \ // RUN: {key: readability-identifier-naming.ClassConstantCase, value: CamelCase}, \ // RUN: {key: readability-identifier-naming.ClassConstantPrefix, value: 'k'}, \ // RUN: {key: readability-identifier-naming.ClassMemberCase, value: CamelCase}, \ // RUN: {key: readability-identifier-naming.ClassMethodCase, value: camelBack}, \ // RUN: {key: readability-identifier-naming.ConstantCase, value: UPPER_CASE}, \ // RUN: {key: readability-identifier-naming.ConstantSuffix, value: '_CST'}, \ // RUN: {key: readability-identifier-naming.ConstexprFunctionCase, value: lower_case}, \ // RUN: {key: readability-identifier-naming.ConstexprMethodCase, value: lower_case}, \ // RUN: {key: readability-identifier-naming.ConstexprVariableCase, value: lower_case}, \ // RUN: {key: readability-identifier-naming.EnumCase, value: CamelCase}, \ // RUN: {key: readability-identifier-naming.EnumPrefix, value: 'E'}, \ // RUN: {key: readability-identifier-naming.ScopedEnumConstantCase, value: CamelCase}, \ // RUN: {key: readability-identifier-naming.EnumConstantCase, value: UPPER_CASE}, \ // RUN: {key: readability-identifier-naming.FunctionCase, value: camelBack}, \ // RUN: {key: readability-identifier-naming.GlobalConstantCase, value: UPPER_CASE}, \ // RUN: {key: readability-identifier-naming.GlobalFunctionCase, value: CamelCase}, \ // RUN: {key: readability-identifier-naming.GlobalVariableCase, value: lower_case}, \ // RUN: {key: readability-identifier-naming.GlobalVariablePrefix, value: 'g_'}, \ // RUN: {key: readability-identifier-naming.InlineNamespaceCase, value: lower_case}, \ // RUN: {key: readability-identifier-naming.LocalConstantCase, value: CamelCase}, \ // RUN: {key: readability-identifier-naming.LocalConstantPrefix, value: 'k'}, \ // RUN: {key: readability-identifier-naming.LocalVariableCase, value: lower_case}, \ // RUN: {key: readability-identifier-naming.MemberCase, value: CamelCase}, \ // RUN: {key: readability-identifier-naming.MemberPrefix, value: 'm_'}, \ // RUN: {key: readability-identifier-naming.ConstantMemberCase, value: lower_case}, \ // RUN: {key: readability-identifier-naming.PrivateMemberPrefix, value: '__'}, \ // RUN: {key: readability-identifier-naming.ProtectedMemberPrefix, value: '_'}, \ // RUN: {key: readability-identifier-naming.PublicMemberCase, value: lower_case}, \ // RUN: {key: readability-identifier-naming.MethodCase, value: camelBack}, \ // RUN: {key: readability-identifier-naming.PrivateMethodPrefix, value: '__'}, \ // RUN: {key: readability-identifier-naming.ProtectedMethodPrefix, value: '_'}, \ // RUN: {key: readability-identifier-naming.NamespaceCase, value: lower_case}, \ // RUN: {key: readability-identifier-naming.ParameterCase, value: camelBack}, \ // RUN: {key: readability-identifier-naming.ParameterPrefix, value: 'a_'}, \ // RUN: {key: readability-identifier-naming.ConstantParameterCase, value: camelBack}, \ // RUN: {key: readability-identifier-naming.ConstantParameterPrefix, value: 'i_'}, \ // RUN: {key: readability-identifier-naming.ParameterPackCase, value: camelBack}, \ // RUN: {key: readability-identifier-naming.PureFunctionCase, value: lower_case}, \ // RUN: {key: readability-identifier-naming.PureMethodCase, value: camelBack}, \ // RUN: {key: readability-identifier-naming.StaticConstantCase, value: UPPER_CASE}, \ // RUN: {key: readability-identifier-naming.StaticVariableCase, value: camelBack}, \ // RUN: {key: readability-identifier-naming.StaticVariablePrefix, value: 's_'}, \ // RUN: {key: readability-identifier-naming.StructCase, value: lower_case}, \ // RUN: {key: readability-identifier-naming.TemplateParameterCase, value: UPPER_CASE}, \ // RUN: {key: readability-identifier-naming.TemplateTemplateParameterCase, value: CamelCase}, \ // RUN: {key: readability-identifier-naming.TemplateUsingCase, value: lower_case}, \ // RUN: {key: readability-identifier-naming.TemplateUsingPrefix, value: 'u_'}, \ // RUN: {key: readability-identifier-naming.TypeTemplateParameterCase, value: camelBack}, \ // RUN: {key: readability-identifier-naming.TypeTemplateParameterSuffix, value: '_t'}, \ // RUN: {key: readability-identifier-naming.TypedefCase, value: lower_case}, \ // RUN: {key: readability-identifier-naming.TypedefSuffix, value: '_t'}, \ // RUN: {key: readability-identifier-naming.UnionCase, value: CamelCase}, \ // RUN: {key: readability-identifier-naming.UnionPrefix, value: 'U'}, \ // RUN: {key: readability-identifier-naming.UsingCase, value: lower_case}, \ // RUN: {key: readability-identifier-naming.ValueTemplateParameterCase, value: camelBack}, \ // RUN: {key: readability-identifier-naming.VariableCase, value: lower_case}, \ // RUN: {key: readability-identifier-naming.VirtualMethodCase, value: Camel_Snake_Case}, \ // RUN: {key: readability-identifier-naming.VirtualMethodPrefix, value: 'v_'}, \ // RUN: {key: readability-identifier-naming.MacroDefinitionCase, value: UPPER_CASE}, \ // RUN: {key: readability-identifier-naming.TypeAliasCase, value: camel_Snake_Back}, \ // RUN: {key: readability-identifier-naming.TypeAliasSuffix, value: '_t'}, \ // RUN: {key: readability-identifier-naming.IgnoreFailedSplit, value: 0}, \ // RUN: {key: readability-identifier-naming.GlobalPointerCase, value: CamelCase}, \ // RUN: {key: readability-identifier-naming.GlobalPointerSuffix, value: '_Ptr'}, \ // RUN: {key: readability-identifier-naming.GlobalConstantPointerCase, value: UPPER_CASE}, \ // RUN: {key: readability-identifier-naming.GlobalConstantPointerSuffix, value: '_Ptr'}, \ // RUN: {key: readability-identifier-naming.PointerParameterCase, value: lower_case}, \ // RUN: {key: readability-identifier-naming.PointerParameterPrefix, value: 'p_'}, \ // RUN: {key: readability-identifier-naming.ConstantPointerParameterCase, value: CamelCase}, \ // RUN: {key: readability-identifier-naming.ConstantPointerParameterPrefix, value: 'cp_'}, \ // RUN: {key: readability-identifier-naming.LocalPointerCase, value: CamelCase}, \ // RUN: {key: readability-identifier-naming.LocalPointerPrefix, value: 'l_'}, \ // RUN: {key: readability-identifier-naming.LocalConstantPointerCase, value: CamelCase}, \ // RUN: {key: readability-identifier-naming.LocalConstantPointerPrefix, value: 'lc_'}, \ // RUN: ]}' -- -fno-delayed-template-parsing -Dbad_macro -std=c++17 -fcoroutines-ts \ // RUN: -I%S/Inputs/readability-identifier-naming \ // RUN: -isystem %S/Inputs/readability-identifier-naming/system // clang-format off #include <system-header.h> #include <coroutines.h> #include "user-header.h" // NO warnings or fixes expected from declarations within header files without // the -header-filter= option namespace FOO_NS { // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: invalid case style for namespace 'FOO_NS' [readability-identifier-naming] // CHECK-FIXES: {{^}}namespace foo_ns {{{$}} inline namespace InlineNamespace { // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: invalid case style for inline namespace 'InlineNamespace' // CHECK-FIXES: {{^}}inline namespace inline_namespace {{{$}} SYSTEM_NS::structure g_s1; // NO warnings or fixes expected as SYSTEM_NS and structure are declared in a header file USER_NS::object g_s2; // NO warnings or fixes expected as USER_NS and object are declared in a header file SYSTEM_MACRO(var1); // NO warnings or fixes expected as var1 is from macro expansion USER_MACRO(var2); // NO warnings or fixes expected as var2 is declared in a macro expansion #define BLA int FOO_bar BLA; // NO warnings or fixes expected as FOO_bar is from macro expansion int global0; #define USE_NUMBERED_GLOBAL(number) auto use_global##number = global##number USE_NUMBERED_GLOBAL(0); // NO warnings or fixes expected as global0 is pieced together in a macro // expansion. int global1; #define USE_NUMBERED_BAL(prefix, number) \ auto use_##prefix##bal##number = prefix##bal##number USE_NUMBERED_BAL(glo, 1); // NO warnings or fixes expected as global1 is pieced together in a macro // expansion. int global2; #define USE_RECONSTRUCTED(glo, bal) auto use_##glo##bal = glo##bal USE_RECONSTRUCTED(glo, bal2); // NO warnings or fixes expected as global2 is pieced together in a macro // expansion. int global; // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: invalid case style for global variable 'global' // CHECK-FIXES: {{^}}int g_global;{{$}} #define USE_IN_MACRO(m) auto use_##m = m USE_IN_MACRO(global); int global3; // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: invalid case style for global variable 'global3' // CHECK-FIXES: {{^}}int g_global3;{{$}} #define ADD_TO_SELF(m) (m) + (m) int g_twice_global3 = ADD_TO_SELF(global3); // CHECK-FIXES: {{^}}int g_twice_global3 = ADD_TO_SELF(g_global3);{{$}} enum my_enumeration { // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: invalid case style for enum 'my_enumeration' // CHECK-FIXES: {{^}}enum EMyEnumeration {{{$}} MyConstant = 1, // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: invalid case style for enum constant 'MyConstant' // CHECK-FIXES: {{^}} MY_CONSTANT = 1,{{$}} your_CONST = 1, // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: invalid case style for enum constant 'your_CONST' // CHECK-FIXES: {{^}} YOUR_CONST = 1,{{$}} THIS_ConstValue = 1, // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: invalid case style for enum constant 'THIS_ConstValue' // CHECK-FIXES: {{^}} THIS_CONST_VALUE = 1,{{$}} }; enum class EMyEnumeration { myConstant = 1, // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: invalid case style for scoped enum constant 'myConstant' // CHECK-FIXES: {{^}} MyConstant = 1,{{$}} your_CONST = 1, // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: invalid case style for scoped enum constant 'your_CONST' // CHECK-FIXES: {{^}} YourConst = 1,{{$}} THIS_ConstValue = 1, // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: invalid case style for scoped enum constant 'THIS_ConstValue' // CHECK-FIXES: {{^}} ThisConstValue = 1,{{$}} }; constexpr int ConstExpr_variable = MyConstant; // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: invalid case style for constexpr variable 'ConstExpr_variable' // CHECK-FIXES: {{^}}constexpr int const_expr_variable = MY_CONSTANT;{{$}} class my_class { // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: invalid case style for class 'my_class' // CHECK-FIXES: {{^}}class CMyClass {{{$}} public: my_class(); // CHECK-FIXES: {{^}} CMyClass();{{$}} my_class(void*) : my_class() {} // CHECK-FIXES: {{^}} CMyClass(void*) : CMyClass() {}{{$}} ~ my_class(); // (space in destructor token test, we could check trigraph but they will be deprecated) // CHECK-FIXES: {{^}} ~{{$}} // CHECK-FIXES: {{^}} CMyClass();{{$}} private: const int MEMBER_one_1 = ConstExpr_variable; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: invalid case style for constant member 'MEMBER_one_1' // CHECK-FIXES: {{^}} const int member_one_1 = const_expr_variable;{{$}} int member2 = 2; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: invalid case style for private member 'member2' // CHECK-FIXES: {{^}} int __member2 = 2;{{$}} int _memberWithExtraUnderscores_ = 42; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: invalid case style for private member '_memberWithExtraUnderscores_' // CHECK-FIXES: {{^}} int __memberWithExtraUnderscores = 42;{{$}} private: int private_member = 3; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: invalid case style for private member 'private_member' // CHECK-FIXES: {{^}} int __private_member = 3;{{$}} protected: int ProtMember; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: invalid case style for protected member 'ProtMember' // CHECK-FIXES: {{^}} int _ProtMember;{{$}} public: int PubMem; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: invalid case style for public member 'PubMem' // CHECK-FIXES: {{^}} int pub_mem;{{$}} static const int classConstant; // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: invalid case style for class constant 'classConstant' // CHECK-FIXES: {{^}} static const int kClassConstant;{{$}} static int ClassMember_2; // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: invalid case style for class member 'ClassMember_2' // CHECK-FIXES: {{^}} static int ClassMember2;{{$}} }; class my_class; // No warning needed here as this is tied to the previous declaration. // Just make sure the fix is applied. // CHECK-FIXES: {{^}}class CMyClass;{{$}} class my_forward_declared_class; // No warning should be triggered. const int my_class::classConstant = 4; // CHECK-FIXES: {{^}}const int CMyClass::kClassConstant = 4;{{$}} int my_class::ClassMember_2 = 5; // CHECK-FIXES: {{^}}int CMyClass::ClassMember2 = 5;{{$}} class my_derived_class : public virtual my_class {}; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: invalid case style for class 'my_derived_class' // CHECK-FIXES: {{^}}class CMyDerivedClass : public virtual CMyClass {};{{$}} class CMyWellNamedClass {}; // No warning expected as this class is well named. template <typename t_t> class CMyWellNamedClass2 : public my_class { // CHECK-FIXES: {{^}}class CMyWellNamedClass2 : public CMyClass {{{$}} t_t my_Bad_Member; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: invalid case style for private member 'my_Bad_Member' // CHECK-FIXES: {{^}} t_t __my_Bad_Member;{{$}} int my_Other_Bad_Member = 42; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: invalid case style for private member 'my_Other_Bad_Member' // CHECK-FIXES: {{^}} int __my_Other_Bad_Member = 42;{{$}} public: CMyWellNamedClass2() = default; CMyWellNamedClass2(CMyWellNamedClass2 const&) = default; CMyWellNamedClass2(CMyWellNamedClass2 &&) = default; CMyWellNamedClass2(t_t a_v, void *p_p) : my_class(p_p), my_Bad_Member(a_v) {} // CHECK-FIXES: {{^}} CMyWellNamedClass2(t_t a_v, void *p_p) : CMyClass(p_p), __my_Bad_Member(a_v) {}{{$}} CMyWellNamedClass2(t_t a_v) : my_class(), my_Bad_Member(a_v), my_Other_Bad_Member(11) {} // CHECK-FIXES: {{^}} CMyWellNamedClass2(t_t a_v) : CMyClass(), __my_Bad_Member(a_v), __my_Other_Bad_Member(11) {}{{$}} }; void InstantiateClassMethods() { // Ensure we trigger the instantiation of each constructor CMyWellNamedClass2<int> x; CMyWellNamedClass2<int> x2 = x; CMyWellNamedClass2<int> x3 = static_cast<CMyWellNamedClass2<int>&&>(x2); CMyWellNamedClass2<int> x4(42); CMyWellNamedClass2<int> x5(42, nullptr); } class AOverridden { public: virtual ~AOverridden() = default; virtual void BadBaseMethod() = 0; // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: invalid case style for virtual method 'BadBaseMethod' // CHECK-FIXES: {{^}} virtual void v_Bad_Base_Method() = 0; }; class COverriding : public AOverridden { public: // Overriding a badly-named base isn't a new violation. void BadBaseMethod() override {} // CHECK-FIXES: {{^}} void v_Bad_Base_Method() override {} void foo() { BadBaseMethod(); // CHECK-FIXES: {{^}} v_Bad_Base_Method(); this->BadBaseMethod(); // CHECK-FIXES: {{^}} this->v_Bad_Base_Method(); AOverridden::BadBaseMethod(); // CHECK-FIXES: {{^}} AOverridden::v_Bad_Base_Method(); COverriding::BadBaseMethod(); // CHECK-FIXES: {{^}} COverriding::v_Bad_Base_Method(); } }; void VirtualCall(AOverridden &a_vItem) { a_vItem.BadBaseMethod(); // CHECK-FIXES: {{^}} a_vItem.v_Bad_Base_Method(); } template <typename derived_t> class CRTPBase { public: void BadBaseMethod(int) {} // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: invalid case style for method 'BadBaseMethod' }; class CRTPDerived : CRTPBase<CRTPDerived> { public: // Hiding a badly-named base isn't a new violation. double BadBaseMethod(double) { return 0; } }; template<typename T> // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: invalid case style for type template parameter 'T' // CHECK-FIXES: {{^}}template<typename t_t>{{$}} class my_templated_class : CMyWellNamedClass {}; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: invalid case style for class 'my_templated_class' // CHECK-FIXES: {{^}}class CMyTemplatedClass : CMyWellNamedClass {};{{$}} template<typename T> // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: invalid case style for type template parameter 'T' // CHECK-FIXES: {{^}}template<typename t_t>{{$}} class my_other_templated_class : my_templated_class< my_class>, private my_derived_class {}; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: invalid case style for class 'my_other_templated_class' // CHECK-FIXES: {{^}}class CMyOtherTemplatedClass : CMyTemplatedClass< CMyClass>, private CMyDerivedClass {};{{$}} template<typename t_t> using mysuper_tpl_t = my_other_templated_class <:: FOO_NS ::my_class>; // CHECK-FIXES: {{^}}using mysuper_tpl_t = CMyOtherTemplatedClass <:: foo_ns ::CMyClass>;{{$}} const int global_Constant = 6; // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: invalid case style for global constant 'global_Constant' // CHECK-FIXES: {{^}}const int GLOBAL_CONSTANT = 6;{{$}} int Global_variable = 7; // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: invalid case style for global variable 'Global_variable' // CHECK-FIXES: {{^}}int g_global_variable = 7;{{$}} void global_function(int PARAMETER_1, int const CONST_parameter) { // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: invalid case style for global function 'global_function' // CHECK-MESSAGES: :[[@LINE-2]]:26: warning: invalid case style for parameter 'PARAMETER_1' // CHECK-MESSAGES: :[[@LINE-3]]:49: warning: invalid case style for constant parameter 'CONST_parameter' // CHECK-FIXES: {{^}}void GlobalFunction(int a_parameter1, int const i_constParameter) {{{$}} static const int THIS_static_ConsTant = 4; // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: invalid case style for static constant 'THIS_static_ConsTant' // CHECK-FIXES: {{^}} static const int THIS_STATIC_CONS_TANT = 4;{{$}} static int THIS_static_variable; // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: invalid case style for static variable 'THIS_static_variable' // CHECK-FIXES: {{^}} static int s_thisStaticVariable;{{$}} int const local_Constant = 3; // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: invalid case style for local constant 'local_Constant' // CHECK-FIXES: {{^}} int const kLocalConstant = 3;{{$}} int LOCAL_VARIABLE; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: invalid case style for local variable 'LOCAL_VARIABLE' // CHECK-FIXES: {{^}} int local_variable;{{$}} int LOCAL_Array__[] = {0, 1, 2}; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: invalid case style for local variable 'LOCAL_Array__' // CHECK-FIXES: {{^}} int local_array[] = {0, 1, 2};{{$}} for (auto _ : LOCAL_Array__) { } } template<typename ... TYPE_parameters> // CHECK-MESSAGES: :[[@LINE-1]]:23: warning: invalid case style for type template parameter 'TYPE_parameters' // CHECK-FIXES: {{^}}template<typename ... typeParameters_t>{{$}} void Global_Fun(TYPE_parameters... PARAMETER_PACK) { // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: invalid case style for global function 'Global_Fun' // CHECK-MESSAGES: :[[@LINE-2]]:36: warning: invalid case style for parameter pack 'PARAMETER_PACK' // CHECK-FIXES: {{^}}void GlobalFun(typeParameters_t... parameterPack) {{{$}} global_function(1, 2); // CHECK-FIXES: {{^}} GlobalFunction(1, 2);{{$}} FOO_bar = Global_variable; // CHECK-FIXES: {{^}} FOO_bar = g_global_variable;{{$}} // NO fix expected for FOO_bar declared in macro expansion } template<template<typename> class TPL_parameter, int COUNT_params, typename ... TYPE_parameters> // CHECK-MESSAGES: :[[@LINE-1]]:35: warning: invalid case style for template template parameter 'TPL_parameter' // CHECK-MESSAGES: :[[@LINE-2]]:54: warning: invalid case style for value template parameter 'COUNT_params' // CHECK-MESSAGES: :[[@LINE-3]]:81: warning: invalid case style for type template parameter 'TYPE_parameters' // CHECK-FIXES: {{^}}template<template<typename> class TplParameter, int countParams, typename ... typeParameters_t>{{$}} class test_CLASS { // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: invalid case style for class 'test_CLASS' // CHECK-FIXES: {{^}}class CTestClass {{{$}} }; class abstract_class { // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: invalid case style for abstract class 'abstract_class' // CHECK-FIXES: {{^}}class AAbstractClass {{{$}} virtual ~abstract_class() = 0; // CHECK-FIXES: {{^}} virtual ~AAbstractClass() = 0;{{$}} virtual void VIRTUAL_METHOD(); // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: invalid case style for virtual method 'VIRTUAL_METHOD' // CHECK-FIXES: {{^}} virtual void v_Virtual_Method();{{$}} void non_Virtual_METHOD() {} // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: invalid case style for private method 'non_Virtual_METHOD' // CHECK-FIXES: {{^}} void __non_Virtual_METHOD() {}{{$}} public: static void CLASS_METHOD() {} // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: invalid case style for class method 'CLASS_METHOD' // CHECK-FIXES: {{^}} static void classMethod() {}{{$}} constexpr int CST_expr_Method() { return 2; } // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: invalid case style for constexpr method 'CST_expr_Method' // CHECK-FIXES: {{^}} constexpr int cst_expr_method() { return 2; }{{$}} private: void PRIVate_Method(); // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: invalid case style for private method 'PRIVate_Method' // CHECK-FIXES: {{^}} void __PRIVate_Method();{{$}} protected: void protected_Method(); // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: invalid case style for protected method 'protected_Method' // CHECK-FIXES: {{^}} void _protected_Method();{{$}} public: void public_Method(); // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: invalid case style for method 'public_Method' // CHECK-FIXES: {{^}} void publicMethod();{{$}} }; constexpr int CE_function() { return 3; } // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: invalid case style for constexpr function 'CE_function' // CHECK-FIXES: {{^}}constexpr int ce_function() { return 3; }{{$}} struct THIS___Structure { // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: invalid case style for struct 'THIS___Structure' // CHECK-FIXES: {{^}}struct this_structure {{{$}} THIS___Structure(); // CHECK-FIXES: {{^}} this_structure();{{$}} union __MyUnion_is_wonderful__ {}; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: invalid case style for union '__MyUnion_is_wonderful__' // CHECK-FIXES: {{^}} union UMyUnionIsWonderful {};{{$}} }; typedef THIS___Structure struct_type; // CHECK-MESSAGES: :[[@LINE-1]]:26: warning: invalid case style for typedef 'struct_type' // CHECK-FIXES: {{^}}typedef this_structure struct_type_t;{{$}} struct_type GlobalTypedefTestFunction(struct_type a_argument1) { // CHECK-FIXES: {{^}}struct_type_t GlobalTypedefTestFunction(struct_type_t a_argument1) { struct_type typedef_test_1; // CHECK-FIXES: {{^}} struct_type_t typedef_test_1; } using my_struct_type = THIS___Structure; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: invalid case style for type alias 'my_struct_type' // CHECK-FIXES: {{^}}using my_Struct_Type_t = this_structure;{{$}} template<typename t_t> using SomeOtherTemplate = my_other_templated_class <:: FOO_NS ::my_class>; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: invalid case style for type alias 'SomeOtherTemplate' // CHECK-FIXES: {{^}}using some_Other_Template_t = CMyOtherTemplatedClass <:: foo_ns ::CMyClass>;{{$}} static void static_Function() { // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: invalid case style for function 'static_Function' // CHECK-FIXES: {{^}}static void staticFunction() {{{$}} ::FOO_NS::InlineNamespace::abstract_class::CLASS_METHOD(); // CHECK-FIXES: {{^}} ::foo_ns::inline_namespace::AAbstractClass::classMethod();{{$}} ::FOO_NS::InlineNamespace::static_Function(); // CHECK-FIXES: {{^}} ::foo_ns::inline_namespace::staticFunction();{{$}} using ::FOO_NS::InlineNamespace::CE_function; // CHECK-FIXES: {{^}} using ::foo_ns::inline_namespace::ce_function;{{$}} unsigned MY_LOCAL_array[] = {1,2,3}; // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: invalid case style for local variable 'MY_LOCAL_array' // CHECK-FIXES: {{^}} unsigned my_local_array[] = {1,2,3};{{$}} unsigned const MyConstLocal_array[] = {1,2,3}; // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: invalid case style for local constant 'MyConstLocal_array' // CHECK-FIXES: {{^}} unsigned const kMyConstLocalArray[] = {1,2,3};{{$}} static unsigned MY_STATIC_array[] = {1,2,3}; // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: invalid case style for static variable 'MY_STATIC_array' // CHECK-FIXES: {{^}} static unsigned s_myStaticArray[] = {1,2,3};{{$}} static unsigned const MyConstStatic_array[] = {1,2,3}; // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: invalid case style for static constant 'MyConstStatic_array' // CHECK-FIXES: {{^}} static unsigned const MY_CONST_STATIC_ARRAY[] = {1,2,3};{{$}} char MY_LOCAL_string[] = "123"; // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: invalid case style for local variable 'MY_LOCAL_string' // CHECK-FIXES: {{^}} char my_local_string[] = "123";{{$}} char const MyConstLocal_string[] = "123"; // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: invalid case style for local constant 'MyConstLocal_string' // CHECK-FIXES: {{^}} char const kMyConstLocalString[] = "123";{{$}} static char MY_STATIC_string[] = "123"; // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: invalid case style for static variable 'MY_STATIC_string' // CHECK-FIXES: {{^}} static char s_myStaticString[] = "123";{{$}} static char const MyConstStatic_string[] = "123"; // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: invalid case style for static constant 'MyConstStatic_string' // CHECK-FIXES: {{^}} static char const MY_CONST_STATIC_STRING[] = "123";{{$}} } #define MY_TEST_Macro(X) X() // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: invalid case style for macro definition 'MY_TEST_Macro' // CHECK-FIXES: {{^}}#define MY_TEST_MACRO(X) X() void MY_TEST_Macro(function) {} // CHECK-FIXES: {{^}}void MY_TEST_MACRO(function) {} } } template <typename t_t> struct a { typename t_t::template b<> c; char const MY_ConstMember_string[4] = "123"; // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: invalid case style for constant member 'MY_ConstMember_string' // CHECK-FIXES: {{^}} char const my_const_member_string[4] = "123";{{$}} static char const MyConstClass_string[]; // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: invalid case style for class constant 'MyConstClass_string' // CHECK-FIXES: {{^}} static char const kMyConstClassString[];{{$}} }; template<typename t_t> char const a<t_t>::MyConstClass_string[] = "123"; // CHECK-FIXES: {{^}}char const a<t_t>::kMyConstClassString[] = "123";{{$}} template <template <typename> class A> struct b { A<int> c; }; unsigned MY_GLOBAL_array[] = {1,2,3}; // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: invalid case style for global variable 'MY_GLOBAL_array' // CHECK-FIXES: {{^}}unsigned g_my_global_array[] = {1,2,3};{{$}} unsigned const MyConstGlobal_array[] = {1,2,3}; // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: invalid case style for global constant 'MyConstGlobal_array' // CHECK-FIXES: {{^}}unsigned const MY_CONST_GLOBAL_ARRAY[] = {1,2,3};{{$}} int * MyGlobal_Ptr;// -> ok int * const MyConstantGlobalPointer = nullptr; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: invalid case style for global constant pointer 'MyConstantGlobalPointer' // CHECK-FIXES: {{^}}int * const MY_CONSTANT_GLOBAL_POINTER_Ptr = nullptr;{{$}} void MyPoiterFunction(int * p_normal_pointer, int * const constant_ptr){ // CHECK-MESSAGES: :[[@LINE-1]]:59: warning: invalid case style for constant pointer parameter 'constant_ptr' // CHECK-FIXES: {{^}}void MyPoiterFunction(int * p_normal_pointer, int * const cp_ConstantPtr){{{$}} int * l_PointerA; int * const pointer_b = nullptr; // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: invalid case style for local constant pointer 'pointer_b' // CHECK-FIXES: {{^}} int * const lc_PointerB = nullptr;{{$}} } using namespace FOO_NS; // CHECK-FIXES: {{^}}using namespace foo_ns; using namespace FOO_NS::InlineNamespace; // CHECK-FIXES: {{^}}using namespace foo_ns::inline_namespace; void QualifiedTypeLocTest(THIS___Structure); // CHECK-FIXES: {{^}}void QualifiedTypeLocTest(this_structure);{{$}} void QualifiedTypeLocTest(THIS___Structure &); // CHECK-FIXES: {{^}}void QualifiedTypeLocTest(this_structure &);{{$}} void QualifiedTypeLocTest(THIS___Structure &&); // CHECK-FIXES: {{^}}void QualifiedTypeLocTest(this_structure &&);{{$}} void QualifiedTypeLocTest(const THIS___Structure); // CHECK-FIXES: {{^}}void QualifiedTypeLocTest(const this_structure);{{$}} void QualifiedTypeLocTest(const THIS___Structure &); // CHECK-FIXES: {{^}}void QualifiedTypeLocTest(const this_structure &);{{$}} void QualifiedTypeLocTest(volatile THIS___Structure &); // CHECK-FIXES: {{^}}void QualifiedTypeLocTest(volatile this_structure &);{{$}} namespace redecls { // We only want the warning to show up once here for the first decl. // CHECK-MESSAGES: :[[@LINE+1]]:6: warning: invalid case style for global function 'badNamedFunction' void badNamedFunction(); void badNamedFunction(); void badNamedFunction(){} // CHECK-FIXES: {{^}}void BadNamedFunction(); // CHECK-FIXES-NEXT: {{^}}void BadNamedFunction(); // CHECK-FIXES-NEXT: {{^}}void BadNamedFunction(){} void ReferenceBadNamedFunction() { auto l_Ptr = badNamedFunction; // CHECK-FIXES: {{^}} auto l_Ptr = BadNamedFunction; l_Ptr(); badNamedFunction(); // CHECK-FIXES: {{^}} BadNamedFunction(); } } // namespace redecls namespace scratchspace { #define DUP(Tok) Tok #define M1(Tok) DUP(badName##Tok()) // We don't want a warning here as the call to this in Foo is in a scratch // buffer so its fix-it wouldn't be applied, resulting in invalid code. void badNameWarn(); void Foo() { M1(Warn); } #undef M1 #undef DUP } // namespace scratchspace template<typename type_t> auto GetRes(type_t& Param) -> decltype(Param.res()); // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: invalid case style for parameter 'Param' // CHECK-FIXES: auto GetRes(type_t& a_param) -> decltype(a_param.res()); // Check implicit declarations in coroutines struct async_obj { public: never_suspend operator co_await() const noexcept; }; task ImplicitDeclTest(async_obj &a_object) { co_await a_object; // CHECK-MESSAGES-NOT: warning: invalid case style for local variable }
49.300477
122
0.700742
guoyuqi020
f665bb9c364dcaf3584521579f56f09dde23b664
446
cpp
C++
Dynamic Programming/cm2.cpp
AadityaJ/CodeMonk
bd719f6bd6f9792c98b538c1ef9948d2abf057d0
[ "MIT" ]
null
null
null
Dynamic Programming/cm2.cpp
AadityaJ/CodeMonk
bd719f6bd6f9792c98b538c1ef9948d2abf057d0
[ "MIT" ]
null
null
null
Dynamic Programming/cm2.cpp
AadityaJ/CodeMonk
bd719f6bd6f9792c98b538c1ef9948d2abf057d0
[ "MIT" ]
null
null
null
//https://www.hackerearth.com/code-monk-dynamic-programming/algorithm/vibhu-and-his-mathematics/description/ #include <stdio.h> #define MOD 1000000007 long long int funct[1000001]; int main(int argc, char const *argv[]) { int t; scanf("%d",&t); funct[1]=1;funct[2]=2; for(int i=3;i<=1000000;i++){ funct[i]=funct[i-1]+(i-1)*funct[i-2]; funct[i]%=MOD; } while(t--){ int n; scanf("%d",&n); printf("%lld\n",funct[n]); } return 0; }
22.3
108
0.639013
AadityaJ
f6661df82957b56134818bc7031e0f98525764df
7,624
cc
C++
src/kern/linux/printk.cc
He-Liu-ooo/Computer-Architecture-THUEE-2022-spring-
9d36aaacbc7eea357608524113bec97bae2ea229
[ "BSD-3-Clause" ]
16
2020-09-24T00:17:36.000Z
2021-08-12T06:11:52.000Z
src/kern/linux/printk.cc
gibchikafa/gem5
0d703041fcd5d119012b62287695723a2955b408
[ "BSD-3-Clause" ]
5
2021-01-27T23:09:06.000Z
2022-01-07T03:19:39.000Z
src/kern/linux/printk.cc
gibchikafa/gem5
0d703041fcd5d119012b62287695723a2955b408
[ "BSD-3-Clause" ]
15
2020-11-18T00:15:28.000Z
2021-12-12T03:18:34.000Z
/* * Copyright (c) 2004-2005 The Regents of The University of Michigan * 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 holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "kern/linux/printk.hh" #include <sys/types.h> #include <algorithm> #include <iostream> #include <sstream> #include "cpu/thread_context.hh" #include "mem/port_proxy.hh" namespace Linux { int printk(std::string &str, ThreadContext *tc, Addr format_ptr, PrintkVarArgs args) { std::string format; std::ostringstream out; tc->getVirtProxy().readString(format, format_ptr); const char *p = format.c_str(); while (*p) { switch (*p) { case '%': { bool more = true; bool islong = false; bool leftjustify = false; bool format = false; bool zero = false; int width = 0; while (more && *++p) { switch (*p) { case 'l': case 'L': islong = true; break; case '-': leftjustify = true; break; case '#': format = true; break; case '0': if (width) width *= 10; else zero = true; break; default: if (*p >= '1' && *p <= '9') width = 10 * width + *p - '0'; else more = false; break; } } bool hexnum = false; bool octal = false; bool sign = false; switch (*p) { case 'X': case 'x': hexnum = true; break; case 'O': case 'o': octal = true; break; case 'D': case 'd': sign = true; break; case 'P': format = true; M5_FALLTHROUGH; case 'p': hexnum = true; break; } switch (*p) { case 'D': case 'd': case 'U': case 'u': case 'X': case 'x': case 'O': case 'o': case 'P': case 'p': { if (hexnum) out << std::hex; if (octal) out << std::oct; if (format) { if (!zero) out.setf(std::ios::showbase); else { if (hexnum) { out << "0x"; width -= 2; } else if (octal) { out << "0"; width -= 1; } } } if (zero) out.fill('0'); if (width > 0) out.width(width); if (leftjustify && !zero) out.setf(std::ios::left); if (sign) { if (islong) out << args.get<int64_t>(); else out << args.get<int32_t>(); } else { if (islong) out << args.get<uint64_t>(); else out << args.get<uint32_t>(); } if (zero) out.fill(' '); if (width > 0) out.width(0); out << std::dec; } break; case 's': { Addr s_ptr = args.get<Addr>(); std::string s; if (s_ptr) tc->getVirtProxy().readString(s, s_ptr); else s = "<NULL>"; if (width > 0) out.width(width); if (leftjustify) out.setf(std::ios::left); out << s; } break; case 'C': case 'c': { uint64_t mask = (*p == 'C') ? 0xffL : 0x7fL; uint64_t num; int cwidth; if (islong) { num = args.get<uint64_t>(); cwidth = sizeof(uint64_t); } else { num = args.get<uint32_t>(); cwidth = sizeof(uint32_t); } while (cwidth-- > 0) { char c = (char)(num & mask); if (c) out << c; num >>= 8; } } break; case 'b': { uint64_t n = args.get<uint64_t>(); Addr s_ptr = args.get<Addr>(); std::string s; tc->getVirtProxy().readString(s, s_ptr); out << s << ": " << n; } break; case '%': out << '%'; break; } ++p; } break; case '\n': out << std::endl; ++p; break; case '\r': ++p; if (*p != '\n') out << std::endl; break; default: { size_t len = strcspn(p, "%\n\r\0"); out.write(p, len); p += len; } } } str = out.str(); return str.length(); } } // namespace Linux
30.374502
73
0.385624
He-Liu-ooo
f66af4089ace1b4e59493c318915422ca2b46929
5,053
cpp
C++
SmsMaker.cpp
andre-i/microSmartHome
aec33d49c87c84ab86656813a6c927eb99d2cc3a
[ "MIT" ]
null
null
null
SmsMaker.cpp
andre-i/microSmartHome
aec33d49c87c84ab86656813a6c927eb99d2cc3a
[ "MIT" ]
null
null
null
SmsMaker.cpp
andre-i/microSmartHome
aec33d49c87c84ab86656813a6c927eb99d2cc3a
[ "MIT" ]
null
null
null
#include "SmsMaker.h" extern volatile uint8_t delayEspired; SmsMaker::SmsMaker(Modem *m) { modem = m; } /* send sms on cool firing , motion in house, droped external voltage messageType : COOL, MOTION, VOLTAGE */ bool SmsMaker::sendWarningSms(uint8_t clientOrder, int messageType) { if (digitalRead(DUCT_PIN) == LOW) { Serial.print(F(" try send_WarningSms for client")); Serial.print(String(clientOrder) + " msgTYPE=" + String(messageType)); } char mess[MAX_MESS_LEN]; char phone[49]; if (modem->fillUCS2PhoneNumber(clientOrder, phone) == false) { #if DEBUG Serial.println(F(" err exit - Fail get phone")); #endif return false; } phone[48] = '\0'; strcpy_P(mess, (char *)pgm_read_word(&(messages[messageType]))); #if DEBUG /* uint8_t i = 0; Serial.print(F(" text msg: ")); while (mess[i] != '\0') { Serial.write(mess[i]); i++; } Serial.println(F(" :")); */ #endif return sendSms( "UCS2\0", phone, mess ); } /* it sms be send only admin it show clients and in phones Note: phones with 0 is empty phone */ bool SmsMaker::sendInfoSms() { #if DEBUG Serial.println(F("\nsendInfoSms")); #endif String answ = ""; char phone[14]; uint8_t j = 0; for (uint8_t i = 1; i <= COOL_THEMPERATURE_RECORD ; i++) { if (modem->fillGSMPhone(i, phone) == false) { Serial.println(F("\nError on fill phone")); // if clients not have phone - fill number of '0' for (uint8_t k = 0; k < 5; k++)phone[k] = '0'; phone[5] = '\0'; if ( i == 1)return false; } answ += '#'; //write current value for cool themperature if (i == COOL_THEMPERATURE_RECORD)answ += 'T'; else answ += i; answ += '#'; while (phone[j] != '\0') { answ += phone[j]; j++; } j = 0; answ += "#\n"; } // add send motion mode answ += "#Motion mode: "; answ += (modem->isSendMotion() == SEND_SMS) ? "SEND#\n" : "NO_SEND#\n"; // on drop out voltage add it by info if (digitalRead(VOLTAGE_PIN) == 0) answ += "# 0 Volt #\n"; if (modem->fillGSMPhone(1, phone) == false)return false; Serial.print("Try send sms :"); Serial.println(answ); return sendSms("GSM\0" , phone, (char*)answ.c_str()); } /* @phone - international phone format( 13 chars starts with '+' and ends with '\0' ) it must have appropriate format for GSM and Unicode sms @smsFormat "GSM\0" or "UCS2\0" @text must be ends with '\0' char */ bool SmsMaker::sendSms( char *smsFormat, char *phone, char *text) { #if DEBUG //Serial.println(F(" Start write sms")); /* uint8_t i = 0; Serial.print(F("\n sendSms [ format: ")); Serial.print(smsFormat); Serial.print(F(" phone: ")); while (phone[i] != '\0') { Serial.write(phone[i]); i++; } Serial.print("]\n text:\n"); i=0; while(text[i] != '\0'){ Serial.write(text[i]); i++; } Serial.println("\n\t_send success_\n"); modem->dropGSM(); return true; */ #endif if (digitalRead(DUCT_PIN) == LOW) { Serial.println(F(" DEBUG mode emulator: set SMS true")); return true; } if (!setSmsFormat(smsFormat)) { #if DEBUG // Serial.print(F(" err - can`t set format")); #endif return false; } modem->print("OK \r"); // REBOOT if any wrong if (!modem->checkOnOK(0)) { modem->rebootSIM(); Serial.println(F("WARNING: [ rebootSIM before send sms ]")); } modem->println("AT+CMGS=\"" + String(phone) + "\" \r"); setEspiredTime(DELAY_FOR_OK); while (modem->available() < 6 && delayEspired != 0)delay(5); char ch = '\0'; setEspiredTime(DELAY_FOR_OK); while (modem->available() > 0 && (ch = modem->read()) != '>' && delayEspired != 0) delay(2); modem->dropGSM(); if (ch != '>') { #if DEBUG Serial.println(F(" err: espired time for write text")); #endif return false; } writeText(text); modem->write(0x1a); modem->write('\r'); modem->flush(); #if DEBUG Serial.print(F(" SMS send : ")); #endif setEspiredTime(DELAY_FOR_ANSWER); while (modem->available() < 3 && delayEspired != 0)delay(5); if (!modem->checkOnOK(0)) { #if DEBUG Serial.println(F("'false'")); #endif return false; } #if DEBUG Serial.println(F("'true'")); #endif return true; } /* tune modem for send sms appropriate format */ bool SmsMaker::setSmsFormat(char *format) { modem->dropGSM(); if (strstr(format, "CS2\0") != NULL) { // ucs2 format modem->println(F("AT+CSMP=17,167,0,8 \r")); if (!modem->checkOnOK(2))return false; if (!modem->setFormatSms(UCS2_FORMAT))return false; } else if (strstr(format, "SM\0") != NULL) { // gsm format if (!modem->setFormatSms(GSM_FORMAT))return false; } else { Serial.println(F("\ntry set WRONG smsFormat")); return false; } return true; } /* write text as chars stream to modem input */ void SmsMaker::writeText(char *text) { char ch; uint8_t i = 0; while ( text[i] != '\0') { #if DEBUG // Serial.write(text[i]); #endif modem->write(text[i]); i++; } }
25.39196
94
0.593905
andre-i
f66c177a62b7e762b7d10fc419dba12629bd0263
2,706
cpp
C++
test/HttpRequest_test.cpp
MisakiOfScut/SingHttpServer
039636d7cee16ccc46c281456d71a410f3f16e23
[ "Apache-2.0" ]
1
2021-03-05T09:27:35.000Z
2021-03-05T09:27:35.000Z
test/HttpRequest_test.cpp
MisakiOfScut/SingHttpServer
039636d7cee16ccc46c281456d71a410f3f16e23
[ "Apache-2.0" ]
null
null
null
test/HttpRequest_test.cpp
MisakiOfScut/SingHttpServer
039636d7cee16ccc46c281456d71a410f3f16e23
[ "Apache-2.0" ]
null
null
null
#include "../src/Http/HttpContext.h" #include <gtest/gtest.h> #define BOOST_CHECK_EQUAL(val1, val2) ASSERT_EQ(val1, val2) using namespace sing; using std::endl; using std::cout; TEST(HttpRequest_test,test_parse){ HttpContext context(0); string s("GET /index.html HTTP/1.1\r\n" "Host: www.wws.com\r\n" "\r\n"); context.getInput()->append(s); ASSERT_EQ(context.getInput()->findCRLF(),context.getInput()->peek()+24); ASSERT_TRUE(context.parseRequest()); ASSERT_TRUE(context.parseFinsh()); HttpRequest* request = context.getRequest(); BOOST_CHECK_EQUAL(request->getMethod(), HttpRequest::Get); BOOST_CHECK_EQUAL(request->getPath(), string("/index.html")); BOOST_CHECK_EQUAL(request->getVersion(), HttpRequest::HTTP11); BOOST_CHECK_EQUAL(request->getHeaders("Host"), string("www.wws.com")); BOOST_CHECK_EQUAL(request->getHeaders("User-Agent"), string("")); } TEST(HttpRequest_test,test_parse_in_2pieces){ string s("GET /index.html HTTP/1.1\r\n" "Host: www.wws.com\r\n" "\r\n"); for(size_t s1=0;s1<s.size();++s1){ HttpContext context(0); context.getInput()->append(s.c_str(),s1); ASSERT_TRUE(context.parseRequest()); ASSERT_FALSE(context.parseFinsh()); size_t s2 = s.size()-s1; context.getInput()->append(s.c_str()+s1,s2); ASSERT_TRUE(context.parseRequest()); ASSERT_TRUE(context.parseFinsh()); HttpRequest* request = context.getRequest(); BOOST_CHECK_EQUAL(request->getMethod(), HttpRequest::Get); BOOST_CHECK_EQUAL(request->getPath(), string("/index.html")); BOOST_CHECK_EQUAL(request->getVersion(), HttpRequest::HTTP11); BOOST_CHECK_EQUAL(request->getHeaders("Host"), string("www.wws.com")); BOOST_CHECK_EQUAL(request->getHeaders("User-Agent"), string("")); } } TEST(HttpRequest_test,test_empty_headers){ HttpContext context(0); string s("GET /index.html HTTP/1.0\r\n" "Host: www.wws.com\r\n" "User-agent:\r\n" "\r\n"); context.getInput()->append(s); ASSERT_EQ(context.getInput()->findCRLF(),context.getInput()->peek()+24); ASSERT_TRUE(context.parseRequest()); ASSERT_TRUE(context.parseFinsh()); HttpRequest* request = context.getRequest(); BOOST_CHECK_EQUAL(request->getMethod(), HttpRequest::Get); BOOST_CHECK_EQUAL(request->getPath(), string("/index.html")); BOOST_CHECK_EQUAL(request->getVersion(), HttpRequest::HTTP11); BOOST_CHECK_EQUAL(request->getHeaders("Host"), string("www.wws.com")); BOOST_CHECK_EQUAL(request->getHeaders("User-Agent"), string("")); }
39.794118
78
0.652254
MisakiOfScut
f676f5bb8105ff52c4925f9100fbd079e0368624
1,633
cpp
C++
3rdParty/iresearch/core/search/all_iterator.cpp
RudySchockaert-EngieIT/arangodb
e53ad4c33b72343e6fc0e2737657724b3bb49bc1
[ "Apache-2.0" ]
null
null
null
3rdParty/iresearch/core/search/all_iterator.cpp
RudySchockaert-EngieIT/arangodb
e53ad4c33b72343e6fc0e2737657724b3bb49bc1
[ "Apache-2.0" ]
null
null
null
3rdParty/iresearch/core/search/all_iterator.cpp
RudySchockaert-EngieIT/arangodb
e53ad4c33b72343e6fc0e2737657724b3bb49bc1
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2017 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Andrey Abramov //////////////////////////////////////////////////////////////////////////////// #include "all_iterator.hpp" #include "formats/empty_term_reader.hpp" NS_ROOT all_iterator::all_iterator( const sub_reader& reader, const byte_type* query_stats, const order::prepared& order, uint64_t docs_count, boost_t boost) : attributes{{ { type<document>::id(), &doc_ }, { type<cost>::id(), &cost_ }, { type<score>::id(), &score_ }, }}, max_doc_(doc_id_t(doc_limits::min() + docs_count - 1)) { // set estimation value cost_.value(max_doc_); // set score if (!order.empty()) { score_.prepare( order, order.prepare_scorers(reader, irs::empty_term_reader(docs_count), query_stats, *this, boost) ); } } NS_END // ROOT
29.690909
80
0.595836
RudySchockaert-EngieIT
f67e569d9b1614fb16741eb759612e438b66aa9d
1,069
cc
C++
Codeforces/271 Division 2/Problem D/D.cc
VastoLorde95/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
170
2017-07-25T14:47:29.000Z
2022-01-26T19:16:31.000Z
Codeforces/271 Division 2/Problem D/D.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
null
null
null
Codeforces/271 Division 2/Problem D/D.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
55
2017-07-28T06:17:33.000Z
2021-10-31T03:06:22.000Z
#include<cstdio> #include<iostream> #include<cmath> #include<algorithm> #include<cstring> #include<map> #include<set> #include<vector> #include<utility> #include<queue> #include<stack> #define sd(x) scanf("%d",&x) #define sd2(x,y) scanf("%d%d",&x,&y) #define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z) #define fi first #define se second #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) #define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #define tr(x) cout<<x<<endl; #define tr2(x,y) cout<<x<<" "<<y<<endl; #define tr3(x,y,z) cout<<x<<" "<<y<<" "<<z<<endl; #define tr4(w,x,y,z) cout<<w<<" "<<x<<" "<<y<<" "<<z<<endl; using namespace std; int t, k, a, b; long long MOD = 1000000007, dp[100001], sum[100001]; int main(){ _ cin >> t >> k; dp[0] = 1; for(int i = 1; i < k; i++){ dp[i] = 1; } for(int i = k; i <= 100000; i++){ dp[i] = (dp[i-1] + dp[i-k])%MOD; } for(int i = 1; i <= 100000; i++){ sum[i] = (sum[i-1] + dp[i])%MOD; } while(t--){ cin >> a >> b; cout << (sum[b] - sum[a-1] + MOD)%MOD << endl; } return 0; }
20.169811
72
0.566885
VastoLorde95
f680fffdcc4c4a383bde3156c19f293eb92f1079
11,521
hpp
C++
src/core/utils/parse_cmdline.hpp
yiyang-tian/openthread
885e2043c430b55d3501502e57323dfb7fadae03
[ "BSD-3-Clause" ]
2
2016-09-10T04:10:24.000Z
2017-01-04T21:34:14.000Z
src/core/utils/parse_cmdline.hpp
yiyang-tian/openthread
885e2043c430b55d3501502e57323dfb7fadae03
[ "BSD-3-Clause" ]
null
null
null
src/core/utils/parse_cmdline.hpp
yiyang-tian/openthread
885e2043c430b55d3501502e57323dfb7fadae03
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2018, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file includes definitions for command line parser. */ #ifndef PARSE_CMD_LINE_HPP_ #define PARSE_CMD_LINE_HPP_ #include <stdint.h> #include <openthread/error.h> #include <openthread/ip6.h> namespace ot { namespace Utils { namespace CmdLineParser { /** * @addtogroup utils-parse-cmd-line * * @brief * This module includes definitions for command line parser. * * @{ */ /** * This enumeration type represents the parse mode value used as a parameter in `ParseAsHexString()`. * */ enum HexStringParseMode : uint8_t { kDisallowTruncate, // Disallow truncation of hex string. kAllowTruncate, // Allow truncation of hex string. }; /** * This function parses a given command line string and breaks it into an argument list. * * Note: this method may change the input @p aCommandString, it will put a '\0' by the end of each argument, * and @p aArgs will point to the arguments in the input @p aCommandString. Backslash ('\') can be used * to escape separators (' ', '\t', '\r', '\n') and the backslash itself. * * @param[in] aCommandString A null-terminated input string. * @param[out] aArgsLength The argument counter of the command line. * @param[out] aArgs The argument vector of the command line. * @param[in] aArgsLengthMax The maximum argument counter. * */ otError ParseCmd(char *aCommandString, uint8_t &aArgsLength, char *aArgs[], uint8_t aArgsLengthMax); /** * This function parses a string as a `uint8_t` value. * * The number in string is parsed as decimal or hex format (if contains `0x` or `0X` prefix). * * @param[in] aString The string to parse. * @param[out] aUint8 A reference to an `uint8_t` variable to output the parsed value. * * @retval kErrorNone The string was parsed successfully. * @retval kErrorInvalidArgs The string does not contain valid number (e.g., value out of range). * */ otError ParseAsUint8(const char *aString, uint8_t &aUint8); /** * This function parses a string as a `uint16_t` value. * * The number in string is parsed as decimal or hex format (if contains `0x` or `0X` prefix). * * @param[in] aString The string to parse. * @param[out] aUint16 A reference to an `uint16_t` variable to output the parsed value. * * @retval kErrorNone The string was parsed successfully. * @retval kErrorInvalidArgs The string does not contain valid number (e.g., value out of range). * */ otError ParseAsUint16(const char *aString, uint16_t &aUint16); /** * This function parses a string as a `uint32_t` value. * * The number in string is parsed as decimal or hex format (if contains `0x` or `0X` prefix). * * @param[in] aString The string to parse. * @param[out] aUint32 A reference to an `uint32_t` variable to output the parsed value. * * @retval kErrorNone The string was parsed successfully. * @retval kErrorInvalidArgs The string does not contain valid number (e.g., value out of range). * */ otError ParseAsUint32(const char *aString, uint32_t &aUint32); /** * This function parses a string as a `uint64_t` value. * * The number in string is parsed as decimal or hex format (if contains `0x` or `0X` prefix). * * @param[in] aString The string to parse. * @param[out] aUint64 A reference to an `uint64_t` variable to output the parsed value. * * @retval kErrorNone The string was parsed successfully. * @retval kErrorInvalidArgs The string does not contain valid number (e.g., value out of range). * */ otError ParseAsUint64(const char *aString, uint64_t &aUint64); /** * This function parses a string as a `int8_t` value. * * The number in string is parsed as decimal or hex format (if contains `0x` or `0X` prefix). The string can start with * `+`/`-` sign. * * @param[in] aString The string to parse. * @param[out] aInt8 A reference to an `int8_t` variable to output the parsed value. * * @retval kErrorNone The string was parsed successfully. * @retval kErrorInvalidArgs The string does not contain valid number (e.g., value out of range). * */ otError ParseAsInt8(const char *aString, int8_t &aInt8); /** * This function parses a string as a `int16_t` value. * * The number in string is parsed as decimal or hex format (if contains `0x` or `0X` prefix). The string can start with * `+`/`-` sign. * * @param[in] aString The string to parse. * @param[out] aInt16 A reference to an `int16_t` variable to output the parsed value. * * @retval kErrorNone The string was parsed successfully. * @retval kErrorInvalidArgs The string does not contain valid number (e.g., value out of range). * */ otError ParseAsInt16(const char *aString, int16_t &aInt16); /** * This function parses a string as a `int32_t` value. * * The number in string is parsed as decimal or hex format (if contains `0x` or `0X` prefix). The string can start with * `+`/`-` sign. * * @param[in] aString The string to parse. * @param[out] aInt32 A reference to an `int32_t` variable to output the parsed value. * * @retval kErrorNone The string was parsed successfully. * @retval kErrorInvalidArgs The string does not contain valid number (e.g., value out of range). * */ otError ParseAsInt32(const char *aString, int32_t &aInt32); /** * This function parses a string as a `bool` value. * * Zero value is treated as `false, non-zero value as `true`. * * @param[in] aString The string to parse. * @param[out] aBool A reference to a `bool` variable to output the parsed value. * * @retval kErrorNone The string was parsed successfully. * @retval kErrorInvalidArgs The string does not contain valid number. * */ otError ParseAsBool(const char *aString, bool &aBool); #if OPENTHREAD_FTD || OPENTHREAD_MTD /** * This function parses a string as an IPv6 address. * * * @param[in] aString The string to parse. * @param[out] aAddress A reference to an `otIp6Address` to output the parsed IPv6 address. * * @retval kErrorNone The string was parsed successfully. * @retval kErrorInvalidArgs The string does not contain valid IPv6 address. * */ inline otError ParseAsIp6Address(const char *aString, otIp6Address &aAddress) { return otIp6AddressFromString(aString, &aAddress); } /** * This function parses a string as an IPv6 prefix. * * The string is parsed as `{IPv6Address}/{PrefixLength}`. * * @param[in] aString The string to parse. * @param[out] aPrefix A reference to an `otIp6Prefix` to output the parsed IPv6 prefix. * * @retval kErrorNone The string was parsed successfully. * @retval kErrorInvalidArgs The string does not contain valid IPv6 prefix * */ otError ParseAsIp6Prefix(const char *aString, otIp6Prefix &aPrefix); #endif // OPENTHREAD_FTD || OPENTHREAD_MTD /** * This function parses a hex string into a byte array of fixed expected size. * * This function returns `kErrorNone` only when the hex string contains exactly @p aSize bytes (after parsing). If * there are fewer or more bytes in hex string that @p aSize, the parsed bytes (up to @p aSize) are copied into the * `aBuffer` and `kErrorInvalidArgs` is returned. * * @param[in] aString The string to parse. * @param[out] aBuffer A pointer to a buffer to output the parsed byte sequence. * @param[in] aSize The expected size of byte sequence (number of bytes after parsing). * * @retval kErrorNone The string was parsed successfully. * @retval kErrorInvalidArgs The string does not contain valid hex bytes and/or not @p aSize bytes. * */ otError ParseAsHexString(const char *aString, uint8_t *aBuffer, uint16_t aSize); /** * This template function parses a hex string into a a given fixed size array. * * This function returns `kErrorNone` only when the hex string contains exactly @p kBufferSize bytes (after parsing). * If there are fewer or more bytes in hex string that @p kBufferSize, the parsed bytes (up to @p kBufferSize) are * copied into the `aBuffer` and `kErrorInvalidArgs` is returned. * * @tparam kBufferSize The byte array size (number of bytes). * * @param[in] aString The string to parse. * @param[out] aBuffer A reference to a byte array to output the parsed byte sequence. * * @retval kErrorNone The string was parsed successfully. * @retval kErrorInvalidArgs The string does not contain valid hex bytes and/or not @p aSize bytes. * */ template <uint16_t kBufferSize> static otError ParseAsHexString(const char *aString, uint8_t (&aBuffer)[kBufferSize]) { return ParseAsHexString(aString, aBuffer, kBufferSize); } /** * This function parses a hex string into a byte array. * * If @p aMode disallows truncation (`kDisallowTruncate`), this function verifies that parses hex string bytes fit in * @p aBuffer with its given size in @aSize. Otherwise when @p aMode allows truncation, extra bytes after @p aSize bytes * are ignored. * * @param[in] aString The string to parse. * @param[inout] aSize On entry indicates the number of bytes in @p aBuffer (max size of @p aBuffer). * On exit provides number of bytes parsed and copied into @p aBuffer * @param[out] aBuffer A pointer to a buffer to output the parsed byte sequence. * @param[in] aMode Indicates parsing mode whether to allow truncation or not. * * @retval kErrorNone The string was parsed successfully. * @retval kErrorInvalidArgs The string does not contain valid format or too many bytes (if truncation not allowed) * */ otError ParseAsHexString(const char * aString, uint16_t & aSize, uint8_t * aBuffer, HexStringParseMode aMode = kDisallowTruncate); /** * @} */ } // namespace CmdLineParser } // namespace Utils } // namespace ot #endif // PARSE_CMD_LINE_HPP_
38.922297
120
0.707317
yiyang-tian
f68180defcba9d340fb4dc6facbfe74e7085ca73
4,331
cpp
C++
prototypes_cinder/FakeSignal/src/PlayBack.cpp
redpaperheart/pinball_dreams
f1b873dc451157d9f2987501080a907635c80350
[ "Unlicense" ]
1
2016-07-29T21:19:12.000Z
2016-07-29T21:19:12.000Z
prototypes_cinder/FakeSignal/src/PlayBack.cpp
redpaperheart/pinball_dreams
f1b873dc451157d9f2987501080a907635c80350
[ "Unlicense" ]
null
null
null
prototypes_cinder/FakeSignal/src/PlayBack.cpp
redpaperheart/pinball_dreams
f1b873dc451157d9f2987501080a907635c80350
[ "Unlicense" ]
null
null
null
// // PlayBack.cpp // FakeSignal // // Created by red paper heart on 7/14/16. // // #include "PlayBack.hpp" #include "cinder/Json.h" PlayBack::PlayBack() { mplayBackButton = Rectf(660,150,740,190); } void PlayBack::draw() { switch (mButtonStatus){ case GREY: gl::color(0, 0, 0,0.8); break; case START: case PAUSE: gl::color(0, 0, 1,0.5); break; default:break; } gl::drawSolidRect(mplayBackButton); switch (mButtonStatus){ case GREY: gl::drawStringCentered("Start", vec2(700,170),Color(1,1,1)); break; case START: gl::drawStringCentered("Pause", vec2(700,170),Color(0,0,0)); break; case PAUSE: gl::drawStringCentered("Start", vec2(700,170),Color(0,0,0)); break; default:break; } if(mIfPlayBack){ gl::drawStringCentered(to_string( mVectCounter)+"/"+to_string(mFrameVec.size()), vec2(700,210),Color(0,0,0)); } } float PlayBack::loadRecordedData(fs::path path) { fs::path recordedData; if (fs::is_regular_file(path) && path.extension() == ".json") { recordedData = path; }else { app::console() << "It's not JSON file!" << endl; return 0; } string fileName = path.stem().string(); mSignalVec.clear(); mFrameVec.clear(); mVectCounter = 0; //app::console() << "JSON file type" << " , " << mPlayBack << endl; //parsing json file. load data try{ JsonTree doc (loadFile(recordedData)); int i = 0; for (auto &signal:doc["osc_data"].getChildren()){ string signalArr = signal["signal"].getValue<string>(); int frameCnt = signal["frameCnt"].getValue<int>(); string comment = signal["comment"].getValue<string>(); float time = signal["time"].getValue<float>(); if(i == 0 ) mPlaybackStartFrame = frameCnt-5; mSignalVec.push_back(signalArr); mFrameVec.push_back(frameCnt); mCommentVec.push_back(comment); mTimeVec.push_back(time); i++; } app::console() <<"data amount: " <<mFrameVec.size() << endl; }catch(Exception e){ app::console() << e.what() << endl; return 0; } mIfPlayBack = true; mStartFrame = app::getElapsedFrames(); mButtonStatus = START; mBreakTime = 0; //calculate the average framerate float avgFrameRate = 0; for (int i = 1; i<mFrameVec.size();i++){ avgFrameRate+= (mFrameVec[i]-mFrameVec[i-1])/(mTimeVec[i]-mTimeVec[i-1]); } return avgFrameRate/(mFrameVec.size()-1); } void PlayBack::changeStatus() { switch (mButtonStatus){ case START: mButtonStatus = PAUSE; mIfPlayBack = false; mStopeFrame = app::getElapsedFrames(); app::console() << "Stop Frame: "<< mStopeFrame << endl; break; case PAUSE: mButtonStatus = START; mIfPlayBack = true; mRestartFrame = app::getElapsedFrames(); mBreakTime += mRestartFrame - mStopeFrame; app::console() << "Restart Frame: "<< mRestartFrame << " Break Time:" << mBreakTime << endl; break; default:break; } } string PlayBack::playback() { string returnStr = ""; if(mIfPlayBack){ //app::console() << app::getElapsedFrames() - mStartFrame << " " << mFrameVec[mVectCounter]-mPlaybackStartFrame << endl; if ((app::getElapsedFrames() - mStartFrame - mBreakTime) == mFrameVec[mVectCounter]- mPlaybackStartFrame){ app::console() << mVectCounter+1 << "/" << mFrameVec.size() << " "<< mCommentVec[mVectCounter] << " "; //sendMsg( mSignalVec[mVectCounter] ); returnStr = mSignalVec[mVectCounter]; mVectCounter++; } if( mVectCounter == mFrameVec.size() ){ mVectCounter = 0; mStartFrame = app::getElapsedFrames() + 30; mBreakTime = 0; } } return returnStr; }
27.411392
130
0.529208
redpaperheart
f681abbd9846f03279b9be67876f1fe9bd6a670e
28,577
cpp
C++
FireRender.Maya.Src/Translators/MeshTranslator.cpp
V-Gorash/RadeonProRenderMayaPlugin
3b844ad4602177eeb413c0708bd75c4439d97a7d
[ "Apache-2.0" ]
22
2020-05-15T14:07:40.000Z
2022-03-17T08:10:42.000Z
FireRender.Maya.Src/Translators/MeshTranslator.cpp
V-Gorash/RadeonProRenderMayaPlugin
3b844ad4602177eeb413c0708bd75c4439d97a7d
[ "Apache-2.0" ]
38
2020-05-13T23:24:21.000Z
2022-02-28T12:16:51.000Z
FireRender.Maya.Src/Translators/MeshTranslator.cpp
V-Gorash/RadeonProRenderMayaPlugin
3b844ad4602177eeb413c0708bd75c4439d97a7d
[ "Apache-2.0" ]
19
2020-05-13T15:24:09.000Z
2022-03-29T13:36:02.000Z
/********************************************************************** Copyright 2020 Advanced Micro Devices, Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ********************************************************************/ // If you experience performance issues on mesh creation functionality in Debug // you can set (only for this file) Optimization option to "Maximize speed" and switch off Basic runtime checks to "Default" #include "MeshTranslator.h" #include "DependencyNode.h" #include "FireRenderThread.h" #include <maya/MFnMesh.h> #include <maya/MFnSubd.h> #include <maya/MFloatPointArray.h> #include <maya/MFloatVectorArray.h> #include <maya/MFloatArray.h> #include <maya/MPointArray.h> #include <maya/MItMeshPolygon.h> #include <maya/MSelectionList.h> #include <maya/MAnimControl.h> #include <unordered_map> #include "SingleShaderMeshTranslator.h" #include "MultipleShaderMeshTranslator.h" #ifdef OPTIMIZATION_CLOCK #include <chrono> #endif FireMaya::MeshTranslator::MeshPolygonData::MeshPolygonData() : pVertices(nullptr) , countVertices(0) , pNormals(nullptr) , countNormals(0) , triangleVertexIndicesCount(0) , motionSamplesCount(0) , haveDeformation(false) , fullName("") , m_isInitialized(false) { } void ChangeCurrentTimeAndUpdateMesh(MFnMesh& fnMesh, const MTime& time, MString fullDagPath) { MGlobal::viewFrame(time); // We need to update fnMesh function set in order to apply time change MDagPath dagPath; MSelectionList sl; sl.add(fullDagPath); if (!sl.isEmpty()) { sl.getDagPath(0, dagPath); fnMesh.setObject(dagPath); } else { assert(false); } } bool DoesMeshHaveDeformation(const MString& fullDagPath) { // back-off if (fullDagPath.length() == 0) return false; // Check if mesh has deformers or rigs inside construction history MString command; command.format("source common.mel; hasGivenMeshDeformerOrRigAttached(\"^1s\");", fullDagPath); MStatus status; MString result = MGlobal::executeCommandStringResult(command, false, false, &status); if (result.asInt() == 0) { return false; } return true; } bool FireMaya::MeshTranslator::MeshPolygonData::ProcessDeformationFrameCount(MFnMesh& fnMesh, MString fullDagPath) { if (motionSamplesCount < 2 || fullDagPath.length() == 0) { return false; } // Check if mesh has deformers or rigs inside construction history MString name = fullDagPath; MString command; command.format("source common.mel; hasGivenMeshDeformerOrRigAttached(\"^1s\");", name); MStatus status; MString result = MGlobal::executeCommandStringResult(command, false, false, &status); if (result.asInt() == 0) { return false; } MTime initialTime = MAnimControl::currentTime(); MTime currentTime = initialTime; if (initialTime == MAnimControl::maxTime()) { return false; } size_t floatsVertexOneFrame = 3 * countVertices; size_t floatsNormalOneFrame = 3 * countNormals; unsigned int currentTimeIndex = 0; MDagPath dagPath; for (unsigned int currentTimeIndex = 0; currentTimeIndex < motionSamplesCount; ++currentTimeIndex) { // positioning on next point of time (starting from currentTime) currentTime += (float)currentTimeIndex / (motionSamplesCount - 1); ChangeCurrentTimeAndUpdateMesh(fnMesh, currentTime, fullDagPath); const float* pData = fnMesh.getRawPoints(&status); assert(MStatus::kSuccess == status); std::copy(pData, pData + floatsVertexOneFrame, arrVertices.data() + floatsVertexOneFrame * currentTimeIndex); pData = fnMesh.getRawNormals(&status); assert(MStatus::kSuccess == status); std::copy(pData, pData + floatsNormalOneFrame, arrNormals.data() + floatsNormalOneFrame * currentTimeIndex); } ChangeCurrentTimeAndUpdateMesh(fnMesh, initialTime, fullDagPath); return true; } void FireMaya::MeshTranslator::MeshPolygonData::clear() { m_isInitialized = false; arrVertices.clear(); arrNormals.clear(); uvCoords.clear(); sizeCoords.clear(); puvCoords.clear(); } bool FireMaya::MeshTranslator::MeshPolygonData::Initialize(MFnMesh& fnMesh, unsigned int deformationFrameCount, MString fullDagPath) { GetUVCoords(fnMesh, uvSetNames, uvCoords, puvCoords, sizeCoords); unsigned int uvSetCount = uvSetNames.length(); MStatus mstatus; MString meshName = fnMesh.name(); // pointer to array of vertices coordinates in Maya pVertices = fnMesh.getRawPoints(&mstatus); assert(MStatus::kSuccess == mstatus); // For empty meshes vertices is null if (pVertices == nullptr) { return false; } countVertices = fnMesh.numVertices(&mstatus); assert(MStatus::kSuccess == mstatus); if (countVertices == 0) { return false; } // pointer to array of normal coordinates in Maya pNormals = fnMesh.getRawNormals(&mstatus); assert(MStatus::kSuccess == mstatus); countNormals = fnMesh.numNormals(&mstatus); assert(MStatus::kSuccess == mstatus); size_t floatsVertexOneFrame = 3 * countVertices; size_t floatsNormalOneFrame = 3 * countNormals; haveDeformation = DoesMeshHaveDeformation(fullDagPath) && (deformationFrameCount > 0); arrVertices.resize(haveDeformation ? floatsVertexOneFrame * deformationFrameCount : floatsVertexOneFrame ); arrNormals.resize(haveDeformation ? floatsNormalOneFrame * deformationFrameCount : floatsNormalOneFrame ); if (haveDeformation) { motionSamplesCount = deformationFrameCount; } if (!haveDeformation) { const float* pData = fnMesh.getRawPoints(&mstatus); assert(MStatus::kSuccess == mstatus); std::copy(pData, pData + countVertices * 3, arrVertices.data()); pData = fnMesh.getRawNormals(&mstatus); assert(MStatus::kSuccess == mstatus); std::copy(pData, pData + countNormals * 3, arrNormals.data()); } else { ReadDeformationFrame(fnMesh, 0); } // get triangle count (max possible count; this number is used for reserve only) MIntArray triangleCounts; // basically number of triangles in polygons; size of array equal to number of polygons in mesh MIntArray triangleVertices; // indices of points in triangles (3 indices per triangle) mstatus = fnMesh.getTriangles(triangleCounts, triangleVertices); triangleVertexIndicesCount = triangleVertices.length(); m_isInitialized = true; return true; } bool FireMaya::MeshTranslator::MeshPolygonData::ReadDeformationFrame(MFnMesh& fnMesh, unsigned int currentDeformationFrame) { if (!haveDeformation) { return true; } size_t floatsVertexOneFrame = 3 * countVertices; size_t floatsNormalOneFrame = 3 * countNormals; MStatus status; const float* pData = fnMesh.getRawPoints(&status); assert(MStatus::kSuccess == status); assert(arrVertices.size() >= floatsVertexOneFrame * currentDeformationFrame); std::copy(pData, pData + floatsVertexOneFrame, arrVertices.data() + floatsVertexOneFrame * currentDeformationFrame); pData = fnMesh.getRawNormals(&status); assert(MStatus::kSuccess == status); assert(arrNormals.size() >= floatsNormalOneFrame * currentDeformationFrame); std::copy(pData, pData + floatsNormalOneFrame, arrNormals.data() + floatsNormalOneFrame * currentDeformationFrame); return true; } bool FireMaya::MeshTranslator::PreProcessMesh( MeshPolygonData& outMeshPolygonData, const frw::Context& context, const MObject& originalObject, unsigned int deformationFrameCount /*= 0*/, unsigned int currentDeformationFrame /*= 0*/, MString fullDagPath /*= ""*/) { MAIN_THREAD_ONLY; MStatus mayaStatus; MFnDagNode node(originalObject); outMeshPolygonData.fullName = node.fullPathName(); DebugPrint("PreProcessMesh: %s, deformantion frame %d", outMeshPolygonData.fullName.asUTF8(), currentDeformationFrame); // Don't render intermediate object if (node.isIntermediateObject(&mayaStatus)) { return false; } // Create tesselated object MObject tessellated = GetTesselatedObjectIfNecessary(originalObject, mayaStatus); if (MStatus::kSuccess != mayaStatus) { mayaStatus.perror("Tesselation error"); return false; } MObject smoothed = GetSmoothedObjectIfNecessary(originalObject, mayaStatus); if (MStatus::kSuccess != mayaStatus) { mayaStatus.perror("Smoothing error"); return false; } // Consider geting mesh from tesselated or smoothed objects MObject object = originalObject; if (!tessellated.isNull()) { object = tessellated; } if (!smoothed.isNull()) { object = smoothed; } // get fnMesh MFnMesh fnMesh(object, &mayaStatus); if (MStatus::kSuccess != mayaStatus) { mayaStatus.perror("MFnMesh constructor error"); return false; } // all checks clear => proceed with extracting mesh data from Maya bool successfullyProcessed = false; // get number of materials used in this mesh if (currentDeformationFrame == 0) { outMeshPolygonData.materialCount = GetFaceMaterials(fnMesh, outMeshPolygonData.faceMaterialIndices); // for tesselated or smoothed mesh disable deformation MB for now successfullyProcessed = outMeshPolygonData.Initialize( fnMesh, object != originalObject ? 0 : deformationFrameCount, fullDagPath ); } else { successfullyProcessed = outMeshPolygonData.ReadDeformationFrame( fnMesh, currentDeformationFrame ); } if (!successfullyProcessed) { std::string nodeName = fnMesh.name().asChar(); std::string message = nodeName + " wasn't created: Mesh has no vertices"; MGlobal::displayWarning(message.c_str()); return false; } // Now remove any temporary mesh we created. if (!tessellated.isNull()) { RemoveTesselatedTemporaryMesh(node, tessellated); } if (!smoothed.isNull()) { RemoveSmoothedTemporaryMesh(node, smoothed); } return successfullyProcessed; } std::vector<frw::Shape> FireMaya::MeshTranslator::TranslateMesh( MeshPolygonData& meshPolygonData, const frw::Context& context, const MObject& originalObject, std::vector<int>& outFaceMaterialIndices, unsigned int deformationFrameCount, MString fullDagPath) { std::vector<frw::Shape> resultShapes; DebugPrint("TranslateMesh: %s", meshPolygonData.fullName.asUTF8()); outFaceMaterialIndices.clear(); TahoePluginVersion version = GetTahoeVersionToUse(); bool isRPR20 = version == TahoePluginVersion::RPR2; // get fnMesh // - NOTE: this will be removed in future PR MObject object = originalObject; MStatus mayaStatus; MObject tessellated = GetTesselatedObjectIfNecessary(originalObject, mayaStatus); if (MStatus::kSuccess != mayaStatus) { mayaStatus.perror("Tesselation error"); } MObject smoothed = GetSmoothedObjectIfNecessary(originalObject, mayaStatus); if (MStatus::kSuccess != mayaStatus) { mayaStatus.perror("Smoothing error"); } if (!tessellated.isNull()) { object = tessellated; } if (!smoothed.isNull()) { object = smoothed; } MFnMesh fnMesh(object, &mayaStatus); if (MStatus::kSuccess != mayaStatus) { mayaStatus.perror("MFnMesh constructor"); } // translate mesh if (isRPR20) { resultShapes.resize(1); SingleShaderMeshTranslator::TranslateMesh( context, fnMesh, resultShapes, meshPolygonData, meshPolygonData.faceMaterialIndices, outFaceMaterialIndices ); } else { resultShapes.resize(meshPolygonData.materialCount); MultipleShaderMeshTranslator::TranslateMesh(context, fnMesh, resultShapes, meshPolygonData, meshPolygonData.faceMaterialIndices); } // Now remove any temporary mesh we created. MFnDagNode node(originalObject); if (!tessellated.isNull()) { RemoveTesselatedTemporaryMesh(node, tessellated); } if (!smoothed.isNull()) { RemoveSmoothedTemporaryMesh(node, smoothed); } return resultShapes; } std::vector<frw::Shape> FireMaya::MeshTranslator::TranslateMesh( const frw::Context& context, const MObject& originalObject, std::vector<int>& outFaceMaterialIndices, unsigned int deformationFrameCount, MString fullDagPath) { MAIN_THREAD_ONLY; #ifdef OPTIMIZATION_CLOCK std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now(); #endif std::vector<frw::Shape> resultShapes; MStatus mayaStatus; MFnDagNode node(originalObject); DebugPrint("TranslateMesh: %s", node.fullPathName().asUTF8()); // Don't render intermediate object if (node.isIntermediateObject(&mayaStatus)) { return resultShapes; } // Create tesselated object MObject tessellated = GetTesselatedObjectIfNecessary(originalObject, mayaStatus); if (MStatus::kSuccess != mayaStatus) { mayaStatus.perror("Tesselation error"); return resultShapes; } MObject smoothed = GetSmoothedObjectIfNecessary(originalObject, mayaStatus); if (MStatus::kSuccess != mayaStatus) { mayaStatus.perror("Smoothing error"); return resultShapes; } // Consider geting mesh from tesselated or smoothed objects MObject object = originalObject; if (!tessellated.isNull()) { object = tessellated; } if (!smoothed.isNull()) { object = smoothed; } MFnMesh fnMesh(object, &mayaStatus); if (MStatus::kSuccess != mayaStatus) { mayaStatus.perror("MFnMesh constructor"); return resultShapes; } // get number of materials used in this mesh MIntArray faceMaterialIndices; int materialCount = GetFaceMaterials(fnMesh, faceMaterialIndices); // get common data from mesh MeshPolygonData meshPolygonData; /// for tesselated or smoothed mesh disable deformation MB for now bool successfullyInitialized = meshPolygonData.Initialize(fnMesh, object != originalObject ? 0 : deformationFrameCount, fullDagPath); if (!successfullyInitialized) { std::string nodeName = fnMesh.name().asChar(); std::string message = nodeName + " wasn't created: Mesh has no vertices"; MGlobal::displayWarning(message.c_str()); return resultShapes; } outFaceMaterialIndices.clear(); TahoePluginVersion version = GetTahoeVersionToUse(); bool isRPR20 = version == TahoePluginVersion::RPR2; if (isRPR20) { resultShapes.resize(1); SingleShaderMeshTranslator::TranslateMesh( context, fnMesh, resultShapes, meshPolygonData, faceMaterialIndices, outFaceMaterialIndices ); #ifdef OPTIMIZATION_CLOCK std::chrono::steady_clock::time_point fin = std::chrono::steady_clock::now(); std::chrono::milliseconds elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(fin - start); #endif } else { resultShapes.resize(materialCount); MultipleShaderMeshTranslator::TranslateMesh(context, fnMesh, resultShapes, meshPolygonData, faceMaterialIndices); } // Now remove any temporary mesh we created. if (!tessellated.isNull()) { RemoveTesselatedTemporaryMesh(node, tessellated); } if (!smoothed.isNull()) { RemoveSmoothedTemporaryMesh(node, smoothed); } #ifdef OPTIMIZATION_CLOCK std::chrono::steady_clock::time_point fin = std::chrono::steady_clock::now(); std::chrono::milliseconds elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(fin - start); FireRenderContext::inTranslateMesh += elapsed.count(); #endif return resultShapes; } MObject FireMaya::MeshTranslator::Smoothed2ndUV(const MObject& object, MStatus& status) { MFnMesh mesh(object); // clone original mesh MObject clonedMesh = mesh.copy(object); // get UVs from original mesh from second uv set MStringArray uvsetNames; mesh.getUVSetNames(uvsetNames); MFloatArray uArray; MFloatArray vArray; status = mesh.getUVs(uArray, vArray, &uvsetNames[1]); MIntArray uvCounts; MIntArray uvIds; status = mesh.getAssignedUVs(uvCounts, uvIds, &uvsetNames[1]); // get cloned mesh MDagPath item; MFnDagNode cloned_node(clonedMesh); cloned_node.getPath(item); item.extendToShape(); clonedMesh = item.node(); if (!clonedMesh.hasFn(MFn::kMesh)) return MObject::kNullObj; // assign UVs from second UV set to cloned mesh MFnMesh fnClonedMesh(clonedMesh); MStringArray uvSetNamesCloned; fnClonedMesh.getUVSetNames(uvSetNamesCloned); status = fnClonedMesh.deleteUVSet(uvSetNamesCloned[1]); fnClonedMesh.clearUVs(); status = fnClonedMesh.setUVs(uArray, vArray); status = fnClonedMesh.assignUVs(uvCounts, uvIds); // proceed with smoothing MFnDagNode dagClonedNode(clonedMesh); MObject clonedSmoothedMesh = fnClonedMesh.generateSmoothMesh(dagClonedNode.parent(0), NULL, &status); // destroy temporary object MGlobal::deleteNode(clonedMesh); return clonedSmoothedMesh; } MString GenerateSmoothOptions(const MFnDagNode& dagMesh) { std::map<std::string, std::string> optionMap; MPlug useSmoothPreviewForRenderPlug = dagMesh.findPlug("useSmoothPreviewForRender"); assert(!useSmoothPreviewForRenderPlug.isNull()); std::string smoothLevelPlugName = "smoothLevel"; if (useSmoothPreviewForRenderPlug.asInt() == 0) { smoothLevelPlugName = "renderSmoothLevel"; } MPlug smoothLevelPlug = dagMesh.findPlug(smoothLevelPlugName.c_str()); assert(!smoothLevelPlug.isNull()); std::string smoothLevel = std::to_string(smoothLevelPlug.asInt()); optionMap["dv"] = smoothLevel; MPlug useGlobalSmoothDrawTypePlug = dagMesh.findPlug("useGlobalSmoothDrawType"); assert(!useGlobalSmoothDrawTypePlug.isNull()); int smoothingType = 0; // read from globals if (useGlobalSmoothDrawTypePlug.asInt() > 0 ) { MGlobal::executeCommand("optionVar -q proxySubdivisionType", smoothingType); optionMap["sdt"] = std::to_string(smoothingType); } // read from node else { MPlug smoothDrawTypePlug = dagMesh.findPlug("smoothDrawType"); smoothingType = smoothDrawTypePlug.asInt(); assert(!smoothDrawTypePlug.isNull()); optionMap["sdt"] = std::to_string(smoothingType); } if (smoothingType == 0) // maya catmull-clark { MPlug keepBordersPlug = dagMesh.findPlug("keepBorder"); assert(!keepBordersPlug.isNull()); optionMap["kb"] = std::to_string(keepBordersPlug.asInt()); MPlug shouldSmoothUVs = dagMesh.findPlug("smoothUVs"); assert(!shouldSmoothUVs.isNull()); optionMap["suv"] = std::to_string(shouldSmoothUVs.asInt()); } else // OpenSubdiv catmull-clark { int uvBoundarySmoothType = 0; if (useGlobalSmoothDrawTypePlug.asInt() > 0) { MGlobal::executeCommand("optionVar -q proxySmoothOsdFvarBoundary", uvBoundarySmoothType); optionMap["ofb"] = std::to_string(uvBoundarySmoothType); } else { MPlug plug_uvSmooth = dagMesh.findPlug("osdFvarBoundary"); assert(!plug_uvSmooth.isNull()); optionMap["ofb"] = std::to_string(plug_uvSmooth.asInt()); } } MString result; for (auto it = optionMap.begin(); it != optionMap.end(); ++it) { result = result + "-" + it->first.c_str() + " " + it->second.c_str() + " "; } return result; } MObject FireMaya::MeshTranslator::GenerateSmoothMesh(const MObject& object, const MObject& parent, MStatus& status) { status = MStatus::kSuccess; // check if we need to generate a smooth mesh DependencyNode attributes(object); bool smoothPreview = attributes.getBool("displaySmoothMesh"); if (!smoothPreview) return MObject::kNullObj; // remember current selection MSelectionList currentSelection; MGlobal::getActiveSelectionList(currentSelection); // copy original mesh and smooth is via mel MFnDagNode dagMesh(object); MDagPath meshPath; dagMesh.getPath(meshPath); MString meshName = meshPath.fullPathName(&status); assert(status == MStatus::kSuccess); if (status != MStatus::kSuccess) return MObject::kNullObj; MString options = GenerateSmoothOptions(dagMesh); MString command = R"( proc string generateSmoothMesh() { $res = `duplicate -rc ^1s`; polySmooth ^2s $res[0]; select -clear; select -add $res[0]; return $res[0]; } generateSmoothMesh(); )"; command.format(command, meshName, options); MString result; status = MGlobal::executeCommand(command, result); if (status != MStatus::kSuccess) // failed to generate smoothMesh { return MObject::kNullObj; } // find generated mesh by returned name MObject smoothedMesh = MObject::kNullObj; MSelectionList clonedMeshSelection; MGlobal::getActiveSelectionList(clonedMeshSelection); if (status != MStatus::kSuccess) // failed to find cloned object return MObject::kNullObj; int len = clonedMeshSelection.length(); assert(len == 1); status = clonedMeshSelection.getDependNode(0, smoothedMesh); // set selection to previous selection MGlobal::setActiveSelectionList(currentSelection); // return created mesh return smoothedMesh; } MObject FireMaya::MeshTranslator::TessellateNurbsSurface(const MObject& object, const MObject& parent, MStatus& status) { // Read tessellation attributes. DependencyNode attributes(object); int modeU = attributes.getInt("modeU"); int numberU = attributes.getInt("numberU"); int modeV = attributes.getInt("modeV"); int numberV = attributes.getInt("numberV"); bool smoothEdge = attributes.getBool("smoothEdge"); bool useChordHeightRatio = attributes.getBool("useChordHeightRatio"); bool edgeSwap = attributes.getBool("edgeSwap"); bool useMinScreen = attributes.getBool("useMinScreen"); double chordHeightRatio = attributes.getDouble("chordHeightRatio"); double minScreen = attributes.getDouble("minScreen"); // Construct tessellation parameters. MTesselationParams params( MTesselationParams::kGeneralFormat, MTesselationParams::kTriangles); const std::map<int, int> modeToTesParam = { { 1, MTesselationParams::kSurface3DEquiSpaced }, { 2, MTesselationParams::kSurfaceEquiSpaced }, { 3, MTesselationParams::kSpanEquiSpaced }, { 4, MTesselationParams::kSurfaceEquiSpaced } }; std::map<int, int>::const_iterator it = modeToTesParam.find(modeU); assert(it != modeToTesParam.end()); params.setUIsoparmType((MTesselationParams::IsoparmType) it->second); it = modeToTesParam.find(modeV); assert(it != modeToTesParam.end()); params.setVIsoparmType((MTesselationParams::IsoparmType) it->second); params.setUNumber(numberU); params.setVNumber(numberV); params.setSubdivisionFlag(MTesselationParams::kUseChordHeightRatio, useChordHeightRatio); params.setChordHeightRatio(chordHeightRatio); params.setSubdivisionFlag(MTesselationParams::kUseMinScreenSize, useMinScreen); params.setMinScreenSize(minScreen, minScreen); params.setSubdivisionFlag(MTesselationParams::kUseEdgeSmooth, smoothEdge); params.setSubdivisionFlag(MTesselationParams::kUseTriangleEdgeSwapping, edgeSwap); // Tessellate the surface and return the resulting mesh object. MFnNurbsSurface surface(object); MObject tesselated = surface.tesselate(params, parent, &status); // failure is possible and should be handled return tesselated; } MObject FireMaya::MeshTranslator::GetSmoothedObjectIfNecessary(const MObject& originalObject, MStatus& mstatus) { MFnDagNode node(originalObject); DebugPrint("TranslateMesh: %s", node.fullPathName().asUTF8()); MObject parent = node.parent(0); // tessellate to mesh if we aren't already one if (!originalObject.hasFn(MFn::kMesh)) { return MObject::kNullObj; } // is mesh => can smooth MObject smoothed = GenerateSmoothMesh(originalObject, parent, mstatus); if (mstatus != MStatus::kSuccess) { mstatus.perror("MFnMesh::generateSmoothMesh"); return MObject::kNullObj; } if (smoothed != MObject::kNullObj) { // get shape MDagPath createdMeshPath; MFnDagNode smoothedObj(smoothed); mstatus = smoothedObj.getPath(createdMeshPath); assert(mstatus == MStatus::kSuccess); createdMeshPath.extendToShape(); smoothed = createdMeshPath.node(); } return smoothed; } MObject FireMaya::MeshTranslator::GetTesselatedObjectIfNecessary(const MObject& originalObject, MStatus& mstatus) { #ifdef OPTIMIZATION_CLOCK std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now(); #endif MFnDagNode node(originalObject); DebugPrint("TranslateMesh: %s", node.fullPathName().asUTF8()); MObject parent = node.parent(0); MObject tessellated = MObject::kNullObj; // tessellate to mesh if (originalObject.hasFn(MFn::kNurbsSurface)) { tessellated = TessellateNurbsSurface(originalObject, parent, mstatus); if (mstatus != MStatus::kSuccess) { mstatus.perror("MFnNurbsSurface::tessellate"); } } else if (originalObject.hasFn(MFn::kSubdiv)) { MFnSubd surface(originalObject); tessellated = surface.tesselate(false, 1, 1, parent, &mstatus); if (mstatus != MStatus::kSuccess) { mstatus.perror("MFnSubd::tessellate"); } } #ifdef OPTIMIZATION_CLOCK std::chrono::steady_clock::time_point fin = std::chrono::steady_clock::now(); std::chrono::microseconds elapsed = std::chrono::duration_cast<std::chrono::microseconds>(fin - start); FireRenderContext::getTessellatedObj += elapsed.count(); #endif return tessellated; } void FireMaya::MeshTranslator::RemoveTesselatedTemporaryMesh(const MFnDagNode& node, MObject tessellated) { MStatus mayaStatus; MObject parent = node.parent(0); FireRenderThread::RunProcOnMainThread([&] { #ifdef OPTIMIZATION_CLOCK std::chrono::steady_clock::time_point start_del = std::chrono::steady_clock::now(); #endif MFnDagNode parentNode(parent, &mayaStatus); if (MStatus::kSuccess == mayaStatus) { mayaStatus = parentNode.removeChild(tessellated); if (MStatus::kSuccess != mayaStatus) { mayaStatus.perror("MFnDagNode::removeChild"); } } // double-check if node hasn't already been removed if (!tessellated.isNull()) { MGlobal::deleteNode(tessellated); } #ifdef OPTIMIZATION_CLOCK std::chrono::steady_clock::time_point fin_del = std::chrono::steady_clock::now(); std::chrono::microseconds elapsed_del = std::chrono::duration_cast<std::chrono::microseconds>(fin_del - start_del); FireRenderContext::deleteNodes += elapsed_del.count(); #endif }); } void FireMaya::MeshTranslator::RemoveSmoothedTemporaryMesh(const MFnDagNode& node, MObject smoothed) { FireRenderThread::RunProcOnMainThread([&] { #ifdef OPTIMIZATION_CLOCK std::chrono::steady_clock::time_point start_del = std::chrono::steady_clock::now(); #endif MFnDagNode shapeNode(smoothed); assert(shapeNode.parentCount() == 1); MObject parent = shapeNode.parent(0); assert(!parent.isNull()); MGlobal::deleteNode(parent); #ifdef OPTIMIZATION_CLOCK std::chrono::steady_clock::time_point fin_del = std::chrono::steady_clock::now(); std::chrono::microseconds elapsed_del = std::chrono::duration_cast<std::chrono::microseconds>(fin_del - start_del); FireRenderContext::deleteNodes += elapsed_del.count(); #endif }); } void FireMaya::MeshTranslator::GetUVCoords( const MFnMesh& fnMesh, MStringArray& uvSetNames, std::vector<std::vector<Float2> >& uvCoords, std::vector<const float*>& puvCoords, std::vector<size_t>& sizeCoords) { uvSetNames.clear(); fnMesh.getUVSetNames(uvSetNames); unsigned int uvSetCount = uvSetNames.length(); // RPR supports only 2 UV sets. There is no way to get this value from RPR so it's hardcoded static const int rprMaxUVSetCount = 2; if (uvSetCount > rprMaxUVSetCount) { uvSetCount = rprMaxUVSetCount; MGlobal::displayError("Object " + fnMesh.fullPathName() + " have more than 2 UV sets. Only two UV sets per object supported. Scene will be rendered with first two UV sets."); } uvSetNames.setLength(uvSetCount); puvCoords.reserve(uvSetCount); sizeCoords.reserve(uvSetCount); MStatus mstatus; // Core accepts only equal sized UV coordinate arrays // We should fill less array with zeros size_t maxUVSize = 0; // - fill these arrays with data // - up to 2 UV channels is supported for (unsigned int currUVCHannel = 0; currUVCHannel < uvSetCount; ++currUVCHannel) { // - get data from Maya MFloatArray uArray; MFloatArray vArray; mstatus = fnMesh.getUVs(uArray, vArray, &uvSetNames[currUVCHannel]); assert(MStatus::kSuccess == mstatus); assert(uArray.length() == vArray.length()); // - RPR needs UV pairs instead of 2 parallel arrays (U and V) that Maya returns uvCoords.emplace_back(); uvCoords[currUVCHannel].reserve(uArray.length()); for (unsigned int idx = 0; idx < uArray.length(); ++idx) { Float2 uv; uv.x = uArray[idx]; uv.y = vArray[idx]; uvCoords[currUVCHannel].push_back(uv); } if (maxUVSize < uvCoords[currUVCHannel].size()) { maxUVSize = uvCoords[currUVCHannel].size(); } } // making equal size for (unsigned int currUVCHannel = 0; currUVCHannel < uvSetCount; ++currUVCHannel) { sizeCoords.push_back(maxUVSize); uvCoords[currUVCHannel].resize(maxUVSize); puvCoords.push_back(uvCoords[currUVCHannel].size() > 0 ? (float*)uvCoords[currUVCHannel].data() : nullptr); } }
28.548452
176
0.747839
V-Gorash
f68b24d072cc0b3577fac83e25b89828cd14deef
632
hpp
C++
src/picotorrent/advancedpage.hpp
kk7945287/pictorr
09bf9ccbd89f0b459cb07e3012ced9c35bea005c
[ "MIT" ]
null
null
null
src/picotorrent/advancedpage.hpp
kk7945287/pictorr
09bf9ccbd89f0b459cb07e3012ced9c35bea005c
[ "MIT" ]
null
null
null
src/picotorrent/advancedpage.hpp
kk7945287/pictorr
09bf9ccbd89f0b459cb07e3012ced9c35bea005c
[ "MIT" ]
null
null
null
#pragma once #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <memory> class wxPropertyGrid; namespace pt { class Configuration; class Translator; class AdvancedPage : public wxPanel { public: AdvancedPage(wxWindow* parent, std::shared_ptr<Configuration> config, std::shared_ptr<Translator> translator); void ApplyConfiguration(); bool ValidateConfiguration(wxString& error); private: wxWindow* m_parent; wxPropertyGrid* m_pg; std::shared_ptr<Configuration> m_cfg; std::shared_ptr<Translator> m_translator; }; }
19.151515
118
0.678797
kk7945287
f68d414eff261ae76c536e71101d4d82cd2b25a2
2,112
cpp
C++
webRecognize/src/stream_content/Range.cpp
enzo418/Recognice-CCTV-c-
15da07a559d6de611452df4d404a15d4551c3017
[ "Apache-2.0" ]
1
2020-09-06T21:44:56.000Z
2020-09-06T21:44:56.000Z
webRecognize/src/stream_content/Range.cpp
enzo418/Recognice-CCTV-c-
15da07a559d6de611452df4d404a15d4551c3017
[ "Apache-2.0" ]
null
null
null
webRecognize/src/stream_content/Range.cpp
enzo418/Recognice-CCTV-c-
15da07a559d6de611452df4d404a15d4551c3017
[ "Apache-2.0" ]
null
null
null
#include "Range.hpp" std::vector<std::string> splitString(const std::string& str, const std::string& delim) { std::vector<std::string> tokens; size_t prev = 0, pos = 0; do { pos = str.find(delim, prev); if (pos == std::string::npos) pos = str.length(); std::string token = str.substr(prev, pos-prev); if (!token.empty()) { tokens.push_back(token); } prev = pos + delim.length(); } while (pos < str.length() && prev < str.length()); return tokens; } Range getRange(const std::string& range_s, const long& filesize) { // read: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range Range range; size_t mpos = range_s.find('-'); auto parts = splitString(range_s, "-"); if (mpos == 0) { // <unit>=-<suffix-length> // <suffix-length> is // an integer indicating the number of units at the end of the file to return. range.start = filesize - std::stol(parts[0]); range.end = filesize - 1; } else if (mpos == range_s.length() - 1) { // <unit>=<range-start>- range.start = std::stol(parts[0]); range.end = filesize - 1; } else { // <unit>=<range-start>-<range-end> range.start = std::stol(parts[0]); range.end = std::stol(parts[1]); } return range; } inline void getRanges(const std::string& rangesHeader, std::vector<Range>& outranges, const long& filesize) { auto ranges = splitString(rangesHeader, ", "); for(auto& range : ranges) { outranges.push_back(getRange(range, filesize)); } } bool parseRangeHeader(const std::string& rangesHeader, const long& filesize, std::vector<Range>& ranges) { if (rangesHeader.substr(0, 6) == "bytes=") { getRanges(rangesHeader.substr(6, rangesHeader.length() - 1), ranges, filesize); return true; } else { return false; } } std::string getRangeStringForResponse(Range r, const long& filesize) { // bytes start-end/total return "bytes " + std::to_string(r.start) + "-" + std::to_string(r.end) + "/" + std::to_string(filesize); }
34.622951
110
0.603693
enzo418
f691e7f968538dcfc57ac4f022eeb336a5c7f0c6
909
hpp
C++
include/natalie/proc_value.hpp
watzon/natalie
d4013d99d1302944838293b26e54c866fb99bd32
[ "MIT" ]
null
null
null
include/natalie/proc_value.hpp
watzon/natalie
d4013d99d1302944838293b26e54c866fb99bd32
[ "MIT" ]
null
null
null
include/natalie/proc_value.hpp
watzon/natalie
d4013d99d1302944838293b26e54c866fb99bd32
[ "MIT" ]
null
null
null
#pragma once #include <assert.h> #include "natalie/class_value.hpp" #include "natalie/forward.hpp" #include "natalie/global_env.hpp" #include "natalie/macros.hpp" #include "natalie/value.hpp" namespace Natalie { struct ProcValue : Value { enum class ProcType { Proc, Lambda }; ProcValue(Env *env, Block *block, ProcType type = ProcType::Proc) : Value { Value::Type::Proc, NAT_OBJECT->const_get(env, "Proc", true)->as_class() } , m_block { block } , m_type { type } { assert(m_block); } Block *block() { return m_block; } bool is_lambda() { return m_type == ProcType::Lambda; } virtual ProcValue *to_proc(Env *) override { // TODO: might need to return a copy with m_type set to Proc if this is a Lambda return this; } private: Block *m_block { nullptr }; ProcType m_type { ProcType::Proc }; }; }
22.725
91
0.625963
watzon
f69289e8b6797b59b7c181c3868331d49db42cf1
15,302
cpp
C++
sdk/Windows/SMXDeviceConnection.cpp
steprevolution/stepmaniax-sdk
60e84d3f80d36bf195aedd20335173022d678ca2
[ "MIT" ]
33
2017-12-31T17:50:09.000Z
2022-03-10T01:21:56.000Z
sdk/Windows/SMXDeviceConnection.cpp
steprevolution/stepmaniax-sdk
60e84d3f80d36bf195aedd20335173022d678ca2
[ "MIT" ]
2
2021-02-16T03:15:01.000Z
2021-04-21T01:56:23.000Z
sdk/Windows/SMXDeviceConnection.cpp
steprevolution/stepmaniax-sdk
60e84d3f80d36bf195aedd20335173022d678ca2
[ "MIT" ]
5
2018-01-11T17:18:08.000Z
2020-07-06T07:32:50.000Z
#include "SMXDeviceConnection.h" #include "Helpers.h" #include <string> #include <memory> using namespace std; using namespace SMX; #include <hidsdi.h> #include <SetupAPI.h> SMX::SMXDeviceConnection::PendingCommandPacket::PendingCommandPacket() { } SMXDeviceConnection::PendingCommand::PendingCommand() { memset(&m_Overlapped, 0, sizeof(m_Overlapped)); } shared_ptr<SMX::SMXDeviceConnection> SMXDeviceConnection::Create() { return CreateObj<SMXDeviceConnection>(); } SMX::SMXDeviceConnection::SMXDeviceConnection(shared_ptr<SMXDeviceConnection> &pSelf): m_pSelf(GetPointers(pSelf, this)) { memset(&overlapped_read, 0, sizeof(overlapped_read)); } SMX::SMXDeviceConnection::~SMXDeviceConnection() { Close(); } bool SMX::SMXDeviceConnection::Open(shared_ptr<AutoCloseHandle> DeviceHandle, wstring &sError) { m_hDevice = DeviceHandle; if(!HidD_SetNumInputBuffers(DeviceHandle->value(), 512)) Log(ssprintf("Error: HidD_SetNumInputBuffers: %ls", GetErrorString(GetLastError()).c_str())); // Begin the first async read. BeginAsyncRead(sError); // Request device info. RequestDeviceInfo([&](string response) { Log(ssprintf("Received device info. Master version: %i, P%i", m_DeviceInfo.m_iFirmwareVersion, m_DeviceInfo.m_bP2+1)); m_bGotInfo = true; }); return true; } void SMX::SMXDeviceConnection::Close() { Log("Closing device"); if(m_hDevice) CancelIo(m_hDevice->value()); // If we're being closed while a command was in progress, call its completion // callback, so it's guaranteed to always be called. if(m_pCurrentCommand && m_pCurrentCommand->m_pComplete) m_pCurrentCommand->m_pComplete(""); // If any commands were queued with completion callbacks, call their completion // callbacks. for(auto &pendingCommand: m_aPendingCommands) { if(pendingCommand->m_pComplete) pendingCommand->m_pComplete(""); } m_hDevice.reset(); m_sReadBuffers.clear(); m_aPendingCommands.clear(); memset(&overlapped_read, 0, sizeof(overlapped_read)); m_bActive = false; m_bGotInfo = false; m_pCurrentCommand = nullptr; m_iInputState = 0; } void SMX::SMXDeviceConnection::SetActive(bool bActive) { if(m_bActive == bActive) return; m_bActive = bActive; } void SMX::SMXDeviceConnection::Update(wstring &sError) { if(!sError.empty()) return; if(m_hDevice == nullptr) { sError = L"Device not open"; return; } // A read packet can allow us to initiate a write, so check reads before writes. CheckReads(sError); CheckWrites(sError); } bool SMX::SMXDeviceConnection::ReadPacket(string &out) { if(m_sReadBuffers.empty()) return false; out = m_sReadBuffers.front(); m_sReadBuffers.pop_front(); return true; } void SMX::SMXDeviceConnection::CheckReads(wstring &error) { if(m_pCurrentCommand) { // See if this command timed out. This doesn't happen often, so this is // mostly just a failsafe. The controller takes a moment to initialize on // startup, so we use a large enough timeout that this doesn't trigger on // every connection. double fSecondsAgo = SMX::GetMonotonicTime() - m_pCurrentCommand->m_fSentAt; if(fSecondsAgo > 2.0f) { // If we didn't get a response in this long, we're not going to. Retry the // command by cancelling its I/O and moving it back to the command queue. // // if we were delayed and the response is in the queue, we'll get out of sync Log("Command timed out. Retrying..."); CancelIoEx(m_hDevice->value(), &m_pCurrentCommand->m_Overlapped); // Block until the cancellation completes. This should happen quickly. DWORD unused; GetOverlappedResult(m_hDevice->value(), &m_pCurrentCommand->m_Overlapped, &unused, true); m_aPendingCommands.push_front(m_pCurrentCommand); m_pCurrentCommand = nullptr; Log("Command requeued"); } } DWORD bytes; int result = GetOverlappedResult(m_hDevice->value(), &overlapped_read, &bytes, FALSE); if(result == 0) { int windows_error = GetLastError(); if(windows_error != ERROR_IO_PENDING && windows_error != ERROR_IO_INCOMPLETE) error = wstring(L"Error reading device: ") + GetErrorString(windows_error).c_str(); return; } HandleUsbPacket(string(overlapped_read_buffer, bytes)); // Start the next read. BeginAsyncRead(error); } void SMX::SMXDeviceConnection::HandleUsbPacket(const string &buf) { if(buf.empty()) return; // Log(ssprintf("Read: %s", BinaryToHex(buf).c_str())); int iReportId = buf[0]; switch(iReportId) { case 3: // Input state. We could also read this as a normal HID button change. m_iInputState = ((buf[2] & 0xFF) << 8) | ((buf[1] & 0xFF) << 0); // Log(ssprintf("Input state: %x (%x %x)\n", m_iInputState, buf[2], buf[1])); break; case 6: // A HID serial packet. if(buf.size() < 3) return; int cmd = buf[1]; #define PACKET_FLAG_START_OF_COMMAND 0x04 #define PACKET_FLAG_END_OF_COMMAND 0x01 #define PACKET_FLAG_HOST_CMD_FINISHED 0x02 #define PACKET_FLAG_DEVICE_INFO 0x80 int bytes = buf[2]; if(3 + bytes > buf.size()) { Log("Communication error: oversized packet (ignored)"); return; } string sPacket( buf.begin()+3, buf.begin()+3+bytes ); if(cmd & PACKET_FLAG_DEVICE_INFO) { // This is a response to RequestDeviceInfo. Since any application can send this, // we ignore the packet if we didn't request it, since it might be requested for // a different program. if(m_pCurrentCommand == nullptr || !m_pCurrentCommand->m_bIsDeviceInfoCommand) break; // We're little endian and the device is too, so we can just match the struct. // We're depending on correct padding. struct data_info_packet { char cmd; // always 'I' uint8_t packet_size; // not used char player; // '0' for P1, '1' for P2: char unused2; uint8_t serial[16]; uint16_t firmware_version; char unused3; // always '\n' }; // The packet contains data_info_packet. The packet is actually one byte smaller // due to a padding byte added (it contains 23 bytes of data but the struct is // 24 bytes). Resize to be sure. sPacket.resize(sizeof(data_info_packet)); // Convert the info packet from the wire protocol to our friendlier API. const data_info_packet *packet = (data_info_packet *) sPacket.data(); m_DeviceInfo.m_bP2 = packet->player == '1'; m_DeviceInfo.m_iFirmwareVersion = packet->firmware_version; // The serial is binary in this packet. Hex format it, which is the same thing // we'll get if we read the USB serial number (eg. HidD_GetSerialNumberString). string sHexSerial = BinaryToHex(packet->serial, 16); memcpy(m_DeviceInfo.m_Serial, sHexSerial.c_str(), 33); if(m_pCurrentCommand->m_pComplete) m_pCurrentCommand->m_pComplete(sPacket); m_pCurrentCommand = nullptr; break; } // If we're not active, ignore all packets other than device info. This is always false // while we're in Open() waiting for the device info response. if(!m_bActive) break; if(cmd & PACKET_FLAG_START_OF_COMMAND && !m_sCurrentReadBuffer.empty()) { // When we get a start packet, the read buffer should already be empty. If // it isn't, we got a command that didn't end with an END_OF_COMMAND packet, // and something is wrong. This shouldn't happen, so warn about it and recover // by clearing the junk in the buffer. Log(ssprintf("Got PACKET_FLAG_START_OF_COMMAND, but we had %i bytes in the read buffer", m_sCurrentReadBuffer.size())); m_sCurrentReadBuffer.clear(); } m_sCurrentReadBuffer.append(sPacket); // Note that if PACKET_FLAG_HOST_CMD_FINISHED is set, PACKET_FLAG_END_OF_COMMAND // will always also be set. if(cmd & PACKET_FLAG_HOST_CMD_FINISHED) { // This tells us that a command we wrote to the device has finished executing, and // it's safe to start writing another. if(m_pCurrentCommand && m_pCurrentCommand->m_pComplete) m_pCurrentCommand->m_pComplete(m_sCurrentReadBuffer); m_pCurrentCommand = nullptr; } if(cmd & PACKET_FLAG_END_OF_COMMAND) { if(!m_sCurrentReadBuffer.empty()) m_sReadBuffers.push_back(m_sCurrentReadBuffer); m_sCurrentReadBuffer.clear(); } break; } } void SMX::SMXDeviceConnection::BeginAsyncRead(wstring &error) { while(1) { // Our read buffer is 64 bytes. The HID input packet is much smaller than that, // but Windows pads packets to the maximum size of any HID report, and the HID // serial packet is 64 bytes, so we'll get 64 bytes even for 3-byte input packets. // If this didn't happen, we'd have to be smarter about pulling data out of the // read buffer. DWORD bytes; memset(overlapped_read_buffer, sizeof(overlapped_read_buffer), 0); if(!ReadFile(m_hDevice->value(), overlapped_read_buffer, sizeof(overlapped_read_buffer), &bytes, &overlapped_read)) { int windows_error = GetLastError(); if(windows_error != ERROR_IO_PENDING && windows_error != ERROR_IO_INCOMPLETE) error = wstring(L"Error reading device: ") + GetErrorString(windows_error).c_str(); return; } // The async read finished synchronously. This just means that there was already data waiting. // Handle the result, and loop to try to start the next async read again. HandleUsbPacket(string(overlapped_read_buffer, bytes)); } } void SMX::SMXDeviceConnection::CheckWrites(wstring &error) { if(m_pCurrentCommand) { // A command is in progress. See if its writes have completed. if(m_pCurrentCommand->m_bWriting) { DWORD bytes; int iResult = GetOverlappedResult(m_hDevice->value(), &m_pCurrentCommand->m_Overlapped, &bytes, FALSE); if(iResult == 0) { int windows_error = GetLastError(); if(windows_error != ERROR_IO_PENDING && windows_error != ERROR_IO_INCOMPLETE) error = wstring(L"Error writing to device: ") + GetErrorString(windows_error).c_str(); return; } m_pCurrentCommand->m_bWriting = false; } // Don't clear m_pCurrentCommand here. It'll stay set until we get a PACKET_FLAG_HOST_CMD_FINISHED // packet from the device, which tells us it's ready to receive another command. // // Don't send packets if there's a command in progress. return; } // Stop if we have nothing to do. if(m_aPendingCommands.empty()) return; // Send the next command. shared_ptr<PendingCommand> pPendingCommand = m_aPendingCommands.front(); // Record the time. We can use this for timeouts. pPendingCommand->m_fSentAt = SMX::GetMonotonicTime(); for(shared_ptr<PendingCommandPacket> &pPacket: pPendingCommand->m_Packets) { // In theory the API allows this to return success if the write completed successfully without needing to // be async, like reads can. However, this can't really happen (the write always needs to go to the device // first, unlike reads which might already be buffered), and there's no way to test it if we implement that, // so this assumes all writes are async. DWORD unused; // Log(ssprintf("Write: %s", BinaryToHex(pPacket->sData).c_str())); if(!WriteFile(m_hDevice->value(), pPacket->sData.data(), pPacket->sData.size(), &unused, &pPendingCommand->m_Overlapped)) { int windows_error = GetLastError(); if(windows_error != ERROR_IO_PENDING && windows_error != ERROR_IO_INCOMPLETE) { error = wstring(L"Error writing to device: ") + GetErrorString(windows_error).c_str(); return; } } } pPendingCommand->m_bWriting = true; // Remove this command and store it in m_pCurrentCommand, and we'll stop sending data until the command finishes. m_pCurrentCommand = pPendingCommand; m_aPendingCommands.pop_front(); } // Request device info. This is the same as sending an 'i' command, but we can send it safely // at any time, even if another application is talking to the device, so we can do this during // enumeration. void SMX::SMXDeviceConnection::RequestDeviceInfo(function<void(string response)> pComplete) { shared_ptr<PendingCommand> pPendingCommand = make_shared<PendingCommand>(); pPendingCommand->m_pComplete = pComplete; pPendingCommand->m_bIsDeviceInfoCommand = true; shared_ptr<PendingCommandPacket> pCommandPacket = make_shared<PendingCommandPacket>(); string sPacket({ 5, // report ID (char) (uint8_t) PACKET_FLAG_DEVICE_INFO, // flags (char) 0, // bytes in packet }); sPacket.resize(64, 0); pCommandPacket->sData = sPacket; pPendingCommand->m_Packets.push_back(pCommandPacket); m_aPendingCommands.push_back(pPendingCommand); } void SMX::SMXDeviceConnection::SendCommand(const string &cmd, function<void(string response)> pComplete) { shared_ptr<PendingCommand> pPendingCommand = make_shared<PendingCommand>(); pPendingCommand->m_pComplete = pComplete; // Send the command in packets. We allow sending zero-length packets here // for testing purposes. int i = 0; do { shared_ptr<PendingCommandPacket> pCommandPacket = make_shared<PendingCommandPacket>(); int iFlags = 0; int iPacketSize = min(cmd.size() - i, 61); bool bFirstPacket = (i == 0); if(bFirstPacket) iFlags |= PACKET_FLAG_START_OF_COMMAND; bool bLastPacket = (i + iPacketSize == cmd.size()); if(bLastPacket) iFlags |= PACKET_FLAG_END_OF_COMMAND; string sPacket({ 5, // report ID (char) iFlags, (char) iPacketSize, // bytes in packet }); sPacket.append(cmd.begin() + i, cmd.begin() + i + iPacketSize); sPacket.resize(64, 0); pCommandPacket->sData = sPacket; pPendingCommand->m_Packets.push_back(pCommandPacket); i += iPacketSize; } while(i < cmd.size()); m_aPendingCommands.push_back(pPendingCommand); }
34.936073
129
0.63874
steprevolution
f692fb51430b7f5773f596e9bd87068f645886c1
2,233
hpp
C++
src/composable_kernel/composable_kernel/include/utility/array_multi_index.hpp
j4yan/MIOpen
dc38f79bee97e047d866d9c1e25289cba86fab56
[ "MIT" ]
745
2017-07-01T22:03:25.000Z
2022-03-26T23:46:27.000Z
src/composable_kernel/composable_kernel/include/utility/array_multi_index.hpp
j4yan/MIOpen
dc38f79bee97e047d866d9c1e25289cba86fab56
[ "MIT" ]
1,348
2017-07-02T12:37:48.000Z
2022-03-31T23:45:51.000Z
src/composable_kernel/composable_kernel/include/utility/array_multi_index.hpp
j4yan/MIOpen
dc38f79bee97e047d866d9c1e25289cba86fab56
[ "MIT" ]
158
2017-07-01T19:37:04.000Z
2022-03-30T11:57:04.000Z
#ifndef CK_ARRAY_MULTI_INDEX_HPP #define CK_ARRAY_MULTI_INDEX_HPP #include "common_header.hpp" namespace ck { template <index_t N> using MultiIndex = Array<index_t, N>; template <typename... Xs> __host__ __device__ constexpr auto make_multi_index(Xs&&... xs) { return make_array<index_t>(index_t{xs}...); } template <index_t NSize> __host__ __device__ constexpr auto make_zero_multi_index() { return unpack([](auto... xs) { return make_multi_index(xs...); }, typename uniform_sequence_gen<NSize, 0>::type{}); } template <typename T> __host__ __device__ constexpr auto to_multi_index(const T& x) { return unpack([](auto... ys) { return make_multi_index(ys...); }, x); } template <index_t NSize, typename X> __host__ __device__ constexpr auto operator+=(MultiIndex<NSize>& y, const X& x) { static_assert(X::Size() == NSize, "wrong! size not the same"); static_for<0, NSize, 1>{}([&](auto i) { y(i) += x[i]; }); return y; } template <index_t NSize, typename X> __host__ __device__ constexpr auto operator-=(MultiIndex<NSize>& y, const X& x) { static_assert(X::Size() == NSize, "wrong! size not the same"); static_for<0, NSize, 1>{}([&](auto i) { y(i) -= x[i]; }); return y; } template <index_t NSize, typename T> __host__ __device__ constexpr auto operator+(const MultiIndex<NSize>& a, const T& b) { using type = MultiIndex<NSize>; static_assert(T::Size() == NSize, "wrong! size not the same"); type r; static_for<0, NSize, 1>{}([&](auto i) { r(i) = a[i] + b[i]; }); return r; } template <index_t NSize, typename T> __host__ __device__ constexpr auto operator-(const MultiIndex<NSize>& a, const T& b) { using type = MultiIndex<NSize>; static_assert(T::Size() == NSize, "wrong! size not the same"); type r; static_for<0, NSize, 1>{}([&](auto i) { r(i) = a[i] - b[i]; }); return r; } template <index_t NSize, typename T> __host__ __device__ constexpr auto operator*(const MultiIndex<NSize>& a, const T& b) { using type = MultiIndex<NSize>; static_assert(T::Size() == NSize, "wrong! size not the same"); type r; static_for<0, NSize, 1>{}([&](auto i) { r(i) = a[i] * b[i]; }); return r; } } // namespace ck #endif
28.628205
84
0.652485
j4yan
f695d4b11de5b86d50febfe9a805745deedb8bb9
2,338
cc
C++
example/publisher_raw.cc
pedro-salgueiro/ign-transport
57558607ceb98dd4d90f6bb546a1fb70f85f78af
[ "ECL-2.0", "Apache-2.0" ]
21
2020-04-15T16:58:42.000Z
2022-03-07T00:27:15.000Z
example/publisher_raw.cc
pedro-salgueiro/ign-transport
57558607ceb98dd4d90f6bb546a1fb70f85f78af
[ "ECL-2.0", "Apache-2.0" ]
164
2020-04-29T23:29:49.000Z
2022-03-25T22:30:10.000Z
example/publisher_raw.cc
pedro-salgueiro/ign-transport
57558607ceb98dd4d90f6bb546a1fb70f85f78af
[ "ECL-2.0", "Apache-2.0" ]
23
2020-05-15T18:34:59.000Z
2022-02-01T16:46:52.000Z
/* * Copyright (C) 2018 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <atomic> #include <chrono> #include <csignal> #include <iostream> #include <string> #include <thread> #include <ignition/msgs.hh> #include <ignition/transport.hh> /// \brief Flag used to break the publisher loop and terminate the program. static std::atomic<bool> g_terminatePub(false); ////////////////////////////////////////////////// /// \brief Function callback executed when a SIGINT or SIGTERM signals are /// captured. This is used to break the infinite loop that publishes messages /// and exit the program smoothly. void signal_handler(int _signal) { if (_signal == SIGINT || _signal == SIGTERM) g_terminatePub = true; } ////////////////////////////////////////////////// int main(int argc, char **argv) { // Install a signal handler for SIGINT and SIGTERM. std::signal(SIGINT, signal_handler); std::signal(SIGTERM, signal_handler); // Create a transport node and advertise a topic. ignition::transport::Node node; std::string topic = "/foo"; ignition::msgs::StringMsg msg; msg.set_data("HELLO"); auto pub = node.Advertise(topic, msg.GetTypeName()); if (!pub) { std::cerr << "Error advertising topic [" << topic << "]" << std::endl; return -1; } // Prepare the message. std::string rawMsg; msg.SerializeToString(&rawMsg); // Publish messages at 1Hz. while (!g_terminatePub) { // Note: This will copy rawMsg when publishing to remote subscribers. A // remote subscriber is a subscriber in a separate process. if (!pub.PublishRaw(rawMsg, msg.GetTypeName())) break; std::cout << "Publishing on topic [" << topic << "]" << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } return 0; }
29.594937
77
0.669376
pedro-salgueiro
f699fdcf190556331e43d5bfbbc93d4a0cc33b38
935
cpp
C++
CCC/CCC17S3.cpp
Genius1506/Competitive-Programming
0fcbd9cd1a2381cf6dcb6e31f4ad0afe7cb98947
[ "MIT" ]
null
null
null
CCC/CCC17S3.cpp
Genius1506/Competitive-Programming
0fcbd9cd1a2381cf6dcb6e31f4ad0afe7cb98947
[ "MIT" ]
null
null
null
CCC/CCC17S3.cpp
Genius1506/Competitive-Programming
0fcbd9cd1a2381cf6dcb6e31f4ad0afe7cb98947
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #define ll long long #define all(x) x.begin(),x.end() #define INF (0x3f3f3f3f) #define ms(a,b) memset(a,b,sizeof(a)); int main(){ ios::sync_with_stdio(0); cin.tie(0); int n; cin >> n; vector<int>miku(2005); for(int i = 0; i < n; i++){ int x; cin >> x; miku[x]++; } vector<int>yotsuba(4005); for(int i = 1; i <= 2000; i++){ if(miku[i]){ for(int j = i; j <= 2000; j++){ if(i==j){ yotsuba[i+j] += (miku[i])/2; } else{ yotsuba[i+j] += min(miku[i],miku[j]); } } } } int ans = 0, num = 0; for(int i = 1; i <= 4000; i++){ if(yotsuba[i]>ans){ ans = yotsuba[i]; num = 0; } if(yotsuba[i]==ans) num++; } cout << ans << ' ' << num << '\n'; }
23.974359
57
0.40107
Genius1506
f69e5920f1f019f6c6daa61a386d70ce091b57c5
53,236
cpp
C++
src/pairwise.cpp
toshihr/mtrap
e6001ef79c89bbb7c5b731fe6ade4659add5d1ea
[ "BSD-3-Clause" ]
null
null
null
src/pairwise.cpp
toshihr/mtrap
e6001ef79c89bbb7c5b731fe6ade4659add5d1ea
[ "BSD-3-Clause" ]
null
null
null
src/pairwise.cpp
toshihr/mtrap
e6001ef79c89bbb7c5b731fe6ade4659add5d1ea
[ "BSD-3-Clause" ]
null
null
null
#include <cstdlib> #include <iostream> #include <iomanip> #include <cmath> #include <Eigen/Dense> #include <Eigen/StdVector> #include <algorithm> #include <string> #include <fstream> #include <map> #include <set> #include <cstdlib> #include <cassert> #include "scorematrix.h" #include "tqmatrix.h" #include "pairwise.h" #include "tree.h" #include "globaloption.h" #include "utility.h" #include "SparseMatrix.h" #include "sequences.h" #include "entropy.h" #include "distance.h" using namespace std; using namespace ScoreMatrix; AlignerMTRAP::AlignerMTRAP() :pName1(NULL),pName2(NULL),pSeq1(NULL),pSeq2(NULL),pGlobalOption(NULL),initialized(false),passDone(false) { // regionEnds1.push_back(3); // regionEnds2.push_back(2); regionEnds1.push_back(pSeq1->size()); regionEnds2.push_back(pSeq2->size()); } AlignerMTRAP::AlignerMTRAP(std::string* pN1, std::string* pS1, std::string* pN2, std::string* pS2, GlobalOption* pG) :pName1(pN1),pName2(pN2),pSeq1(pS1),pSeq2(pS2),pGlobalOption(pG),initialized(true),passDone(false) { // regionEnds1.push_back(3); // regionEnds2.push_back(2); regionEnds1.push_back(pSeq1->size()); regionEnds2.push_back(pSeq2->size()); } PROFILE_TYPE AlignerMTRAP::calcPathMatrix() { assert(this->initialized); const string& A = *pSeq1; const string& B = *pSeq2; const PATH_TYPE numRow = A.size(); // vertical <-> sequence 1 const PATH_TYPE numCol = B.size(); // horizonal <-> sequence 2 const int D = 0, U = 1, L = 2, N = 3; const ScoreMatrix::EncodedResidue PRE = ScoreMatrix::encode('@'); const ScoreMatrix::EncodedResidue GAP = ScoreMatrix::encode(ScoreMatrix::GAP); const PATH_TYPE ZERO = PATH_ZERO; const PATH_TYPE INF = PATH_INF; // --- initialize --- assert(A[0] == PRE && B[0] == PRE && "calcPathMatrix: sequences must have the prefix '@'"); assign3Matrix(PM, 3, numRow, numCol, ZERO); assign3Matrix(DM, 3, numRow, numCol, N); int RB = 0, CB = 0; // Begins of the regions Row, Column for(int region_i=0; region_i<regionEnds1.size(); region_i++) { const int RE = regionEnds1[region_i]; // End of the region Row const int CE = regionEnds2[region_i]; // End of the region Column // ====== FIRST ROW ====== // --- [0,0] --- if(RB == 0 && CB == 0) { set3Matrix(PM,RB,CB,ZERO,INF,INF); set3Matrix(DM,RB,CB, N, N, N); }else{ set3Matrix(PM,RB,CB,PM[D][RB-1][CB-1],INF,INF); set3Matrix(DM,RB,CB, D, N, N); } // --- [0,1]: gap open --- { const int c=CB+1; const PATH_TYPE l = PM[D][RB][CB] + ScoreMatrix::distTQplusDiff_INT[PRE][B[c-1]][GAP][B[c]]; set3Matrix(PM,RB,c,INF,INF, l ); set3Matrix(DM,RB,c, N , N , L ); } // --- [0,c] for c=2,...,numCol-1: gap extension --- for(int c=CB+2; c<CE; c++) { const PATH_TYPE l = PM[L][RB][c-1] + ScoreMatrix::distTQplusDiff_INT[GAP][B[c-1]][GAP][B[c]]; set3Matrix(PM,RB,c,INF,INF, l ); set3Matrix(DM,RB,c, N , N , L ); } // ====== SECOND ROW ====== { // --- [1,0]: FIRST COLUMN --- const int r=RB+1; const PATH_TYPE u = PM[D][RB][CB] + ScoreMatrix::distTQplusDiff_INT[A[r-1]][PRE][A[r]][GAP]; set3Matrix(PM,r,CB,INF, u ,INF); set3Matrix(DM,r,CB, N , U , N ); // --- [1,1]: SECOND COLUMN --- { const int c=CB+1; // PM[0] const PATH_TYPE dd = PM[D][r-1][c-1] + ScoreMatrix::distTQplusDiff_INT[A[r-1]][B[c-1]][A[r]][B[c]]; const pair<PATH_TYPE,int> minD(dd, D ); // PM[1] const PATH_TYPE lu = PM[L][r-1][c ] + ScoreMatrix::distTQplusDiff_INT[GAP ][B[c ]][A[r]][GAP ]; const pair<PATH_TYPE,int> minU(lu, L ); // PM[2] const PATH_TYPE ul = PM[U][r ][c-1] + ScoreMatrix::distTQplusDiff_INT[A[r ]][GAP ][GAP ][B[c]]; const pair<PATH_TYPE,int> minL(ul, U ); // set PM and DM [0,1,2][r][c] set3Matrix(PM,r,c,minD.first ,minU.first ,minL.first ); set3Matrix(DM,r,c,minD.second,minU.second,minL.second); } // --- [1,c] for c=2,...,numCol-1: rest columns --- for(int c=CB+2; c<CE; c++) { // PM[0] const PATH_TYPE ld = PM[L][r-1][c-1] + ScoreMatrix::distTQplusDiff_INT[GAP ][B[c-1]][A[r]][B[c]]; const pair<PATH_TYPE,int> minD(ld, L ); // PM[1] const PATH_TYPE lu = PM[L][r-1][c ] + ScoreMatrix::distTQplusDiff_INT[GAP ][B[c ]][A[r]][GAP ]; const pair<PATH_TYPE,int> minU(lu, L ); // PM[2] const PATH_TYPE dl = PM[D][r ][c-1] + ScoreMatrix::distTQplusDiff_INT[A[r ]][B[c-1]][GAP ][B[c]]; #ifndef OMIT_GAP_CROSS_PATH const PATH_TYPE ul = PM[U][r ][c-1] + ScoreMatrix::distTQplusDiff_INT[A[r ]][GAP ][GAP ][B[c]]; #endif const PATH_TYPE ll = PM[L][r ][c-1] + ScoreMatrix::distTQplusDiff_INT[GAP ][B[c-1]][GAP ][B[c]]; #ifndef OMIT_GAP_CROSS_PATH const pair<PATH_TYPE,int> minL = choiceMin(dl,ul,ll, D , U , L ); #else const pair<PATH_TYPE,int> minL = choiceMin(dl,ll, D , L ); #endif // set PM and DM [0,1,2][r][c] set3Matrix(PM,r,c,minD.first ,minU.first ,minL.first ); set3Matrix(DM,r,c,minD.second,minU.second,minL.second); } } // ====== REST ROWS ====== for(int r=RB+2; r<RE; r++) { // --- [r,0] for r=2,...,numRow-1: FIRST COLUMN --- const PATH_TYPE u = PM[U][r-1][CB] + ScoreMatrix::distTQplusDiff_INT[A[r-1]][GAP][A[r]][GAP]; set3Matrix(PM,r,CB,INF, u ,INF); set3Matrix(DM,r,CB, N , U , N ); // --- [r,1] for r=2,...,numRow-1: SECOND COLUMN --- { const int c=CB+1; // PM[0] const PATH_TYPE ud = PM[U][r-1][c-1] + ScoreMatrix::distTQplusDiff_INT[A[r-1]][GAP ][A[r]][B[c]]; const pair<PATH_TYPE,int> minD(ud, U ); // PM[1] const PATH_TYPE du = PM[D][r-1][c ] + ScoreMatrix::distTQplusDiff_INT[A[r-1]][B[c ]][A[r]][GAP ]; const PATH_TYPE uu = PM[U][r-1][c ] + ScoreMatrix::distTQplusDiff_INT[A[r-1]][GAP ][A[r]][GAP ]; #ifndef OMIT_GAP_CROSS_PATH const PATH_TYPE lu = PM[L][r-1][c ] + ScoreMatrix::distTQplusDiff_INT[GAP ][B[c ]][A[r]][GAP ]; const pair<PATH_TYPE,int> minU = choiceMin(du,uu,lu, D , U , L ); #else const pair<PATH_TYPE,int> minU = choiceMin(du,uu, D , U ); #endif // PM[2] const PATH_TYPE ul = PM[U][r ][c-1] + ScoreMatrix::distTQplusDiff_INT[A[r ]][GAP ][GAP ][B[c]]; const pair<PATH_TYPE,int> minL(ul, U ); // set PM and DM [0,1,2][r][c] set3Matrix(PM,r,c,minD.first ,minU.first ,minL.first ); set3Matrix(DM,r,c,minD.second,minU.second,minL.second); } // --- [r,c] for c=2,...,numCol, r=2,...,numRow-1: rest columns --- for(int c=CB+2; c<CE; c++) { #ifndef OMIT_GAP_CROSS_PATH typedef Eigen::Matrix<PATH_TYPE,9,1> Vector9i; const Vector9i V = (Vector9i() << PM[D][r-1][c-1], /* dd */ PM[U][r-1][c-1], /* ud */ PM[L][r-1][c-1], /* ld */ PM[D][r-1][c ], /* du */ PM[U][r-1][c ], /* uu */ PM[L][r-1][c ], /* lu */ PM[D][r ][c-1], /* dl*/ PM[U][r ][c-1], /* ul */ PM[L][r ][c-1] /* ll */).finished() + (Vector9i() << ScoreMatrix::distTQplusDiff_INT[A[r-1]][B[c-1]][A[r]][B[c]], /* dd */ ScoreMatrix::distTQplusDiff_INT[A[r-1]][GAP ][A[r]][B[c]], /* ud */ ScoreMatrix::distTQplusDiff_INT[GAP ][B[c-1]][A[r]][B[c]], /* ld */ ScoreMatrix::distTQplusDiff_INT[A[r-1]][B[c ]][A[r]][GAP ], /* du */ ScoreMatrix::distTQplusDiff_INT[A[r-1]][GAP ][A[r]][GAP ], /* uu */ ScoreMatrix::distTQplusDiff_INT[GAP ][B[c ]][A[r]][GAP ], /* lu */ ScoreMatrix::distTQplusDiff_INT[A[r ]][B[c-1]][GAP ][B[c]], /* dl */ ScoreMatrix::distTQplusDiff_INT[A[r ]][GAP ][GAP ][B[c]], /* ul */ ScoreMatrix::distTQplusDiff_INT[GAP ][B[c-1]][GAP ][B[c]] /* ll */).finished(); const pair<PATH_TYPE,int> minD = choiceMin(V[0],V[1],V[2], D , U , L ); const pair<PATH_TYPE,int> minU = choiceMin(V[3],V[4],V[5], D , U , L ); const pair<PATH_TYPE,int> minL = choiceMin(V[6],V[7],V[8], D , U , L ); #else // if the size is a multiple of 128bits (16bytes), the fixed-size Eigen objects can be vectorized. // 32bit x 4 = 128bit, 64bit x 2 = 128bit typedef Eigen::Matrix<PATH_TYPE,8,1> Vector8i; const Vector8i V ( (Vector8i() << PM[D][r-1][c-1], /* dd */ PM[U][r-1][c-1], /* ud */ PM[L][r-1][c-1], /* ld */ PM[D][r-1][c ], /* du */ PM[U][r-1][c ], /* uu */ PM[D][r ][c-1], /* dl */ PM[L][r ][c-1], /* ll */ 0 ).finished() + (Vector8i() << ScoreMatrix::distTQplusDiff_INT[A[r-1]][B[c-1]][A[r]][B[c]], /* dd */ ScoreMatrix::distTQplusDiff_INT[A[r-1]][GAP ][A[r]][B[c]], /* ud */ ScoreMatrix::distTQplusDiff_INT[GAP ][B[c-1]][A[r]][B[c]], /* ld */ ScoreMatrix::distTQplusDiff_INT[A[r-1]][B[c ]][A[r]][GAP ], /* du */ ScoreMatrix::distTQplusDiff_INT[A[r-1]][GAP ][A[r]][GAP ], /* uu */ ScoreMatrix::distTQplusDiff_INT[A[r ]][B[c-1]][GAP ][B[c]], /* dl */ ScoreMatrix::distTQplusDiff_INT[GAP ][B[c-1]][GAP ][B[c]], /* ll */ 0 ).finished() ); const pair<PATH_TYPE,int> minD = choiceMin(V[0],V[1],V[2], D , U , L ); const pair<PATH_TYPE,int> minU = choiceMin(V[3],V[4] , D , U ); const pair<PATH_TYPE,int> minL = choiceMin(V[5] ,V[6], D , L ); #endif // set PM and DM [0,1,2][r][c] set3Matrix(PM,r,c,minD.first ,minU.first ,minL.first ); set3Matrix(DM,r,c,minD.second,minU.second,minL.second); } } RB = RE; CB = CE; } // end of region loop this->passDone = true; return choiceMin(PM[D][numRow-1][numCol-1],PM[U][numRow-1][numCol-1],PM[L][numRow-1][numCol-1]) / ScoreMatrix::FIXED_SCALE; } VPROFILE* AlignerMTRAP::genProfile() { assert(this->passDone); const string& A = *pSeq1; const string& B = *pSeq2; const int numRow = A.size(); // vertical <-> sequence 1 const int numCol = B.size(); // horizonal <-> sequence 2 const int D = 0, U = 1, L = 2; VPROFILE* profilePtr = new VPROFILE(numRow*numCol, PROFILE_ZERO); VPROFILE& profile = *profilePtr; // --- distance --- // string* alignment = this->genAlignment(); // string* seq1 = genGappedSeq(*(this->pSeq1),*alignment,'X'); // string* seq2 = genGappedSeq(*(this->pSeq2),*alignment,'Y'); // const PROFILE_TYPE dist_gid = Distance::calcDistance<PROFILE_TYPE>(*seq1, *seq2, Distance::GID); // const PROFILE_TYPE dist_lid = Distance::calcDistance<PROFILE_TYPE>(*seq1, *seq2, Distance::LID); // const PROFILE_TYPE dist_eer2 = Distance::calcDistance<PROFILE_TYPE>(*seq1, *seq2, Distance::EER2); // delete alignment; // delete seq1; // delete seq2; // --- traceback --- // the first row and first column are all 0 // matchにしか値はないため端に行った時点で終了で問題ない int r = numRow - 1; int c = numCol - 1; pair<PATH_TYPE,int> MM = choiceMin(PM[D][r][c],PM[U][r][c],PM[L][r][c], D , U , L ); while( r != 0 && c != 0 ) { switch(MM.second) { case D: // profile は row0 row1 ... rown と格納されている profile[r*numCol+c] = 1.0; MM.second = DM[D][r][c]; r--; c--; break; case U: MM.second = DM[U][r][c]; r--; break; case L: MM.second = DM[L][r][c]; c--; break; default: assert(false && "genProfile: error!!"); } } return profilePtr; } std::string* AlignerMTRAP::genAlignment() { assert(this->passDone); const string& A = *pSeq1; const string& B = *pSeq2; const int numRow = A.size(); // vertical <-> sequence 1 const int numCol = B.size(); // horizonal <-> sequence 2 const int D = 0, U = 1, L = 2; string* alignment = new string(); assert(alignment); int r = numRow - 1; int c = numCol - 1; pair<PATH_TYPE,int> MM = choiceMin(PM[D][r][c],PM[U][r][c],PM[L][r][c], D , U , L ); // --- traceback --- while( r != 0 || c != 0 ) { switch(MM.second) { case D: alignment->push_back('B'); MM.second = DM[D][r][c]; r--; c--; break; case U: alignment->push_back('X'); MM.second = DM[U][r][c]; r--; break; case L: alignment->push_back('Y'); MM.second = DM[L][r][c]; c--; break; default: assert(false && "genProfile: error!!"); } } reverse(alignment->begin(), alignment->end()); return alignment; } void AlignerMTRAP::showPathMatrix() { assert(this->passDone); PATH_MATRIX* pM = &PM; PATH_MATRIX& M = *pM; const string& A = *pSeq1; const string& B = *pSeq2; const int numRow = A.size(); // vertical <-> sequence 1 const int numCol = B.size(); // horizonal <-> sequence 2 putLog("path matrix DUL:"); for(int r=0; r<numRow; r++) { stringstream line; for(int c=0; c<numCol; c++) { line << "("; for(int i=0; i<3; i++) { if(PATH_INF == M[i][r][c]) { line << left << setw(10) << "INF"; }else if(PATH_ZERO == M[i][r][c]) { line << left << setw(10) << "---"; }else{ // line << scientific << left << setw(10) << setprecision(2) << (M[i][r][c] / ScoreMatrix::FIXED_SCALE); line << scientific << left << setw(10) << setprecision(2) << M[i][r][c]; } } line << ") "; } if(M == PM) { char MARK[4] = {'D','U','L','-'}; line << "|"; for(int c=0; c<numCol; c++) { for(int i=0; i<3; i++) { line << left << setw(1) << MARK[DM[i][r][c]]; } line << ' '; } } putLog(line.str()); } putLog(""); } void AlignerMTRAP::showPartMatrix(ScoreMatrix::VVVPART* pM) { assert(pM != NULL); VVVPART& M = *pM; const string& A = *pSeq1; const string& B = *pSeq2; const int numRow = A.size(); // vertical <-> sequence 1 const int numCol = B.size(); // horizonal <-> sequence 2 const PART_TYPE ZERO = PART_ZERO; putLog("partition function matrix DUL:"); for(int r=0; r<numRow; r++) { stringstream line; for(int c=0; c<numCol; c++) { line << "("; for(int i=0; i<3; i++) { if(PART_INF - M[i][r][c] < PART_ONE/1000000000) { line << left << setw(10) << "INF"; }else if(fabs(ZERO - M[i][r][c]) < PART_ONE/1000000000) { line << left << setw(10) << "---"; }else{ line << scientific << left << setw(10) << setprecision(2) << M[i][r][c]; } } line << ") "; } putLog(line.str()); } putLog(""); } /* The correspondence among AlignerMTRAP, Probalign and Miyazawa's paper * Z[D][r,c] <-> Zm <-> Zij * Z[U][r,c] <-> Zf <-> ZBij * Z[L][r,c] <-> Ze <-> ZAij */ ScoreMatrix::PART_TYPE AlignerMTRAP::calcPartForward(ScoreMatrix::VVVPART& Z) { assert(this->initialized); const string& A = *pSeq1; const string& B = *pSeq2; const int numRow = A.size(); // vertical <-> sequence 1 const int numCol = B.size(); // horizonal <-> sequence 2 const int D = 0, U = 1, L = 2; const ScoreMatrix::EncodedResidue PRE = ScoreMatrix::encode('@'); const ScoreMatrix::EncodedResidue GAP = ScoreMatrix::encode(ScoreMatrix::GAP); const PART_TYPE ZERO = PART_ZERO; const PART_TYPE ONE = PART_ONE; // --- initialize --- assert(A[0] == PRE && B[0] == PRE && "calcPartForward: sequences must have the prefix '@'"); assign3Matrix(Z, 3, numRow, numCol, ZERO); // ====== FIRST ROW ====== // --- [0,0] --- set3Matrix(Z,0,0,ONE,ZERO,ZERO); // --- [0,1]: gap open --- { const int c=1; const PART_TYPE l = Z[D][0][c-1] * ScoreMatrix::distTQplusDiffExt[PRE][B[c-1]][GAP][B[c]]; #ifdef PAIRWISE_PART_PROBALIGN_STYLE set3Matrix(Z,0,c, ZERO, ZERO, l ); #else // miyazawa p.1009 (32) line 1 with i = 0 set3Matrix(Z,0,c, l , ZERO, l ); #endif } // --- [0,c] for c=2,...,numCol-1: gap extension --- for(int c=2; c<numCol; c++) { #ifdef PAIRWISE_PART_PROBALIGN_STYLE const PART_TYPE l = Z[L][0][c-1] * ScoreMatrix::distTQplusDiffExt[GAP][B[c-1]][GAP][B[c]]; set3Matrix(Z,0,c, ZERO, ZERO, l ); #else // miyazawa p.1009 (32) line 2 with i = 0 const PART_TYPE l = Z[D][0][c-1] * ScoreMatrix::distTQplusDiffExt[PRE][B[c-1]][GAP][B[c]] + Z[L][0][c-1] * ScoreMatrix::distTQplusDiffExt[GAP][B[c-1]][GAP][B[c]]; set3Matrix(Z,0,c, l , ZERO, l ); #endif } // ====== SECOND ROW ====== // these code is same as REST ROW if the PAIRWISE_PART_PROBALIGN_STYLE is defined { // --- [1,0]: FIRST COLUMN --- const int r=1; const PART_TYPE u = Z[D][r-1][0] * ScoreMatrix::distTQplusDiffExt[A[r-1]][PRE][A[r]][GAP]; #ifdef PAIRWISE_PART_PROBALIGN_STYLE set3Matrix(Z,r,0, ZERO, u , ZERO); #else // miyazawa p.1009 (32) line 3 with j = 0 set3Matrix(Z,r,0, u , u , ZERO); #endif // --- [1,1]: HERE IS DIFFERENT FROM MTRAP --- #ifndef PAIRWISE_PART_PROBALIGN_STYLE assert(false && "calcPartForward: [1,1] these code should be written!"); // but the result becomes same one. // because, for example, Z[U,L][0][0] = 0, so the result becomes same one. // multiply 0 is the key."" #endif // --- [1,c] for c=1,...,numCol-1: rest columns --- for(int c=1; c<numCol; c++) { // PM[0] const PART_TYPE dd = Z[D][r-1][c-1] * ScoreMatrix::distTQplusDiffExt[A[r-1]][B[c-1]][A[r]][B[c]]; const PART_TYPE ud = Z[U][r-1][c-1] * ScoreMatrix::distTQplusDiffExt[A[r-1]][GAP ][A[r]][B[c]]; const PART_TYPE ld = Z[L][r-1][c-1] * ScoreMatrix::distTQplusDiffExt[GAP ][B[c-1]][A[r]][B[c]]; const PART_TYPE sumD = dd + ud + ld; // PM[1] const PART_TYPE du = Z[D][r-1][c ] * ScoreMatrix::distTQplusDiffExt[A[r-1]][B[c ]][A[r]][GAP ]; const PART_TYPE uu = Z[U][r-1][c ] * ScoreMatrix::distTQplusDiffExt[A[r-1]][GAP ][A[r]][GAP ]; #ifndef OMIT_GAP_CROSS_PATH const PART_TYPE lu = Z[L][r-1][c ] * ScoreMatrix::distTQplusDiffExt[A[GAP]][B[c-1]][A[r]][GAP ]; const PART_TYPE sumU = du + uu + lu; #else const PART_TYPE sumU = du + uu; #endif // PM[2] const PART_TYPE dl = Z[D][r ][c-1] * ScoreMatrix::distTQplusDiffExt[A[r ]][B[c-1]][GAP ][B[c]]; #ifndef OMIT_GAP_CROSS_PATH const PART_TYPE ul = Z[U][r ][c-1] * ScoreMatrix::distTQplusDiffExt[A[r ]][GAP ][GAP ][B[c]]; #endif const PART_TYPE ll = Z[L][r ][c-1] * ScoreMatrix::distTQplusDiffExt[GAP ][B[c-1]][GAP ][B[c]]; #ifndef OMIT_GAP_CROSS_PATH const PART_TYPE sumL = dl + ul + ll; #else const PART_TYPE sumL = dl + ll; #endif // set PM and DM [0,1,2][r][c] set3Matrix(Z,r,c, sumD , sumU , sumL); } } // ====== REST ROWS ====== for(int r=2; r<numRow; r++) { // --- [r,0] for r=2,...,numRow-1: FIRST COLUMN --- #ifdef PAIRWISE_PART_PROBALIGN_STYLE const PART_TYPE u = Z[U][r-1][0] * ScoreMatrix::distTQplusDiffExt[A[r-1]][GAP][A[r]][GAP]; set3Matrix(Z,r,0, ZERO, u , ZERO); #else // miyazawa style const PART_TYPE u = Z[D][r-1][0] * ScoreMatrix::distTQplusDiffExt[A[r-1]][PRE][A[r]][GAP] + Z[U][r-1][0] * ScoreMatrix::distTQplusDiffExt[A[r-1]][GAP][A[r]][GAP]; set3Matrix(Z,r,0, u , u , ZERO); #endif // --- [r,1] for r=2,...,numRow-1: HERE IS DIFFERENT FROM MTRAP --- // --- [r,c] for c=1,...,numCol, r=2,...,numRow-1: rest columns --- for(int c=1; c<numCol; c++) { typedef Eigen::Array<PART_TYPE,8,1> Array8f; const Array8f V ( (Array8f() << Z[D][r-1][c-1], /* dd */ Z[U][r-1][c-1], /* ud */ Z[L][r-1][c-1], /* ld */ Z[D][r-1][c ], /* du */ Z[U][r-1][c ], /* uu */ Z[D][r ][c-1], /* dl */ Z[L][r ][c-1], /* ll */ PART_ZERO ).finished() * (Array8f() << ScoreMatrix::distTQplusDiffExt[A[r-1]][B[c-1]][A[r]][B[c]], /* dd */ ScoreMatrix::distTQplusDiffExt[A[r-1]][GAP ][A[r]][B[c]], /* ud */ ScoreMatrix::distTQplusDiffExt[GAP ][B[c-1]][A[r]][B[c]], /* ld */ ScoreMatrix::distTQplusDiffExt[A[r-1]][B[c ]][A[r]][GAP ], /* du */ ScoreMatrix::distTQplusDiffExt[A[r-1]][GAP ][A[r]][GAP ], /* uu */ ScoreMatrix::distTQplusDiffExt[A[r ]][B[c-1]][GAP ][B[c]], /* dl */ ScoreMatrix::distTQplusDiffExt[GAP ][B[c-1]][GAP ][B[c]], /* ll */ PART_ZERO ).finished() ); const PART_TYPE sumD = V.matrix().block<3,1>(0,0).sum(); // du + uu + lu const PART_TYPE sumU = V.matrix().block<2,1>(3,0).sum(); // du + uu (du + uu + lu) const PART_TYPE sumL = V.matrix().block<2,1>(5,0).sum(); // dl + ll (dl + ul + ll) // // PM[0] // const PART_TYPE dd = Z[D][r-1][c-1] * ScoreMatrix::distTQplusDiffExt[A[r-1]][B[c-1]][A[r]][B[c]]; // const PART_TYPE ud = Z[U][r-1][c-1] * ScoreMatrix::distTQplusDiffExt[A[r-1]][GAP ][A[r]][B[c]]; // const PART_TYPE ld = Z[L][r-1][c-1] * ScoreMatrix::distTQplusDiffExt[GAP ][B[c-1]][A[r]][B[c]]; // const PART_TYPE sumD = dd + ud + ld; // // PM[1] // const PART_TYPE du = Z[D][r-1][c ] * ScoreMatrix::distTQplusDiffExt[A[r-1]][B[c ]][A[r]][GAP ]; // const PART_TYPE uu = Z[U][r-1][c ] * ScoreMatrix::distTQplusDiffExt[A[r-1]][GAP ][A[r]][GAP ]; //#ifndef OMIT_GAP_CROSS_PATH // const PART_TYPE lu = Z[L][r-1][c ] * ScoreMatrix::distTQplusDiffExt[A[GAP]][B[c-1]][A[r]][GAP ]; // const PART_TYPE sumU = du + uu + lu; //#else // const PART_TYPE sumU = du + uu; //#endif // // PM[2] // const PART_TYPE dl = Z[D][r ][c-1] * ScoreMatrix::distTQplusDiffExt[A[r ]][B[c-1]][GAP ][B[c]]; //#ifndef OMIT_GAP_CROSS_PATH // const PART_TYPE ul = Z[U][r ][c-1] * ScoreMatrix::distTQplusDiffExt[A[r ]][GAP ][GAP ][B[c]]; //#endif // const PART_TYPE ll = Z[L][r ][c-1] * ScoreMatrix::distTQplusDiffExt[GAP ][B[c-1]][GAP ][B[c]]; //#ifndef OMIT_GAP_CROSS_PATH // const PART_TYPE sumL = dl + ul + ll; //#else // const PART_TYPE sumL = dl + ll; //#endif // set PM and DM [0,1,2][r][c] set3Matrix(Z,r,c, sumD, sumU , sumL); } } this->passDone = true; return Z[D][numRow-1][numCol-1] + Z[U][numRow-1][numCol-1] + Z[L][numRow-1][numCol-1]; } VPROFILE* AlignerMTRAP::genPartProfile() { assert(this->initialized); VVVPART forwardZ; const PART_TYPE denoZ = calcPartForward(forwardZ); // appending '@' right side is necessary for using ScoreMatrix::distTQplusDiffExt const string A = pSeq1->substr(1, pSeq1->size()-1) + ScoreMatrix::encode('@'); const string B = pSeq2->substr(1, pSeq2->size()-1) + ScoreMatrix::encode('@'); const int numRow = A.size(); // vertical <-> sequence 1 const int numCol = B.size(); // horizonal <-> sequence 2 const int D = 0, U = 1, L = 2; const ScoreMatrix::EncodedResidue PRE = ScoreMatrix::encode('@'); const ScoreMatrix::EncodedResidue GAP = ScoreMatrix::encode(ScoreMatrix::GAP); const PART_TYPE ZERO = PART_ZERO; const PART_TYPE ONE = PART_ONE; // --- initialize --- assert(A[numRow-1] == PRE && B[numCol-1] == PRE && "calcPartForward: sequences must have the prefix '@'"); VVVPART Z; assign3Matrix(Z, 3, numRow, numCol, ZERO); VPROFILE *profilePtr = new VPROFILE(numRow * numCol); VPROFILE & profile = *profilePtr; VPROFILE::iterator ptr = profile.begin(); // ====== FIRST ROW ====== // --- [0,0] --- set3Matrix(Z,numRow-1,numCol-1,ONE,ZERO,ZERO); // --- [0,1]: gap open --- { const int c=numCol-2, cc = c; const PART_TYPE l = Z[D][numRow-1][c+1] * ScoreMatrix::distTQplusDiffExtBackward[PRE][B[cc+1]][GAP][B[cc]]; #ifdef PAIRWISE_PART_PROBALIGN_STYLE set3Matrix(Z,numRow-1,c, ZERO, ZERO, l ); #else // miyazawa p.1009 (32) line 1 with i = 0 set3Matrix(Z,numRow-1,c, l , ZERO, l ); #endif } // --- [0,c] for c=2,...,numCol-1: gap extension --- for(int c=numCol-3; c>=0; c--) { const int cc = c; #ifdef PAIRWISE_PART_PROBALIGN_STYLE const PART_TYPE l = Z[L][numRow-1][c+1] * ScoreMatrix::distTQplusDiffExtBackward[GAP][B[cc+1]][GAP][B[cc]]; set3Matrix(Z,numRow-1,c, ZERO, ZERO, l ); #else // miyazawa p.1009 (32) line 2 with i = 0 const PART_TYPE l = Z[D][numRow-1][c+1] * ScoreMatrix::distTQplusDiffExtBackward[PRE][B[cc+1]][GAP][B[cc]] + Z[L][numRow-1][c+1] * ScoreMatrix::distTQplusDiffExtBackward[GAP][B[cc+1]][GAP][B[cc]]; set3Matrix(Z,numRow-1,c, l , ZERO, l ); #endif } // ====== SECOND ROW ====== { // --- [1,0]: FIRST COLUMN --- const int r=numRow-2, rr = r; const PART_TYPE u = Z[D][r+1][numCol-1] * ScoreMatrix::distTQplusDiffExtBackward[A[rr+1]][PRE][A[rr]][GAP]; #ifdef PAIRWISE_PART_PROBALIGN_STYLE set3Matrix(Z,r,numCol-1, ZERO, u , ZERO); #else // miyazawa p.1009 (32) line 3 with j = 0 set3Matrix(Z,r,numCol-1, u , u , ZERO); #endif // --- [1,1]: HERE IS DIFFERENT FROM MTRAP --- // --- [1,c] for c=1,...,numCol-1: rest columns --- for(int c=numCol-2; c>=0; c--) { const int cc = c; // PM[0] const PART_TYPE dd = Z[D][r+1][c+1] * ScoreMatrix::distTQplusDiffExtBackward[A[rr+1]][B[cc+1]][A[rr]][B[cc]]; const PART_TYPE ud = Z[U][r+1][c+1] * ScoreMatrix::distTQplusDiffExtBackward[A[rr+1]][GAP ][A[rr]][B[cc]]; const PART_TYPE ld = Z[L][r+1][c+1] * ScoreMatrix::distTQplusDiffExtBackward[GAP ][B[cc+1]][A[rr]][B[cc]]; const PART_TYPE sumD = dd + ud + ld; // PM[1] const PART_TYPE du = Z[D][r+1][c ] * ScoreMatrix::distTQplusDiffExtBackward[A[rr+1]][B[cc ]][A[rr]][GAP ]; const PART_TYPE uu = Z[U][r+1][c ] * ScoreMatrix::distTQplusDiffExtBackward[A[rr+1]][GAP ][A[rr]][GAP ]; #ifndef OMIT_GAP_CROSS_PATH const PART_TYPE lu = Z[L][r+1][c ] * ScoreMatrix::distTQplusDiffExtBackward[GAP ][B[cc ]][A[rr]][GAP ]; const PART_TYPE sumU = du + uu + lu; #else const PART_TYPE sumU = du + uu; #endif // PM[2] const PART_TYPE dl = Z[D][r ][c+1] * ScoreMatrix::distTQplusDiffExtBackward[A[rr ]][B[cc+1]][GAP ][B[cc]]; #ifndef OMIT_GAP_CROSS_PATH const PART_TYPE ul = Z[U][r ][c+1] * ScoreMatrix::distTQplusDiffExtBackward[A[rr ]][GAP ][GAP ][B[cc]]; #endif const PART_TYPE ll = Z[L][r ][c+1] * ScoreMatrix::distTQplusDiffExtBackward[GAP ][B[cc+1]][GAP ][B[cc]]; #ifndef OMIT_GAP_CROSS_PATH const PART_TYPE sumL = dl + ul + ll; #else const PART_TYPE sumL = dl + ll; #endif // set PM and DM [0,1,2][r][c] set3Matrix(Z,r,c, sumD , sumU , sumL); // --- calculate P(Ar ~ Bc) --- /*{ // [1] --- probalign (code) style --- const PART_TYPE s = forwardZ[D][r+1][c+1] * Z[D][r][c]; const PART_TYPE scorez = ScoreMatrix::distTQplusDiffExtBackward[A[rr+1]][B[cc+1]][A[rr]][B[cc]]; const PART_TYPE prob = s / (scorez * denoZ); //cerr << r << "," << c << ":" << s << "/(" << scorez << " x " << denoZ << ")=" << prob << endl; if(0.001 <= prob) ptr[rr*numCol+cc] = min(1.0, prob); }*/ /*{ // [2] --- this code generates same result as probalign if epsilon == 0 --- const PART_TYPE s = forwardZ[D][r+1][c+1] * (Z[D][r+1][c+1]+Z[U][r+1][c+1]+Z[L][r+1][c+1]); const PART_TYPE prob = s / denoZ; if(0.001 <= prob) ptr[(r+1)*numCol+(c+1)] = min(1.0, prob); }*/ { // [2] --- this code generates same result as probalign if epsilon == 0 --- const PART_TYPE s = forwardZ[D][r+1][c+1] * Z[D][r][c] / ScoreMatrix::distTQplusDiffExtBackward[PRE][PRE][A[rr]][B[cc]]; const PART_TYPE prob = s / denoZ; if(0.001 <= prob) ptr[(r+1)*numCol+(c+1)] = min(static_cast<PART_TYPE>(1.0), prob); } /*{ // [2] --- this code generates same result as probalign if epsilon == 0 --- const PART_TYPE s = (forwardZ[D][r][c] + forwardZ[U][r][c] + forwardZ[L][r][c]) * (Z[D][r+1][c+1]+Z[U][r+1][c+1]+Z[L][r+1][c+1]); const PART_TYPE scorez = ScoreMatrix::distTQplusDiffExtBackward[PRE][PRE][A[rr]][B[cc]]; const PART_TYPE prob = s * scorez / denoZ; if(0.001 <= prob) ptr[(r+1)*numCol+(c+1)] = min(1.0, prob); }*/ } } // ====== REST ROWS ====== for(int r=numRow-3; r>=0; r--) { // --- [r,0] for r=2,...,numRow-1: FIRST COLUMN --- const int rr = r; #ifdef PAIRWISE_PART_PROBALIGN_STYLE const PART_TYPE u = Z[U][r+1][numCol-1] * ScoreMatrix::distTQplusDiffExtBackward[A[rr+1]][GAP][A[rr]][GAP]; set3Matrix(Z,r,numCol-1, ZERO, u , ZERO); #else // miyazawa style const PART_TYPE u = Z[D][r+1][numCol-1] * ScoreMatrix::distTQplusDiffExtBackward[A[rr+1]][PRE][A[rr]][GAP] + Z[U][r+1][numCol-1] * ScoreMatrix::distTQplusDiffExtBackward[A[rr+1]][GAP][A[rr]][GAP]; set3Matrix(Z,r,numCol-1, u , u , ZERO); #endif // --- [r,1] for r=2,...,numRow-1: HERE IS DIFFERENT FROM MTRAP --- // --- [r,c] for c=1,...,numCol, r=2,...,numRow-1: rest columns --- for(int c=numCol-2; c>=0; c--) { const int cc = c; // PM[0] const PART_TYPE dd = Z[D][r+1][c+1] * ScoreMatrix::distTQplusDiffExtBackward[A[rr+1]][B[cc+1]][A[rr]][B[cc]]; const PART_TYPE ud = Z[U][r+1][c+1] * ScoreMatrix::distTQplusDiffExtBackward[A[rr+1]][GAP ][A[rr]][B[cc]]; const PART_TYPE ld = Z[L][r+1][c+1] * ScoreMatrix::distTQplusDiffExtBackward[GAP ][B[cc+1]][A[rr]][B[cc]]; const PART_TYPE sumD = dd + ud + ld; // PM[1] const PART_TYPE du = Z[D][r+1][c ] * ScoreMatrix::distTQplusDiffExtBackward[A[rr+1]][B[cc ]][A[rr]][GAP ]; const PART_TYPE uu = Z[U][r+1][c ] * ScoreMatrix::distTQplusDiffExtBackward[A[rr+1]][GAP ][A[rr]][GAP ]; #ifndef OMIT_GAP_CROSS_PATH const PART_TYPE lu = Z[L][r+1][c ] * ScoreMatrix::distTQplusDiffExtBackward[GAP ][B[cc ]][A[rr]][GAP ]; const PART_TYPE sumU = du + uu + lu; #else const PART_TYPE sumU = du + uu; #endif // PM[2] const PART_TYPE dl = Z[D][r ][c+1] * ScoreMatrix::distTQplusDiffExtBackward[A[rr ]][B[cc+1]][GAP ][B[cc]]; #ifndef OMIT_GAP_CROSS_PATH const PART_TYPE ul = Z[U][r ][c+1] * ScoreMatrix::distTQplusDiffExtBackward[A[rr ]][GAP ][GAP ][B[cc]]; #endif const PART_TYPE ll = Z[L][r ][c+1] * ScoreMatrix::distTQplusDiffExtBackward[GAP ][B[cc+1]][GAP ][B[cc]]; #ifndef OMIT_GAP_CROSS_PATH const PART_TYPE sumL = dl + ul + ll; #else const PART_TYPE sumL = dl + ll; #endif // set PM and DM [0,1,2][r][c] set3Matrix(Z,r,c, sumD, sumU, sumL); // --- calculate P(Ar ~ Bc) --- /*{ // [1] --- probalign (code) style --- const PART_TYPE s = forwardZ[D][r+1][c+1] * Z[D][r][c]; const PART_TYPE scorez = ScoreMatrix::distTQplusDiffExtBackward[A[rr+1]][B[cc+1]][A[rr]][B[cc]]; const PART_TYPE prob = s / (scorez * denoZ); //cerr << r << "," << c << ":" << s << "/(" << scorez << " x " << denoZ << ")=" << prob << endl; if(0.001 <= prob) ptr[rr*numCol+cc] = min(1.0, prob); }*/ /*{ // [2] --- this code generates same result as probalign if epsilon == 0 --- const PART_TYPE s = forwardZ[D][r+1][c+1] * (Z[D][r+1][c+1]+Z[U][r+1][c+1]+Z[L][r+1][c+1]); const PART_TYPE prob = s / denoZ; if(0.001 <= prob) ptr[(r+1)*numCol+(c+1)] = min(1.0, prob); }*/ { // [2] --- this code generates same result as probalign if epsilon == 0 --- const PART_TYPE s = forwardZ[D][r+1][c+1] * Z[D][r][c] / ScoreMatrix::distTQplusDiffExtBackward[PRE][PRE][A[rr]][B[cc]]; const PROFILE_TYPE prob = static_cast<PROFILE_TYPE>(s / denoZ); if(PROFILE_ONE/1000 <= prob) ptr[(r+1)*numCol+(c+1)] = min(PROFILE_ONE, prob); } /*{ // [2] --- this code generates same result as probalign if epsilon == 0 --- const PART_TYPE s = (forwardZ[D][r][c] + forwardZ[U][r][c] + forwardZ[L][r][c]) * (Z[D][r+1][c+1]+Z[U][r+1][c+1]+Z[L][r+1][c+1]); const PART_TYPE scorez = ScoreMatrix::distTQplusDiffExtBackward[PRE][PRE][A[rr]][B[cc]]; const PART_TYPE prob = s * scorez / denoZ; if(0.001 <= prob) ptr[(r+1)*numCol+(c+1)] = min(1.0, prob); }*/ } } #ifdef DEBUG putLog("forward Z=" + DS(denoZ)); putLog("backward Z=" + DS(Z[D][0][0] + Z[U][0][0] + Z[L][0][0])); putLog("forward Z:"); showPartMatrix(&forwardZ); putLog("backward Z:"); showPartMatrix(&Z); #endif return profilePtr; } // MSAProbs::MSA::DoIterativeRefinement()相当 void doIterativeRef(const VVpSM& sparseProfiles, Sequences* & alignment, VPROFILE* pSeqsWeights, const GlobalOption& gOption, int seedid) { const int numSeqs = alignment->seqs.size(); VI indexList(numSeqs), g1(numSeqs/2), g2(numSeqs - g1.size()); srand(seedid); for(int i=0; i<numSeqs; i++)indexList[i] = i; random_shuffle(indexList.begin(), indexList.end()); const int g1size = g1.size(); int i = 0; for(; i<g1size; i++) g1[i] = indexList[i]; for(; i<numSeqs;i++) g2[i - g1size] = indexList[i]; assert(!g1.empty()); assert(!g2.empty()); // split the alignment to two alignments Sequences* align1 = alignment->extract(g1); Sequences* align2 = alignment->extract(g2); delete alignment; // realign alignment = mergeAlignments(align1, align2, sparseProfiles, pSeqsWeights); delete align1; delete align2; } // MSAProbs::MSA::ComputeFinalAlignment()相当 Sequences* genFinalAlignment(tr_node* pGuideTree, const Sequences* pSeqs, const VVpSM& sparseProfiles, VPROFILE* pSeqsWeights, const GlobalOption& gOption) { Sequences* alignment = doProgressiveAlignment(pGuideTree, pSeqs, sparseProfiles, pSeqsWeights); // --- treat an ordering --- // TODO: // --- iterative refinements --- if(pSeqs->seqs.size() > 2) { for(int i=0; i<gOption.numIterativeRefReps; i++) { putLog("iterative " + IS(i+1) + "."); doIterativeRef(sparseProfiles, alignment, pSeqsWeights, gOption, i); } } // --- sort --- if(gOption.sortByInputOrder) alignment->sort(); return alignment; } // MSAProbs::MSA::ProcessTree()相当 // 再帰するごとにpTreeは変化するが,pSeqs等は固定 Sequences* doProgressiveAlignment(tr_node* pTree, const Sequences* pSeqs, const VVpSM& sparseProfiles, VPROFILE* pSeqsWeights){ Sequences* result; //putLog("progressive alignment: node id=" + binary2string<int>(pTree->id)); if(pTree->id < 0) { // node Sequences* alignLeft = doProgressiveAlignment(pTree->pLeft, pSeqs, sparseProfiles, pSeqsWeights); Sequences* alignRight = doProgressiveAlignment(pTree->pRight, pSeqs, sparseProfiles, pSeqsWeights); assert(alignLeft); assert(alignRight); //putLog("merge the two alignments"); result = mergeAlignments(alignLeft, alignRight, sparseProfiles, pSeqsWeights); //putLog("done"); assert(result); delete alignLeft; delete alignRight; }else{ // leaf result = new Sequences(); assert(result); result->addSequence(pSeqs->names[pTree->id], pSeqs->seqs[pTree->id], pTree->id); } return result; } // probcons::ProbabilisticModel.h::BuildPosterior()相当 // M[i,j] = sum{s in align1} sum{s in align2} f(s,t,i,j) // where // f(s,t,i,j) = P(s[i'] <-> t[j']) when s[i'] is a symbol in the ith site of align1 and // t[j'] is a symbol in the jth site of align2 // 0 otherwise VPROFILE* buildProfile(VPROFILE* pSeqsWeights, Sequences* align1, Sequences* align2, const VVpSM& sparseProfiles){ // cout << "build profile:" << endl; // align1->output(cout); // align2->output(cout); const PROFILE_TYPE cutoff = 0.0; // size of the alignment 1 and 2 includes the size of prefix '@' // this is the same size of the new profile const int numNewRow = align1->seqs[0]->size(); const int numNewCol = align2->seqs[0]->size(); VPROFILE* profilePtr = new VPROFILE(numNewRow * numNewCol, PROFILE_ZERO); assert(profilePtr); VPROFILE& profile = *profilePtr; // compute the total sum of all weights //putLog("compute the total sum of all weights"); PROFILE_TYPE totalWeights = 0.0; for(size_t i=0; i<align1->seqs.size(); i++) { const int first = align1->index[i]; const PROFILE_TYPE w1 = (*pSeqsWeights)[first]; for(size_t j=0; j<align2->seqs.size(); j++) { const int second = align2->index[j]; const PROFILE_TYPE w2 = (*pSeqsWeights)[second]; totalWeights += w1 * w2; } } // generate the weighted profile //putLog("generate the weighted profile"); // for each s in align1 for(size_t i=0; i<align1->seqs.size(); i++) { const int first = align1->index[i]; const PROFILE_TYPE w1 = (*pSeqsWeights)[first]; VI* mapping1 = genNonGapIndexList(*(align1->seqs[i])); for(size_t j=0; j<align2->seqs.size(); j++) { const int second = align2->index[j]; const PROFILE_TYPE w2 = (*pSeqsWeights)[second]; VI* mapping2 = genNonGapIndexList(*(align2->seqs[j])); PROFILE_TYPE w = w1 * w2 / totalWeights; pair<int,int> ij = myMinmax(first,second); //cout << "ij=" << ij.first << "," << ij.second << endl; SparseMatrix* matrix = sparseProfiles[ij.first][ij.second]; assert(matrix && "ij is wrong!!"); int seq1Length = matrix->GetSeq1Length(); // numRow - 1 int seq2Length = matrix->GetSeq2Length(); // numCol - 1 // here, not use the trans matrix because of the calculation costs if(ij.first == first) { for(int ii=1; ii<=seq1Length; ii++) { SafeVector<PID>::iterator row = matrix->GetRowPtr(ii); const int base = (*mapping1)[ii] * numNewCol; const int sparseRow = matrix->GetRowSize(ii); // add in all relevant values for(int jj=0; jj<sparseRow; jj++) { profile[base + (*mapping2)[row[jj].first]] += w * row[jj].second; } // subtract cutoff for(int jj=0; jj<seq2Length; jj++) { profile[base + (*mapping2)[jj]] -= w * cutoff; } } }else{ for(int jj=1; jj<=seq1Length; jj++) { SafeVector<PID>::iterator row = matrix->GetRowPtr(jj); const int base = (*mapping2)[jj]; const int sparseRow = matrix->GetRowSize(jj); // add in all relevant values for(int ii=0; ii<sparseRow; ii++) { profile[base + (*mapping1)[row[ii].first] * numNewCol] += w * row[ii].second; } // subtract cutoff for(int ii=0; ii<seq2Length; ii++) { profile[base + (*mapping1)[ii] * numNewCol] -= w * cutoff; } } } delete mapping2; } delete mapping1; } return profilePtr; } // probcons::MSA::AlignAlignments()相当 Sequences* mergeAlignments(Sequences* align1, Sequences* align2, const VVpSM& sparseProfiles, SafeVector<PROFILE_TYPE>* pSeqsWeights){ // make a profile //putLog("make a profile from alignment"); //putLog("group1:"); //align1->output(cout); //putLog("group2:"); //align2->output(cout); VPROFILE* profile = buildProfile(pSeqsWeights, align1, align2, sparseProfiles); //SparseMatrix sm = SparseMatrix(align1->seqs[0]->size(), align2->seqs[0]->size(), *profile); //sm.Print(cout); // do profile alignment //putLog("do profile alignment"); pair<string*, PROFILE_TYPE> alignment = doProfileAlignment(align1->seqs[0]->size(), align2->seqs[0]->size(), *profile); // finalize delete profile; // generate the final alignment //putLog("generate the alignment"); Sequences* result = new Sequences(); for(size_t i=0; i<align1->seqs.size(); i++) result->addSequence(align1->names[i], pString(genGappedSeq(*align1->seqs[i], *alignment.first, 'X')), align1->index[i]); for(size_t i=0; i<align2->seqs.size(); i++) result->addSequence(align2->names[i], pString(genGappedSeq(*align2->seqs[i], *alignment.first, 'Y')), align2->index[i]); delete alignment.first; //putLog("merged:"); //result->output(cout); return result; } // probcons::ProbabilisticModel.h::ComputeAlignment()相当 // return the best alignment string and the best alignment score pair<std::string*, PROFILE_TYPE> doProfileAlignment(int seq1Length, int seq2Length, const VPROFILE& profile) { const int numRow = seq1Length; // with the length of prefix '@' const int numCol = seq2Length; // with the length of prefix '@' PROFILE_TYPE* twoRows = new PROFILE_TYPE[numCol*2]; assert(twoRows); PROFILE_TYPE* oldRow = twoRows; PROFILE_TYPE* newRow = twoRows + numCol; char* tracebackMatrix = new char[numRow * numCol]; assert(tracebackMatrix); char* tracebackPtr = tracebackMatrix; assert(profile.size() == numRow * numCol && "the size of profile is wrong!!"); // initialization for(int c=0; c<numCol; c++) { oldRow[c] = 0.0; *(tracebackPtr++) = 'L'; // Left } // omit the first row VPROFILE::const_iterator profilePtr = profile.begin() + numCol; // fill the matrix (dynamic programming) for(int r=1; r<numRow; r++) { // initialize left column newRow[0] = 0.0; profilePtr++; *(tracebackPtr++) = 'U'; // Upper // fill in rest of row for(int c=1; c<numCol; c++) { // current node (r,c) is newRow[c] so // Diag (r-1,c-1) = oldRow[c-1] // Left (r,c-1) = newRow[c-1] // Upper (r-1,c) = oldRow[c] // TODO: dの計算はベクトル化し高速化できる(Eigen3の出番) const PROFILE_TYPE d = *(profilePtr++) + oldRow[c-1]; const PROFILE_TYPE l = newRow[c-1]; const PROFILE_TYPE u = oldRow[c]; pair<PROFILE_TYPE,char> best = choiceMax(d,u,l,'D','U','L'); newRow[c] = best.first; *(tracebackPtr++) = best.second; } // swap rows PROFILE_TYPE* temp = oldRow; oldRow = newRow; newRow = temp; } // store alignment score PROFILE_TYPE total = oldRow[seq2Length-1]; delete [] twoRows; // debug: output the tracebackMatrix /*cout << "numRow,numCol=" << numRow << "," << numCol << endl; for(int i=0; i<numRow; i++) { for(int j=0; j<numCol; j++) { cout << tracebackMatrix[i*numCol+j]; } cout << endl; }*/ // compute traceback string* alignment = new string(); assert(alignment); int r = numRow - 1; int c = numCol - 1; while( r != 0 || c != 0) { const char ch = tracebackMatrix[r * numCol + c]; switch(ch){ case 'L': c--; alignment->push_back('Y'); break; // seq1にギャップ case 'U': r--; alignment->push_back('X'); break; // seq2にギャップ case 'D': c--; r--; alignment->push_back('B'); break; // seq1にギャップ default: assert(false); } } // finalize delete [] tracebackMatrix; reverse(alignment->begin(), alignment->end()); return make_pair(alignment, total); } // MSA::DoRelaxation()相当 // TODO: アルゴリズムの理解 void doConsistencyTrans(const VPROFILE& seqsWeights, const Sequences* pSeqs, VVpSM& sparseProfiles) { const int numSeqs = pSeqs->seqs.size(); VVpSM newSparseProfiles(numSeqs, VpSM(numSeqs, static_cast<pSparseMatrix>(NULL))); #ifdef _OPENMP int pairIndex; #pragma omp parallel for private(pairIndex) default(shared) schedule(dynamic) for(pairIndex=0; pairIndex<globalOption.numProfilePairs; pairIndex++) { int i = globalOption.profilePairs[pairIndex].first; int j = globalOption.profilePairs[pairIndex].second; const PROFILE_TYPE wi = seqsWeights[i]; const PROFILE_TYPE wj = seqsWeights[j]; #else for(int i=0; i<numSeqs; i++) { const PROFILE_TYPE wi = seqsWeights[i]; for(int j=i+1; j<numSeqs; j++) { const PROFILE_TYPE wj = seqsWeights[j]; #endif string& seq1 = *(pSeqs->seqs[i]); string& seq2 = *(pSeqs->seqs[j]); VPROFILE* profilePtr = sparseProfiles[i][j]->GetPosterior(); assert(profilePtr); VPROFILE& profile = *profilePtr; const int numRow = seq1.size(); const int numCol = seq2.size(); // --- consistency calculation --- // STEP1: only calculate the summation where z = x and z = y const PROFILE_TYPE w1 = wi*wi*wj + wi*wj*wj; PROFILE_TYPE sumW = w1; for(int k=0; k<numRow*numCol; k++) profile[k] *= w1; // STEP2: calculate the other parts for(int k=0; k<numSeqs; k++) if(k != i && k != j) { const PROFILE_TYPE wk = seqsWeights[k]; const PROFILE_TYPE w2 = wi*wj*wk; sumW += w2; if(k < i) { consistencyZXZY(w2, sparseProfiles[k][i], sparseProfiles[k][j], profile); }else if(k > i && k < j){ consistencyXZZY(w2, sparseProfiles[i][k], sparseProfiles[k][j], profile); }else{ // TODO: 転置するコストを考えると特化consistency関数を作成すべき SparseMatrix* t = sparseProfiles[j][k]->ComputeTranspose(); consistencyXZZY(w2, sparseProfiles[i][k], t, profile); delete t; } } // for k // STEP3: for(int k=0; k<numRow*numCol; k++) profile[k] /= sumW; // STEP4: mask out SparseMatrix* matXY = sparseProfiles[i][j]; for(int y=0; y<numCol; y++) profile[y] = 0.0; for(int x=1; x<numRow; x++) { SafeVector<PID>::iterator XYptr = matXY->GetRowPtr(x); SafeVector<PID>::iterator XYend = XYptr + matXY->GetRowSize(x); VPROFILE::iterator base = profile.begin() + x * numCol; int curr = 0; for( ;XYptr != XYend; curr++, ++XYptr) { // set 0 before the first filled column for( ;curr < XYptr->first; curr++) base[curr] = 0.0; } // set 0 after last column for( ; curr<numCol; curr++) base[curr] = 0.0; } // --- save the new profile --- newSparseProfiles[i][j] = new SparseMatrix(seq1.size()-1, seq2.size()-1, profile); // --- finalize --- delete profilePtr; #ifndef _OPENMP } // for j #endif } // for i // copy for (int i=0; i<numSeqs-1; i++){ for (int j=i+1; j<numSeqs; j++){ delete sparseProfiles[i][j]; sparseProfiles[i][j] = newSparseProfiles[i][j]; } } } // MSA::Relax()相当 void consistencyXZZY(PROFILE_TYPE weight, SparseMatrix* matXZ, SparseMatrix* matZY, VPROFILE& profile) { assert(matXZ); assert(matZY); const int numRow = matXZ->GetSeq1Length() + 1; // X const int numCol = matZY->GetSeq2Length() + 1; // Y assert(matXZ->GetSeq2Length() == matZY->GetSeq1Length()); for(int i=1; i<numRow; i++) { // every x[i] SafeVector<PID>::iterator XZptr = matXZ->GetRowPtr(i); SafeVector<PID>::iterator XZend = XZptr + matXZ->GetRowSize(i); VPROFILE::iterator base = profile.begin() + i * numCol; while (XZptr != XZend) { // x[i] <-> z[k] SafeVector<PID>::iterator ZYptr = matZY->GetRowPtr(XZptr->first); SafeVector<PID>::iterator ZYend = ZYptr + matZY->GetRowSize(XZptr->first); const PROFILE_TYPE valXZ = XZptr->second; while(ZYptr != ZYend) { // z[k] <-> y[j] base[ZYptr->first] += weight * valXZ * ZYptr->second; ZYptr++; } XZptr++; } } } // MSA::Relax1()相当 void consistencyZXZY(PROFILE_TYPE weight, SparseMatrix* matZX, SparseMatrix* matZY, VPROFILE& profile) { assert(matZX); assert(matZY); const int numRow = matZX->GetSeq1Length() + 1; // Z const int numCol = matZY->GetSeq2Length() + 1; // Y for(int k=1; k<numRow; k++) { SafeVector<PID>::iterator ZXptr = matZX->GetRowPtr(k); SafeVector<PID>::iterator ZXend = ZXptr + matZX->GetRowSize(k); while (ZXptr != ZXend) { // x[i] <-> z[k] SafeVector<PID>::iterator ZYptr = matZY->GetRowPtr(k); SafeVector<PID>::iterator ZYend = ZYptr + matZY->GetRowSize(k); const PROFILE_TYPE valZX = ZXptr->second; VPROFILE::iterator base = profile.begin() + ZXptr->first * numCol; while(ZYptr != ZYend) { // z[k] <-> y[j] base[ZYptr->first] += weight * valZX * ZYptr->second; ZYptr++; } ZXptr++; } } } void showProfile(VPROFILE* profile, int numRow, int numCol) { for(int r=0; r<numRow; r++) { stringstream line; for(int c=0; c<numCol; c++) { line << left << setw(8) << setprecision(3) << (*profile)[r*numCol+c]; } putLog(line.str()); } }
40.48365
168
0.520005
toshihr
f69ec72ee80677404c8e4a4123e1c38e1de29936
4,144
cpp
C++
eagle_mpc_2_control/src/motor_test.cpp
PepMS/eagle_mpc_ros2
19f9d23606524960ef2d4ad2ccf609c91f813b2e
[ "MIT" ]
5
2021-08-07T06:16:20.000Z
2022-02-27T21:43:33.000Z
eagle_mpc_2_control/src/motor_test.cpp
PepMS/px4_mpc
19f9d23606524960ef2d4ad2ccf609c91f813b2e
[ "MIT" ]
null
null
null
eagle_mpc_2_control/src/motor_test.cpp
PepMS/px4_mpc
19f9d23606524960ef2d4ad2ccf609c91f813b2e
[ "MIT" ]
2
2021-01-05T03:12:13.000Z
2021-01-05T03:12:13.000Z
//////////////////////////////////////////////////////////////////////////////////// // MIT License // // Copyright (c) 2020 Pep Martí Saumell // // 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 "eagle_mpc_2_control/motor_test.hpp" using namespace std::chrono_literals; namespace eagle_mpc_ros2 { MotorTest::MotorTest(const std::string& node_name) : ControllerAbstract(node_name) { actuator_normalized_[0] = -1.0; actuator_normalized_[1] = -1.0; actuator_normalized_[2] = -1.0; actuator_normalized_[3] = -1.0; RCLCPP_INFO(get_logger(), "MOTOR TEST Created!"); counter_ = 0; motor_idx_ = 0; change_motor_timer_ = create_wall_timer(5s, std::bind(&MotorTest::changeMotorCallback, this), callback_group_other_); rclcpp::SubscriptionOptions sub_opt_commands = rclcpp::SubscriptionOptions(); sub_opt_commands.callback_group = callback_group_commands_; angular_velocity_subs_ = nullptr; angular_velocity_subs_ = create_subscription<px4_msgs::msg::VehicleAngularVelocity>( "VehicleAngularVelocity_PubSubTopic", rclcpp::QoS(1), std::bind(&MotorTest::vehicleAngularVelocityCallback, this, std::placeholders::_1), sub_opt_commands); motor_value_ = -1.0; } MotorTest::~MotorTest() {} void MotorTest::computeControls() {} void MotorTest::vehicleAngularVelocityCallback(const px4_msgs::msg::VehicleAngularVelocity::SharedPtr msg) { mut_state_.lock(); state_(10) = msg->xyz[0]; state_(11) = -msg->xyz[1]; state_(12) = -msg->xyz[2]; mut_state_.unlock(); timestamp_.store(msg->timestamp); if (platform_motor_control_enabled_ && motor_value_ < -0.975) { // actuator_normalized_[0] = motor_value_; // actuator_normalized_[1] = motor_value_; // actuator_normalized_[2] = motor_value_; // actuator_normalized_[3] = motor_value_; // actuator_direct_control_msg_.timestamp = timestamp_.load(); actuator_direct_control_msg_.timestamp = msg->timestamp; actuator_direct_control_msg_.output[0] = motor_value_; actuator_direct_control_msg_.output[1] = motor_value_; actuator_direct_control_msg_.output[2] = motor_value_; actuator_direct_control_msg_.output[3] = motor_value_; actuator_direct_control_pub_->publish(actuator_direct_control_msg_); RCLCPP_INFO(get_logger(), "Sent motor value: %f", motor_value_); motor_value_ += 0.001; } } void MotorTest::publishControls() {} void MotorTest::changeMotorCallback() { // RCLCPP_INFO(get_logger(), "Writing motor: %ld", motor_idx_); motor_idx_++; motor_idx_ = motor_idx_ > 3 ? 0 : motor_idx_; } } // namespace eagle_mpc_ros2 int main(int argc, char* argv[]) { rclcpp::init(argc, argv); std::shared_ptr<eagle_mpc_ros2::MotorTest> controller = std::make_shared<eagle_mpc_ros2::MotorTest>("MotorTest"); rclcpp::executors::MultiThreadedExecutor executor; executor.add_node(controller); executor.spin(); rclcpp::shutdown(); return 0; }
37.333333
117
0.694981
PepMS
f6a043340753792232e2b08a3a5bc56d9b9184e9
2,732
cpp
C++
src/ensnare/private/config.cpp
dumjyl/cpp_interop
87d2dd7cb9a00a46fb101677e633b706ffd5a46d
[ "MIT" ]
null
null
null
src/ensnare/private/config.cpp
dumjyl/cpp_interop
87d2dd7cb9a00a46fb101677e633b706ffd5a46d
[ "MIT" ]
4
2020-01-14T08:38:32.000Z
2020-01-17T06:03:44.000Z
src/ensnare/private/config.cpp
dumjyl/clang-tooling-nim
87d2dd7cb9a00a46fb101677e633b706ffd5a46d
[ "MIT" ]
null
null
null
#include "ensnare/private/config.hpp" #include "llvm/Support/CommandLine.h" namespace cl = llvm::cl; using namespace ensnare; cl::list<Str> syms("sym", cl::desc("specify specific symbols to bind. FIXME: not implimented")); cl::list<Str> gensym_types("gensym-type", cl::desc("mangle a type symbol")); cl::list<Str> include_dirs("include-dir", cl::desc("allow binding any headers in this directory")); cl::opt<bool> fold_type_suffix("fold-type-suffix", cl::desc("fold the inner type of a typedef with _t suffix")); cl::opt<bool> disable_includes("disable-includes", cl::desc("do not gather system includes. FIXME: not implimented")); cl::opt<bool> ignore_const("ignore-const", cl::desc("ignore const qualifiers")); cl::opt<Str> output(cl::Positional, cl::desc("output wrapper name/path")); cl::list<Str> args(cl::ConsumeAfter, cl::desc("clang args...")); const Vec<Header>& ensnare::Config::headers() const { return _headers; } const Path& ensnare::Config::output() const { return _output; } const Vec<Str>& ensnare::Config::user_clang_args() const { return _user_clang_args; } const Vec<Str>& ensnare::Config::syms() const { return _syms; } const Vec<Str>& ensnare::Config::gensym_types() const { return _gensym_types; } const Vec<Str>& ensnare::Config::include_dirs() const { return _include_dirs; } bool ensnare::Config::disable_includes() const { return _disable_includes; } bool ensnare::Config::fold_type_suffix() const { return _fold_type_suffix; } bool ensnare::Config::ignore_const() const { return _ignore_const; } ensnare::Config::Config(int argc, const char* argv[]) { llvm::cl::ParseCommandLineOptions(argc, argv); _syms = ::syms; _gensym_types = ::gensym_types; _include_dirs = ::include_dirs; _fold_type_suffix = ::fold_type_suffix; _disable_includes = ::disable_includes; _ignore_const = ::ignore_const; _output = Str(::output); for (const auto& arg : args) { auto header = Header::parse(arg); if (header) { _headers.push_back(*header); } else { _user_clang_args.push_back(arg); } } }; Str ensnare::Config::header_file() const { if (_headers.size() == 0) { fatal("no headers given"); } else { Str result; for (const auto& header : _headers) { result += header.render(); } return result; }; } void ensnare::Config::dump() const { print("Config:"); print(" output: ", _output); for (const auto& header : _headers) { print(" header: ", Str(header)); } for (const auto& arg : _user_clang_args) { print(" clang arg: ", arg); } for (const auto& sym : _syms) { print(" sym: ", sym); } }
37.944444
99
0.654466
dumjyl
f6a2cb6dbeb1e50bf05847798c10116bc1c5f2b1
3,182
cpp
C++
Foundation/testsuite/src/HashSetTest.cpp
e0861280/poco
961ca3e246f55646ab6e101e35e3ec0db359360f
[ "BSL-1.0" ]
null
null
null
Foundation/testsuite/src/HashSetTest.cpp
e0861280/poco
961ca3e246f55646ab6e101e35e3ec0db359360f
[ "BSL-1.0" ]
null
null
null
Foundation/testsuite/src/HashSetTest.cpp
e0861280/poco
961ca3e246f55646ab6e101e35e3ec0db359360f
[ "BSL-1.0" ]
1
2019-09-13T16:32:18.000Z
2019-09-13T16:32:18.000Z
// // HashSetTest.cpp // // $Id: //poco/1.4/Foundation/testsuite/src/HashSetTest.cpp#1 $ // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #include "HashSetTest.h" #include "Poco/CppUnit/TestCaller.h" #include "Poco/CppUnit/TestSuite.h" #include "Poco/HashSet.h" #include <set> using Poco::Hash; using Poco::HashSet; HashSetTest::HashSetTest(const std::string& rName): CppUnit::TestCase(rName) { } HashSetTest::~HashSetTest() { } void HashSetTest::testInsert() { const int N = 1000; HashSet<int, Hash<int> > hs; assert (hs.empty()); for (int i = 0; i < N; ++i) { std::pair<HashSet<int, Hash<int> >::Iterator, bool> res = hs.insert(i); assert (*res.first == i); assert (res.second); HashSet<int, Hash<int> >::Iterator it = hs.find(i); assert (it != hs.end()); assert (*it == i); assert (hs.size() == i + 1); } assert (!hs.empty()); for (int i = 0; i < N; ++i) { HashSet<int, Hash<int> >::Iterator it = hs.find(i); assert (it != hs.end()); assert (*it == i); } for (int i = 0; i < N; ++i) { std::pair<HashSet<int, Hash<int> >::Iterator, bool> res = hs.insert(i); assert (*res.first == i); assert (!res.second); } } void HashSetTest::testErase() { const int N = 1000; HashSet<int, Hash<int> > hs; for (int i = 0; i < N; ++i) { hs.insert(i); } assert (hs.size() == N); for (int i = 0; i < N; i += 2) { hs.erase(i); HashSet<int, Hash<int> >::Iterator it = hs.find(i); assert (it == hs.end()); } assert (hs.size() == N/2); for (int i = 0; i < N; i += 2) { HashSet<int, Hash<int> >::Iterator it = hs.find(i); assert (it == hs.end()); } for (int i = 1; i < N; i += 2) { HashSet<int, Hash<int> >::Iterator it = hs.find(i); assert (it != hs.end()); assert (*it == i); } for (int i = 0; i < N; i += 2) { hs.insert(i); } for (int i = 0; i < N; ++i) { HashSet<int, Hash<int> >::Iterator it = hs.find(i); assert (it != hs.end()); assert (*it == i); } } void HashSetTest::testIterator() { const int N = 1000; HashSet<int, Hash<int> > hs; for (int i = 0; i < N; ++i) { hs.insert(i); } std::set<int> values; HashSet<int, Hash<int> >::Iterator it = hs.begin(); while (it != hs.end()) { assert (values.find(*it) == values.end()); values.insert(*it); ++it; } assert (values.size() == N); } void HashSetTest::testConstIterator() { const int N = 1000; HashSet<int, Hash<int> > hs; for (int i = 0; i < N; ++i) { hs.insert(i); } std::set<int> values; HashSet<int, Hash<int> >::ConstIterator it = hs.begin(); while (it != hs.end()) { assert (values.find(*it) == values.end()); values.insert(*it); ++it; } assert (values.size() == N); } void HashSetTest::setUp() { } void HashSetTest::tearDown() { } CppUnit::Test* HashSetTest::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HashSetTest"); CppUnit_addTest(pSuite, HashSetTest, testInsert); CppUnit_addTest(pSuite, HashSetTest, testErase); CppUnit_addTest(pSuite, HashSetTest, testIterator); CppUnit_addTest(pSuite, HashSetTest, testConstIterator); return pSuite; }
17.016043
76
0.589252
e0861280
f6a4b2256caa16cc8318635c61ae1f5f11eb4278
8,614
cpp
C++
Fundamental/CCore/src/CharProp.cpp
SergeyStrukov/CCore-4-xx
5faeadd50a24a7dbe18ffff8efe5f49212588637
[ "BSL-1.0" ]
null
null
null
Fundamental/CCore/src/CharProp.cpp
SergeyStrukov/CCore-4-xx
5faeadd50a24a7dbe18ffff8efe5f49212588637
[ "BSL-1.0" ]
null
null
null
Fundamental/CCore/src/CharProp.cpp
SergeyStrukov/CCore-4-xx
5faeadd50a24a7dbe18ffff8efe5f49212588637
[ "BSL-1.0" ]
null
null
null
/* CharProp.cpp */ //---------------------------------------------------------------------------------------- // // Project: CCore 4.01 // // Tag: Fundamental Mini // // License: Boost Software License - Version 1.0 - August 17th, 2003 // // see http://www.boost.org/LICENSE_1_0.txt or the local copy // // Copyright (c) 2020 Sergey Strukov. All rights reserved. // //---------------------------------------------------------------------------------------- #include <CCore/inc/CharProp.h> namespace CCore { /* CutLine() */ StrLen CutLine(StrLen &text) { SplitLine split(text); text=split.rest; return split.line; } /* struct SplitLine */ SplitLine::SplitLine(StrLen text) { for(StrLen next=text; +next ;++next) { char ch=*next; if( ch=='\r' || ch=='\n' ) { line=text.prefix(next); ++next; if( ch=='\r' && +next && *next=='\n' ) ++next; rest=next; eol=true; return; } } line=text; rest=Empty; eol=false; } /* class ASCIICode */ const bool ASCIICode::IsSpaceTable[256]= { false,false,false,false,false,false,false,false,false,true ,true ,true ,true ,true ,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, true ,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false }; const bool ASCIICode::IsPunctTable[256]= { false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,true ,true ,true ,true ,true ,true ,true ,true ,true ,true ,true ,true ,true ,true ,true , false,false,false,false,false,false,false,false,false,false,true ,true ,true ,true ,true ,true , true ,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,true ,true ,true ,true ,false, true ,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,true ,true ,true ,true ,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false }; const bool ASCIICode::IsSpaceOrPunctTable[256]= { false,false,false,false,false,false,false,false,false,true ,true ,true ,true ,true ,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, true ,true ,true ,true ,true ,true ,true ,true ,true ,true ,true ,true ,true ,true ,true ,true , false,false,false,false,false,false,false,false,false,false,true ,true ,true ,true ,true ,true , true ,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,true ,true ,true ,true ,false, true ,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,true ,true ,true ,true ,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false }; const signed char ASCIICode::DecValueTable[256]= { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; const signed char ASCIICode::HexValueTable[256]= { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; /* char sets */ const char * GetSpaceChars() { return " \t\f\v\r\n"; } const char * GetPunctChars() { return "!\"#$%&'()*+,-./:;<=>?@[\\]^`{|}~"; } const char * GetDigitChars() { return "0123456789"; } const char * GetHexDigitChars() { return "0123456789abcdefABCDEF"; } const char * GetCLetterChars() { return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_"; } } // namespace CCore
48.943182
98
0.605642
SergeyStrukov
f6ab2ad17f4fbbd80e61208f14188f46366553c8
13,203
cpp
C++
Editor/SourceListView.cpp
ahwayakchih/Medo
acc34c189676544c092fbc6800c27a25d05de6dd
[ "MIT" ]
null
null
null
Editor/SourceListView.cpp
ahwayakchih/Medo
acc34c189676544c092fbc6800c27a25d05de6dd
[ "MIT" ]
null
null
null
Editor/SourceListView.cpp
ahwayakchih/Medo
acc34c189676544c092fbc6800c27a25d05de6dd
[ "MIT" ]
null
null
null
/* PROJECT: Medo * AUTHORS: Zenja Solaja, Melbourne Australia * COPYRIGHT: Zen Yes Pty Ltd, 2019-2021 * DESCRIPTION: Source item */ #include <cassert> #include <InterfaceKit.h> #include <support/String.h> #include <ControlLook.h> #ifndef _GRAPHICS_DEFS_H #include <interface/GraphicsDefs.h> #endif #include "ImageUtility.h" #include "Language.h" #include "MediaSource.h" #include "MedoWindow.h" #include "SourceListView.h" #include "Theme.h" #include "TimelineEdit.h" #include "VideoManager.h" /********************************* SourceListItem **********************************/ static const float kThumbnailHeight = 84.0f; static const float kThumbnailWidth = kThumbnailHeight * (16.0f/9.0f); /* FUNCTION: SourceListItem :: SourceListItem ARGS: filename RETURN: n/a DESCRIPTION: Constructor */ SourceListItem :: SourceListItem(MediaSource *media_source) : fMediaSource(media_source), fBitmap(nullptr) { assert(media_source != nullptr); CreateBitmap(media_source); } /* FUNCTION: SourceListItem :: ~SourceListItem ARGS: n/a RETURN: n/a DESCRIPTION: Destructor */ SourceListItem :: ~SourceListItem() { delete fBitmap; } /* FUNCTION: SourceListItem :: CreateBitmap ARGS: media_source RETURN: n/a DESCRIPTION: Create thumbnail Video files may have initial frame, so use subsequent frames as thumbnail */ void SourceListItem :: CreateBitmap(MediaSource *media_source) { const float kFontFactor = be_plain_font->Size()/20.0f; // Has video? if ((media_source->GetMediaType() == MediaSource::MEDIA_VIDEO) || (media_source->GetMediaType() == MediaSource::MEDIA_VIDEO_AND_AUDIO)) { int64 frame_idx = 0; while (!fBitmap) { BBitmap *frame = frame_idx == 0 ? media_source->GetBitmap() : gVideoManager->GetFrameBitmap(media_source, frame_idx, true); float w = frame->Bounds().Width(); float h = frame->Bounds().Height(); uint8 *s = (uint8 *)frame->Bits(); int32 bytes_per_row = frame->BytesPerRow(); int32 sw = bytes_per_row / 4; int32 sh = frame->BitsLength() / bytes_per_row; float dx = sw/w; float dy = sh/h; float intensity = 0.0f; // scan frame diagonally, calculate intesity for (int row = 0; row < int(h); row++) { int col = w * row/h; // scaled column uint32 x= dx*col; uint32 y = dy*row; uint32 colour = *((uint32 *)(s + y*bytes_per_row + x*4)); intensity += 0.3f*((colour>>16)&0xff) + 0.59f*((colour>>8)&0xff) + 0.11f*(colour&0xff); } if (intensity / h > 256.0f*0.2f) fBitmap = CreateThumbnail(frame, ceilf(kThumbnailWidth*kFontFactor), kThumbnailHeight*kFontFactor); else { frame_idx += kFramesSecond; if (frame_idx >= media_source->GetVideoDuration()) break; } } } if (!fBitmap) fBitmap = CreateThumbnail(media_source->GetBitmap(), ceilf(kThumbnailWidth*kFontFactor), kThumbnailHeight*kFontFactor); } /* FUNCTION: SourceListItem :: Update ARGS: parent font RETURN: n/a DESCRIPTION: Hook called when item added to view */ void SourceListItem :: Update(BView *parent, const BFont *font) { const float kFontFactor = be_plain_font->Size()/20.0f; SetWidth(kThumbnailWidth*kFontFactor + 3*be_control_look->DefaultLabelSpacing() + font->StringWidth(fMediaSource->GetFilename())); SetHeight(kThumbnailHeight*kFontFactor + 2*be_control_look->DefaultLabelSpacing()); font_height h; font->GetHeight(&h); fBaselineOffset = 0.5f*kThumbnailHeight*kFontFactor; } /* FUNCTION: SourceListItem :: DrawItem ARGS: parent frame erase_bg RETURN: n/a DESCRIPTION: Draw item */ void SourceListItem :: DrawItem(BView *parent, BRect frame, bool erase_bg) { const float kFontFactor = be_plain_font->Size()/20.0f; rgb_color lowColor = parent->LowColor(); erase_bg = true; if (IsSelected() || erase_bg) { rgb_color color; if (IsSelected()) color = Theme::GetUiColour(UiColour::eListSelection); else color = parent->ViewColor(); parent->SetLowColor(color); parent->FillRect(frame, B_SOLID_LOW); } else parent->SetLowColor(parent->ViewColor()); const float offset = be_control_look->DefaultLabelSpacing(); parent->MovePenTo(offset, offset); BRect thumb_rect(frame.left + offset, frame.top + offset, frame.left + kThumbnailWidth*kFontFactor + offset, frame.top + kThumbnailHeight*kFontFactor + offset); if (fMediaSource->GetMediaType() != MediaSource::MEDIA_AUDIO) { // Adjust aspect (fBitmap is kHumbnailWidth x kThumbnailHeight, so we need to inverse scale in call to DrawBitmapAsync) float aspect = (float)fMediaSource->GetVideoWidth() / (float)fMediaSource->GetVideoHeight(); if (aspect > 1.0f) { float h = thumb_rect.Width() / aspect; thumb_rect.top += 0.5f*(thumb_rect.Height() - h); thumb_rect.bottom = thumb_rect.top + h; } else if (aspect < 1.0f) { float w = thumb_rect.Height() * aspect; thumb_rect.left += 0.5f*(thumb_rect.Width() - w); thumb_rect.right = thumb_rect.left + w; } } parent->DrawBitmapAsync(fBitmap, thumb_rect); parent->SetHighColor(Theme::GetUiColour(UiColour::eListText)); font_height fh; be_plain_font->GetHeight(&fh); BString aString(fMediaSource->GetFilename()); int trunc = aString.FindLast('/') + 1; BString line1(aString.RemoveChars(0, trunc)); aString.SetTo(fMediaSource->GetFilename()); BString line2(aString.Truncate(trunc)); parent->MovePenTo(kThumbnailWidth*kFontFactor + frame.left + 3*offset, frame.top + fBaselineOffset); be_plain_font->TruncateString(&line1, B_TRUNCATE_MIDDLE, frame.Width() - (kThumbnailWidth*kFontFactor + 3*be_control_look->DefaultLabelSpacing())); parent->DrawString(line1); parent->MovePenTo(kThumbnailWidth*kFontFactor + frame.left + 3*offset, frame.top + fBaselineOffset + fh.ascent + fh.descent); be_plain_font->TruncateString(&line2, B_TRUNCATE_BEGINNING, frame.Width() - (kThumbnailWidth*kFontFactor + 3*be_control_look->DefaultLabelSpacing())); parent->DrawString(line2); parent->SetLowColor(lowColor); } /*********************************/ class InstructionListItem : public BListItem { public: void DrawItem(BView *parent, BRect frame, bool erase_bg) { parent->MovePenTo(10, frame.bottom); parent->SetHighColor(Theme::GetUiColour(UiColour::eListText)); parent->DrawString(GetText(TXT_MENU_PROJECT_ADD_SOURCE)); } }; /********************************* SourceListView **********************************/ enum kSourceListMessages { kMsgGetInfo = 'slvm', kMsgRemoveSource, }; /* FUNCTION: SourceListView :: SourceListView ARGS: frame name func RETURN: n/a DESCRIPTION: constructor */ SourceListView :: SourceListView(BRect frame, const char *name, std::function<const char *(BListItem *)> func) #if SOURCE_LIST_VIEW_TOOLTIP : ListViewToolTip(frame, name, func) #else : BListView(frame, name) #endif { AddItem(new InstructionListItem); fInstructionItemVisible = true; SetViewColor(Theme::GetUiColour(UiColour::eListBackground)); // Drag drop message fMsgDragDrop = new BMessage(TimelineEdit::eMsgDragDropClip); // Source selected message fMsgNotifySourceSelected = new BMessage(MedoWindow::eMsgActionTabSourceSelected); fMsgNotifySourceSelected->AddPointer("MediaSource", nullptr); } /* FUNCTION: SourceListView :: ~SourceListView ARGS: n/a RETURN: n/a DESCRIPTION: Destructor */ SourceListView :: ~SourceListView() { delete fMsgDragDrop; delete fMsgNotifySourceSelected; } /* FUNCTION: SourceListView :: SelectionChanged ARGS: none RETURN: n/a DESCRIPTION: Hook function called when selection changed */ void SourceListView :: SelectionChanged() { BListView::SelectionChanged(); int32 index = CurrentSelection(); if (index >= 0) { fMsgNotifySourceSelected->ReplacePointer("MediaSource", ((SourceListItem *)ItemAt(index))->GetMediaSource()); Window()->PostMessage(fMsgNotifySourceSelected); } } /* FUNCTION: SourceListView :: MouseDown ARGS: point RETURN: n/a DESCRIPTION: Process mouse down Initiate drag/drop message */ void SourceListView :: MouseDown(BPoint point) { if (!Window()->IsActive()) Window()->Activate(); if (fInstructionItemVisible) { Window()->PostMessage(MedoWindow::eMsgMenuProjectAddSource); return; } #if SOURCE_LIST_VIEW_TOOLTIP ListViewToolTip::MouseDown(point); #else BListView::MouseDown(point); #endif int32 index = CurrentSelection(); if (index < 0) return; uint32 buttons; BMessage* msg = Window()->CurrentMessage(); msg->FindInt32("buttons", (int32*)&buttons); bool ctrl_modifier = ((MedoWindow *)Window())->GetKeyModifiers() & B_CONTROL_KEY; if ((buttons & B_SECONDARY_MOUSE_BUTTON) || ctrl_modifier) { ContextMenu(point); return; } } /* FUNCTION: SourceListView :: InitiateDrag ARGS: point index wasSelected RETURN: true if processed DESCRIPTION: Initiate drag/drop message */ bool SourceListView :: InitiateDrag(BPoint point, int32 index, bool wasSelected) { uint32 buttons; BMessage* msg = Window()->CurrentMessage(); msg->FindInt32("buttons", (int32*)&buttons); if (buttons & B_SECONDARY_MOUSE_BUTTON) return false; SourceListItem *item = (SourceListItem *)ItemAt(index); if (!item) return false; MediaSource *media_source = item->GetMediaSource(); SetMouseEventMask(B_POINTER_EVENTS, 0); fMsgDragDrop->MakeEmpty(); int64 clip_start = 0; fMsgDragDrop->AddInt64("start", clip_start); int64 clip_end = 0; switch (media_source->GetMediaType()) { case MediaSource::MEDIA_VIDEO: case MediaSource::MEDIA_VIDEO_AND_AUDIO: clip_end = media_source->GetVideoDuration(); break; case MediaSource::MEDIA_AUDIO: clip_end = media_source->GetAudioDuration(); break; default: clip_end = 2*kFramesSecond; } fMsgDragDrop->AddInt64("end", clip_end); fMsgDragDrop->AddPointer("source", media_source); fMsgDragDrop->AddInt64("xoffset", 0); const float kFontFactor = be_plain_font->Size()/20.0f; DragMessage(fMsgDragDrop, new BBitmap(item->GetBitmap()), BPoint(0.25f*kThumbnailWidth*kFontFactor, 0.25f*kThumbnailHeight*kFontFactor)); return true; } /* FUNCTION: SourceListView :: MouseUp ARGS: point RETURN: n/a DESCRIPTION: Process mouse up */ void SourceListView :: MouseUp(BPoint point) { int32 index = CurrentSelection(); if (index >= 0) { fMsgNotifySourceSelected->ReplacePointer("MediaSource", ((SourceListItem *)ItemAt(index))->GetMediaSource()); Window()->PostMessage(fMsgNotifySourceSelected); } } /* FUNCTION: SourceListView :: ContextMenu ARGS: point RETURN: n/a DESCRIPTION: Show context menu for media source */ void SourceListView :: ContextMenu(BPoint point) { ConvertToScreen(&point); // Initialise PopUp menu BPopUpMenu *aPopUpMenu = new BPopUpMenu("ContextMenuSourceList", false, false); aPopUpMenu->SetAsyncAutoDestruct(true); BMenuItem *aMenuItem_1 = new BMenuItem("File Info", new BMessage(kMsgGetInfo)); aPopUpMenu->AddItem(aMenuItem_1); int32 index = CurrentSelection(); assert(index >= 0); SourceListItem *item = (SourceListItem *)ItemAt(index); MediaSource *media_source = item->GetMediaSource(); BMenuItem *aMenuItem_2 = new BMenuItem(gProject->IsMediaSourceUsed(media_source) ? "Remove Media (including all References)" : "Remove Media", new BMessage(kMsgRemoveSource)); aPopUpMenu->AddItem(aMenuItem_2); aPopUpMenu->SetTargetForItems(this); aPopUpMenu->Go(point, true /*notify*/, false /*stay open when mouse away*/, true /*async*/); } /* FUNCTION: SourceListView :: MessageReceived ARGS: msg RETURN: n/a DESCRIPTION: Hook function */ void SourceListView :: MessageReceived(BMessage *msg) { switch (msg->what) { case kMsgGetInfo: { int32 index = CurrentSelection(); if (index < 0) return; SourceListItem *item = (SourceListItem *)ItemAt(index); MediaSource *media_source = item->GetMediaSource(); BString aString; media_source->CreateFileInfoString(&aString); BAlert *alert = new BAlert("FileInfo", aString.String(), "OK"); alert->Go(); break; } case kMsgRemoveSource: { int32 index = CurrentSelection(); if (index < 0) return; SourceListItem *item = (SourceListItem *)ItemAt(index); MediaSource *media_source = item->GetMediaSource(); gProject->RemoveMediaSource(media_source); RemoveItem(index); ((MedoWindow *)Window())->InvalidatePreview(); if (CountItems() == 0) { AddItem(new InstructionListItem); fInstructionItemVisible = true; } break; } default: #if SOURCE_LIST_VIEW_TOOLTIP ListViewToolTip::MessageReceived(msg); #else BListView::MessageReceived(msg); #endif } } /* FUNCTION: SourceListView :: AddItem ARGS: item RETURN: true if success DESCRIPTION: Hook function */ bool SourceListView :: AddItem(BListItem* item) { if (fInstructionItemVisible) { InstructionListItem *item = (InstructionListItem *)RemoveItem(0); delete item; fInstructionItemVisible = false; } return BListView::AddItem(item); } /* FUNCTION: SourceListView :: RemoveAllMediaSources ARGS: none RETURN: n/a DESCRIPTION: Called when new project loaded */ void SourceListView :: RemoveAllMediaSources() { while (CountItems() > 0) { SourceListItem *item = (SourceListItem *)ItemAt(0); gProject->RemoveMediaSource(item->GetMediaSource()); RemoveItem(0); } }
27.50625
161
0.713626
ahwayakchih
f6ad4d18b5631071947408dc5350d6e6aeee5066
4,658
cc
C++
test/syscalls/linux/madvise.cc
jmgao/gvisor
b915a25597a961311ceb57f89d18eaee9c9461d8
[ "Apache-2.0" ]
null
null
null
test/syscalls/linux/madvise.cc
jmgao/gvisor
b915a25597a961311ceb57f89d18eaee9c9461d8
[ "Apache-2.0" ]
null
null
null
test/syscalls/linux/madvise.cc
jmgao/gvisor
b915a25597a961311ceb57f89d18eaee9c9461d8
[ "Apache-2.0" ]
null
null
null
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <fcntl.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "gtest/gtest.h" #include "test/util/file_descriptor.h" #include "test/util/logging.h" #include "test/util/memory_util.h" #include "test/util/posix_error.h" #include "test/util/temp_path.h" #include "test/util/test_util.h" namespace gvisor { namespace testing { namespace { void ExpectAllMappingBytes(Mapping const& m, char c) { auto const v = m.view(); for (size_t i = 0; i < kPageSize; i++) { ASSERT_EQ(v[i], c) << "at offset " << i; } } // Equivalent to ExpectAllMappingBytes but async-signal-safe and with less // helpful failure messages. void CheckAllMappingBytes(Mapping const& m, char c) { auto const v = m.view(); for (size_t i = 0; i < kPageSize; i++) { TEST_CHECK_MSG(v[i] == c, "mapping contains wrong value"); } } TEST(MadviseDontneedTest, ZerosPrivateAnonPage) { auto m = ASSERT_NO_ERRNO_AND_VALUE( MmapAnon(kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE)); ExpectAllMappingBytes(m, 0); memset(m.ptr(), 1, m.len()); ExpectAllMappingBytes(m, 1); ASSERT_THAT(madvise(m.ptr(), m.len(), MADV_DONTNEED), SyscallSucceeds()); ExpectAllMappingBytes(m, 0); } TEST(MadviseDontneedTest, ZerosCOWAnonPageInCallerOnly) { auto m = ASSERT_NO_ERRNO_AND_VALUE( MmapAnon(kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE)); ExpectAllMappingBytes(m, 0); memset(m.ptr(), 2, m.len()); ExpectAllMappingBytes(m, 2); // Do madvise in a child process. pid_t pid = fork(); CheckAllMappingBytes(m, 2); if (pid == 0) { TEST_PCHECK(madvise(m.ptr(), m.len(), MADV_DONTNEED) == 0); CheckAllMappingBytes(m, 0); _exit(0); } ASSERT_THAT(pid, SyscallSucceeds()); int status = 0; ASSERT_THAT(waitpid(-1, &status, 0), SyscallSucceedsWithValue(pid)); EXPECT_TRUE(WIFEXITED(status)); EXPECT_EQ(WEXITSTATUS(status), 0); // The child's madvise should not have affected the parent. ExpectAllMappingBytes(m, 2); } TEST(MadviseDontneedTest, DoesNotModifySharedAnonPage) { auto m = ASSERT_NO_ERRNO_AND_VALUE( MmapAnon(kPageSize, PROT_READ | PROT_WRITE, MAP_SHARED)); ExpectAllMappingBytes(m, 0); memset(m.ptr(), 3, m.len()); ExpectAllMappingBytes(m, 3); ASSERT_THAT(madvise(m.ptr(), m.len(), MADV_DONTNEED), SyscallSucceeds()); ExpectAllMappingBytes(m, 3); } TEST(MadviseDontneedTest, CleansPrivateFilePage) { TempPath f = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith( /* parent = */ GetAbsoluteTestTmpdir(), /* content = */ std::string(kPageSize, 4), TempPath::kDefaultFileMode)); FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(f.path(), O_RDWR)); Mapping m = ASSERT_NO_ERRNO_AND_VALUE(Mmap( nullptr, kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd.get(), 0)); ExpectAllMappingBytes(m, 4); memset(m.ptr(), 5, m.len()); ExpectAllMappingBytes(m, 5); ASSERT_THAT(madvise(m.ptr(), m.len(), MADV_DONTNEED), SyscallSucceeds()); ExpectAllMappingBytes(m, 4); } TEST(MadviseDontneedTest, DoesNotModifySharedFilePage) { TempPath f = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith( /* parent = */ GetAbsoluteTestTmpdir(), /* content = */ std::string(kPageSize, 6), TempPath::kDefaultFileMode)); FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(f.path(), O_RDWR)); Mapping m = ASSERT_NO_ERRNO_AND_VALUE(Mmap( nullptr, kPageSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd.get(), 0)); ExpectAllMappingBytes(m, 6); memset(m.ptr(), 7, m.len()); ExpectAllMappingBytes(m, 7); ASSERT_THAT(madvise(m.ptr(), m.len(), MADV_DONTNEED), SyscallSucceeds()); ExpectAllMappingBytes(m, 7); } TEST(MadviseDontneedTest, IgnoresPermissions) { auto m = ASSERT_NO_ERRNO_AND_VALUE(MmapAnon(kPageSize, PROT_NONE, MAP_PRIVATE)); EXPECT_THAT(madvise(m.ptr(), m.len(), MADV_DONTNEED), SyscallSucceeds()); } } // namespace } // namespace testing } // namespace gvisor
32.573427
78
0.711894
jmgao
f6af9e0f63fb0cd558edbadf9707a02274bb9a42
5,651
hpp
C++
set.hpp
user1095108/sg
44c9d3a5351add4bfa39f472e1478a75f0519325
[ "Unlicense" ]
1
2021-09-27T11:51:19.000Z
2021-09-27T11:51:19.000Z
set.hpp
user1095108/sg
44c9d3a5351add4bfa39f472e1478a75f0519325
[ "Unlicense" ]
null
null
null
set.hpp
user1095108/sg
44c9d3a5351add4bfa39f472e1478a75f0519325
[ "Unlicense" ]
null
null
null
#ifndef SG_SET_HPP # define SG_SET_HPP # pragma once #include "utils.hpp" #include "mapiterator.hpp" namespace sg { template <typename Key, class Compare = std::compare_three_way> class set { public: struct node; using key_type = Key; using value_type = Key; using difference_type = std::ptrdiff_t; using size_type = std::uintmax_t; using reference = value_type&; using const_reference = value_type const&; using const_iterator = mapiterator<node const>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; using iterator = mapiterator<node>; using reverse_iterator = std::reverse_iterator<iterator>; struct node { using value_type = set::value_type; static constinit inline Compare const cmp; node* l_{}, *r_{}; Key const kv_; explicit node(auto&& ...a) noexcept(noexcept(Key(std::forward<decltype(a)>(a)...))): kv_(std::forward<decltype(a)>(a)...) { } ~node() noexcept(std::is_nothrow_destructible_v<decltype(kv_)>) { delete l_; delete r_; } // auto&& key() const noexcept { return kv_; } // static auto emplace(auto& r, auto&& ...a) noexcept(noexcept(new node(key_type(std::forward<decltype(a)>(a)...)))) { bool s{}; // success node* q; key_type k(std::forward<decltype(a)>(a)...); auto const f([&](auto&& f, auto& n) noexcept(noexcept(new node(std::move(k)))) -> size_type { if (!n) { s = (n = q = new node(std::move(k))); return 1; } // size_type sl, sr; if (auto const c(cmp(k, n->key())); c < 0) { if (sl = f(f, n->l_); !sl) { return {}; } sr = detail::size(n->r_); } else if (c > 0) { if (sr = f(f, n->r_); !sr) { return {}; } sl = detail::size(n->l_); } else { q = n; return {}; } // auto const s(1 + sl + sr), S(2 * s); return (3 * sl > S) || (3 * sr > S) ? (n = n->rebuild(s), 0) : s; } ); f(f, r); return std::pair(q, s); } auto rebuild(size_type const sz) noexcept { auto const l(static_cast<node**>(SG_ALLOCA(sizeof(this) * sz))); { auto f([l(l)](auto&& f, auto const n) mutable noexcept -> void { if (n) { f(f, detail::left_node(n)); *l++ = n; f(f, detail::right_node(n)); } } ); f(f, this); } auto const f([l](auto&& f, size_type const a, decltype(a) b) noexcept -> node* { auto const i((a + b) / 2); auto const n(l[i]); switch (b - a) { case 0: n->l_ = n->r_ = {}; break; case 1: { auto const nb(n->r_ = l[b]); nb->l_ = nb->r_ = n->l_ = {}; break; } default: detail::assign(n->l_, n->r_)(f(f, a, i - 1), f(f, i + 1, b)); } return n; } ); // return f(f, {}, sz - 1); } }; private: using this_class = set; node* root_{}; public: set() = default; set(std::initializer_list<value_type> const l) noexcept(noexcept(*this = l)) requires(std::is_copy_constructible_v<value_type>) { *this = l; } set(set const& o) noexcept(noexcept(*this = o)) requires(std::is_copy_constructible_v<value_type>) { *this = o; } set(set&& o) noexcept(noexcept(*this = std::move(o))) { *this = std::move(o); } set(std::input_iterator auto const i, decltype(i) j) noexcept(noexcept(insert(i, j))) requires(std::is_constructible_v<Key, decltype(*i)>) { insert(i, j); } ~set() noexcept(noexcept(delete root_)) { delete root_; } # include "common.hpp" // auto size() const noexcept { return detail::size(root_); } // size_type count(auto const& k) const noexcept { return bool(detail::find(root_, k)); } // auto emplace(auto&& ...a) noexcept(noexcept(node::emplace(root_, std::forward<decltype(a)>(a)...))) { auto const [n, s](node::emplace(root_, std::forward<decltype(a)>(a)...)); return std::tuple(iterator(&root_, n), s); } // auto equal_range(auto const& k) noexcept { auto const [nl, g](detail::equal_range(root_, k)); return std::pair(iterator(&root_, nl), iterator(&root_, g)); } auto equal_range(auto const& k) const noexcept { auto const [nl, g](detail::equal_range(root_, k)); return std::pair(const_iterator(&root_, nl), const_iterator(&root_, g)); } // iterator erase(const_iterator const i) { return {&root_, detail::erase(root_, *i)}; } size_type erase(auto const& k) requires(!std::is_convertible_v<decltype(k), const_iterator>) { return bool(detail::erase(root_, k)); } // auto insert(value_type const& v) { auto const [n, s](node::emplace(root_, v)); return std::tuple(iterator(&root_, n), s); } auto insert(value_type&& v) { auto const [n, s](node::emplace(root_, std::move(v))); return std::tuple(iterator(&root_, n), s); } void insert(std::input_iterator auto const i, decltype(i) j) { std::for_each( i, j, [&](auto&& v){ emplace(std::forward<decltype(v)>(v)); } ); } }; } #endif // SG_SET_HPP
20.182143
77
0.511945
user1095108
f6afe39638f9658003b3f627d8227bbb01cd1dd5
6,826
hpp
C++
tests/include/testing_ellmv.hpp
DevilInChina/aocl-sparse
d3f6fadfb0406ce124daae0456e09321a3019baf
[ "MIT" ]
null
null
null
tests/include/testing_ellmv.hpp
DevilInChina/aocl-sparse
d3f6fadfb0406ce124daae0456e09321a3019baf
[ "MIT" ]
null
null
null
tests/include/testing_ellmv.hpp
DevilInChina/aocl-sparse
d3f6fadfb0406ce124daae0456e09321a3019baf
[ "MIT" ]
null
null
null
/* ************************************************************************ * Copyright (c) 2020 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * ************************************************************************ */ #pragma once #ifndef TESTING_ELLMV_HPP #define TESTING_ELLMV_HPP #include "aoclsparse.hpp" #include "flops.hpp" #include "gbyte.hpp" #include "aoclsparse_arguments.hpp" #include "aoclsparse_init.hpp" #include "aoclsparse_test.hpp" #include "aoclsparse_check.hpp" #include "utility.hpp" #include "aoclsparse_random.hpp" #include "aoclsparse_convert.hpp" template <typename T> void testing_ellmv(const Arguments& arg) { aoclsparse_int M = arg.M; aoclsparse_int N = arg.N; aoclsparse_int nnz = arg.nnz; aoclsparse_matrix_init mat = arg.matrix; aoclsparse_operation trans = arg.transA; aoclsparse_index_base base = arg.baseA; std::string filename = arg.filename; T h_alpha = static_cast<T>(arg.alpha); T h_beta = static_cast<T>(arg.beta); // Create matrix descriptor aoclsparse_local_mat_descr descr; // Set matrix index base CHECK_AOCLSPARSE_ERROR(aoclsparse_set_mat_index_base(descr, base)); // Allocate memory for matrix std::vector<aoclsparse_int> hcsr_row_ptr; std::vector<aoclsparse_int> hcsr_col_ind; std::vector<T> hcsr_val; std::vector<aoclsparse_int> hell_col_ind; std::vector<T> hell_val; aoclsparse_int ell_width; aoclsparse_seedrand(); // Sample matrix aoclsparse_init_csr_matrix(hcsr_row_ptr, hcsr_col_ind, hcsr_val, M, N, nnz, base, mat, filename.c_str(), false, false); // Allocate memory for vectors std::vector<T> hx(N); std::vector<T> hy(M); std::vector<T> hy_gold(M); // Initialize data aoclsparse_init<T>(hx, 1, N, 1); aoclsparse_init<T>(hy, 1, M, 1); hy_gold = hy; // Convert CSR matrix to ELL csr_to_ell( M, nnz, hcsr_row_ptr, hcsr_col_ind, hcsr_val, hell_col_ind, hell_val, ell_width, base, base); if(arg.unit_check) { CHECK_AOCLSPARSE_ERROR(aoclsparse_ellmv(trans, &h_alpha, M, N, nnz, hell_val.data(), hell_col_ind.data(), ell_width, descr, hx.data(), &h_beta, hy.data())); // Reference SPMV CSR implementation for(int i = 0; i < M; i++) { T result = 0.0; for(int j = hcsr_row_ptr[i] - base; j < hcsr_row_ptr[i+1] - base; j++) { result += h_alpha * hcsr_val[j] * hx[hcsr_col_ind[j] - base]; } hy_gold[i] = (h_beta * hy_gold[i]) + result; } near_check_general<T>(1, M, 1, hy_gold.data(), hy.data()); } int number_hot_calls = arg.iters; double cpu_time_used = 1e9; // Performance run for(int iter = 0; iter < number_hot_calls; ++iter) { double cpu_time_start = get_time_us(); CHECK_AOCLSPARSE_ERROR(aoclsparse_ellmv(trans, &h_alpha, M, N, nnz, hell_val.data(), hell_col_ind.data(), ell_width, descr, hx.data(), &h_beta, hy.data())); double cpu_time_stop = get_time_us(); cpu_time_used = std::min(cpu_time_used , (cpu_time_stop - cpu_time_start) ); } double cpu_gflops = spmv_gflop_count<T>(M, nnz, h_beta != static_cast<T>(0)) / cpu_time_used * 1e6; double cpu_gbyte = ellmv_gbyte_count<T>(M, N, nnz, h_beta != static_cast<T>(0)) / cpu_time_used * 1e6; std::cout.precision(2); std::cout.setf(std::ios::fixed); std::cout.setf(std::ios::left); std::cout << std::setw(12) << "M" << std::setw(12) << "N" << std::setw(12) << "nnz" << std::setw(12) << "alpha" << std::setw(12) << "beta" << std::setw(12) << "GFlop/s" << std::setw(12) << "GB/s" << std::setw(12) << "msec" << std::setw(12) << "iter" << std::setw(12) << "verified" << std::endl; std::cout << std::setw(12) << M << std::setw(12) << N << std::setw(12) << nnz << std::setw(12) << h_alpha << std::setw(12) << h_beta << std::setw(12) << cpu_gflops << std::setw(12) << cpu_gbyte << std::setw(12) << cpu_time_used / 1e3 << std::setw(12) << number_hot_calls << std::setw(12) << (arg.unit_check ? "yes" : "no") << std::endl; } #endif // TESTING_ELLMV_HPP
40.152941
105
0.490331
DevilInChina
f6b0ff8822edee3ba67df0f9bab88b4f38c87e8e
334
cpp
C++
All Algorithms/Kadane's Algorithm/Kadane'sAlgorithm.cpp
ravimishra21/free-programming-books
e47f9eaa9a51723a097442673d86f1914768d581
[ "CC-BY-4.0" ]
null
null
null
All Algorithms/Kadane's Algorithm/Kadane'sAlgorithm.cpp
ravimishra21/free-programming-books
e47f9eaa9a51723a097442673d86f1914768d581
[ "CC-BY-4.0" ]
null
null
null
All Algorithms/Kadane's Algorithm/Kadane'sAlgorithm.cpp
ravimishra21/free-programming-books
e47f9eaa9a51723a097442673d86f1914768d581
[ "CC-BY-4.0" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() { long long int n,i; cin>>n; long long int arr[n]; for(int i=0;i<n;i++) cin>>arr[i]; long long int cs=arr[0],ms=arr[0]; for(i=1;i<n;i++) { cs=max(cs+arr[i],arr[i]); ms=max(ms,cs); } cout<< ms <<endl; return 0; }
13.916667
38
0.48503
ravimishra21
f6b1b1e49799d699d070188407d86949d4f4cee5
298
cpp
C++
doc/examples/begin.cpp
Hexlord/json
66869458b5227170e052d01aa65b47ee8350b666
[ "MIT" ]
23
2016-01-20T07:50:24.000Z
2021-09-08T05:08:19.000Z
json-master/doc/examples/begin.cpp
bobismijnnaam/bobetex
9960eafd31c73b4070b236d5dfafd5734492aaf5
[ "MIT" ]
18
2016-06-01T11:56:54.000Z
2016-06-06T10:58:53.000Z
json-master/doc/examples/begin.cpp
bobismijnnaam/bobetex
9960eafd31c73b4070b236d5dfafd5734492aaf5
[ "MIT" ]
19
2016-01-24T13:05:24.000Z
2021-06-25T01:36:47.000Z
#include <json.hpp> using namespace nlohmann; int main() { // create an array value json array = {1, 2, 3, 4, 5}; // get am iterator to the first element json::iterator it = array.begin(); // serialize the element that the iterator points to std::cout << *it << '\n'; }
18.625
56
0.607383
Hexlord
f6b5fd3a6465dda4620f207e14ca84cb2974ba62
449
cpp
C++
BAC/exercises/ch8/UVa10340.cpp
Anyrainel/aoapc-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
3
2017-08-15T06:00:01.000Z
2018-12-10T09:05:53.000Z
BAC/exercises/ch8/UVa10340.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
null
null
null
BAC/exercises/ch8/UVa10340.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
2
2017-09-16T18:46:27.000Z
2018-05-22T05:42:03.000Z
// UVa10340 All in All // Rujia Liu // 题意:输入两个字符串S和T,判断S是否为T的(不一定连续的)子串 #include<iostream> #include<string> using namespace std; int main() { string s, t; while(cin >> s >> t) { int n = s.length(), m = t.length(); bool ok = true; int i, j; for(i = j = 0; i < n; i++, j++) { while(j < m && t[j] != s[i]) j++; if(j == m) { ok = false; break; } } if(ok) cout << "Yes\n"; else cout << "No\n"; } return 0; }
19.521739
48
0.498886
Anyrainel
f6b86e26f21ab2e25e3351ce99200d1b1a963a37
505
cpp
C++
src/serialize19.lib/serialize19/serialize.std_tuple.test.cpp
Fettpet/co-cpp19
928a835c4f66032aa88ce01df7899da86d37df22
[ "MIT" ]
8
2020-05-31T16:13:13.000Z
2022-01-12T08:52:42.000Z
src/serialize19.lib/serialize19/serialize.std_tuple.test.cpp
Fettpet/co-cpp19
928a835c4f66032aa88ce01df7899da86d37df22
[ "MIT" ]
null
null
null
src/serialize19.lib/serialize19/serialize.std_tuple.test.cpp
Fettpet/co-cpp19
928a835c4f66032aa88ce01df7899da86d37df22
[ "MIT" ]
2
2020-07-21T10:58:28.000Z
2021-07-26T06:52:05.000Z
#include "ReadArchive.h" #include "dynamicWrite.h" #include "serialize.std_string.h" #include "serialize.std_tuple.h" #include <gtest/gtest.h> using namespace serialize19; TEST(serialize, std_tuple) { using T = std::tuple<int, float, std::string>; auto input = T{23, 3.14f, std::string("glurbz")}; auto buffer = dynamicWrite(input); auto reader = ReadArchive{buffer.slice()}; auto output = T{}; serialize(reader, output); EXPECT_EQ(output, input); }
22.954545
54
0.653465
Fettpet
f6c05c96eb644ee7bad5df3a536c766ab5689011
1,914
cpp
C++
ui-qt/ToolLib/Measure/L2LDistance/FWL2LDistanceLabel.cpp
qianyongjun123/FPGA-Industrial-Smart-Camera
54b3e2c2661cf7f6774a7fb4d6ae637fa73cba32
[ "MIT" ]
1
2017-12-28T08:08:02.000Z
2017-12-28T08:08:02.000Z
ui-qt/ToolLib/Measure/L2LDistance/FWL2LDistanceLabel.cpp
qianyongjun123/FPGA-Industrial-Smart-Camera
54b3e2c2661cf7f6774a7fb4d6ae637fa73cba32
[ "MIT" ]
null
null
null
ui-qt/ToolLib/Measure/L2LDistance/FWL2LDistanceLabel.cpp
qianyongjun123/FPGA-Industrial-Smart-Camera
54b3e2c2661cf7f6774a7fb4d6ae637fa73cba32
[ "MIT" ]
3
2017-12-28T08:08:05.000Z
2021-11-12T07:59:13.000Z
#include "FWL2LDistanceLabel.h" #include "BasicDefine.h" FWL2LDistanceLabel::FWL2LDistanceLabel(QWidget *parent) : QLabel(parent) { i_learn_result = 0; m_Line1 = QLine(0,0,0,0); m_Line2 = QLine(0,0,0,0); m_samplint_line = QLine(0,0,0,0); m_pen_color = NULL; } /** * @brief FWL2LDistanceLabel::SetLine1 * @param line * @author dgq * @note 设置直线一的值并更新OSD显示 */ void FWL2LDistanceLabel::SetLine1(QLine line) { m_Line1 = line; update(); } /** * @brief FWL2LDistanceLabel::SetLine2 * @param line * @author dgq * @note 设置直线一的值并更新OSD显示 */ void FWL2LDistanceLabel::SetLine2(QLine line) { m_Line2 = line; update(); } /** * @brief FWL2LDistanceLabel::SetLineSamp * @param line * @author dgq * @note 设置取样成功后的直线的值并更新OSD显示 */ void FWL2LDistanceLabel::SetLineSamp(QLine line) { i_learn_result = 1; m_samplint_line = line; update(); } /** * @brief FWL2LDistanceLabel::paintEvent * @param e * @author dgq * @note OSD显示 */ void FWL2LDistanceLabel::paintEvent(QPaintEvent *e) { QLabel::paintEvent(e); QPainter painter(this); QPen pen; PEN_COLOR * pencolor = (PEN_COLOR*)m_pen_color; if(pencolor !=NULL) { pen.setColor(pencolor->m_vt_color[pencolor->task_osd.task_osd_edit_color]); pen.setWidth(pencolor->task_osd.task_osd_edit_width); painter.setPen(pen); } painter.drawLine(m_Line1); painter.drawLine(m_Line2); if(i_learn_result)//取样成功后需要画的osd { if(pencolor !=NULL) { pen.setColor(pencolor->m_vt_color[pencolor->task_osd.task_osd_Calc_color]); pen.setWidth(pencolor->task_osd.task_osd_Calc__width); pen.setStyle(Qt::DashLine); painter.setPen(pen); } painter.drawLine(m_samplint_line); } i_learn_result = 0; } void FWL2LDistanceLabel::SetPenColor(void *pen_color) { this->m_pen_color = pen_color; }
21.505618
87
0.662487
qianyongjun123
f6c294015ddda1b69d9b51f929f51a93f901ac3e
977
cpp
C++
codeforces/C - Holidays/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/C - Holidays/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/C - Holidays/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Feb/15/2019 00:45 * solution_verdict: Accepted language: GNU C++14 * run_time: 62 ms memory_used: 3900 KB * problem: https://codeforces.com/contest/44/problem/C ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e6; int cnt[N+2]; int main() { ios_base::sync_with_stdio(0);cin.tie(0); int n,m;cin>>n>>m; while(m--) { int lt,rt;cin>>lt>>rt; for(int i=lt;i<=rt;i++) cnt[i]++; } for(int i=1;i<=n;i++) { if(cnt[i]!=1) { cout<<i<<" "<<cnt[i]<<endl,exit(0); } } cout<<"OK"<<endl; return 0; }
31.516129
111
0.360287
kzvd4729
f6c37d0f48494b76d5bc71ef0b67de8f52d9abd8
1,047
hpp
C++
AqooleEngine/src/main/cpp/boost/boost/qvm/lite.hpp
kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine-
72c8f34b6b6d507319069e681ff8c5008337b7c6
[ "Apache-2.0", "MIT" ]
null
null
null
AqooleEngine/src/main/cpp/boost/boost/qvm/lite.hpp
kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine-
72c8f34b6b6d507319069e681ff8c5008337b7c6
[ "Apache-2.0", "MIT" ]
null
null
null
AqooleEngine/src/main/cpp/boost/boost/qvm/lite.hpp
kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine-
72c8f34b6b6d507319069e681ff8c5008337b7c6
[ "Apache-2.0", "MIT" ]
null
null
null
// Copyright 2008-2022 Emil Dotchevski and Reverge Studios, Inc. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/qvm/error.hpp> #include <boost/qvm/mat_operations.hpp> #include <boost/qvm/mat_access.hpp> #include <boost/qvm/mat_traits_defaults.hpp> #include <boost/qvm/mat_traits_array.hpp> #include <boost/qvm/mat.hpp> #include <boost/qvm/math.hpp> #include <boost/qvm/quat_operations.hpp> #include <boost/qvm/quat_access.hpp> #include <boost/qvm/quat_traits_defaults.hpp> #include <boost/qvm/quat_traits.hpp> #include <boost/qvm/quat.hpp> #include <boost/qvm/quat_vec_operations.hpp> #include <boost/qvm/vec_operations.hpp> #include <boost/qvm/vec_access.hpp> #include <boost/qvm/vec_traits_defaults.hpp> #include <boost/qvm/vec_traits_array.hpp> #include <boost/qvm/vec.hpp> #include <boost/qvm/vec_mat_operations.hpp> #include <boost/qvm/vec_register.hpp> #include <boost/qvm/map.hpp> #include <boost/qvm/to_string.hpp>
37.392857
79
0.78319
kodai731
f6c3f03820f5d7e04fc9e16bd317002a7c5385e2
592
cpp
C++
CodeChef/LongChallenge/FebLongChallenge2018/feb_long_2018_chefchr.cpp
ysumit99/Compi-Coding
d0e96c4f024328b0bfb799fab927919dae367f7a
[ "MIT" ]
1
2019-04-19T13:06:33.000Z
2019-04-19T13:06:33.000Z
CodeChef/LongChallenge/FebLongChallenge2018/feb_long_2018_chefchr.cpp
ysumit99/Compi-Coding
d0e96c4f024328b0bfb799fab927919dae367f7a
[ "MIT" ]
null
null
null
CodeChef/LongChallenge/FebLongChallenge2018/feb_long_2018_chefchr.cpp
ysumit99/Compi-Coding
d0e96c4f024328b0bfb799fab927919dae367f7a
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main(int argc, char const *argv[]) { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin>>t; while(t--) { string str,sub_str; int count_chef = 0; cin>>str; if(str.length() < 4) { cout<<"normal"<<"\n"; continue;; } for (int i = 0; i < str.length(); ++i) { sub_str = str.substr (i,4); sort(sub_str.begin(),sub_str.end()); if(sub_str == "cefh") count_chef++; } if(count_chef == 0) cout<<"normal"<<"\n"; else cout<<"lovely "<<count_chef<<"\n"; } return 0; }
12.333333
40
0.54223
ysumit99
f6c7cf2d5a6a4bcaaf356762cb5494b72ae0ae8e
2,442
cpp
C++
TritonCore/src/Triton2/Core/Extension/Text.cpp
nfwGytautas/Triton
aa4e586b1170a9bc5f63b4f15920b20e1d05e8f1
[ "Apache-2.0" ]
2
2019-10-17T15:47:54.000Z
2019-10-17T15:47:56.000Z
TritonCore/src/Triton2/Core/Extension/Text.cpp
nfwGytautas/Triton
aa4e586b1170a9bc5f63b4f15920b20e1d05e8f1
[ "Apache-2.0" ]
null
null
null
TritonCore/src/Triton2/Core/Extension/Text.cpp
nfwGytautas/Triton
aa4e586b1170a9bc5f63b4f15920b20e1d05e8f1
[ "Apache-2.0" ]
1
2019-10-07T08:19:28.000Z
2019-10-07T08:19:28.000Z
#include "TRpch.h" #include "Text.h" #include "Triton2/Limits.h" namespace Triton { namespace Extension { IO::Mesh buildVertexArray(reference<FontAsset> font, const std::string& text, float x, float y) { // Modifier for the final vertex vector length unsigned int stride = Triton::Limits::VAO_2D_TEXT; std::vector<float> result(text.length() * 6 * stride); std::vector<unsigned int> indices(result.size()); auto charMetrics = font->metrics(); auto fontWidth = font->width(); auto fontHeight = font->height(); auto charHeight = 32; // Initialize the index to the vertex array. int index = 0; float scale = 1; std::string::const_iterator c; for (c = text.begin(); c != text.end(); c++) { IO::FontData::CharMetrics metrics = charMetrics[*c]; float xSize = metrics.End.x - metrics.Start.x; float ySize = metrics.End.y - metrics.Start.y; float xpos = x + metrics.Offset.x * scale; float ypos = y - (ySize - metrics.Offset.y) * scale; float w = xSize * scale; float h = ySize * scale; // First triangle result.push_back(xpos); result.push_back(ypos + h); result.push_back(1.0f); result.push_back(metrics.Start.x / fontWidth); result.push_back(metrics.Start.y / fontHeight); result.push_back(xpos + w); result.push_back(ypos); result.push_back(1.0f); result.push_back(metrics.End.x / fontWidth); result.push_back(metrics.End.y / fontHeight); result.push_back(xpos); result.push_back(ypos); result.push_back(1.0f); result.push_back(metrics.Start.x / fontWidth); result.push_back(metrics.End.y / fontHeight); // Second triangle in quad. result.push_back(xpos); result.push_back(ypos + h); result.push_back(1.0f); result.push_back(metrics.Start.x / fontWidth); result.push_back(metrics.Start.y / fontHeight); result.push_back(xpos + w); result.push_back(ypos + h); result.push_back(1.0f); result.push_back(metrics.End.x / fontWidth); result.push_back(metrics.Start.y / fontHeight); result.push_back(xpos + w); result.push_back(ypos); result.push_back(1.0f); result.push_back(metrics.End.x / fontWidth); result.push_back(metrics.End.y / fontHeight); x += metrics.Advance * scale; } for (int i = 0; i < indices.size(); i++) { indices[i] = i; } return IO::Mesh{1, stride, result, indices}; } } }
23.941176
97
0.651106
nfwGytautas
f6c84d0a653e2ff6d51e89a938478889fe4916ea
1,457
cpp
C++
codeforces/B - Steps/Wrong answer on test 3.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/B - Steps/Wrong answer on test 3.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/B - Steps/Wrong answer on test 3.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: May/07/2017 12:17 * solution_verdict: Wrong answer on test 3 language: GNU C++14 * run_time: 30 ms memory_used: 0 KB * problem: https://codeforces.com/contest/152/problem/B ****************************************************************************************/ #include<bits/stdc++.h> using namespace std; #define inf 99999999999999; int main() { long long int n,m,k,s1,s2,x,y,cnt=0,d1,d2,m1,m2,m3,i; cin>>n>>m; cin>>s1>>s2; cin>>k; for(i=1; i<=k; i++) { cin>>x>>y; if(x==0) { d1=inf; m1=inf; } else if(x>0) { d1=n-s1; m1=d1/x; } else { d1=s1-1; m1=d1/abs(x); } if(y==0) { d2=inf; m2=inf; } else if(x>0) { d2=m-s2; m2=d2/y; } else { d2=s2-1; m2=d2/abs(y); } m3=min(m1,m2); cnt=cnt+m3; s1=s1+(x*m3); s2=s2+(y*m3); } cout<<cnt<<endl; return 0; }
26.017857
111
0.291695
kzvd4729
f6ca39fbb207befce417aa7b2ff66961f668cf7b
1,155
cpp
C++
test/che/ss.cpp
shze/biosim
e9e6d97de0ccf8067e1db15980eb600389fff6ca
[ "MIT" ]
null
null
null
test/che/ss.cpp
shze/biosim
e9e6d97de0ccf8067e1db15980eb600389fff6ca
[ "MIT" ]
null
null
null
test/che/ss.cpp
shze/biosim
e9e6d97de0ccf8067e1db15980eb600389fff6ca
[ "MIT" ]
null
null
null
#include <boost/test/unit_test.hpp> #include <boost/concept_check.hpp> #include "che/ss.h" // header to test using namespace biosim; BOOST_AUTO_TEST_SUITE(suite_ss) BOOST_AUTO_TEST_CASE(ss_ctor) { che::ss s; BOOST_CHECK(s.defined() == false); BOOST_CHECK(s.get_length() == 0); BOOST_CHECK(s.get_sequence().empty()); BOOST_CHECK(s.get_sses().empty()); che::sequence<che::cchb_dssp> v; s = che::ss(v); BOOST_CHECK(s.defined()); BOOST_CHECK(s.get_sequence().empty()); BOOST_CHECK(s.get_sses().empty()); v.emplace_back('H'); s = che::ss(v); BOOST_CHECK(s.defined()); BOOST_CHECK(s.get_sequence().size() == 1); BOOST_CHECK(s.get_sses().size() == 1); std::set<che::cchb_dssp_interval> pool; s = che::ss(pool); BOOST_CHECK(s.defined()); BOOST_CHECK(s.get_sequence().empty()); BOOST_CHECK(s.get_sses().empty()); pool.insert(che::cchb_dssp_interval(5, 10, che::cchb_dssp('H'))); s = che::ss(pool); BOOST_CHECK(s.defined()); BOOST_CHECK(s.get_sequence().size() == 11); // sse position is 0-based, sequence is 0-4 C, 5-10 H, length is 11 BOOST_CHECK(s.get_sses().size() == 1); } BOOST_AUTO_TEST_SUITE_END()
26.860465
113
0.673593
shze
f6ca420e99479cf72f5207334b1baa865fbae9c5
712
cpp
C++
DFNs/StereoRectification/StereoRectificationInterface.cpp
H2020-InFuse/cdff
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
[ "BSD-2-Clause" ]
7
2019-02-26T15:09:50.000Z
2021-09-30T07:39:01.000Z
DFNs/StereoRectification/StereoRectificationInterface.cpp
H2020-InFuse/cdff
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
[ "BSD-2-Clause" ]
null
null
null
DFNs/StereoRectification/StereoRectificationInterface.cpp
H2020-InFuse/cdff
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
[ "BSD-2-Clause" ]
1
2020-12-06T12:09:05.000Z
2020-12-06T12:09:05.000Z
/** * @addtogroup DFNs * @{ */ #include "StereoRectificationInterface.hpp" namespace CDFF { namespace DFN { StereoRectificationInterface::StereoRectificationInterface() : inOriginalStereoPair(), outRectifiedStereoPair() { asn1SccFramePair_Initialize(& inOriginalStereoPair); asn1SccFramePair_Initialize(& outRectifiedStereoPair); } StereoRectificationInterface::~StereoRectificationInterface() { } void StereoRectificationInterface::originalStereoPairInput(const asn1SccFramePair& data) { inOriginalStereoPair = data; } const asn1SccFramePair& StereoRectificationInterface::rectifiedStereoPairOutput() const { return outRectifiedStereoPair; } } } /** @} */
18.25641
88
0.755618
H2020-InFuse
f6cade48f2bbf011f12e2d7e48286139b3c9a82f
2,811
cpp
C++
src/jsonserializer/typeconverters/qjsonchronodurationconverter.cpp
cmguo/QtJsonSerializer
ae7f4df2cd38177b85cfe4c3a677180611bd904d
[ "BSD-3-Clause" ]
1
2019-07-01T15:57:51.000Z
2019-07-01T15:57:51.000Z
src/jsonserializer/typeconverters/qjsonchronodurationconverter.cpp
cmguo/QtJsonSerializer
ae7f4df2cd38177b85cfe4c3a677180611bd904d
[ "BSD-3-Clause" ]
2
2019-10-24T12:30:44.000Z
2020-07-08T16:07:48.000Z
src/jsonserializer/typeconverters/qjsonchronodurationconverter.cpp
cmguo/QtJsonSerializer
ae7f4df2cd38177b85cfe4c3a677180611bd904d
[ "BSD-3-Clause" ]
3
2019-09-17T15:07:07.000Z
2020-07-08T13:54:04.000Z
#include "qjsonchronodurationconverter_p.h" #include "qjsonserializerexception.h" #include <chrono> using namespace std::chrono; Q_DECLARE_METATYPE(std::chrono::nanoseconds) Q_DECLARE_METATYPE(std::chrono::microseconds) Q_DECLARE_METATYPE(std::chrono::milliseconds) Q_DECLARE_METATYPE(std::chrono::seconds) Q_DECLARE_METATYPE(std::chrono::minutes) Q_DECLARE_METATYPE(std::chrono::hours) bool QJsonChronoDurationConverter::canConvert(int metaTypeId) const { return metaTypeId == qMetaTypeId<nanoseconds>() || metaTypeId == qMetaTypeId<microseconds>() || metaTypeId == qMetaTypeId<milliseconds>() || metaTypeId == qMetaTypeId<seconds>() || metaTypeId == qMetaTypeId<minutes>() || metaTypeId == qMetaTypeId<hours>(); } QList<QJsonValue::Type> QJsonChronoDurationConverter::jsonTypes() const { return {QJsonValue::Double}; } QJsonValue QJsonChronoDurationConverter::serialize(int propertyType, const QVariant &value, const QJsonTypeConverter::SerializationHelper *) const { if (propertyType == qMetaTypeId<nanoseconds>()) return static_cast<qint64>(value.value<nanoseconds>().count()); else if (propertyType == qMetaTypeId<microseconds>()) return static_cast<qint64>(value.value<microseconds>().count()); else if (propertyType == qMetaTypeId<milliseconds>()) return static_cast<qint64>(value.value<milliseconds>().count()); else if (propertyType == qMetaTypeId<seconds>()) return static_cast<qint64>(value.value<seconds>().count()); else if (propertyType == qMetaTypeId<minutes>()) return static_cast<qint64>(value.value<minutes>().count()); else if (propertyType == qMetaTypeId<hours>()) return static_cast<qint64>(value.value<hours>().count()); else throw QJsonSerializationException{"Invalid type id"}; } QVariant QJsonChronoDurationConverter::deserialize(int propertyType, const QJsonValue &value, QObject *, const QJsonTypeConverter::SerializationHelper *) const { if (propertyType == qMetaTypeId<nanoseconds>()) return QVariant::fromValue(nanoseconds{static_cast<nanoseconds::rep>(value.toDouble())}); else if (propertyType == qMetaTypeId<microseconds>()) return QVariant::fromValue(microseconds{static_cast<microseconds::rep>(value.toDouble())}); else if (propertyType == qMetaTypeId<milliseconds>()) return QVariant::fromValue(milliseconds{static_cast<milliseconds::rep>(value.toDouble())}); else if (propertyType == qMetaTypeId<seconds>()) return QVariant::fromValue(seconds{static_cast<seconds::rep>(value.toDouble())}); else if (propertyType == qMetaTypeId<minutes>()) return QVariant::fromValue(minutes{static_cast<minutes::rep>(value.toDouble())}); else if (propertyType == qMetaTypeId<hours>()) return QVariant::fromValue(hours{static_cast<hours::rep>(value.toDouble())}); else throw QJsonDeserializationException{"Invalid type id"}; }
43.921875
159
0.765564
cmguo
f6cb34cedc43ea44cf965ac5d462697f86374af2
4,348
hpp
C++
src/cpu/gemm/gemm_pack.hpp
JackAKirk/oneDNN
432c3f0c1c265a0fa96aa46c256d150ea670eb5a
[ "Apache-2.0" ]
1,327
2018-01-25T21:23:47.000Z
2020-04-03T09:39:30.000Z
src/cpu/gemm/gemm_pack.hpp
JackAKirk/oneDNN
432c3f0c1c265a0fa96aa46c256d150ea670eb5a
[ "Apache-2.0" ]
583
2020-04-04T02:37:25.000Z
2022-03-31T00:12:03.000Z
src/cpu/gemm/gemm_pack.hpp
JackAKirk/oneDNN
432c3f0c1c265a0fa96aa46c256d150ea670eb5a
[ "Apache-2.0" ]
365
2018-01-29T16:12:36.000Z
2020-04-03T08:32:27.000Z
/******************************************************************************* * Copyright 2019-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. *******************************************************************************/ #ifndef CPU_GEMM_GEMM_PACK_HPP #define CPU_GEMM_GEMM_PACK_HPP #include "oneapi/dnnl/dnnl_config.h" #include "oneapi/dnnl/dnnl_types.h" #include "common/bfloat16.hpp" namespace dnnl { namespace impl { namespace cpu { bool pack_sgemm_supported(); bool pack_gemm_bf16bf16f32_supported(); dnnl_status_t DNNL_API sgemm_pack_get_size(const char *identifier, const char *transa, const char *transb, const dim_t *M, const dim_t *N, const dim_t *K, const dim_t *lda, const dim_t *ldb, size_t *size, bool *pack = nullptr); dnnl_status_t DNNL_API gemm_bf16bf16f32_pack_get_size(const char *identifier, const char *transa, const char *transb, const dim_t *M, const dim_t *N, const dim_t *K, const dim_t *lda, const dim_t *ldb, size_t *size, bool *pack = nullptr); dnnl_status_t DNNL_API gemm_s8u8s32_pack_get_size(const char *identifier, const char *transa, const char *transb, const dim_t *M, const dim_t *N, const dim_t *K, const dim_t *lda, const dim_t *ldb, size_t *size, bool *pack = nullptr); dnnl_status_t DNNL_API gemm_s8s8s32_pack_get_size(const char *identifier, const char *transa, const char *transb, const dim_t *M, const dim_t *N, const dim_t *K, const dim_t *lda, const dim_t *ldb, size_t *size, bool *pack = nullptr); dnnl_status_t DNNL_API sgemm_pack(const char *identifier, const char *transa, const char *transb, const dim_t *M, const dim_t *N, const dim_t *K, const dim_t *lda, const dim_t *ldb, const float *src, float *dst); dnnl_status_t DNNL_API gemm_bf16bf16f32_pack(const char *identifier, const char *transa, const char *transb, const dim_t *M, const dim_t *N, const dim_t *K, const dim_t *lda, const dim_t *ldb, const bfloat16_t *src, bfloat16_t *dst); dnnl_status_t DNNL_API gemm_s8u8s32_pack(const char *identifier, const char *transa, const char *transb, const dim_t *M, const dim_t *N, const dim_t *K, const dim_t *lda, const dim_t *ldb, const void *src, void *dst); dnnl_status_t DNNL_API gemm_s8s8s32_pack(const char *identifier, const char *transa, const char *transb, const dim_t *M, const dim_t *N, const dim_t *K, const dim_t *lda, const dim_t *ldb, const void *src, void *dst); dnnl_status_t DNNL_API sgemm_compute(const char *transa, const char *transb, const dim_t *M, const dim_t *N, const dim_t *K, const float *A, const dim_t *lda, const float *B, const dim_t *ldb, const float *beta, float *C, const dim_t *ldc); dnnl_status_t DNNL_API gemm_bf16bf16f32_compute(const char *transa, const char *transb, const dim_t *M, const dim_t *N, const dim_t *K, const bfloat16_t *A, const dim_t *lda, const bfloat16_t *B, const dim_t *ldb, const float *beta, float *C, const dim_t *ldc); dnnl_status_t DNNL_API gemm_s8u8s32_compute(const char *transa, const char *transb, const char *offsetc, const dim_t *M, const dim_t *N, const dim_t *K, const int8_t *A, const dim_t *lda, const uint8_t *B, const dim_t *ldb, const float *beta, int32_t *C, const dim_t *ldc, const int32_t *co); dnnl_status_t DNNL_API gemm_s8s8s32_compute(const char *transa, const char *transb, const char *offsetc, const dim_t *M, const dim_t *N, const dim_t *K, const int8_t *A, const dim_t *lda, const int8_t *B, const dim_t *ldb, const float *beta, int32_t *C, const dim_t *ldc, const int32_t *co); } // namespace cpu } // namespace impl } // namespace dnnl #endif // CPU_GEMM_GEMM_PACK_HPP
44.367347
80
0.678933
JackAKirk
f6cc5ae58a1f4457304d681f62627c6f33d32358
8,113
hpp
C++
include/GlobalNamespace/LevelSearchViewController_BeatmapLevelPackCollection.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/LevelSearchViewController_BeatmapLevelPackCollection.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/LevelSearchViewController_BeatmapLevelPackCollection.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: LevelSearchViewController #include "GlobalNamespace/LevelSearchViewController.hpp" // Including type: IAnnotatedBeatmapLevelCollection #include "GlobalNamespace/IAnnotatedBeatmapLevelCollection.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: IBeatmapLevelCollection class IBeatmapLevelCollection; } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: Sprite class Sprite; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Size: 0x18 #pragma pack(push, 1) // Autogenerated type: LevelSearchViewController/BeatmapLevelPackCollection // [TokenAttribute] Offset: FFFFFFFF class LevelSearchViewController::BeatmapLevelPackCollection : public ::Il2CppObject/*, public GlobalNamespace::IAnnotatedBeatmapLevelCollection*/ { public: // private IBeatmapLevelCollection <beatmapLevelCollection>k__BackingField // Size: 0x8 // Offset: 0x10 GlobalNamespace::IBeatmapLevelCollection* beatmapLevelCollection; // Field size check static_assert(sizeof(GlobalNamespace::IBeatmapLevelCollection*) == 0x8); // Creating value type constructor for type: BeatmapLevelPackCollection BeatmapLevelPackCollection(GlobalNamespace::IBeatmapLevelCollection* beatmapLevelCollection_ = {}) noexcept : beatmapLevelCollection{beatmapLevelCollection_} {} // Creating interface conversion operator: operator GlobalNamespace::IAnnotatedBeatmapLevelCollection operator GlobalNamespace::IAnnotatedBeatmapLevelCollection() noexcept { return *reinterpret_cast<GlobalNamespace::IAnnotatedBeatmapLevelCollection*>(this); } // Creating conversion operator: operator GlobalNamespace::IBeatmapLevelCollection* constexpr operator GlobalNamespace::IBeatmapLevelCollection*() const noexcept { return beatmapLevelCollection; } // Get instance field: private IBeatmapLevelCollection <beatmapLevelCollection>k__BackingField GlobalNamespace::IBeatmapLevelCollection* _get_$beatmapLevelCollection$k__BackingField(); // Set instance field: private IBeatmapLevelCollection <beatmapLevelCollection>k__BackingField void _set_$beatmapLevelCollection$k__BackingField(GlobalNamespace::IBeatmapLevelCollection* value); // public System.String get_collectionName() // Offset: 0x1FE2698 ::Il2CppString* get_collectionName(); // public UnityEngine.Sprite get_coverImage() // Offset: 0x1FE26A0 UnityEngine::Sprite* get_coverImage(); // public IBeatmapLevelCollection get_beatmapLevelCollection() // Offset: 0x1FE26A8 GlobalNamespace::IBeatmapLevelCollection* get_beatmapLevelCollection(); // private System.Void set_beatmapLevelCollection(IBeatmapLevelCollection value) // Offset: 0x1FE26B0 void set_beatmapLevelCollection(GlobalNamespace::IBeatmapLevelCollection* value); // public System.Void .ctor(IBeatmapLevelCollection beatmapLevelCollection) // Offset: 0x1FE2660 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static LevelSearchViewController::BeatmapLevelPackCollection* New_ctor(GlobalNamespace::IBeatmapLevelCollection* beatmapLevelCollection) { static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::LevelSearchViewController::BeatmapLevelPackCollection::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<LevelSearchViewController::BeatmapLevelPackCollection*, creationType>(beatmapLevelCollection))); } }; // LevelSearchViewController/BeatmapLevelPackCollection #pragma pack(pop) static check_size<sizeof(LevelSearchViewController::BeatmapLevelPackCollection), 16 + sizeof(GlobalNamespace::IBeatmapLevelCollection*)> __GlobalNamespace_LevelSearchViewController_BeatmapLevelPackCollectionSizeCheck; static_assert(sizeof(LevelSearchViewController::BeatmapLevelPackCollection) == 0x18); } DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::LevelSearchViewController::BeatmapLevelPackCollection*, "", "LevelSearchViewController/BeatmapLevelPackCollection"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::LevelSearchViewController::BeatmapLevelPackCollection::get_collectionName // Il2CppName: get_collectionName template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (GlobalNamespace::LevelSearchViewController::BeatmapLevelPackCollection::*)()>(&GlobalNamespace::LevelSearchViewController::BeatmapLevelPackCollection::get_collectionName)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LevelSearchViewController::BeatmapLevelPackCollection*), "get_collectionName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::LevelSearchViewController::BeatmapLevelPackCollection::get_coverImage // Il2CppName: get_coverImage template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::Sprite* (GlobalNamespace::LevelSearchViewController::BeatmapLevelPackCollection::*)()>(&GlobalNamespace::LevelSearchViewController::BeatmapLevelPackCollection::get_coverImage)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LevelSearchViewController::BeatmapLevelPackCollection*), "get_coverImage", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::LevelSearchViewController::BeatmapLevelPackCollection::get_beatmapLevelCollection // Il2CppName: get_beatmapLevelCollection template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::IBeatmapLevelCollection* (GlobalNamespace::LevelSearchViewController::BeatmapLevelPackCollection::*)()>(&GlobalNamespace::LevelSearchViewController::BeatmapLevelPackCollection::get_beatmapLevelCollection)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LevelSearchViewController::BeatmapLevelPackCollection*), "get_beatmapLevelCollection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::LevelSearchViewController::BeatmapLevelPackCollection::set_beatmapLevelCollection // Il2CppName: set_beatmapLevelCollection template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LevelSearchViewController::BeatmapLevelPackCollection::*)(GlobalNamespace::IBeatmapLevelCollection*)>(&GlobalNamespace::LevelSearchViewController::BeatmapLevelPackCollection::set_beatmapLevelCollection)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("", "IBeatmapLevelCollection")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LevelSearchViewController::BeatmapLevelPackCollection*), "set_beatmapLevelCollection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::LevelSearchViewController::BeatmapLevelPackCollection::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
67.608333
298
0.794651
marksteward
f6cdfd9deba1dd7d21b118ca2d4427fd90c9cd94
3,706
cpp
C++
test/tutorial_codeexamples/modelfittting.cpp
zhxinyu/cosan
ea93704782e6c66f6bcf65362c957d719e25b074
[ "MIT" ]
null
null
null
test/tutorial_codeexamples/modelfittting.cpp
zhxinyu/cosan
ea93704782e6c66f6bcf65362c957d719e25b074
[ "MIT" ]
null
null
null
test/tutorial_codeexamples/modelfittting.cpp
zhxinyu/cosan
ea93704782e6c66f6bcf65362c957d719e25b074
[ "MIT" ]
1
2021-04-13T05:56:38.000Z
2021-04-13T05:56:38.000Z
// // Created by Xinyu Zhang on 3/26/21. // #include <iostream> #include <cosan/data/CosanData.h> #include <cosan/base/CosanBO.h> #include <cosan/preprocessing/overunderflow.h> #include <cosan/preprocessing/missingvalues.h> #include <cosan/preprocessing/normalizer.h> #include <cosan/preprocessing/standardScaler.h> #include <cosan/preprocessing/encoder.h> #include <cosan/preprocessing/minmaxscaler.h> #include <cosan/preprocessing/polynomialfeatures.h> #include <cosan/preprocessing/principalcomponentanalysis.h> #include <cosan/preprocessing/customtransform.h> #include <cosan/model/CosanLinearRegression.h> #include <cosan/model/CosanRidgeRegression.h> #include <cosan/model/CosanPrincipalComponentRegression.h> #include <cosan/model/CosanPCRRidge.h> typedef double NumericType; int main() { Cosan::CosanRawData<NumericType> CRD("./example_data/toy2/X_.csv","./example_data/toy2/Y_.csv"); Cosan::OverUnderFlow ouf(CRD); Cosan::MissingValues MissV(CRD); Cosan::Normalizer NM(CRD,2); Cosan::StandardScaler SS(CRD); bool bias = true; Cosan::CosanLinearRegression CLR(CRD,bias);//The second argument indicates whether to consider intercept term. The default is true. //or // Cosan::CosanLinearRegression CLR(bias); // CLR.fit(CRD.GetInput(),CRD.GetTarget()); return 0; } // // Cosan::CosanLinearRegression CLR(true); // CLR.fit(CD.GetInput(),CD.GetTarget()); // std::cout<<CD.GetrowsX()<<" "<<CD.GetcolsX()<<" "<<std::endl; // for (auto each : CD.GetIdxpinfX()) {std::cout<<each[0]<<" "<<each[1]<<std::endl;} // for (auto each : CD.GetIdxminfX()) {std::cout<<each[0]<<" "<<each[1]<<std::endl;} // for (auto each : CD.GetIdxmissingX()) {std::cout<<each[0]<<" "<<each[1]<<std::endl;} // for (auto each : CD.GetcolCatX()) {std::cout<<each<<std::endl;} // for (auto each : CD.GetsvaluesX()) {std::cout<<each<<std::endl;} // for (const auto & [ key, value ] : CD.GetRawToNumIdx()){ // std::cout<<key<<":"<<value<<std::endl;} // for (const auto & [ key, value ] : CD.GetRawToCatIdx()){ // std::cout<<key<<":"<<value<<std::endl;} // Cosan::CosanRawData CD1("./example_data/toy2/X_2.csv"); // // Cosan::CosanLinearRegression CLR(true); // // CLR.fit(CD.GetInput(),CD.GetTarget()); // std::cout<<CD1.GetSummaryMessageX()<<std::endl; // // std::cout<<CD.GetrowsX()<<" "<<CD.GetcolsX()<<" "<<std::endl; // // for (auto each : CD.GetIdxpinfX()) {std::cout<<each[0]<<" "<<each[1]<<std::endl;} // // for (auto each : CD.GetIdxminfX()) {std::cout<<each[0]<<" "<<each[1]<<std::endl;} // // for (auto each : CD.GetIdxmissingX()) {std::cout<<each[0]<<" "<<each[1]<<std::endl;} // // for (auto each : CD.GetcolCatX()) {std::cout<<each<<std::endl;} // // for (auto each : CD.GetsvaluesX()) {std::cout<<each<<std::endl;} // for (const auto & [ key, value ] : CD1.GetRawToNumIdx()){ // std::cout<<key<<":"<<value<<std::endl;} // for (const auto & [ key, value ] : CD1.GetRawToCatIdx()){ // std::cout<<key<<":"<<value<<std::endl;} // std::cout<<CD.GetInput()<<std::endl; // double RegularizationTerm = 1; // Cosan::CosanRidgeRegression CRR(RegularizationTerm,true); // CRR.fit(CD.GetInput(),CD.GetTarget()); // std::cout<<CRR.GetBeta()<<std::endl; // save_csv("./example_data/toy/beta_c1.csv",CRR.GetBeta()); // m(0, 0) = 3; // m(1, 0) = 2.5; // m(0, 1) = -1; // m(1,1) = m(1,0)+m(0,1); // std::cout<<y.rows()<<y.cols()<<std::endl; // Eigen::MatrixXd beta = (X.transpose()*X).ldlt().solve(X.transpose()*y); // // m.transposeInPlace(); // cout<<m<<endl; // m.resize(1,4); // cout<<n<<endl;
40.282609
135
0.618457
zhxinyu
f6ce6cd0f4814cfea1b0ec889e96b0a9db85037b
20,682
cc
C++
wrspice/devlib/bsim3.2.4/b3acld.cc
wrcad/xictools
f46ba6d42801426739cc8b2940a809b74f1641e2
[ "Apache-2.0" ]
73
2017-10-26T12:40:24.000Z
2022-03-02T16:59:43.000Z
wrspice/devlib/bsim3.2.4/b3acld.cc
chris-ayala/xictools
4ea72c118679caed700dab3d49a8d36445acaec3
[ "Apache-2.0" ]
12
2017-11-01T10:18:22.000Z
2022-03-20T19:35:36.000Z
wrspice/devlib/bsim3.2.4/b3acld.cc
chris-ayala/xictools
4ea72c118679caed700dab3d49a8d36445acaec3
[ "Apache-2.0" ]
34
2017-10-06T17:04:21.000Z
2022-02-18T16:22:03.000Z
/*========================================================================* * * * Distributed by Whiteley Research Inc., Sunnyvale, California, USA * * http://wrcad.com * * Copyright (C) 2017 Whiteley Research Inc., all rights reserved. * * Author: Stephen R. Whiteley, except as indicated. * * * * As fully as possible recognizing licensing terms and conditions * * imposed by earlier work from which this work was derived, if any, * * this work is released under the Apache License, Version 2.0 (the * * "License"). You may not use this file except in compliance with * * the License, and compliance with inherited licenses which are * * specified in a sub-header below this one if applicable. A copy * * of the License is provided with this distribution, or you may * * obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * See the License for the specific language governing permissions * * and limitations under the License. * * * * 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 NON- * * INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED * * OR STEPHEN R. WHITELEY 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. * * * *========================================================================* * XicTools Integrated Circuit Design System * * * * WRspice Circuit Simulation and Analysis Tool: Device Library * * * *========================================================================* $Id:$ *========================================================================*/ /********** * Copyright 2001 Regents of the University of California. All rights reserved. * File: b3acld.c of BSIM3v3.2.4 * Author: 1995 Min-Chie Jeng and Mansun Chan * Author: 1997-1999 Weidong Liu. * Author: 2001 Xuemei Xi **********/ #include "b3defs.h" #include "gencurrent.h" #define BSIM3nextModel next() #define BSIM3nextInstance next() #define BSIM3instances inst() int BSIM3dev::acLoad(sGENmodel *genmod, sCKT *ckt) { sBSIM3model *model = static_cast<sBSIM3model*>(genmod); sBSIM3instance *here; double xcggb, xcgdb, xcgsb, xcbgb, xcbdb, xcbsb, xcddb, xcssb, xcdgb; double gdpr, gspr, gds, gbd, gbs, capbd, capbs, xcsgb, xcdsb, xcsdb; double cggb, cgdb, cgsb, cbgb, cbdb, cbsb, cddb, cdgb, cdsb, omega; double GSoverlapCap, GDoverlapCap, GBoverlapCap, FwdSum, RevSum, Gm, Gmbs; double dxpart, sxpart, xgtg, xgtd, xgts, xgtb, xcqgb, xcqdb, xcqsb, xcqbb; double gbspsp, gbbdp, gbbsp, gbspg, gbspb; double gbspdp, gbdpdp, gbdpg, gbdpb, gbdpsp; double ddxpart_dVd, ddxpart_dVg, ddxpart_dVb, ddxpart_dVs; double dsxpart_dVd, dsxpart_dVg, dsxpart_dVb, dsxpart_dVs; double T1, CoxWL, qcheq, Cdg, Cdd, Cds, /*Cdb,*/ Csg, Csd, Css /*, Csb*/; double ScalingFactor = 1.0e-9; omega = ckt->CKTomega; for (; model != NULL; model = model->BSIM3nextModel) { for (here = model->BSIM3instances; here!= NULL; here = here->BSIM3nextInstance) { if (here->BSIM3mode >= 0) { Gm = here->BSIM3gm; Gmbs = here->BSIM3gmbs; FwdSum = Gm + Gmbs; RevSum = 0.0; gbbdp = -here->BSIM3gbds; gbbsp = here->BSIM3gbds + here->BSIM3gbgs + here->BSIM3gbbs; gbdpg = here->BSIM3gbgs; gbdpb = here->BSIM3gbbs; gbdpdp = here->BSIM3gbds; gbdpsp = -(gbdpg + gbdpb + gbdpdp); gbspdp = 0.0; gbspg = 0.0; gbspb = 0.0; gbspsp = 0.0; if (here->BSIM3nqsMod == 0) { cggb = here->BSIM3cggb; cgsb = here->BSIM3cgsb; cgdb = here->BSIM3cgdb; cbgb = here->BSIM3cbgb; cbsb = here->BSIM3cbsb; cbdb = here->BSIM3cbdb; cdgb = here->BSIM3cdgb; cdsb = here->BSIM3cdsb; cddb = here->BSIM3cddb; xgtg = xgtd = xgts = xgtb = 0.0; sxpart = 0.6; dxpart = 0.4; ddxpart_dVd = ddxpart_dVg = ddxpart_dVb = ddxpart_dVs = 0.0; dsxpart_dVd = dsxpart_dVg = dsxpart_dVb = dsxpart_dVs = 0.0; } else { cggb = cgdb = cgsb = 0.0; cbgb = cbdb = cbsb = 0.0; cdgb = cddb = cdsb = 0.0; xgtg = here->BSIM3gtg; xgtd = here->BSIM3gtd; xgts = here->BSIM3gts; xgtb = here->BSIM3gtb; xcqgb = here->BSIM3cqgb * omega; xcqdb = here->BSIM3cqdb * omega; xcqsb = here->BSIM3cqsb * omega; xcqbb = here->BSIM3cqbb * omega; CoxWL = model->BSIM3cox * here->pParam->BSIM3weffCV * here->pParam->BSIM3leffCV; qcheq = -(here->BSIM3qgate + here->BSIM3qbulk); if (fabs(qcheq) <= 1.0e-5 * CoxWL) { if (model->BSIM3xpart < 0.5) { dxpart = 0.4; } else if (model->BSIM3xpart > 0.5) { dxpart = 0.0; } else { dxpart = 0.5; } ddxpart_dVd = ddxpart_dVg = ddxpart_dVb = ddxpart_dVs = 0.0; } else { dxpart = here->BSIM3qdrn / qcheq; Cdd = here->BSIM3cddb; Csd = -(here->BSIM3cgdb + here->BSIM3cddb + here->BSIM3cbdb); ddxpart_dVd = (Cdd - dxpart * (Cdd + Csd)) / qcheq; Cdg = here->BSIM3cdgb; Csg = -(here->BSIM3cggb + here->BSIM3cdgb + here->BSIM3cbgb); ddxpart_dVg = (Cdg - dxpart * (Cdg + Csg)) / qcheq; Cds = here->BSIM3cdsb; Css = -(here->BSIM3cgsb + here->BSIM3cdsb + here->BSIM3cbsb); ddxpart_dVs = (Cds - dxpart * (Cds + Css)) / qcheq; ddxpart_dVb = -(ddxpart_dVd + ddxpart_dVg + ddxpart_dVs); } sxpart = 1.0 - dxpart; dsxpart_dVd = -ddxpart_dVd; dsxpart_dVg = -ddxpart_dVg; dsxpart_dVs = -ddxpart_dVs; dsxpart_dVb = -(dsxpart_dVd + dsxpart_dVg + dsxpart_dVs); } } else { Gm = -here->BSIM3gm; Gmbs = -here->BSIM3gmbs; FwdSum = 0.0; RevSum = -(Gm + Gmbs); gbbsp = -here->BSIM3gbds; gbbdp = here->BSIM3gbds + here->BSIM3gbgs + here->BSIM3gbbs; gbdpg = 0.0; gbdpsp = 0.0; gbdpb = 0.0; gbdpdp = 0.0; gbspg = here->BSIM3gbgs; gbspsp = here->BSIM3gbds; gbspb = here->BSIM3gbbs; gbspdp = -(gbspg + gbspsp + gbspb); if (here->BSIM3nqsMod == 0) { cggb = here->BSIM3cggb; cgsb = here->BSIM3cgdb; cgdb = here->BSIM3cgsb; cbgb = here->BSIM3cbgb; cbsb = here->BSIM3cbdb; cbdb = here->BSIM3cbsb; cdgb = -(here->BSIM3cdgb + cggb + cbgb); cdsb = -(here->BSIM3cddb + cgsb + cbsb); cddb = -(here->BSIM3cdsb + cgdb + cbdb); xgtg = xgtd = xgts = xgtb = 0.0; sxpart = 0.4; dxpart = 0.6; ddxpart_dVd = ddxpart_dVg = ddxpart_dVb = ddxpart_dVs = 0.0; dsxpart_dVd = dsxpart_dVg = dsxpart_dVb = dsxpart_dVs = 0.0; } else { cggb = cgdb = cgsb = 0.0; cbgb = cbdb = cbsb = 0.0; cdgb = cddb = cdsb = 0.0; xgtg = here->BSIM3gtg; xgtd = here->BSIM3gts; xgts = here->BSIM3gtd; xgtb = here->BSIM3gtb; xcqgb = here->BSIM3cqgb * omega; xcqdb = here->BSIM3cqsb * omega; xcqsb = here->BSIM3cqdb * omega; xcqbb = here->BSIM3cqbb * omega; CoxWL = model->BSIM3cox * here->pParam->BSIM3weffCV * here->pParam->BSIM3leffCV; qcheq = -(here->BSIM3qgate + here->BSIM3qbulk); if (fabs(qcheq) <= 1.0e-5 * CoxWL) { if (model->BSIM3xpart < 0.5) { sxpart = 0.4; } else if (model->BSIM3xpart > 0.5) { sxpart = 0.0; } else { sxpart = 0.5; } dsxpart_dVd = dsxpart_dVg = dsxpart_dVb = dsxpart_dVs = 0.0; } else { sxpart = here->BSIM3qdrn / qcheq; Css = here->BSIM3cddb; Cds = -(here->BSIM3cgdb + here->BSIM3cddb + here->BSIM3cbdb); dsxpart_dVs = (Css - sxpart * (Css + Cds)) / qcheq; Csg = here->BSIM3cdgb; Cdg = -(here->BSIM3cggb + here->BSIM3cdgb + here->BSIM3cbgb); dsxpart_dVg = (Csg - sxpart * (Csg + Cdg)) / qcheq; Csd = here->BSIM3cdsb; Cdd = -(here->BSIM3cgsb + here->BSIM3cdsb + here->BSIM3cbsb); dsxpart_dVd = (Csd - sxpart * (Csd + Cdd)) / qcheq; dsxpart_dVb = -(dsxpart_dVd + dsxpart_dVg + dsxpart_dVs); } dxpart = 1.0 - sxpart; ddxpart_dVd = -dsxpart_dVd; ddxpart_dVg = -dsxpart_dVg; ddxpart_dVs = -dsxpart_dVs; ddxpart_dVb = -(ddxpart_dVd + ddxpart_dVg + ddxpart_dVs); } } T1 = *(ckt->CKTstate0 + here->BSIM3qdef) * here->BSIM3gtau; gdpr = here->BSIM3drainConductance; gspr = here->BSIM3sourceConductance; gds = here->BSIM3gds; gbd = here->BSIM3gbd; gbs = here->BSIM3gbs; capbd = here->BSIM3capbd; capbs = here->BSIM3capbs; GSoverlapCap = here->BSIM3cgso; GDoverlapCap = here->BSIM3cgdo; GBoverlapCap = here->pParam->BSIM3cgbo; xcdgb = (cdgb - GDoverlapCap) * omega; xcddb = (cddb + capbd + GDoverlapCap) * omega; xcdsb = cdsb * omega; xcsgb = -(cggb + cbgb + cdgb + GSoverlapCap) * omega; xcsdb = -(cgdb + cbdb + cddb) * omega; xcssb = (capbs + GSoverlapCap - (cgsb + cbsb + cdsb)) * omega; xcggb = (cggb + GDoverlapCap + GSoverlapCap + GBoverlapCap) * omega; xcgdb = (cgdb - GDoverlapCap ) * omega; xcgsb = (cgsb - GSoverlapCap) * omega; xcbgb = (cbgb - GBoverlapCap) * omega; xcbdb = (cbdb - capbd ) * omega; xcbsb = (cbsb - capbs ) * omega; *(here->BSIM3GgPtr +1) += xcggb; *(here->BSIM3BbPtr +1) -= xcbgb + xcbdb + xcbsb; *(here->BSIM3DPdpPtr +1) += xcddb; *(here->BSIM3SPspPtr +1) += xcssb; *(here->BSIM3GbPtr +1) -= xcggb + xcgdb + xcgsb; *(here->BSIM3GdpPtr +1) += xcgdb; *(here->BSIM3GspPtr +1) += xcgsb; *(here->BSIM3BgPtr +1) += xcbgb; *(here->BSIM3BdpPtr +1) += xcbdb; *(here->BSIM3BspPtr +1) += xcbsb; *(here->BSIM3DPgPtr +1) += xcdgb; *(here->BSIM3DPbPtr +1) -= xcdgb + xcddb + xcdsb; *(here->BSIM3DPspPtr +1) += xcdsb; *(here->BSIM3SPgPtr +1) += xcsgb; *(here->BSIM3SPbPtr +1) -= xcsgb + xcsdb + xcssb; *(here->BSIM3SPdpPtr +1) += xcsdb; *(here->BSIM3DdPtr) += gdpr; *(here->BSIM3SsPtr) += gspr; *(here->BSIM3BbPtr) += gbd + gbs - here->BSIM3gbbs; *(here->BSIM3DPdpPtr) += gdpr + gds + gbd + RevSum + dxpart * xgtd + T1 * ddxpart_dVd + gbdpdp; *(here->BSIM3SPspPtr) += gspr + gds + gbs + FwdSum + sxpart * xgts + T1 * dsxpart_dVs + gbspsp; *(here->BSIM3DdpPtr) -= gdpr; *(here->BSIM3SspPtr) -= gspr; *(here->BSIM3BgPtr) -= here->BSIM3gbgs; *(here->BSIM3BdpPtr) -= gbd - gbbdp; *(here->BSIM3BspPtr) -= gbs - gbbsp; *(here->BSIM3DPdPtr) -= gdpr; *(here->BSIM3DPgPtr) += Gm + dxpart * xgtg + T1 * ddxpart_dVg + gbdpg; *(here->BSIM3DPbPtr) -= gbd - Gmbs - dxpart * xgtb - T1 * ddxpart_dVb - gbdpb; *(here->BSIM3DPspPtr) -= gds + FwdSum - dxpart * xgts - T1 * ddxpart_dVs - gbdpsp; *(here->BSIM3SPgPtr) -= Gm - sxpart * xgtg - T1 * dsxpart_dVg - gbspg; *(here->BSIM3SPsPtr) -= gspr; *(here->BSIM3SPbPtr) -= gbs + Gmbs - sxpart * xgtb - T1 * dsxpart_dVb - gbspb; *(here->BSIM3SPdpPtr) -= gds + RevSum - sxpart * xgtd - T1 * dsxpart_dVd - gbspdp; *(here->BSIM3GgPtr) -= xgtg; *(here->BSIM3GbPtr) -= xgtb; *(here->BSIM3GdpPtr) -= xgtd; *(here->BSIM3GspPtr) -= xgts; if (here->BSIM3nqsMod) { *(here->BSIM3QqPtr +1) += omega * ScalingFactor; *(here->BSIM3QgPtr +1) -= xcqgb; *(here->BSIM3QdpPtr +1) -= xcqdb; *(here->BSIM3QspPtr +1) -= xcqsb; *(here->BSIM3QbPtr +1) -= xcqbb; *(here->BSIM3QqPtr) += here->BSIM3gtau; *(here->BSIM3DPqPtr) += dxpart * here->BSIM3gtau; *(here->BSIM3SPqPtr) += sxpart * here->BSIM3gtau; *(here->BSIM3GqPtr) -= here->BSIM3gtau; *(here->BSIM3QgPtr) += xgtg; *(here->BSIM3QdpPtr) += xgtd; *(here->BSIM3QspPtr) += xgts; *(here->BSIM3QbPtr) += xgtb; } // SRW if (here->BSIM3adjoint) { BSIM3adj *adj = here->BSIM3adjoint; adj->matrix->clear(); *(adj->BSIM3GgPtr +1) += xcggb; *(adj->BSIM3BbPtr +1) -= xcbgb + xcbdb + xcbsb; *(adj->BSIM3DPdpPtr +1) += xcddb; *(adj->BSIM3SPspPtr +1) += xcssb; *(adj->BSIM3GbPtr +1) -= xcggb + xcgdb + xcgsb; *(adj->BSIM3GdpPtr +1) += xcgdb; *(adj->BSIM3GspPtr +1) += xcgsb; *(adj->BSIM3BgPtr +1) += xcbgb; *(adj->BSIM3BdpPtr +1) += xcbdb; *(adj->BSIM3BspPtr +1) += xcbsb; *(adj->BSIM3DPgPtr +1) += xcdgb; *(adj->BSIM3DPbPtr +1) -= xcdgb + xcddb + xcdsb; *(adj->BSIM3DPspPtr +1) += xcdsb; *(adj->BSIM3SPgPtr +1) += xcsgb; *(adj->BSIM3SPbPtr +1) -= xcsgb + xcsdb + xcssb; *(adj->BSIM3SPdpPtr +1) += xcsdb; *(adj->BSIM3DdPtr) += gdpr; *(adj->BSIM3SsPtr) += gspr; *(adj->BSIM3BbPtr) += gbd + gbs - here->BSIM3gbbs; *(adj->BSIM3DPdpPtr) += gdpr + gds + gbd + RevSum + dxpart * xgtd + T1 * ddxpart_dVd + gbdpdp; *(adj->BSIM3SPspPtr) += gspr + gds + gbs + FwdSum + sxpart * xgts + T1 * dsxpart_dVs + gbspsp; *(adj->BSIM3DdpPtr) -= gdpr; *(adj->BSIM3SspPtr) -= gspr; *(adj->BSIM3BgPtr) -= here->BSIM3gbgs; *(adj->BSIM3BdpPtr) -= gbd - gbbdp; *(adj->BSIM3BspPtr) -= gbs - gbbsp; *(adj->BSIM3DPdPtr) -= gdpr; *(adj->BSIM3DPgPtr) += Gm + dxpart * xgtg + T1 * ddxpart_dVg + gbdpg; *(adj->BSIM3DPbPtr) -= gbd - Gmbs - dxpart * xgtb - T1 * ddxpart_dVb - gbdpb; *(adj->BSIM3DPspPtr) -= gds + FwdSum - dxpart * xgts - T1 * ddxpart_dVs - gbdpsp; *(adj->BSIM3SPgPtr) -= Gm - sxpart * xgtg - T1 * dsxpart_dVg - gbspg; *(adj->BSIM3SPsPtr) -= gspr; *(adj->BSIM3SPbPtr) -= gbs + Gmbs - sxpart * xgtb - T1 * dsxpart_dVb - gbspb; *(adj->BSIM3SPdpPtr) -= gds + RevSum - sxpart * xgtd - T1 * dsxpart_dVd - gbspdp; *(adj->BSIM3GgPtr) -= xgtg; *(adj->BSIM3GbPtr) -= xgtb; *(adj->BSIM3GdpPtr) -= xgtd; *(adj->BSIM3GspPtr) -= xgts; if (here->BSIM3nqsMod) { *(adj->BSIM3QqPtr +1) += omega * ScalingFactor; *(adj->BSIM3QgPtr +1) -= xcqgb; *(adj->BSIM3QdpPtr +1) -= xcqdb; *(adj->BSIM3QspPtr +1) -= xcqsb; *(adj->BSIM3QbPtr +1) -= xcqbb; *(adj->BSIM3QqPtr) += here->BSIM3gtau; *(adj->BSIM3DPqPtr) += dxpart * here->BSIM3gtau; *(adj->BSIM3SPqPtr) += sxpart * here->BSIM3gtau; *(adj->BSIM3GqPtr) -= here->BSIM3gtau; *(adj->BSIM3QgPtr) += xgtg; *(adj->BSIM3QdpPtr) += xgtd; *(adj->BSIM3QspPtr) += xgts; *(adj->BSIM3QbPtr) += xgtb; } } // SRW - end } } return(OK); }
43.358491
84
0.407359
wrcad
f6d0c09332080e0e583405c03d18cb3e5b963506
408
cpp
C++
codeforces/beta-round-4/div-2/watermelon.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-07-16T01:46:38.000Z
2020-07-16T01:46:38.000Z
codeforces/beta-round-4/div-2/watermelon.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
null
null
null
codeforces/beta-round-4/div-2/watermelon.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-05-27T14:30:43.000Z
2020-05-27T14:30:43.000Z
#include <iostream> using namespace std; inline void use_io_optimizations() { ios_base::sync_with_stdio(false); cin.tie(nullptr); } int main() { use_io_optimizations(); unsigned int watermelon_weight; cin >> watermelon_weight; if (watermelon_weight > 2 && watermelon_weight % 2 == 0) { cout << "YES"; } else { cout << "NO"; } return 0; }
14.068966
60
0.590686
Rkhoiwal
f6d0e6aedafdde0982e2a4a82633b42da85c5617
1,073
cpp
C++
DataSpec/DNACommon/STRG.cpp
RetroView/RetroCommon
a413a010b50a53ebc6b0c726203181fc179d3370
[ "MIT" ]
106
2021-04-09T19:42:56.000Z
2022-03-30T09:13:28.000Z
DataSpec/DNACommon/STRG.cpp
Austint30/metaforce
a491e2e9f229c8db92544b275cd1baa80bacfd17
[ "MIT" ]
58
2021-04-09T12:48:58.000Z
2022-03-22T00:11:42.000Z
DataSpec/DNACommon/STRG.cpp
Austint30/metaforce
a491e2e9f229c8db92544b275cd1baa80bacfd17
[ "MIT" ]
13
2021-04-06T23:23:20.000Z
2022-03-16T02:09:48.000Z
#include "DataSpec/DNACommon/STRG.hpp" #include "DataSpec/DNAMP1/STRG.hpp" #include "DataSpec/DNAMP2/STRG.hpp" #include "DataSpec/DNAMP3/STRG.hpp" #include <logvisor/logvisor.hpp> namespace DataSpec { void ISTRG::gatherDependencies(std::vector<hecl::ProjectPath>& pathsOut) const { /* TODO: parse out resource tokens */ } std::unique_ptr<ISTRG> LoadSTRG(athena::io::IStreamReader& reader) { uint32_t magic = reader.readUint32Big(); if (magic != 0x87654321) { LogDNACommon.report(logvisor::Error, FMT_STRING("invalid STRG magic")); return {}; } uint32_t version = reader.readUint32Big(); switch (version) { case 0: { auto* newStrg = new DNAMP1::STRG; newStrg->_read(reader); return std::unique_ptr<ISTRG>(newStrg); } case 1: { auto* newStrg = new DNAMP2::STRG; newStrg->_read(reader); return std::unique_ptr<ISTRG>(newStrg); } case 3: { auto* newStrg = new DNAMP3::STRG; newStrg->_read(reader); return std::unique_ptr<ISTRG>(newStrg); } default: break; } return {}; } } // namespace DataSpec
24.386364
118
0.679404
RetroView
f6d1ce2a7d149a95999032ee6379f9b1d6e6f7e9
1,471
cc
C++
external_libs/pgenlib/pvar_ffi_support.cc
yujin2011/regenie
7c379b5359cea7f56bea69576ce6c304555ccf51
[ "MIT" ]
89
2020-06-23T05:36:33.000Z
2022-03-26T13:50:42.000Z
external_libs/pgenlib/pvar_ffi_support.cc
yujin2011/regenie
7c379b5359cea7f56bea69576ce6c304555ccf51
[ "MIT" ]
254
2020-06-23T15:45:33.000Z
2022-03-31T18:49:20.000Z
external_libs/pgenlib/pvar_ffi_support.cc
yujin2011/regenie
7c379b5359cea7f56bea69576ce6c304555ccf51
[ "MIT" ]
36
2020-06-23T04:43:36.000Z
2022-03-05T01:29:21.000Z
// This library is part of PLINK 2.00, copyright (C) 2005-2020 Shaun Purcell, // Christopher Chang. // // 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 3 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, see <http://www.gnu.org/licenses/>. // // // * Modified by Joelle Mbatchou - Apr 27 2021 // * - kept only needed functions and modify to recude needed headers #include "pvar_ffi_support.h" namespace plink2 { RefcountedWptr* CreateRefcountedWptr(uintptr_t size) { RefcountedWptr* rwp = static_cast<RefcountedWptr*>(malloc(sizeof(RefcountedWptr))); if (!rwp) { return nullptr; } rwp->ref_ct = 1; rwp->p = static_cast<uintptr_t*>(malloc(sizeof(uintptr_t) * size)); return rwp; } void CondReleaseRefcountedWptr(RefcountedWptr** rwpp) { RefcountedWptr* rwp = *rwpp; if (!rwp) { return; } --rwp->ref_ct; if (!rwp->ref_ct) { free(rwp->p); free(rwp); } *rwpp = nullptr; } } // namespace plink2
29.42
85
0.709041
yujin2011
f6d2dfbfc2f90990b91ebccb326108f5a8981813
831
cpp
C++
2019Homeworks/20191205_P4_Practice1/10.PaidRoads.cpp
Guyutongxue/Introduction_to_Computation
062f688fe3ffb8e29cfaf139223e4994edbf64d6
[ "WTFPL" ]
8
2019-10-09T14:33:42.000Z
2020-12-03T00:49:29.000Z
2019Homeworks/20191205_P4_Practice1/10.PaidRoads.cpp
Guyutongxue/Introduction_to_Computation
062f688fe3ffb8e29cfaf139223e4994edbf64d6
[ "WTFPL" ]
null
null
null
2019Homeworks/20191205_P4_Practice1/10.PaidRoads.cpp
Guyutongxue/Introduction_to_Computation
062f688fe3ffb8e29cfaf139223e4994edbf64d6
[ "WTFPL" ]
null
null
null
#include<iostream> #include<cstring> using namespace std; int n,m; int visit[11]; int mmin=1<<30; struct Road{ int u,v; int c; int p,r; }; Road a[12]; void search(int s,int current){ if(s==n&&current<mmin){ mmin=current; return; } for(int i=1;i<=m;i++){ if(s==a[i].u&&visit[a[i].v]<=3){ int v=a[i].v; if(visit[a[i].c]){ visit[v]++; search(v,current+a[i].p); } else{ visit[v]++; search(v,current+a[i].r); } visit[v]--; } } return; } int main(){ cin>>n>>m; memset(visit,0,sizeof(visit)); for(int i=1;i<=m;i++){ cin>>a[i].u>>a[i].v>>a[i].c>>a[i].p>>a[i].r; } visit[1]=1; search(1,0); if(mmin==1<<30){ cout<<"impossible"<<endl; } else{ cout<<mmin<<endl; } return 0; }
16.62
52
0.471721
Guyutongxue
f6d69bbba3d0df26f01ce3c64c40e9713e54ee9b
380
cpp
C++
ticket_window.cpp
NicholasWhit3/Tickets_System
293e286ec0c71b3a56678fb41b3a58d87b4bfc42
[ "MIT" ]
null
null
null
ticket_window.cpp
NicholasWhit3/Tickets_System
293e286ec0c71b3a56678fb41b3a58d87b4bfc42
[ "MIT" ]
null
null
null
ticket_window.cpp
NicholasWhit3/Tickets_System
293e286ec0c71b3a56678fb41b3a58d87b4bfc42
[ "MIT" ]
null
null
null
#include "ticket_window.h" #include "ticketbase.h" Ticket_Window::Ticket_Window(TicketBase &ticketBase) : _ticketBase(ticketBase) { std::cout << "Working in Ticket_Window::Ticket_Window..." << std::endl; } int Ticket_Window::getWindow_number() const { return window_number; } void Ticket_Window::setWindow_number(int value) { window_number = value; }
21.111111
80
0.710526
NicholasWhit3
f6d69cb0b20e0b82b9fd3bb227fb560026fbb0ea
17,322
hpp
C++
lib/sept/NPTerm.hpp
vdods/sept
08ee1faf1af4feb0dc440a3002eb8cc52681f946
[ "Apache-2.0" ]
null
null
null
lib/sept/NPTerm.hpp
vdods/sept
08ee1faf1af4feb0dc440a3002eb8cc52681f946
[ "Apache-2.0" ]
null
null
null
lib/sept/NPTerm.hpp
vdods/sept
08ee1faf1af4feb0dc440a3002eb8cc52681f946
[ "Apache-2.0" ]
null
null
null
// 2020.04.16 - Victor Dods #pragma once #include <lvd/hash.hpp> #include <lvd/static_if.hpp> #include "sept/core.hpp" #include "sept/Data.hpp" #include <type_traits> namespace sept { using NPTermRepr = uint8_t; // NPTerm is "NonParametricType", meaning types requiring no parameters to instantiate. // Each ParametricType corresponds to a class (e.g. ArrayESTerm_c) or built-in type (e.g. int32_t). enum class NPTerm : NPTermRepr { // The most basic Types. TERM = 0, // Literally everything is a Term (this could be called Any) NON_PARAMETRIC_TERM, // Inhabitants are Terms requiring no parameters to instantiate (all members of the NPTerm enum) PARAMETRIC_TERM, // Inhabitants are Terms requiring parameters to instantiate, e.g. 10.25, 'x', 999000 // Type Types. TYPE, // A Term which has an inhabitation predicate. NON_TYPE, // A Term which is not a Type (this could be called Value) NON_PARAMETRIC_TYPE, // Inhabitants are types requiring no parameters to instantiate (all members of the NPType enum) PARAMETRIC_TYPE, // Inhabitants are types requiring parameters to instantiate, e.g. ArrayESTerm_c(T,N) // NonParametricTerm && NonType VOID, // Void is a NonType that conveys no information TRUE, // The truthier of the two inhabitants of Bool FALSE, // The lying inhabitant of Bool // A few natural Types. VOID_TYPE, // Sole inhabitant is Void TRUE_TYPE, // Sole inhabitant is True FALSE_TYPE, // Sole inhabitant is False EMPTY_TYPE, // A Type defined to have no inhabitants FORMAL_TYPE_OF, // Constructs FormalTypeOf(x) for any term x. Sole inhabitant of FormalTypeOf(x) is x. // POD Types BOOL, // Isomorphic to Union(TrueType,FalseType) SINT8, SINT16, SINT32, SINT64, UINT8, UINT16, UINT32, UINT64, FLOAT32, FLOAT64, // ASCII_CHAR, // TODO: Add UnicodeChar later and whatever else -- TODO: Maybe Ascii should be an abstract type // POD Type Types BOOL_TYPE, // Sole inhabitant is Bool SINT8_TYPE, // Sole inhabitant is Sint8 SINT16_TYPE, // Sole inhabitant is Sint16 SINT32_TYPE, // Sole inhabitant is Sint32 SINT64_TYPE, // Sole inhabitant is Sint64 UINT8_TYPE, // Sole inhabitant is Uint8 UINT16_TYPE, // Sole inhabitant is Uint16 UINT32_TYPE, // Sole inhabitant is Uint32 UINT64_TYPE, // Sole inhabitant is Uint64 FLOAT32_TYPE, // Sole inhabitant is Float32 FLOAT64_TYPE, // Sole inhabitant is Float64 // ASCII_CHAR_TYPE, // Sole inhabitant is AsciiChar // Other Types related to POD Types SINT_TYPE, // Isomorphic to Union(Sint8Type,Sint16Type,Sint32Type,Sint64Type) SINT, // Isomorphic to Union(Sint8,Sint16,Sint32,Sint64) UINT_TYPE, // Isomorphic to Union(Uint8Type,Uint16Type,Uint32Type,Uint64Type) UINT, // Isomorphic to Union(Uint8,Uint16,Uint32,Uint64) FLOAT_TYPE, // Isomorphic to Union(Float32Type,Float64Type) FLOAT, // Isomorphic to Union(Float32,Float64) // TODO: Add CHAR types POD_TYPE, // Isomorphic to Union(BoolType,SintType,UintType,FloatType) (TODO: Somehow add POD as an inhabitant) POD, // Isomorphic to Union(Bool,Sint,Uint,Float). Inhabitants are POD values. POD : PODType. // TODO: Add stuff like Positive, Negative, NonPositive, NonNegative, Zero UNION_TYPE, // Inhabitant is Union. UNION, // Inhabitants have the form Union(T1,...,TN) -- implemented by class UnionTerm_c INTERSECTION, // Inhabitants have the form Intersection(T1,...,TN) NEGATION, // Inhabitants have the form Negation(T) DIFFERENCE, // Inhabitants have the form Difference(T,U1,...,UN) // TODO: UnionType, IntersectionType, etc. ARRAY_TYPE, // Inhabitants are ArrayES, ArrayE, ArrayS, Array. ARRAY_ES, // Inhabitants have the form ArrayES(T,N) -- implemented by class ArrayESTerm_c ARRAY_E, // Inhabitants have the form ArrayE(T) -- implemented by class ArrayETerm_c ARRAY_S, // Inhabitants have the form ArrayS(N) -- implemented by class ArraySTerm_c ARRAY, // Inhabitants have the form Array(...) -- implemented by class ArrayTerm_c ORDERED_MAP_TYPE, // Inhabitants are OrderedMapDC, OrderedMapD, OrderedMapC, OrderedMap. ORDERED_MAP_DC, // Inhabitants have the form OrderedMapDC(Domain,Codomain) -- implemented by class OrderedMapDCTerm_c ORDERED_MAP_D, // Inhabitants have the form OrderedMapD(Domain) -- implemented by class OrderedMapDTerm_c ORDERED_MAP_C, // Inhabitants have the form OrderedMapC(Codomain) -- implemented by class OrderedMapCTerm_c ORDERED_MAP, // Inhabitants have the form OrderedMap(...) -- implemented by class OrderedMapTerm_c TUPLE_TYPE, // Inhabitant is Tuple. TUPLE, // Inhabitants have the form Tuple(...) -- implemented by class TupleTerm_c. MEM_REF_TYPE, // Inhabitant is MemRef MEM_REF, // Inhabitants have the form MemRef(&d), where d is Data GLOBAL_SYM_REF_TYPE, // Inhabitant is GlobalSymRef GLOBAL_SYM_REF, // Inhabitants have the form GlobalSymRef("<symbol-id>") LOCAL_SYM_REF_TYPE, // Inhabitant is LocalSymRef LOCAL_SYM_REF, // Inhabitants have the form LocalSymRef("<symbol-id>", <shared-ptr-to-symbol-table>) PLACEHOLDER_TYPE, PLACEHOLDER, FREEVAR_TYPE, FREEVAR, // // Control terms // OUTPUT_TYPE, // Sole inhabitant is Output OUTPUT, // Inhabitants have the form Output(V) for some value V CLEAR_OUTPUT_TYPE, // Sole inhabitant is ClearOutput CLEAR_OUTPUT, // Singleton END_OF_FILE_TYPE, // Sole inhabitant is EndOfFile END_OF_FILE, // Singleton REQUEST_SYNC_INPUT_TYPE, // Sole inhabitant is RequestSyncInput REQUEST_SYNC_INPUT, // Inhabitants have the form RequestSyncInput(T) for some type T __HIGHEST__ = REQUEST_SYNC_INPUT }; std::string const &as_string (NPTerm t); inline void serialize (NPTerm const &v, std::ostream &out) { static_assert(sizeof(NPTerm) == 1); out.put(uint8_t(v)); } class Data; template <typename Derived_> class SingletonBase_t { public: // TODO: Somehow check that Derived_ is a trivial class. Can't put that check in the constructor, because then // it becomes a non-trivial class. Can't put a static_assert in the body of this class because Derived_ isn't // fully defined yet. // static_assert(std::is_trivial_v<Derived_>, "Derived_ must be a trivial class (see C++ reference for std::is_trivial)"); // Because there is no information in the singleton object (all its information is present // in its type), just need to compare the types. bool operator == (Data const &rhs) { return rhs.type() == typeid(Derived_); } bool operator != (Data const &rhs) { return rhs.type() != typeid(Derived_); } }; template <typename Derived_> std::ostream &operator << (std::ostream &out, SingletonBase_t<Derived_> const &) { return out << Derived_::as_string(); } template <NPTerm ENUM_VALUE_, typename Derived_ = DerivedNone> class NonParametricTerm_t : public SingletonBase_t<lvd::static_if_t<std::is_same_v<Derived_,DerivedNone>,NonParametricTerm_t<ENUM_VALUE_>,Derived_>> { public: using Derived = lvd::static_if_t<std::is_same_v<Derived_,DerivedNone>,NonParametricTerm_t,Derived_>; constexpr NPTerm npterm () const { return ENUM_VALUE_; } Derived const & as_derived () const & { return static_cast<Derived const &>(*this); } Derived &as_derived () & { return static_cast<Derived &>(*this); } operator Derived const & () const & { return as_derived(); } operator Derived & () & { return as_derived(); } static std::string const &as_string () { return sept::as_string(ENUM_VALUE_); } }; using NonParametricTerm_c = NonParametricTerm_t<NPTerm::NON_PARAMETRIC_TERM>; // NOTE: The definition of abstract_type_of(NonParametricTerm_c const &) is in NPType.hpp extern NonParametricTerm_c NonParametricTerm; template <NPTerm ENUM_VALUE_, typename Derived_> constexpr NonParametricTerm_c const &concrete_type_of (NonParametricTerm_t<ENUM_VALUE_,Derived_> const &) { return NonParametricTerm; } // Void_c implements Void, which is the sole inhabitant of VoidType. using Void_c = NonParametricTerm_t<NPTerm::VOID>; extern Void_c Void; class True_c; class False_c; // BoolTerm_c implements the terms of Bool, which can be true or false. Note that True and False // are not instances of BoolTerm_c in a concrete sense, but they are inhabitants of Bool. However, // all the expected constructors, conversion operators, and comparators exist. // NOTE: This is a ParametricTerm // TODO: Probably deprecate BoolTerm_c in favor of just plain bool (which seems to be working). class BoolTerm_c { public: BoolTerm_c () = delete; // Maybe allow this? Maybe don't bother initializing? constexpr BoolTerm_c (BoolTerm_c const &other) : m_value(other.m_value) { } constexpr BoolTerm_c (BoolTerm_c &&other) : m_value(other.m_value) { } constexpr BoolTerm_c (bool value) : m_value(value) { } constexpr explicit BoolTerm_c (True_c const &) : m_value(true) { } constexpr explicit BoolTerm_c (False_c const &) : m_value(false) { } constexpr bool as_bool () const { return m_value; } constexpr operator bool () const { return m_value; } private: bool m_value; }; inline constexpr BoolTerm_c operator == (BoolTerm_c const &lhs, BoolTerm_c const &rhs) { return lhs.as_bool() == rhs.as_bool(); } inline constexpr BoolTerm_c operator != (BoolTerm_c const &lhs, BoolTerm_c const &rhs) { return lhs.as_bool() != rhs.as_bool(); } inline constexpr BoolTerm_c operator == (bool lhs, BoolTerm_c const &rhs) { return lhs == rhs.as_bool(); } inline constexpr BoolTerm_c operator != (bool lhs, BoolTerm_c const &rhs) { return lhs != rhs.as_bool(); } inline constexpr BoolTerm_c operator == (BoolTerm_c const &lhs, bool rhs) { return lhs.as_bool() == rhs; } inline constexpr BoolTerm_c operator != (BoolTerm_c const &lhs, bool rhs) { return lhs.as_bool() != rhs; } // TODO: Maybe implement bitwise operators for logic (shouldn't overload logical operators due // to short-circuiting behavior that is lost when overloading the logical operators) template <typename T_, typename = std::enable_if_t<std::is_integral_v<T_> || std::is_floating_point_v<T_>>> constexpr int compare (T_ lhs, T_ rhs) { return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1); } inline constexpr int compare (BoolTerm_c const &lhs, BoolTerm_c const &rhs) { return compare(lhs.as_bool(), rhs.as_bool()); } class True_c : public NonParametricTerm_t<NPTerm::TRUE,True_c> { public: constexpr bool as_bool () const { return true; } constexpr BoolTerm_c as_BoolTerm () const { return BoolTerm_c(true); } constexpr operator bool () const { return true; } // constexpr operator BoolTerm_c () const { return BoolTerm_c(true); } }; class False_c : public NonParametricTerm_t<NPTerm::FALSE,False_c> { public: constexpr bool as_bool () const { return false; } constexpr BoolTerm_c as_BoolTerm () const { return BoolTerm_c(false); } constexpr operator bool () const { return false; } // constexpr operator BoolTerm_c () const { return BoolTerm_c(false); } }; extern True_c True; extern False_c False; inline constexpr False_c operator == (True_c const &, False_c const &) { return False; } inline constexpr False_c operator == (False_c const &, True_c const &) { return False; } inline constexpr True_c operator == (True_c const &, True_c const &) { return True; } inline constexpr True_c operator == (False_c const &, False_c const &) { return True; } inline constexpr True_c operator != (True_c const &, False_c const &) { return True; } inline constexpr True_c operator != (False_c const &, True_c const &) { return True; } inline constexpr False_c operator != (True_c const &, True_c const &) { return False; } inline constexpr False_c operator != (False_c const &, False_c const &) { return False; } inline constexpr BoolTerm_c operator == (BoolTerm_c const &lhs, True_c const &) { return lhs.as_bool() == true; } inline constexpr BoolTerm_c operator == (BoolTerm_c const &lhs, False_c const &) { return lhs.as_bool() == false; } inline constexpr BoolTerm_c operator == (True_c const &, BoolTerm_c const &rhs) { return rhs.as_bool() == true; } inline constexpr BoolTerm_c operator == (False_c const &, BoolTerm_c const &rhs) { return rhs.as_bool() == false; } inline constexpr BoolTerm_c operator != (BoolTerm_c const &lhs, True_c const &) { return lhs.as_bool() != true; } inline constexpr BoolTerm_c operator != (BoolTerm_c const &lhs, False_c const &) { return lhs.as_bool() != false; } inline constexpr BoolTerm_c operator != (True_c const &, BoolTerm_c const &rhs) { return rhs.as_bool() != true; } inline constexpr BoolTerm_c operator != (False_c const &, BoolTerm_c const &rhs) { return rhs.as_bool() != false; } // TODO: Maybe implement bitwise operators for logic (shouldn't overload logical operators due // to short-circuiting behavior that is lost when overloading the logical operators) template <typename LhsDerived_, typename RhsDerived_> constexpr lvd::static_if_t<std::is_same_v<LhsDerived_,RhsDerived_>,True_c,False_c> operator == (SingletonBase_t<LhsDerived_> const &, SingletonBase_t<RhsDerived_> const &) { // Because there is no information in the singleton object (all its information is present // in its type), just need to compare the types. return lvd::static_if_t<std::is_same_v<LhsDerived_,RhsDerived_>,True_c,False_c>(); } template <typename LhsDerived_, typename RhsDerived_> constexpr lvd::static_if_t<std::is_same_v<LhsDerived_,RhsDerived_>,False_c,True_c> operator != (SingletonBase_t<LhsDerived_> const &lhs, SingletonBase_t<RhsDerived_> const &rhs) { // Because there is no information in the singleton object (all its information is present // in its type), just need to compare the types. return lvd::static_if_t<std::is_same_v<LhsDerived_,RhsDerived_>,False_c,True_c>(); } template <typename Derived_> constexpr int compare (SingletonBase_t<Derived_> const &, SingletonBase_t<Derived_> const &) { // Because there is no information in the singleton object (all its information is present // in its type), just need to compare the types. return 0; } // TODO: Use names to define comparison on differently-typed singletons. inline constexpr int compare (BoolTerm_c const &lhs, True_c const &rhs) { return compare(lhs.as_bool(), rhs.as_bool()); } inline constexpr int compare (BoolTerm_c const &lhs, False_c const &rhs) { return compare(lhs.as_bool(), rhs.as_bool()); } inline constexpr int compare (True_c const &lhs, BoolTerm_c const &rhs) { return compare(lhs.as_bool(), rhs.as_bool()); } inline constexpr int compare (False_c const &lhs, BoolTerm_c const &rhs) { return compare(lhs.as_bool(), rhs.as_bool()); } inline constexpr int compare (True_c const &lhs, False_c const &rhs) { return compare(lhs.as_bool(), rhs.as_bool()); } inline constexpr int compare (False_c const &lhs, True_c const &rhs) { return compare(lhs.as_bool(), rhs.as_bool()); } // // serialize and deserialize definitions // using SerializedTopLevelCodeRepr = uint8_t; // TODO: Could put a lot more into here, in particular commonly-used values/types. enum class SerializedTopLevelCode : SerializedTopLevelCodeRepr { NON_PARAMETRIC_TERM = 0, // A term having no parameters, and therefore fixed size. PARAMETRIC_TERM, // A term that has parameters. }; inline void serialize (SerializedTopLevelCode const &v, std::ostream &out) { static_assert(sizeof(SerializedTopLevelCode) == 1); out.put(uint8_t(v)); } template <NPTerm ENUM_VALUE_, typename Derived_> void serialize (NonParametricTerm_t<ENUM_VALUE_,Derived_> const &value, std::ostream &out) { serialize(SerializedTopLevelCode::NON_PARAMETRIC_TERM, out); serialize(ENUM_VALUE_, out); } } // end namespace sept namespace std { // Template specialization to define std::hash<sept::SingletonBase_t<...>>. template <typename Derived_> struct hash<sept::SingletonBase_t<Derived_>> { size_t operator () (sept::SingletonBase_t<Derived_> const &) const { return lvd::hash(typeid(Derived_)); } }; // Template specialization to define std::hash<sept::NonParametricTerm_t<...>>. template <sept::NPTerm ENUM_VALUE_, typename Derived_> struct hash<sept::NonParametricTerm_t<ENUM_VALUE_,Derived_>> { size_t operator () (sept::NonParametricTerm_t<ENUM_VALUE_,Derived_> const &) const { return lvd::hash(typeid(Derived_), ENUM_VALUE_); } }; // Template specialization to define std::hash<sept::True_c>. template <> struct hash<sept::BoolTerm_c> { size_t operator () (sept::BoolTerm_c const &t) const { return lvd::hash(typeid(sept::BoolTerm_c), t.as_bool()); } }; // Template specialization to define std::hash<sept::True_c>. template <> struct hash<sept::True_c> { size_t operator () (sept::True_c const &) const { return lvd::hash(typeid(sept::True_c)); } }; // Template specialization to define std::hash<sept::False_c>. template <> struct hash<sept::False_c> { size_t operator () (sept::False_c const &) const { return lvd::hash(typeid(sept::False_c)); } }; } // end namespace std
37.820961
179
0.719663
vdods
f6d7b2ff98b2e0e900cb21499e127394549348d4
2,914
cpp
C++
Source/AllProjects/Drivers/UPnPMediaRend/Server/UPnPMediaRendS.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
51
2020-12-26T18:17:16.000Z
2022-03-15T04:29:35.000Z
Source/AllProjects/Drivers/UPnPMediaRend/Server/UPnPMediaRendS.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
null
null
null
Source/AllProjects/Drivers/UPnPMediaRend/Server/UPnPMediaRendS.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
4
2020-12-28T07:24:39.000Z
2021-12-29T12:09:37.000Z
// // FILE NAME: UPnPMediaRendS.cpp // // AUTHOR: Dean Roddey // // CREATED: 10/18/2011 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This is the main implementation file for a media renderer driver that // should control any compliant UPnP media renderer. // // CAVEATS/GOTCHAS: // // LOG: // // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include "UPnPMediaRendS.hpp" namespace UPnPMediaRendS { // ----------------------------------------------------------------------- // Local data // // pfacWeatherS // Our facility object pointer, which is lazily faulted in. // ----------------------------------------------------------------------- TFacility* pfacUPnPMediaRendS = nullptr; } // --------------------------------------------------------------------------- // Glocal functions // --------------------------------------------------------------------------- TFacility& facUPnPMediaRendS() { // // Normally, in a CIDLib facility, this would be a lazy eval method. But, // since this is a driver, we can force it in below when we are loaded. // So we can avoid the overhead of synchronization and checking whether // it exists. // return *UPnPMediaRendS::pfacUPnPMediaRendS; } // --------------------------------------------------------------------------- // Global function that the server framework dynamically finds and uses to // get us to create an instance of our driver. // --------------------------------------------------------------------------- extern "C" CID_FNEXPORT TCQCServerBase* psdrvMakeNewSrv(const TCQCDriverObjCfg& cqcdcToLoad) { // // Sanity check that the passed config object matches our known client // side driver name. // facCQCKit().ValidateDrvCfg ( tCIDLib::ECSSides::Server, cqcdcToLoad, kUPnPMediaRendS::pszServerFacName ); // // Create our facility object now. Since we *should* always be loaded // dynamically and this called before anything else, this insures that // the facilty object is always there and doesn't have to be faulted // in. // UPnPMediaRendS::pfacUPnPMediaRendS = new TFacility ( kUPnPMediaRendS::pszServerFacName , tCIDLib::EModTypes::SharedLib , kUPnPMediaRendS::c4MajVersion , kUPnPMediaRendS::c4MinVersion , kUPnPMediaRendS::c4Revision , tCIDLib::EModFlags::HasMsgFile ); // And now gen up an instance of our driver and return it return new TUPnPMediaRendSDriver(cqcdcToLoad); }
29.734694
81
0.532601
MarkStega
f6dbf256f173d2befe833824cf5eb35125e64716
2,650
hpp
C++
include/TMPro/CaretInfo.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/TMPro/CaretInfo.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/TMPro/CaretInfo.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" // Including type: TMPro.CaretPosition #include "TMPro/CaretPosition.hpp" // Completed includes // Type namespace: TMPro namespace TMPro { // Forward declaring type: CaretInfo struct CaretInfo; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::TMPro::CaretInfo, "TMPro", "CaretInfo"); // Type namespace: TMPro namespace TMPro { // Size: 0x8 #pragma pack(push, 1) // WARNING Layout: Sequential may not be correctly taken into account! // Autogenerated type: TMPro.CaretInfo // [TokenAttribute] Offset: FFFFFFFF struct CaretInfo/*, public ::System::ValueType*/ { public: public: // public System.Int32 index // Size: 0x4 // Offset: 0x0 int index; // Field size check static_assert(sizeof(int) == 0x4); // public TMPro.CaretPosition position // Size: 0x4 // Offset: 0x4 ::TMPro::CaretPosition position; // Field size check static_assert(sizeof(::TMPro::CaretPosition) == 0x4); public: // Creating value type constructor for type: CaretInfo constexpr CaretInfo(int index_ = {}, ::TMPro::CaretPosition position_ = {}) noexcept : index{index_}, position{position_} {} // Creating interface conversion operator: operator ::System::ValueType operator ::System::ValueType() noexcept { return *reinterpret_cast<::System::ValueType*>(this); } // Get instance field reference: public System.Int32 index int& dyn_index(); // Get instance field reference: public TMPro.CaretPosition position ::TMPro::CaretPosition& dyn_position(); // public System.Void .ctor(System.Int32 index, TMPro.CaretPosition position) // Offset: 0x142E5A0 // ABORTED: conflicts with another method. CaretInfo(int index, ::TMPro::CaretPosition position); }; // TMPro.CaretInfo #pragma pack(pop) static check_size<sizeof(CaretInfo), 4 + sizeof(::TMPro::CaretPosition)> __TMPro_CaretInfoSizeCheck; static_assert(sizeof(CaretInfo) == 0x8); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: TMPro::CaretInfo::CaretInfo // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
40.151515
129
0.683019
RedBrumbler
f6dc3039c129c70612c19f72a58cc7cccb61cbcf
17,131
cpp
C++
3rdParty/AlazarTech/ATS-SDK/5.8.2/Samples/ATS9462/DualPort/TS_DisableFileCache/AcqToDisk.cpp
TeravoxelTwoPhotonTomography/fetch
9ae7082689e998050610311589de368d40b21cdc
[ "BSD-3-Clause" ]
2
2015-08-18T18:07:32.000Z
2016-03-24T23:07:18.000Z
3rdParty/AlazarTech/ATS-SDK/5.8.2/Samples/ATS9462/DualPort/TS_DisableFileCache/AcqToDisk.cpp
TeravoxelTwoPhotonTomography/fetch
9ae7082689e998050610311589de368d40b21cdc
[ "BSD-3-Clause" ]
null
null
null
3rdParty/AlazarTech/ATS-SDK/5.8.2/Samples/ATS9462/DualPort/TS_DisableFileCache/AcqToDisk.cpp
TeravoxelTwoPhotonTomography/fetch
9ae7082689e998050610311589de368d40b21cdc
[ "BSD-3-Clause" ]
2
2017-10-21T20:17:50.000Z
2019-12-29T16:27:04.000Z
//--------------------------------------------------------------------------- // // Copyright (c) 2008-2010 AlazarTech, Inc. // // AlazarTech, Inc. licenses this software under specific terms and // conditions. Use of any of the software or derviatives thereof in any // product without an AlazarTech digitizer board is strictly prohibited. // // AlazarTech, Inc. provides this software AS IS, WITHOUT ANY WARRANTY, // EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. AlazarTech makes no // guarantee or representations regarding the use of, or the results of the // use of, the software and documentation in terms of correctness, accuracy, // reliability, currentness, or otherwise; and you rely on the software, // documentation and results solely at your own risk. // // IN NO EVENT SHALL ALAZARTECH BE LIABLE FOR ANY LOSS OF USE, LOSS OF // BUSINESS, LOSS OF PROFITS, INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL // DAMAGES OF ANY KIND. IN NO EVENT SHALL ALAZARTECH'S TOTAL LIABILITY EXCEED // THE SUM PAID TO ALAZARTECH FOR THE PRODUCT LICENSED HEREUNDER. // //--------------------------------------------------------------------------- // AcqToDisk.cpp : // // This program demonstrates how to configure an ATS9462 to make a // triggered streaming AutoDMA acquisition. // #include <stdio.h> #include <conio.h> #include "AlazarError.h" #include "AlazarApi.h" #include "AlazarCmd.h" // TODO: Select the number of DMA buffers to allocate. #define BUFFER_COUNT 4 // Globals variables U16 *BufferArray[BUFFER_COUNT] = { NULL }; double SamplesPerSec = 0.; // Forward declarations BOOL ConfigureBoard(HANDLE boardHandle); BOOL AcquireData(HANDLE boardHandle); //---------------------------------------------------------------------------- // // Function : main // // Description : Program entry point // //---------------------------------------------------------------------------- int main(int argc, char* argv[]) { // TODO: Select a board U32 systemId = 1; U32 boardId = 1; // Get a handle to the board HANDLE boardHandle = AlazarGetBoardBySystemID(systemId, boardId); if (boardHandle == NULL) { printf("Error: Unable to open board system Id %u board Id %u\n", systemId, boardId); return 1; } // Configure the board's sample rate, input, and trigger settings if (!ConfigureBoard(boardHandle)) { printf("Error: Configure board failed\n"); return 1; } // Make an acquisition, optionally saving sample data to a file if (!AcquireData(boardHandle)) { printf("Error: Acquisition failed\n"); return 1; } return 0; } //---------------------------------------------------------------------------- // // Function : ConfigureBoard // // Description : Configure sample rate, input, and trigger settings // //---------------------------------------------------------------------------- BOOL ConfigureBoard(HANDLE boardHandle) { RETURN_CODE retCode; // TODO: Specify the sample rate (see sample rate id below) SamplesPerSec = 20.e6; // TODO: Select clock parameters as required to generate this sample rate. // // For example: if samplesPerSec is 100.e6 (100 MS/s), then: // - select clock source INTERNAL_CLOCK and sample rate SAMPLE_RATE_100MSPS // - select clock source FAST_EXTERNAL_CLOCK, sample rate SAMPLE_RATE_USER_DEF, // and connect a 100 MHz signalto the EXT CLK BNC connector. retCode = AlazarSetCaptureClock( boardHandle, // HANDLE -- board handle INTERNAL_CLOCK, // U32 -- clock source id SAMPLE_RATE_20MSPS, // U32 -- sample rate id CLOCK_EDGE_RISING, // U32 -- clock edge id 0 // U32 -- clock decimation ); if (retCode != ApiSuccess) { printf("Error: AlazarSetCaptureClock failed -- %s\n", AlazarErrorToText(retCode)); return FALSE; } // TODO: Select CHA input parameters as required retCode = AlazarInputControl( boardHandle, // HANDLE -- board handle CHANNEL_A, // U8 -- input channel DC_COUPLING, // U32 -- input coupling id INPUT_RANGE_PM_800_MV, // U32 -- input range id IMPEDANCE_50_OHM // U32 -- input impedance id ); if (retCode != ApiSuccess) { printf("Error: AlazarInputControl failed -- %s\n", AlazarErrorToText(retCode)); return FALSE; } // TODO: Select CHA bandwidth limit as required retCode = AlazarSetBWLimit( boardHandle, // HANDLE -- board handle CHANNEL_A, // U8 -- channel identifier 0 // U32 -- 0 = disable, 1 = enable ); if (retCode != ApiSuccess) { printf("Error: AlazarSetBWLimit failed -- %s\n", AlazarErrorToText(retCode)); return FALSE; } // TODO: Select CHB input parameters as required retCode = AlazarInputControl( boardHandle, // HANDLE -- board handle CHANNEL_B, // U8 -- channel identifier DC_COUPLING, // U32 -- input coupling id INPUT_RANGE_PM_800_MV, // U32 -- input range id IMPEDANCE_50_OHM // U32 -- input impedance id ); if (retCode != ApiSuccess) { printf("Error: AlazarInputControl failed -- %s\n", AlazarErrorToText(retCode)); return FALSE; } // TODO: Select CHB bandwidth limit as required retCode = AlazarSetBWLimit( boardHandle, // HANDLE -- board handle CHANNEL_B, // U8 -- channel identifier 0 // U32 -- 0 = disable, 1 = enable ); if (retCode != ApiSuccess) { printf("Error: AlazarSetBWLimit failed -- %s\n", AlazarErrorToText(retCode)); return FALSE; } // TODO: Select trigger inputs and levels as required retCode = AlazarSetTriggerOperation( boardHandle, // HANDLE -- board handle TRIG_ENGINE_OP_J, // U32 -- trigger operation TRIG_ENGINE_J, // U32 -- trigger engine id TRIG_CHAN_A, // U32 -- trigger source id TRIGGER_SLOPE_POSITIVE, // U32 -- trigger slope id 128, // U32 -- trigger level from 0 (-range) to 255 (+range) TRIG_ENGINE_K, // U32 -- trigger engine id TRIG_DISABLE, // U32 -- trigger source id for engine K TRIGGER_SLOPE_POSITIVE, // U32 -- trigger slope id 128 // U32 -- trigger level from 0 (-range) to 255 (+range) ); if (retCode != ApiSuccess) { printf("Error: AlazarSetTriggerOperation failed -- %s\n", AlazarErrorToText(retCode)); return FALSE; } // TODO: Select external trigger parameters as required retCode = AlazarSetExternalTrigger( boardHandle, // HANDLE -- board handle DC_COUPLING, // U32 -- external trigger coupling id ETR_5V // U32 -- external trigger range id ); // TODO: Set trigger delay as required. double triggerDelay_sec = 0.; U32 triggerDelay_samples = (U32) (triggerDelay_sec * SamplesPerSec + 0.5); retCode = AlazarSetTriggerDelay(boardHandle, triggerDelay_samples); if (retCode != ApiSuccess) { printf("Error: AlazarSetTriggerDelay failed -- %s\n", AlazarErrorToText(retCode)); return FALSE; } // TODO: Set trigger timeout as required. // NOTE: // The board will wait for a for this amount of time for a trigger event. // If a trigger event does not arrive, then the board will automatically // trigger. Set the trigger timeout value to 0 to force the board to wait // forever for a trigger event. // // IMPORTANT: // The trigger timeout value should be set to zero after appropriate // trigger parameters have been determined, otherwise the // board may trigger if the timeout interval expires before a // hardware trigger event arrives. double triggerTimeout_sec = 0.; U32 triggerTimeout_clocks = (U32) (triggerTimeout_sec / 10.e-6 + 0.5); retCode = AlazarSetTriggerTimeOut( boardHandle, // HANDLE -- board handle triggerTimeout_clocks // U32 -- timeout_sec / 10.e-6 (0 means wait forever) ); if (retCode != ApiSuccess) { printf("Error: AlazarSetTriggerTimeOut failed -- %s\n", AlazarErrorToText(retCode)); return FALSE; } // TODO: Configure AUX I/O connector as required retCode = AlazarConfigureAuxIO( boardHandle, // HANDLE -- board handle AUX_OUT_TRIGGER, // U32 -- mode 0 // U32 -- parameter ); if (retCode != ApiSuccess) { printf("Error: AlazarConfigureAuxIO failed -- %s\n", AlazarErrorToText(retCode)); return FALSE; } return TRUE; } //---------------------------------------------------------------------------- // // Function : AcquireData // // Description : Perform an acquisition, optionally saving data to file. // //---------------------------------------------------------------------------- BOOL AcquireData(HANDLE boardHandle) { // TODO: Select the total acquisition length in seconds double acquisitionLength_sec = 10.; // TODO: Select the number of samples in each DMA buffer U32 samplesPerBuffer = 1024 * 1024; // TODO: Select which channels to capture (A, B, or both) U32 channelMask = CHANNEL_A | CHANNEL_B; // TODO: Select if you wish to save the sample data to a file BOOL saveData = FALSE; // Calculate the number of enabled channels from the channel mask int channelCount = 0; switch (channelMask) { case CHANNEL_A: case CHANNEL_B: channelCount = 1; break; case CHANNEL_A | CHANNEL_B: channelCount = 2; break; default: printf("Error: Invalid channel mask %08X\n", channelMask); return FALSE; } // Get the sample size in bits, and the on-board memory size in samples per channel U8 bitsPerSample; U32 maxSamplesPerChannel; RETURN_CODE retCode = AlazarGetChannelInfo(boardHandle, &maxSamplesPerChannel, &bitsPerSample); if (retCode != ApiSuccess) { printf("Error: AlazarGetChannelInfo failed -- %s\n", AlazarErrorToText(retCode)); return FALSE; } // Calculate the size of each DMA buffer in bytes U32 bytesPerSample = (bitsPerSample + 7) / 8; U32 bytesPerBuffer = bytesPerSample * samplesPerBuffer * channelCount; // Calculate the number of buffers in the acquisition INT64 samplesPerAcquisition = (INT64) (SamplesPerSec * acquisitionLength_sec + 0.5); U32 buffersPerAcquisition = (U32) ((samplesPerAcquisition + samplesPerBuffer - 1) / samplesPerBuffer); // Create a data file if required HANDLE fileHandle = INVALID_HANDLE_VALUE; if (saveData) { char *fileName = "data.bin"; DWORD flagsAndAttributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING; fileHandle = CreateFile ( fileName, // lpFileName GENERIC_WRITE, // dwDesiredAccess 0, // dwShareMode NULL, // lpSecurityAttributes CREATE_ALWAYS, // dwCreateDisposition flagsAndAttributes, // dwFlagsAndAttributes NULL // hTemplateFile ); if (fileHandle == INVALID_HANDLE_VALUE) { printf("Error: Unable to create data file -- %u\n", GetLastError()); return FALSE; } } // Allocate memory for DMA buffers BOOL success = TRUE; U32 bufferIndex; for (bufferIndex = 0; (bufferIndex < BUFFER_COUNT) && (success == TRUE); bufferIndex++) { #ifdef _WIN32 // Allocate page aligned memory BufferArray[bufferIndex] = (U16*) VirtualAlloc(NULL, bytesPerBuffer, MEM_COMMIT, PAGE_READWRITE); #else BufferArray[bufferIndex] = (U16*) malloc(bytesPerBuffer); #endif if (BufferArray[bufferIndex] == NULL) { printf("Error: Alloc %u bytes failed\n", bytesPerBuffer); success = FALSE; } } // Configure the board to make an AutoDMA acquisition if (success) { U32 admaFlags = ADMA_EXTERNAL_STARTCAPTURE | // Start acquisition when AlazarStartCapture is called ADMA_TRIGGERED_STREAMING; // Acquire a continuous stream of sample data with trigger retCode = AlazarBeforeAsyncRead( boardHandle, // HANDLE -- board handle channelMask, // U32 -- enabled channel mask 0, // long -- offset from trigger in samples samplesPerBuffer, // U32 -- samples per buffer 1, // U32 -- records per buffer (must be 1) buffersPerAcquisition, // U32 -- records per acquisition admaFlags // U32 -- AutoDMA flags ); if (retCode != ApiSuccess) { printf("Error: AlazarBeforeAsyncRead failed -- %s\n", AlazarErrorToText(retCode)); success = FALSE; } } // Add the buffers to a list of buffers available to be filled by the board for (bufferIndex = 0; (bufferIndex < BUFFER_COUNT) && (success == TRUE); bufferIndex++) { U16* pBuffer = BufferArray[bufferIndex]; retCode = AlazarPostAsyncBuffer(boardHandle, pBuffer, bytesPerBuffer); if (retCode != ApiSuccess) { printf("Error: AlazarPostAsyncBuffer %d failed -- %s\n", bufferIndex, AlazarErrorToText(retCode)); success = FALSE; } } // Arm the board to begin the acquisition if (success) { retCode = AlazarStartCapture(boardHandle); if (retCode != ApiSuccess) { printf("Error: AlazarStartCapture failed -- %s\n", AlazarErrorToText(retCode)); success = FALSE; } } // Wait for each buffer to be filled, process the buffer, and re-post it to the board. if (success) { printf("Capturing %d buffers ... press any key to abort\n", buffersPerAcquisition); DWORD startTickCount = GetTickCount(); U32 buffersCompleted = 0; INT64 bytesTransferred = 0; while (buffersCompleted < buffersPerAcquisition) { // TODO: Set a buffer timeout that is longer than the time // required to capture all the records in one buffer. DWORD timeout_ms = 5000; // Wait for the buffer at the head of the list of available buffers // to be filled by the board. bufferIndex = buffersCompleted % BUFFER_COUNT; U16* pBuffer = BufferArray[bufferIndex]; retCode = AlazarWaitAsyncBufferComplete(boardHandle, pBuffer, timeout_ms); if (retCode != ApiSuccess) { printf("Error: AlazarWaitAsyncBufferComplete failed -- %s\n", AlazarErrorToText(retCode)); success = FALSE; } if (success) { // This buffer is full and has been removed from the list // of buffers available to the board. buffersCompleted++; bytesTransferred += bytesPerBuffer; // TODO: Process sample data in this buffer. // NOTE: // // While you are processing this buffer, the board is already // filling the next available buffer(s). // // You MUST finish processing this buffer and post it back to the // board before the board fills all of its available DMA buffers // and on-board memory. // // Records are arranged in the buffer as follows: R0A, R0B, // where Rxy is a segment of a single continuous record. // // Samples are arranged contiguously for each channel. // A 16-bit sample code occupies each 16-bit value in the record. // // Sample codes are unsigned by default. As a result: // - a sample code of 0x0000 represents a negative full scale input signal. // - a sample code of 0x8000 represents a ~0V signal. // - a sample code of 0xFFFF represents a positive full scale input signal. if (saveData) { // Write buffer to file // WARNING: // WriteFile will fail with error 87 (ERROR_INVALID_PARAMETER) // if number of bytes to write is not evenly divisible by the // number of bytes per sector on the destination volume. DWORD bytesWritten; if (!WriteFile(fileHandle, pBuffer, bytesPerBuffer, &bytesWritten, NULL)) { printf("Error: WriteFile failed with error %lu\n", GetLastError()); success = FALSE; } } } // Add the buffer to the end of the list of available buffers. if (success) { retCode = AlazarPostAsyncBuffer(boardHandle, pBuffer, bytesPerBuffer); if (retCode != ApiSuccess) { printf("Error: AlazarPostAsyncBuffer failed -- %s\n", AlazarErrorToText(retCode)); success = FALSE; } } // If the acquisition failed, exit the acquisition loop if (!success) break; // If a key was pressed, exit the acquisition loop if (_kbhit()) { printf("Aborted...\n"); break; } // Display progress printf("Completed %u buffers\r", buffersCompleted); } // Display results double transferTime_sec = (GetTickCount() - startTickCount) / 1000.; printf("Capture completed in %.2lf sec\n", transferTime_sec); double buffersPerSec; double bytesPerSec; if (transferTime_sec > 0.) { buffersPerSec = buffersCompleted / transferTime_sec; bytesPerSec = bytesTransferred / transferTime_sec; } else { buffersPerSec = 0.; bytesPerSec = 0.; } printf("Captured %d buffers (%.4g buffers per sec)\n", buffersCompleted, buffersPerSec); printf("Transferred %I64d bytes (%.4g bytes per sec)\n", bytesTransferred, bytesPerSec); } // Abort the acquisition retCode = AlazarAbortAsyncRead(boardHandle); if (retCode != ApiSuccess) { printf("Error: AlazarAbortAsyncRead failed -- %s\n", AlazarErrorToText(retCode)); success = FALSE; } // Free all memory allocated for (bufferIndex = 0; bufferIndex < BUFFER_COUNT; bufferIndex++) { if (BufferArray[bufferIndex] != NULL) { #ifdef _WIN32 VirtualFree(BufferArray[bufferIndex], 0, MEM_RELEASE); #else free(BufferArray[bufferIndex]); #endif } } // Close the data file if (fileHandle != INVALID_HANDLE_VALUE) CloseHandle(fileHandle); return success; }
28.647157
103
0.664351
TeravoxelTwoPhotonTomography
f6dc60900f2524d7d0f24c9bb20cee953ec4887e
93,050
cpp
C++
scene/resources/material.cpp
etalot/godot
d4c810a4b6a1f74971e4d588db0b60640e38aebe
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
1
2021-05-12T06:08:05.000Z
2021-05-12T06:08:05.000Z
scene/resources/material.cpp
Abd-Elrazek/godot
10e9221c49eddc05cb36c0b582060cac9e4c8cef
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
scene/resources/material.cpp
Abd-Elrazek/godot
10e9221c49eddc05cb36c0b582060cac9e4c8cef
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
/*************************************************************************/ /* material.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* 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 "material.h" #include "scene/scene_string_names.h" void Material::set_next_pass(const Ref<Material> &p_pass) { ERR_FAIL_COND(p_pass == this); if (next_pass == p_pass) return; next_pass = p_pass; RID next_pass_rid; if (next_pass.is_valid()) next_pass_rid = next_pass->get_rid(); VS::get_singleton()->material_set_next_pass(material, next_pass_rid); } Ref<Material> Material::get_next_pass() const { return next_pass; } void Material::set_render_priority(int p_priority) { ERR_FAIL_COND(p_priority < RENDER_PRIORITY_MIN); ERR_FAIL_COND(p_priority > RENDER_PRIORITY_MAX); render_priority = p_priority; VS::get_singleton()->material_set_render_priority(material, p_priority); } int Material::get_render_priority() const { return render_priority; } RID Material::get_rid() const { return material; } void Material::_validate_property(PropertyInfo &property) const { if (!_can_do_next_pass() && property.name == "next_pass") { property.usage = 0; } } void Material::_bind_methods() { ClassDB::bind_method(D_METHOD("set_next_pass", "next_pass"), &Material::set_next_pass); ClassDB::bind_method(D_METHOD("get_next_pass"), &Material::get_next_pass); ClassDB::bind_method(D_METHOD("set_render_priority", "priority"), &Material::set_render_priority); ClassDB::bind_method(D_METHOD("get_render_priority"), &Material::get_render_priority); ADD_PROPERTY(PropertyInfo(Variant::INT, "render_priority", PROPERTY_HINT_RANGE, itos(RENDER_PRIORITY_MIN) + "," + itos(RENDER_PRIORITY_MAX) + ",1"), "set_render_priority", "get_render_priority"); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "next_pass", PROPERTY_HINT_RESOURCE_TYPE, "Material"), "set_next_pass", "get_next_pass"); BIND_CONSTANT(RENDER_PRIORITY_MAX); BIND_CONSTANT(RENDER_PRIORITY_MIN); } Material::Material() { material = VisualServer::get_singleton()->material_create(); render_priority = 0; } Material::~Material() { VisualServer::get_singleton()->free(material); } /////////////////////////////////// bool ShaderMaterial::_set(const StringName &p_name, const Variant &p_value) { if (shader.is_valid()) { StringName pr = shader->remap_param(p_name); if (!pr) { String n = p_name; if (n.find("param/") == 0) { //backwards compatibility pr = n.substr(6, n.length()); } } if (pr) { VisualServer::get_singleton()->material_set_param(_get_material(), pr, p_value); return true; } } return false; } bool ShaderMaterial::_get(const StringName &p_name, Variant &r_ret) const { if (shader.is_valid()) { StringName pr = shader->remap_param(p_name); if (pr) { r_ret = VisualServer::get_singleton()->material_get_param(_get_material(), pr); return true; } } return false; } void ShaderMaterial::_get_property_list(List<PropertyInfo> *p_list) const { if (!shader.is_null()) { shader->get_param_list(p_list); } } bool ShaderMaterial::property_can_revert(const String &p_name) { if (shader.is_valid()) { StringName pr = shader->remap_param(p_name); if (pr) { Variant default_value = VisualServer::get_singleton()->material_get_param_default(_get_material(), pr); Variant current_value; _get(p_name, current_value); return default_value.get_type() != Variant::NIL && default_value != current_value; } } return false; } Variant ShaderMaterial::property_get_revert(const String &p_name) { Variant r_ret; if (shader.is_valid()) { StringName pr = shader->remap_param(p_name); if (pr) { r_ret = VisualServer::get_singleton()->material_get_param_default(_get_material(), pr); } } return r_ret; } void ShaderMaterial::set_shader(const Ref<Shader> &p_shader) { if (shader.is_valid()) { shader->disconnect("changed", this, "_shader_changed"); } shader = p_shader; RID rid; if (shader.is_valid()) { rid = shader->get_rid(); shader->connect("changed", this, "_shader_changed"); } VS::get_singleton()->material_set_shader(_get_material(), rid); _change_notify(); //properties for shader exposed emit_changed(); } Ref<Shader> ShaderMaterial::get_shader() const { return shader; } void ShaderMaterial::set_shader_param(const StringName &p_param, const Variant &p_value) { VS::get_singleton()->material_set_param(_get_material(), p_param, p_value); } Variant ShaderMaterial::get_shader_param(const StringName &p_param) const { return VS::get_singleton()->material_get_param(_get_material(), p_param); } void ShaderMaterial::_shader_changed() { _change_notify(); //update all properties } void ShaderMaterial::_bind_methods() { ClassDB::bind_method(D_METHOD("set_shader", "shader"), &ShaderMaterial::set_shader); ClassDB::bind_method(D_METHOD("get_shader"), &ShaderMaterial::get_shader); ClassDB::bind_method(D_METHOD("set_shader_param", "param", "value"), &ShaderMaterial::set_shader_param); ClassDB::bind_method(D_METHOD("get_shader_param", "param"), &ShaderMaterial::get_shader_param); ClassDB::bind_method(D_METHOD("_shader_changed"), &ShaderMaterial::_shader_changed); ClassDB::bind_method(D_METHOD("property_can_revert", "name"), &ShaderMaterial::property_can_revert); ClassDB::bind_method(D_METHOD("property_get_revert", "name"), &ShaderMaterial::property_get_revert); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "shader", PROPERTY_HINT_RESOURCE_TYPE, "Shader"), "set_shader", "get_shader"); } void ShaderMaterial::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const { String f = p_function.operator String(); if ((f == "get_shader_param" || f == "set_shader_param") && p_idx == 0) { if (shader.is_valid()) { List<PropertyInfo> pl; shader->get_param_list(&pl); for (List<PropertyInfo>::Element *E = pl.front(); E; E = E->next()) { r_options->push_back("\"" + E->get().name.replace_first("shader_param/", "") + "\""); } } } Resource::get_argument_options(p_function, p_idx, r_options); } bool ShaderMaterial::_can_do_next_pass() const { return shader.is_valid() && shader->get_mode() == Shader::MODE_SPATIAL; } Shader::Mode ShaderMaterial::get_shader_mode() const { if (shader.is_valid()) return shader->get_mode(); else return Shader::MODE_SPATIAL; } ShaderMaterial::ShaderMaterial() { } ShaderMaterial::~ShaderMaterial() { } ///////////////////////////////// Mutex *SpatialMaterial::material_mutex = NULL; SelfList<SpatialMaterial>::List *SpatialMaterial::dirty_materials = NULL; Map<SpatialMaterial::MaterialKey, SpatialMaterial::ShaderData> SpatialMaterial::shader_map; SpatialMaterial::ShaderNames *SpatialMaterial::shader_names = NULL; void SpatialMaterial::init_shaders() { #ifndef NO_THREADS material_mutex = Mutex::create(); #endif dirty_materials = memnew(SelfList<SpatialMaterial>::List); shader_names = memnew(ShaderNames); shader_names->albedo = "albedo"; shader_names->specular = "specular"; shader_names->roughness = "roughness"; shader_names->metallic = "metallic"; shader_names->emission = "emission"; shader_names->emission_energy = "emission_energy"; shader_names->normal_scale = "normal_scale"; shader_names->rim = "rim"; shader_names->rim_tint = "rim_tint"; shader_names->clearcoat = "clearcoat"; shader_names->clearcoat_gloss = "clearcoat_gloss"; shader_names->anisotropy = "anisotropy_ratio"; shader_names->depth_scale = "depth_scale"; shader_names->subsurface_scattering_strength = "subsurface_scattering_strength"; shader_names->transmission = "transmission"; shader_names->refraction = "refraction"; shader_names->point_size = "point_size"; shader_names->uv1_scale = "uv1_scale"; shader_names->uv1_offset = "uv1_offset"; shader_names->uv2_scale = "uv2_scale"; shader_names->uv2_offset = "uv2_offset"; shader_names->uv1_blend_sharpness = "uv1_blend_sharpness"; shader_names->uv2_blend_sharpness = "uv2_blend_sharpness"; shader_names->particles_anim_h_frames = "particles_anim_h_frames"; shader_names->particles_anim_v_frames = "particles_anim_v_frames"; shader_names->particles_anim_loop = "particles_anim_loop"; shader_names->depth_min_layers = "depth_min_layers"; shader_names->depth_max_layers = "depth_max_layers"; shader_names->depth_flip = "depth_flip"; shader_names->grow = "grow"; shader_names->ao_light_affect = "ao_light_affect"; shader_names->proximity_fade_distance = "proximity_fade_distance"; shader_names->distance_fade_min = "distance_fade_min"; shader_names->distance_fade_max = "distance_fade_max"; shader_names->metallic_texture_channel = "metallic_texture_channel"; shader_names->roughness_texture_channel = "roughness_texture_channel"; shader_names->ao_texture_channel = "ao_texture_channel"; shader_names->clearcoat_texture_channel = "clearcoat_texture_channel"; shader_names->rim_texture_channel = "rim_texture_channel"; shader_names->depth_texture_channel = "depth_texture_channel"; shader_names->refraction_texture_channel = "refraction_texture_channel"; shader_names->alpha_scissor_threshold = "alpha_scissor_threshold"; shader_names->texture_names[TEXTURE_ALBEDO] = "texture_albedo"; shader_names->texture_names[TEXTURE_METALLIC] = "texture_metallic"; shader_names->texture_names[TEXTURE_ROUGHNESS] = "texture_roughness"; shader_names->texture_names[TEXTURE_EMISSION] = "texture_emission"; shader_names->texture_names[TEXTURE_NORMAL] = "texture_normal"; shader_names->texture_names[TEXTURE_RIM] = "texture_rim"; shader_names->texture_names[TEXTURE_CLEARCOAT] = "texture_clearcoat"; shader_names->texture_names[TEXTURE_FLOWMAP] = "texture_flowmap"; shader_names->texture_names[TEXTURE_AMBIENT_OCCLUSION] = "texture_ambient_occlusion"; shader_names->texture_names[TEXTURE_DEPTH] = "texture_depth"; shader_names->texture_names[TEXTURE_SUBSURFACE_SCATTERING] = "texture_subsurface_scattering"; shader_names->texture_names[TEXTURE_TRANSMISSION] = "texture_transmission"; shader_names->texture_names[TEXTURE_REFRACTION] = "texture_refraction"; shader_names->texture_names[TEXTURE_DETAIL_MASK] = "texture_detail_mask"; shader_names->texture_names[TEXTURE_DETAIL_ALBEDO] = "texture_detail_albedo"; shader_names->texture_names[TEXTURE_DETAIL_NORMAL] = "texture_detail_normal"; } Ref<SpatialMaterial> SpatialMaterial::materials_for_2d[SpatialMaterial::MAX_MATERIALS_FOR_2D]; void SpatialMaterial::finish_shaders() { for (int i = 0; i < MAX_MATERIALS_FOR_2D; i++) { materials_for_2d[i].unref(); } #ifndef NO_THREADS memdelete(material_mutex); #endif memdelete(dirty_materials); dirty_materials = NULL; memdelete(shader_names); } void SpatialMaterial::_update_shader() { dirty_materials->remove(&element); MaterialKey mk = _compute_key(); if (mk.key == current_key.key) return; //no update required in the end if (shader_map.has(current_key)) { shader_map[current_key].users--; if (shader_map[current_key].users == 0) { //deallocate shader, as it's no longer in use VS::get_singleton()->free(shader_map[current_key].shader); shader_map.erase(current_key); } } current_key = mk; if (shader_map.has(mk)) { VS::get_singleton()->material_set_shader(_get_material(), shader_map[mk].shader); shader_map[mk].users++; return; } //must create a shader! String code = "shader_type spatial;\nrender_mode "; switch (blend_mode) { case BLEND_MODE_MIX: code += "blend_mix"; break; case BLEND_MODE_ADD: code += "blend_add"; break; case BLEND_MODE_SUB: code += "blend_sub"; break; case BLEND_MODE_MUL: code += "blend_mul"; break; } DepthDrawMode ddm = depth_draw_mode; if (features[FEATURE_REFRACTION]) { ddm = DEPTH_DRAW_ALWAYS; } switch (ddm) { case DEPTH_DRAW_OPAQUE_ONLY: code += ",depth_draw_opaque"; break; case DEPTH_DRAW_ALWAYS: code += ",depth_draw_always"; break; case DEPTH_DRAW_DISABLED: code += ",depth_draw_never"; break; case DEPTH_DRAW_ALPHA_OPAQUE_PREPASS: code += ",depth_draw_alpha_prepass"; break; } switch (cull_mode) { case CULL_BACK: code += ",cull_back"; break; case CULL_FRONT: code += ",cull_front"; break; case CULL_DISABLED: code += ",cull_disabled"; break; } switch (diffuse_mode) { case DIFFUSE_BURLEY: code += ",diffuse_burley"; break; case DIFFUSE_LAMBERT: code += ",diffuse_lambert"; break; case DIFFUSE_LAMBERT_WRAP: code += ",diffuse_lambert_wrap"; break; case DIFFUSE_OREN_NAYAR: code += ",diffuse_oren_nayar"; break; case DIFFUSE_TOON: code += ",diffuse_toon"; break; } switch (specular_mode) { case SPECULAR_SCHLICK_GGX: code += ",specular_schlick_ggx"; break; case SPECULAR_BLINN: code += ",specular_blinn"; break; case SPECULAR_PHONG: code += ",specular_phong"; break; case SPECULAR_TOON: code += ",specular_toon"; break; case SPECULAR_DISABLED: code += ",specular_disabled"; break; } if (flags[FLAG_UNSHADED]) { code += ",unshaded"; } if (flags[FLAG_DISABLE_DEPTH_TEST]) { code += ",depth_test_disable"; } if (flags[FLAG_USE_VERTEX_LIGHTING]) { code += ",vertex_lighting"; } if (flags[FLAG_TRIPLANAR_USE_WORLD] && (flags[FLAG_UV1_USE_TRIPLANAR] || flags[FLAG_UV2_USE_TRIPLANAR])) { code += ",world_vertex_coords"; } if (flags[FLAG_DONT_RECEIVE_SHADOWS]) { code += ",shadows_disabled"; } if (flags[FLAG_DISABLE_AMBIENT_LIGHT]) { code += ",ambient_light_disabled"; } if (flags[FLAG_ENSURE_CORRECT_NORMALS]) { code += ",ensure_correct_normals"; } code += ";\n"; code += "uniform vec4 albedo : hint_color;\n"; code += "uniform sampler2D texture_albedo : hint_albedo;\n"; code += "uniform float specular;\n"; code += "uniform float metallic;\n"; if (grow_enabled) { code += "uniform float grow;\n"; } if (proximity_fade_enabled) { code += "uniform float proximity_fade_distance;\n"; } if (distance_fade != DISTANCE_FADE_DISABLED) { code += "uniform float distance_fade_min;\n"; code += "uniform float distance_fade_max;\n"; } if (flags[FLAG_USE_ALPHA_SCISSOR]) { code += "uniform float alpha_scissor_threshold;\n"; } code += "uniform float roughness : hint_range(0,1);\n"; code += "uniform float point_size : hint_range(0,128);\n"; code += "uniform sampler2D texture_metallic : hint_white;\n"; code += "uniform vec4 metallic_texture_channel;\n"; code += "uniform sampler2D texture_roughness : hint_white;\n"; code += "uniform vec4 roughness_texture_channel;\n"; if (billboard_mode == BILLBOARD_PARTICLES) { code += "uniform int particles_anim_h_frames;\n"; code += "uniform int particles_anim_v_frames;\n"; code += "uniform bool particles_anim_loop;\n"; } if (features[FEATURE_EMISSION]) { code += "uniform sampler2D texture_emission : hint_black_albedo;\n"; code += "uniform vec4 emission : hint_color;\n"; code += "uniform float emission_energy;\n"; } if (features[FEATURE_REFRACTION]) { code += "uniform sampler2D texture_refraction;\n"; code += "uniform float refraction : hint_range(-16,16);\n"; code += "uniform vec4 refraction_texture_channel;\n"; } if (features[FEATURE_NORMAL_MAPPING]) { code += "uniform sampler2D texture_normal : hint_normal;\n"; code += "uniform float normal_scale : hint_range(-16,16);\n"; } if (features[FEATURE_RIM]) { code += "uniform float rim : hint_range(0,1);\n"; code += "uniform float rim_tint : hint_range(0,1);\n"; code += "uniform sampler2D texture_rim : hint_white;\n"; } if (features[FEATURE_CLEARCOAT]) { code += "uniform float clearcoat : hint_range(0,1);\n"; code += "uniform float clearcoat_gloss : hint_range(0,1);\n"; code += "uniform sampler2D texture_clearcoat : hint_white;\n"; } if (features[FEATURE_ANISOTROPY]) { code += "uniform float anisotropy_ratio : hint_range(0,256);\n"; code += "uniform sampler2D texture_flowmap : hint_aniso;\n"; } if (features[FEATURE_AMBIENT_OCCLUSION]) { code += "uniform sampler2D texture_ambient_occlusion : hint_white;\n"; code += "uniform vec4 ao_texture_channel;\n"; code += "uniform float ao_light_affect;\n"; } if (features[FEATURE_DETAIL]) { code += "uniform sampler2D texture_detail_albedo : hint_albedo;\n"; code += "uniform sampler2D texture_detail_normal : hint_normal;\n"; code += "uniform sampler2D texture_detail_mask : hint_white;\n"; } if (features[FEATURE_SUBSURACE_SCATTERING]) { code += "uniform float subsurface_scattering_strength : hint_range(0,1);\n"; code += "uniform sampler2D texture_subsurface_scattering : hint_white;\n"; } if (features[FEATURE_TRANSMISSION]) { code += "uniform vec4 transmission : hint_color;\n"; code += "uniform sampler2D texture_transmission : hint_black;\n"; } if (features[FEATURE_DEPTH_MAPPING]) { code += "uniform sampler2D texture_depth : hint_black;\n"; code += "uniform float depth_scale;\n"; code += "uniform int depth_min_layers;\n"; code += "uniform int depth_max_layers;\n"; code += "uniform vec2 depth_flip;\n"; } if (flags[FLAG_UV1_USE_TRIPLANAR]) { code += "varying vec3 uv1_triplanar_pos;\n"; } if (flags[FLAG_UV2_USE_TRIPLANAR]) { code += "varying vec3 uv2_triplanar_pos;\n"; } if (flags[FLAG_UV1_USE_TRIPLANAR]) { code += "uniform float uv1_blend_sharpness;\n"; code += "varying vec3 uv1_power_normal;\n"; } if (flags[FLAG_UV2_USE_TRIPLANAR]) { code += "uniform float uv2_blend_sharpness;\n"; code += "varying vec3 uv2_power_normal;\n"; } code += "uniform vec3 uv1_scale;\n"; code += "uniform vec3 uv1_offset;\n"; code += "uniform vec3 uv2_scale;\n"; code += "uniform vec3 uv2_offset;\n"; code += "\n\n"; code += "void vertex() {\n"; if (flags[FLAG_SRGB_VERTEX_COLOR]) { code += "\tif (!OUTPUT_IS_SRGB) {\n"; code += "\t\tCOLOR.rgb = mix( pow((COLOR.rgb + vec3(0.055)) * (1.0 / (1.0 + 0.055)), vec3(2.4)), COLOR.rgb* (1.0 / 12.92), lessThan(COLOR.rgb,vec3(0.04045)) );\n"; code += "\t}\n"; } if (flags[FLAG_USE_POINT_SIZE]) { code += "\tPOINT_SIZE=point_size;\n"; } if (flags[FLAG_USE_VERTEX_LIGHTING]) { code += "\tROUGHNESS=roughness;\n"; } if (!flags[FLAG_UV1_USE_TRIPLANAR]) { code += "\tUV=UV*uv1_scale.xy+uv1_offset.xy;\n"; } switch (billboard_mode) { case BILLBOARD_DISABLED: { } break; case BILLBOARD_ENABLED: { code += "\tMODELVIEW_MATRIX = INV_CAMERA_MATRIX * mat4(CAMERA_MATRIX[0],CAMERA_MATRIX[1],CAMERA_MATRIX[2],WORLD_MATRIX[3]);\n"; if (flags[FLAG_BILLBOARD_KEEP_SCALE]) { code += "\tMODELVIEW_MATRIX = MODELVIEW_MATRIX * mat4(vec4(length(WORLD_MATRIX[0].xyz),0,0,0),vec4(0,length(WORLD_MATRIX[1].xyz),0,0),vec4(0,0,length(WORLD_MATRIX[2].xyz),0),vec4(0,0,0,1));\n"; } } break; case BILLBOARD_FIXED_Y: { code += "\tMODELVIEW_MATRIX = INV_CAMERA_MATRIX * mat4(CAMERA_MATRIX[0],WORLD_MATRIX[1],vec4(normalize(cross(CAMERA_MATRIX[0].xyz,WORLD_MATRIX[1].xyz)),0.0),WORLD_MATRIX[3]);\n"; if (flags[FLAG_BILLBOARD_KEEP_SCALE]) { code += "\tMODELVIEW_MATRIX = MODELVIEW_MATRIX * mat4(vec4(length(WORLD_MATRIX[0].xyz),0,0,0),vec4(0,1,0,0),vec4(0,0,length(WORLD_MATRIX[2].xyz),0),vec4(0,0,0,1));\n"; } else { code += "\tMODELVIEW_MATRIX = MODELVIEW_MATRIX * mat4(vec4(1,0,0,0),vec4(0,1.0/length(WORLD_MATRIX[1].xyz),0,0),vec4(0,0,1,0),vec4(0,0,0,1));\n"; } } break; case BILLBOARD_PARTICLES: { //make billboard code += "\tmat4 mat_world = mat4(normalize(CAMERA_MATRIX[0])*length(WORLD_MATRIX[0]),normalize(CAMERA_MATRIX[1])*length(WORLD_MATRIX[0]),normalize(CAMERA_MATRIX[2])*length(WORLD_MATRIX[2]),WORLD_MATRIX[3]);\n"; //rotate by rotation code += "\tmat_world = mat_world * mat4( vec4(cos(INSTANCE_CUSTOM.x),-sin(INSTANCE_CUSTOM.x),0.0,0.0), vec4(sin(INSTANCE_CUSTOM.x),cos(INSTANCE_CUSTOM.x),0.0,0.0),vec4(0.0,0.0,1.0,0.0),vec4(0.0,0.0,0.0,1.0));\n"; //set modelview code += "\tMODELVIEW_MATRIX = INV_CAMERA_MATRIX * mat_world;\n"; //handle animation code += "\tfloat particle_total_frames = float(particles_anim_h_frames * particles_anim_v_frames);\n"; code += "\tfloat particle_frame = floor(INSTANCE_CUSTOM.z * float(particle_total_frames));\n"; code += "\tif (!particles_anim_loop) particle_frame=clamp(particle_frame,0.0,particle_total_frames-1.0); else particle_frame=mod(particle_frame,float(particle_total_frames));\n"; code += "\tUV /= vec2(float(particles_anim_h_frames),float(particles_anim_v_frames));\n"; code += "\tUV += vec2(mod(particle_frame,float(particles_anim_h_frames)) / float(particles_anim_h_frames), floor(particle_frame / float(particles_anim_h_frames)) / float(particles_anim_v_frames));\n"; } break; } if (flags[FLAG_FIXED_SIZE]) { code += "\tif (PROJECTION_MATRIX[3][3] != 0.0) {\n"; //orthogonal matrix, try to do about the same //with viewport size code += "\t\tfloat h = abs(1.0 / (2.0 * PROJECTION_MATRIX[1][1]));\n"; code += "\t\tfloat sc = (h * 2.0); //consistent with Y-fov\n"; code += "\t\tMODELVIEW_MATRIX[0]*=sc;\n"; code += "\t\tMODELVIEW_MATRIX[1]*=sc;\n"; code += "\t\tMODELVIEW_MATRIX[2]*=sc;\n"; code += "\t} else {\n"; //just scale by depth code += "\t\tfloat sc = -(MODELVIEW_MATRIX)[3].z;\n"; code += "\t\tMODELVIEW_MATRIX[0]*=sc;\n"; code += "\t\tMODELVIEW_MATRIX[1]*=sc;\n"; code += "\t\tMODELVIEW_MATRIX[2]*=sc;\n"; code += "\t}\n"; } if (detail_uv == DETAIL_UV_2 && !flags[FLAG_UV2_USE_TRIPLANAR]) { code += "\tUV2=UV2*uv2_scale.xy+uv2_offset.xy;\n"; } if (flags[FLAG_UV1_USE_TRIPLANAR] || flags[FLAG_UV2_USE_TRIPLANAR]) { //generate tangent and binormal in world space code += "\tTANGENT = vec3(0.0,0.0,-1.0) * abs(NORMAL.x);\n"; code += "\tTANGENT+= vec3(1.0,0.0,0.0) * abs(NORMAL.y);\n"; code += "\tTANGENT+= vec3(1.0,0.0,0.0) * abs(NORMAL.z);\n"; code += "\tTANGENT = normalize(TANGENT);\n"; code += "\tBINORMAL = vec3(0.0,1.0,0.0) * abs(NORMAL.x);\n"; code += "\tBINORMAL+= vec3(0.0,0.0,-1.0) * abs(NORMAL.y);\n"; code += "\tBINORMAL+= vec3(0.0,1.0,0.0) * abs(NORMAL.z);\n"; code += "\tBINORMAL = normalize(BINORMAL);\n"; } if (flags[FLAG_UV1_USE_TRIPLANAR]) { code += "\tuv1_power_normal=pow(abs(NORMAL),vec3(uv1_blend_sharpness));\n"; code += "\tuv1_power_normal/=dot(uv1_power_normal,vec3(1.0));\n"; code += "\tuv1_triplanar_pos = VERTEX * uv1_scale + uv1_offset;\n"; code += "\tuv1_triplanar_pos *= vec3(1.0,-1.0, 1.0);\n"; } if (flags[FLAG_UV2_USE_TRIPLANAR]) { code += "\tuv2_power_normal=pow(abs(NORMAL), vec3(uv2_blend_sharpness));\n"; code += "\tuv2_power_normal/=dot(uv2_power_normal,vec3(1.0));\n"; code += "\tuv2_triplanar_pos = VERTEX * uv2_scale + uv2_offset;\n"; code += "\tuv2_triplanar_pos *= vec3(1.0,-1.0, 1.0);\n"; } if (grow_enabled) { code += "\tVERTEX+=NORMAL*grow;\n"; } code += "}\n"; code += "\n\n"; if (flags[FLAG_UV1_USE_TRIPLANAR] || flags[FLAG_UV2_USE_TRIPLANAR]) { code += "vec4 triplanar_texture(sampler2D p_sampler,vec3 p_weights,vec3 p_triplanar_pos) {\n"; code += "\tvec4 samp=vec4(0.0);\n"; code += "\tsamp+= texture(p_sampler,p_triplanar_pos.xy) * p_weights.z;\n"; code += "\tsamp+= texture(p_sampler,p_triplanar_pos.xz) * p_weights.y;\n"; code += "\tsamp+= texture(p_sampler,p_triplanar_pos.zy * vec2(-1.0,1.0)) * p_weights.x;\n"; code += "\treturn samp;\n"; code += "}\n"; } code += "\n\n"; code += "void fragment() {\n"; if (!flags[FLAG_UV1_USE_TRIPLANAR]) { code += "\tvec2 base_uv = UV;\n"; } if ((features[FEATURE_DETAIL] && detail_uv == DETAIL_UV_2) || (features[FEATURE_AMBIENT_OCCLUSION] && flags[FLAG_AO_ON_UV2]) || (features[FEATURE_EMISSION] && flags[FLAG_EMISSION_ON_UV2])) { code += "\tvec2 base_uv2 = UV2;\n"; } if (features[FEATURE_DEPTH_MAPPING] && !flags[FLAG_UV1_USE_TRIPLANAR]) { //depthmap not supported with triplanar code += "\t{\n"; code += "\t\tvec3 view_dir = normalize(normalize(-VERTEX)*mat3(TANGENT*depth_flip.x,-BINORMAL*depth_flip.y,NORMAL));\n"; // binormal is negative due to mikktspace, flip 'unflips' it ;-) if (deep_parallax) { code += "\t\tfloat num_layers = mix(float(depth_max_layers),float(depth_min_layers), abs(dot(vec3(0.0, 0.0, 1.0), view_dir)));\n"; code += "\t\tfloat layer_depth = 1.0 / num_layers;\n"; code += "\t\tfloat current_layer_depth = 0.0;\n"; code += "\t\tvec2 P = view_dir.xy * depth_scale;\n"; code += "\t\tvec2 delta = P / num_layers;\n"; code += "\t\tvec2 ofs = base_uv;\n"; code += "\t\tfloat depth = textureLod(texture_depth, ofs,0.0).r;\n"; code += "\t\tfloat current_depth = 0.0;\n"; code += "\t\twhile(current_depth < depth) {\n"; code += "\t\t\tofs -= delta;\n"; code += "\t\t\tdepth = textureLod(texture_depth, ofs,0.0).r;\n"; code += "\t\t\tcurrent_depth += layer_depth;\n"; code += "\t\t}\n"; code += "\t\tvec2 prev_ofs = ofs + delta;\n"; code += "\t\tfloat after_depth = depth - current_depth;\n"; code += "\t\tfloat before_depth = textureLod(texture_depth, prev_ofs, 0.0).r - current_depth + layer_depth;\n"; code += "\t\tfloat weight = after_depth / (after_depth - before_depth);\n"; code += "\t\tofs = mix(ofs,prev_ofs,weight);\n"; } else { code += "\t\tfloat depth = texture(texture_depth, base_uv).r;\n"; code += "\t\tvec2 ofs = base_uv - view_dir.xy / view_dir.z * (depth * depth_scale);\n"; } code += "\t\tbase_uv=ofs;\n"; if (features[FEATURE_DETAIL] && detail_uv == DETAIL_UV_2) { code += "\t\tbase_uv2-=ofs;\n"; } code += "\t}\n"; } if (flags[FLAG_USE_POINT_SIZE]) { code += "\tvec4 albedo_tex = texture(texture_albedo,POINT_COORD);\n"; } else { if (flags[FLAG_UV1_USE_TRIPLANAR]) { code += "\tvec4 albedo_tex = triplanar_texture(texture_albedo,uv1_power_normal,uv1_triplanar_pos);\n"; } else { code += "\tvec4 albedo_tex = texture(texture_albedo,base_uv);\n"; } } if (flags[FLAG_ALBEDO_TEXTURE_FORCE_SRGB]) { code += "\talbedo_tex.rgb = mix(pow((albedo_tex.rgb + vec3(0.055)) * (1.0 / (1.0 + 0.055)),vec3(2.4)),albedo_tex.rgb.rgb * (1.0 / 12.92),lessThan(albedo_tex.rgb,vec3(0.04045)));\n"; } if (flags[FLAG_ALBEDO_FROM_VERTEX_COLOR]) { code += "\talbedo_tex *= COLOR;\n"; } code += "\tALBEDO = albedo.rgb * albedo_tex.rgb;\n"; if (flags[FLAG_UV1_USE_TRIPLANAR]) { code += "\tfloat metallic_tex = dot(triplanar_texture(texture_metallic,uv1_power_normal,uv1_triplanar_pos),metallic_texture_channel);\n"; } else { code += "\tfloat metallic_tex = dot(texture(texture_metallic,base_uv),metallic_texture_channel);\n"; } code += "\tMETALLIC = metallic_tex * metallic;\n"; if (flags[FLAG_UV1_USE_TRIPLANAR]) { code += "\tfloat roughness_tex = dot(triplanar_texture(texture_roughness,uv1_power_normal,uv1_triplanar_pos),roughness_texture_channel);\n"; } else { code += "\tfloat roughness_tex = dot(texture(texture_roughness,base_uv),roughness_texture_channel);\n"; } code += "\tROUGHNESS = roughness_tex * roughness;\n"; code += "\tSPECULAR = specular;\n"; if (features[FEATURE_NORMAL_MAPPING]) { if (flags[FLAG_UV1_USE_TRIPLANAR]) { code += "\tNORMALMAP = triplanar_texture(texture_normal,uv1_power_normal,uv1_triplanar_pos).rgb;\n"; } else { code += "\tNORMALMAP = texture(texture_normal,base_uv).rgb;\n"; } code += "\tNORMALMAP_DEPTH = normal_scale;\n"; } if (features[FEATURE_EMISSION]) { if (flags[FLAG_EMISSION_ON_UV2]) { if (flags[FLAG_UV2_USE_TRIPLANAR]) { code += "\tvec3 emission_tex = triplanar_texture(texture_emission,uv2_power_normal,uv2_triplanar_pos).rgb;\n"; } else { code += "\tvec3 emission_tex = texture(texture_emission,base_uv2).rgb;\n"; } } else { if (flags[FLAG_UV1_USE_TRIPLANAR]) { code += "\tvec3 emission_tex = triplanar_texture(texture_emission,uv1_power_normal,uv1_triplanar_pos).rgb;\n"; } else { code += "\tvec3 emission_tex = texture(texture_emission,base_uv).rgb;\n"; } } if (emission_op == EMISSION_OP_ADD) { code += "\tEMISSION = (emission.rgb+emission_tex)*emission_energy;\n"; } else { code += "\tEMISSION = (emission.rgb*emission_tex)*emission_energy;\n"; } } if (features[FEATURE_REFRACTION]) { if (features[FEATURE_NORMAL_MAPPING]) { code += "\tvec3 ref_normal = normalize( mix(NORMAL,TANGENT * NORMALMAP.x + BINORMAL * NORMALMAP.y + NORMAL * NORMALMAP.z,NORMALMAP_DEPTH) );\n"; } else { code += "\tvec3 ref_normal = NORMAL;\n"; } if (flags[FLAG_UV1_USE_TRIPLANAR]) { code += "\tvec2 ref_ofs = SCREEN_UV - ref_normal.xy * dot(triplanar_texture(texture_refraction,uv1_power_normal,uv1_triplanar_pos),refraction_texture_channel) * refraction;\n"; } else { code += "\tvec2 ref_ofs = SCREEN_UV - ref_normal.xy * dot(texture(texture_refraction,base_uv),refraction_texture_channel) * refraction;\n"; } code += "\tfloat ref_amount = 1.0 - albedo.a * albedo_tex.a;\n"; code += "\tEMISSION += textureLod(SCREEN_TEXTURE,ref_ofs,ROUGHNESS * 8.0).rgb * ref_amount;\n"; code += "\tALBEDO *= 1.0 - ref_amount;\n"; code += "\tALPHA = 1.0;\n"; } else if (features[FEATURE_TRANSPARENT] || flags[FLAG_USE_ALPHA_SCISSOR] || (distance_fade == DISTANCE_FADE_PIXEL_ALPHA) || proximity_fade_enabled) { code += "\tALPHA = albedo.a * albedo_tex.a;\n"; } if (!VisualServer::get_singleton()->is_low_end() && proximity_fade_enabled) { code += "\tfloat depth_tex = textureLod(DEPTH_TEXTURE,SCREEN_UV,0.0).r;\n"; code += "\tvec4 world_pos = INV_PROJECTION_MATRIX * vec4(SCREEN_UV*2.0-1.0,depth_tex*2.0-1.0,1.0);\n"; code += "\tworld_pos.xyz/=world_pos.w;\n"; code += "\tALPHA*=clamp(1.0-smoothstep(world_pos.z+proximity_fade_distance,world_pos.z,VERTEX.z),0.0,1.0);\n"; } if (distance_fade != DISTANCE_FADE_DISABLED) { if ((distance_fade == DISTANCE_FADE_OBJECT_DITHER || distance_fade == DISTANCE_FADE_PIXEL_DITHER)) { if (!VisualServer::get_singleton()->is_low_end()) { code += "\t{\n"; if (distance_fade == DISTANCE_FADE_OBJECT_DITHER) { code += "\t\tfloat fade_distance = abs((INV_CAMERA_MATRIX * WORLD_MATRIX[3]).z);\n"; } else { code += "\t\tfloat fade_distance=-VERTEX.z;\n"; } code += "\t\tfloat fade=clamp(smoothstep(distance_fade_min,distance_fade_max,fade_distance),0.0,1.0);\n"; code += "\t\tint x = int(FRAGCOORD.x) % 4;\n"; code += "\t\tint y = int(FRAGCOORD.y) % 4;\n"; code += "\t\tint index = x + y * 4;\n"; code += "\t\tfloat limit = 0.0;\n\n"; code += "\t\tif (x < 8) {\n"; code += "\t\t\tif (index == 0) limit = 0.0625;\n"; code += "\t\t\tif (index == 1) limit = 0.5625;\n"; code += "\t\t\tif (index == 2) limit = 0.1875;\n"; code += "\t\t\tif (index == 3) limit = 0.6875;\n"; code += "\t\t\tif (index == 4) limit = 0.8125;\n"; code += "\t\t\tif (index == 5) limit = 0.3125;\n"; code += "\t\t\tif (index == 6) limit = 0.9375;\n"; code += "\t\t\tif (index == 7) limit = 0.4375;\n"; code += "\t\t\tif (index == 8) limit = 0.25;\n"; code += "\t\t\tif (index == 9) limit = 0.75;\n"; code += "\t\t\tif (index == 10) limit = 0.125;\n"; code += "\t\t\tif (index == 11) limit = 0.625;\n"; code += "\t\t\tif (index == 12) limit = 1.0;\n"; code += "\t\t\tif (index == 13) limit = 0.5;\n"; code += "\t\t\tif (index == 14) limit = 0.875;\n"; code += "\t\t\tif (index == 15) limit = 0.375;\n"; code += "\t\t}\n\n"; code += "\tif (fade < limit)\n"; code += "\t\tdiscard;\n"; code += "\t}\n\n"; } } else { code += "\tALPHA*=clamp(smoothstep(distance_fade_min,distance_fade_max,-VERTEX.z),0.0,1.0);\n"; } } if (features[FEATURE_RIM]) { if (flags[FLAG_UV1_USE_TRIPLANAR]) { code += "\tvec2 rim_tex = triplanar_texture(texture_rim,uv1_power_normal,uv1_triplanar_pos).xy;\n"; } else { code += "\tvec2 rim_tex = texture(texture_rim,base_uv).xy;\n"; } code += "\tRIM = rim*rim_tex.x;"; code += "\tRIM_TINT = rim_tint*rim_tex.y;\n"; } if (features[FEATURE_CLEARCOAT]) { if (flags[FLAG_UV1_USE_TRIPLANAR]) { code += "\tvec2 clearcoat_tex = triplanar_texture(texture_clearcoat,uv1_power_normal,uv1_triplanar_pos).xy;\n"; } else { code += "\tvec2 clearcoat_tex = texture(texture_clearcoat,base_uv).xy;\n"; } code += "\tCLEARCOAT = clearcoat*clearcoat_tex.x;"; code += "\tCLEARCOAT_GLOSS = clearcoat_gloss*clearcoat_tex.y;\n"; } if (features[FEATURE_ANISOTROPY]) { if (flags[FLAG_UV1_USE_TRIPLANAR]) { code += "\tvec3 anisotropy_tex = triplanar_texture(texture_flowmap,uv1_power_normal,uv1_triplanar_pos).rga;\n"; } else { code += "\tvec3 anisotropy_tex = texture(texture_flowmap,base_uv).rga;\n"; } code += "\tANISOTROPY = anisotropy_ratio*anisotropy_tex.b;\n"; code += "\tANISOTROPY_FLOW = anisotropy_tex.rg*2.0-1.0;\n"; } if (features[FEATURE_AMBIENT_OCCLUSION]) { if (flags[FLAG_AO_ON_UV2]) { if (flags[FLAG_UV2_USE_TRIPLANAR]) { code += "\tAO = dot(triplanar_texture(texture_ambient_occlusion,uv2_power_normal,uv2_triplanar_pos),ao_texture_channel);\n"; } else { code += "\tAO = dot(texture(texture_ambient_occlusion,base_uv2),ao_texture_channel);\n"; } } else { if (flags[FLAG_UV1_USE_TRIPLANAR]) { code += "\tAO = dot(triplanar_texture(texture_ambient_occlusion,uv1_power_normal,uv1_triplanar_pos),ao_texture_channel);\n"; } else { code += "\tAO = dot(texture(texture_ambient_occlusion,base_uv),ao_texture_channel);\n"; } } code += "\tAO_LIGHT_AFFECT = ao_light_affect;\n"; } if (features[FEATURE_SUBSURACE_SCATTERING]) { if (flags[FLAG_UV1_USE_TRIPLANAR]) { code += "\tfloat sss_tex = triplanar_texture(texture_subsurface_scattering,uv1_power_normal,uv1_triplanar_pos).r;\n"; } else { code += "\tfloat sss_tex = texture(texture_subsurface_scattering,base_uv).r;\n"; } code += "\tSSS_STRENGTH=subsurface_scattering_strength*sss_tex;\n"; } if (features[FEATURE_TRANSMISSION]) { if (flags[FLAG_UV1_USE_TRIPLANAR]) { code += "\tvec3 transmission_tex = triplanar_texture(texture_transmission,uv1_power_normal,uv1_triplanar_pos).rgb;\n"; } else { code += "\tvec3 transmission_tex = texture(texture_transmission,base_uv).rgb;\n"; } code += "\tTRANSMISSION = (transmission.rgb+transmission_tex);\n"; } if (features[FEATURE_DETAIL]) { bool triplanar = (flags[FLAG_UV1_USE_TRIPLANAR] && detail_uv == DETAIL_UV_1) || (flags[FLAG_UV2_USE_TRIPLANAR] && detail_uv == DETAIL_UV_2); if (triplanar) { String tp_uv = detail_uv == DETAIL_UV_1 ? "uv1" : "uv2"; code += "\tvec4 detail_tex = triplanar_texture(texture_detail_albedo," + tp_uv + "_power_normal," + tp_uv + "_triplanar_pos);\n"; code += "\tvec4 detail_norm_tex = triplanar_texture(texture_detail_normal," + tp_uv + "_power_normal," + tp_uv + "_triplanar_pos);\n"; } else { String det_uv = detail_uv == DETAIL_UV_1 ? "base_uv" : "base_uv2"; code += "\tvec4 detail_tex = texture(texture_detail_albedo," + det_uv + ");\n"; code += "\tvec4 detail_norm_tex = texture(texture_detail_normal," + det_uv + ");\n"; } if (flags[FLAG_UV1_USE_TRIPLANAR]) { code += "\tvec4 detail_mask_tex = triplanar_texture(texture_detail_mask,uv1_power_normal,uv1_triplanar_pos);\n"; } else { code += "\tvec4 detail_mask_tex = texture(texture_detail_mask,base_uv);\n"; } switch (detail_blend_mode) { case BLEND_MODE_MIX: { code += "\tvec3 detail = mix(ALBEDO.rgb,detail_tex.rgb,detail_tex.a);\n"; } break; case BLEND_MODE_ADD: { code += "\tvec3 detail = mix(ALBEDO.rgb,ALBEDO.rgb+detail_tex.rgb,detail_tex.a);\n"; } break; case BLEND_MODE_SUB: { code += "\tvec3 detail = mix(ALBEDO.rgb,ALBEDO.rgb-detail_tex.rgb,detail_tex.a);\n"; } break; case BLEND_MODE_MUL: { code += "\tvec3 detail = mix(ALBEDO.rgb,ALBEDO.rgb*detail_tex.rgb,detail_tex.a);\n"; } break; } code += "\tvec3 detail_norm = mix(NORMALMAP,detail_norm_tex.rgb,detail_tex.a);\n"; code += "\tNORMALMAP = mix(NORMALMAP,detail_norm,detail_mask_tex.r);\n"; code += "\tALBEDO.rgb = mix(ALBEDO.rgb,detail,detail_mask_tex.r);\n"; } if (flags[FLAG_USE_ALPHA_SCISSOR]) { code += "\tALPHA_SCISSOR=alpha_scissor_threshold;\n"; } code += "}\n"; ShaderData shader_data; shader_data.shader = VS::get_singleton()->shader_create(); shader_data.users = 1; VS::get_singleton()->shader_set_code(shader_data.shader, code); shader_map[mk] = shader_data; VS::get_singleton()->material_set_shader(_get_material(), shader_data.shader); } void SpatialMaterial::flush_changes() { if (material_mutex) material_mutex->lock(); while (dirty_materials->first()) { dirty_materials->first()->self()->_update_shader(); } if (material_mutex) material_mutex->unlock(); } void SpatialMaterial::_queue_shader_change() { if (material_mutex) material_mutex->lock(); if (!element.in_list()) { dirty_materials->add(&element); } if (material_mutex) material_mutex->unlock(); } bool SpatialMaterial::_is_shader_dirty() const { bool dirty = false; if (material_mutex) material_mutex->lock(); dirty = element.in_list(); if (material_mutex) material_mutex->unlock(); return dirty; } void SpatialMaterial::set_albedo(const Color &p_albedo) { albedo = p_albedo; VS::get_singleton()->material_set_param(_get_material(), shader_names->albedo, p_albedo); } Color SpatialMaterial::get_albedo() const { return albedo; } void SpatialMaterial::set_specular(float p_specular) { specular = p_specular; VS::get_singleton()->material_set_param(_get_material(), shader_names->specular, p_specular); } float SpatialMaterial::get_specular() const { return specular; } void SpatialMaterial::set_roughness(float p_roughness) { roughness = p_roughness; VS::get_singleton()->material_set_param(_get_material(), shader_names->roughness, p_roughness); } float SpatialMaterial::get_roughness() const { return roughness; } void SpatialMaterial::set_metallic(float p_metallic) { metallic = p_metallic; VS::get_singleton()->material_set_param(_get_material(), shader_names->metallic, p_metallic); } float SpatialMaterial::get_metallic() const { return metallic; } void SpatialMaterial::set_emission(const Color &p_emission) { emission = p_emission; VS::get_singleton()->material_set_param(_get_material(), shader_names->emission, p_emission); } Color SpatialMaterial::get_emission() const { return emission; } void SpatialMaterial::set_emission_energy(float p_emission_energy) { emission_energy = p_emission_energy; VS::get_singleton()->material_set_param(_get_material(), shader_names->emission_energy, p_emission_energy); } float SpatialMaterial::get_emission_energy() const { return emission_energy; } void SpatialMaterial::set_normal_scale(float p_normal_scale) { normal_scale = p_normal_scale; VS::get_singleton()->material_set_param(_get_material(), shader_names->normal_scale, p_normal_scale); } float SpatialMaterial::get_normal_scale() const { return normal_scale; } void SpatialMaterial::set_rim(float p_rim) { rim = p_rim; VS::get_singleton()->material_set_param(_get_material(), shader_names->rim, p_rim); } float SpatialMaterial::get_rim() const { return rim; } void SpatialMaterial::set_rim_tint(float p_rim_tint) { rim_tint = p_rim_tint; VS::get_singleton()->material_set_param(_get_material(), shader_names->rim_tint, p_rim_tint); } float SpatialMaterial::get_rim_tint() const { return rim_tint; } void SpatialMaterial::set_ao_light_affect(float p_ao_light_affect) { ao_light_affect = p_ao_light_affect; VS::get_singleton()->material_set_param(_get_material(), shader_names->ao_light_affect, p_ao_light_affect); } float SpatialMaterial::get_ao_light_affect() const { return ao_light_affect; } void SpatialMaterial::set_clearcoat(float p_clearcoat) { clearcoat = p_clearcoat; VS::get_singleton()->material_set_param(_get_material(), shader_names->clearcoat, p_clearcoat); } float SpatialMaterial::get_clearcoat() const { return clearcoat; } void SpatialMaterial::set_clearcoat_gloss(float p_clearcoat_gloss) { clearcoat_gloss = p_clearcoat_gloss; VS::get_singleton()->material_set_param(_get_material(), shader_names->clearcoat_gloss, p_clearcoat_gloss); } float SpatialMaterial::get_clearcoat_gloss() const { return clearcoat_gloss; } void SpatialMaterial::set_anisotropy(float p_anisotropy) { anisotropy = p_anisotropy; VS::get_singleton()->material_set_param(_get_material(), shader_names->anisotropy, p_anisotropy); } float SpatialMaterial::get_anisotropy() const { return anisotropy; } void SpatialMaterial::set_depth_scale(float p_depth_scale) { depth_scale = p_depth_scale; VS::get_singleton()->material_set_param(_get_material(), shader_names->depth_scale, p_depth_scale); } float SpatialMaterial::get_depth_scale() const { return depth_scale; } void SpatialMaterial::set_subsurface_scattering_strength(float p_subsurface_scattering_strength) { subsurface_scattering_strength = p_subsurface_scattering_strength; VS::get_singleton()->material_set_param(_get_material(), shader_names->subsurface_scattering_strength, subsurface_scattering_strength); } float SpatialMaterial::get_subsurface_scattering_strength() const { return subsurface_scattering_strength; } void SpatialMaterial::set_transmission(const Color &p_transmission) { transmission = p_transmission; VS::get_singleton()->material_set_param(_get_material(), shader_names->transmission, transmission); } Color SpatialMaterial::get_transmission() const { return transmission; } void SpatialMaterial::set_refraction(float p_refraction) { refraction = p_refraction; VS::get_singleton()->material_set_param(_get_material(), shader_names->refraction, refraction); } float SpatialMaterial::get_refraction() const { return refraction; } void SpatialMaterial::set_detail_uv(DetailUV p_detail_uv) { if (detail_uv == p_detail_uv) return; detail_uv = p_detail_uv; _queue_shader_change(); } SpatialMaterial::DetailUV SpatialMaterial::get_detail_uv() const { return detail_uv; } void SpatialMaterial::set_blend_mode(BlendMode p_mode) { if (blend_mode == p_mode) return; blend_mode = p_mode; _queue_shader_change(); } SpatialMaterial::BlendMode SpatialMaterial::get_blend_mode() const { return blend_mode; } void SpatialMaterial::set_detail_blend_mode(BlendMode p_mode) { detail_blend_mode = p_mode; _queue_shader_change(); } SpatialMaterial::BlendMode SpatialMaterial::get_detail_blend_mode() const { return detail_blend_mode; } void SpatialMaterial::set_depth_draw_mode(DepthDrawMode p_mode) { if (depth_draw_mode == p_mode) return; depth_draw_mode = p_mode; _queue_shader_change(); } SpatialMaterial::DepthDrawMode SpatialMaterial::get_depth_draw_mode() const { return depth_draw_mode; } void SpatialMaterial::set_cull_mode(CullMode p_mode) { if (cull_mode == p_mode) return; cull_mode = p_mode; _queue_shader_change(); } SpatialMaterial::CullMode SpatialMaterial::get_cull_mode() const { return cull_mode; } void SpatialMaterial::set_diffuse_mode(DiffuseMode p_mode) { if (diffuse_mode == p_mode) return; diffuse_mode = p_mode; _queue_shader_change(); } SpatialMaterial::DiffuseMode SpatialMaterial::get_diffuse_mode() const { return diffuse_mode; } void SpatialMaterial::set_specular_mode(SpecularMode p_mode) { if (specular_mode == p_mode) return; specular_mode = p_mode; _queue_shader_change(); } SpatialMaterial::SpecularMode SpatialMaterial::get_specular_mode() const { return specular_mode; } void SpatialMaterial::set_flag(Flags p_flag, bool p_enabled) { ERR_FAIL_INDEX(p_flag, FLAG_MAX); if (flags[p_flag] == p_enabled) return; flags[p_flag] = p_enabled; if (p_flag == FLAG_USE_ALPHA_SCISSOR || p_flag == FLAG_UNSHADED) { _change_notify(); } _queue_shader_change(); } bool SpatialMaterial::get_flag(Flags p_flag) const { ERR_FAIL_INDEX_V(p_flag, FLAG_MAX, false); return flags[p_flag]; } void SpatialMaterial::set_feature(Feature p_feature, bool p_enabled) { ERR_FAIL_INDEX(p_feature, FEATURE_MAX); if (features[p_feature] == p_enabled) return; features[p_feature] = p_enabled; _change_notify(); _queue_shader_change(); } bool SpatialMaterial::get_feature(Feature p_feature) const { ERR_FAIL_INDEX_V(p_feature, FEATURE_MAX, false); return features[p_feature]; } void SpatialMaterial::set_texture(TextureParam p_param, const Ref<Texture> &p_texture) { ERR_FAIL_INDEX(p_param, TEXTURE_MAX); textures[p_param] = p_texture; RID rid = p_texture.is_valid() ? p_texture->get_rid() : RID(); VS::get_singleton()->material_set_param(_get_material(), shader_names->texture_names[p_param], rid); } Ref<Texture> SpatialMaterial::get_texture(TextureParam p_param) const { ERR_FAIL_INDEX_V(p_param, TEXTURE_MAX, Ref<Texture>()); return textures[p_param]; } Ref<Texture> SpatialMaterial::get_texture_by_name(StringName p_name) const { for (int i = 0; i < (int)SpatialMaterial::TEXTURE_MAX; i++) { TextureParam param = TextureParam(i); if (p_name == shader_names->texture_names[param]) return textures[param]; } return Ref<Texture>(); } void SpatialMaterial::_validate_feature(const String &text, Feature feature, PropertyInfo &property) const { if (property.name.begins_with(text) && property.name != text + "_enabled" && !features[feature]) { property.usage = 0; } } void SpatialMaterial::_validate_high_end(const String &text, PropertyInfo &property) const { if (property.name.begins_with(text)) { property.usage |= PROPERTY_USAGE_HIGH_END_GFX; } } void SpatialMaterial::_validate_property(PropertyInfo &property) const { _validate_feature("normal", FEATURE_NORMAL_MAPPING, property); _validate_feature("emission", FEATURE_EMISSION, property); _validate_feature("rim", FEATURE_RIM, property); _validate_feature("clearcoat", FEATURE_CLEARCOAT, property); _validate_feature("anisotropy", FEATURE_ANISOTROPY, property); _validate_feature("ao", FEATURE_AMBIENT_OCCLUSION, property); _validate_feature("depth", FEATURE_DEPTH_MAPPING, property); _validate_feature("subsurf_scatter", FEATURE_SUBSURACE_SCATTERING, property); _validate_feature("transmission", FEATURE_TRANSMISSION, property); _validate_feature("refraction", FEATURE_REFRACTION, property); _validate_feature("detail", FEATURE_DETAIL, property); _validate_high_end("refraction", property); _validate_high_end("subsurf_scatter", property); _validate_high_end("anisotropy", property); _validate_high_end("clearcoat", property); _validate_high_end("depth", property); if (property.name.begins_with("particles_anim_") && billboard_mode != BILLBOARD_PARTICLES) { property.usage = 0; } if (property.name == "params_grow_amount" && !grow_enabled) { property.usage = 0; } if (property.name == "proximity_fade_distance" && !proximity_fade_enabled) { property.usage = 0; } if ((property.name == "distance_fade_max_distance" || property.name == "distance_fade_min_distance") && distance_fade == DISTANCE_FADE_DISABLED) { property.usage = 0; } if (property.name == "params_alpha_scissor_threshold" && !flags[FLAG_USE_ALPHA_SCISSOR]) { property.usage = 0; } if ((property.name == "depth_min_layers" || property.name == "depth_max_layers") && !deep_parallax) { property.usage = 0; } if (flags[FLAG_UNSHADED]) { if (property.name.begins_with("anisotropy")) { property.usage = 0; } if (property.name.begins_with("ao")) { property.usage = 0; } if (property.name.begins_with("clearcoat")) { property.usage = 0; } if (property.name.begins_with("emission")) { property.usage = 0; } if (property.name.begins_with("metallic")) { property.usage = 0; } if (property.name.begins_with("normal")) { property.usage = 0; } if (property.name.begins_with("rim")) { property.usage = 0; } if (property.name.begins_with("roughness")) { property.usage = 0; } if (property.name.begins_with("subsurf_scatter")) { property.usage = 0; } if (property.name.begins_with("transmission")) { property.usage = 0; } } } void SpatialMaterial::set_line_width(float p_line_width) { line_width = p_line_width; VS::get_singleton()->material_set_line_width(_get_material(), line_width); } float SpatialMaterial::get_line_width() const { return line_width; } void SpatialMaterial::set_point_size(float p_point_size) { point_size = p_point_size; VS::get_singleton()->material_set_param(_get_material(), shader_names->point_size, p_point_size); } float SpatialMaterial::get_point_size() const { return point_size; } void SpatialMaterial::set_uv1_scale(const Vector3 &p_scale) { uv1_scale = p_scale; VS::get_singleton()->material_set_param(_get_material(), shader_names->uv1_scale, p_scale); } Vector3 SpatialMaterial::get_uv1_scale() const { return uv1_scale; } void SpatialMaterial::set_uv1_offset(const Vector3 &p_offset) { uv1_offset = p_offset; VS::get_singleton()->material_set_param(_get_material(), shader_names->uv1_offset, p_offset); } Vector3 SpatialMaterial::get_uv1_offset() const { return uv1_offset; } void SpatialMaterial::set_uv1_triplanar_blend_sharpness(float p_sharpness) { uv1_triplanar_sharpness = p_sharpness; VS::get_singleton()->material_set_param(_get_material(), shader_names->uv1_blend_sharpness, p_sharpness); } float SpatialMaterial::get_uv1_triplanar_blend_sharpness() const { return uv1_triplanar_sharpness; } void SpatialMaterial::set_uv2_scale(const Vector3 &p_scale) { uv2_scale = p_scale; VS::get_singleton()->material_set_param(_get_material(), shader_names->uv2_scale, p_scale); } Vector3 SpatialMaterial::get_uv2_scale() const { return uv2_scale; } void SpatialMaterial::set_uv2_offset(const Vector3 &p_offset) { uv2_offset = p_offset; VS::get_singleton()->material_set_param(_get_material(), shader_names->uv2_offset, p_offset); } Vector3 SpatialMaterial::get_uv2_offset() const { return uv2_offset; } void SpatialMaterial::set_uv2_triplanar_blend_sharpness(float p_sharpness) { uv2_triplanar_sharpness = p_sharpness; VS::get_singleton()->material_set_param(_get_material(), shader_names->uv2_blend_sharpness, p_sharpness); } float SpatialMaterial::get_uv2_triplanar_blend_sharpness() const { return uv2_triplanar_sharpness; } void SpatialMaterial::set_billboard_mode(BillboardMode p_mode) { billboard_mode = p_mode; _queue_shader_change(); _change_notify(); } SpatialMaterial::BillboardMode SpatialMaterial::get_billboard_mode() const { return billboard_mode; } void SpatialMaterial::set_particles_anim_h_frames(int p_frames) { particles_anim_h_frames = p_frames; VS::get_singleton()->material_set_param(_get_material(), shader_names->particles_anim_h_frames, p_frames); } int SpatialMaterial::get_particles_anim_h_frames() const { return particles_anim_h_frames; } void SpatialMaterial::set_particles_anim_v_frames(int p_frames) { particles_anim_v_frames = p_frames; VS::get_singleton()->material_set_param(_get_material(), shader_names->particles_anim_v_frames, p_frames); } int SpatialMaterial::get_particles_anim_v_frames() const { return particles_anim_v_frames; } void SpatialMaterial::set_particles_anim_loop(bool p_loop) { particles_anim_loop = p_loop; VS::get_singleton()->material_set_param(_get_material(), shader_names->particles_anim_loop, particles_anim_loop); } bool SpatialMaterial::get_particles_anim_loop() const { return particles_anim_loop; } void SpatialMaterial::set_depth_deep_parallax(bool p_enable) { deep_parallax = p_enable; _queue_shader_change(); _change_notify(); } bool SpatialMaterial::is_depth_deep_parallax_enabled() const { return deep_parallax; } void SpatialMaterial::set_depth_deep_parallax_min_layers(int p_layer) { deep_parallax_min_layers = p_layer; VS::get_singleton()->material_set_param(_get_material(), shader_names->depth_min_layers, p_layer); } int SpatialMaterial::get_depth_deep_parallax_min_layers() const { return deep_parallax_min_layers; } void SpatialMaterial::set_depth_deep_parallax_max_layers(int p_layer) { deep_parallax_max_layers = p_layer; VS::get_singleton()->material_set_param(_get_material(), shader_names->depth_max_layers, p_layer); } int SpatialMaterial::get_depth_deep_parallax_max_layers() const { return deep_parallax_max_layers; } void SpatialMaterial::set_depth_deep_parallax_flip_tangent(bool p_flip) { depth_parallax_flip_tangent = p_flip; VS::get_singleton()->material_set_param(_get_material(), shader_names->depth_flip, Vector2(depth_parallax_flip_tangent ? -1 : 1, depth_parallax_flip_binormal ? -1 : 1)); } bool SpatialMaterial::get_depth_deep_parallax_flip_tangent() const { return depth_parallax_flip_tangent; } void SpatialMaterial::set_depth_deep_parallax_flip_binormal(bool p_flip) { depth_parallax_flip_binormal = p_flip; VS::get_singleton()->material_set_param(_get_material(), shader_names->depth_flip, Vector2(depth_parallax_flip_tangent ? -1 : 1, depth_parallax_flip_binormal ? -1 : 1)); } bool SpatialMaterial::get_depth_deep_parallax_flip_binormal() const { return depth_parallax_flip_binormal; } void SpatialMaterial::set_grow_enabled(bool p_enable) { grow_enabled = p_enable; _queue_shader_change(); _change_notify(); } bool SpatialMaterial::is_grow_enabled() const { return grow_enabled; } void SpatialMaterial::set_alpha_scissor_threshold(float p_threshold) { alpha_scissor_threshold = p_threshold; VS::get_singleton()->material_set_param(_get_material(), shader_names->alpha_scissor_threshold, p_threshold); } float SpatialMaterial::get_alpha_scissor_threshold() const { return alpha_scissor_threshold; } void SpatialMaterial::set_grow(float p_grow) { grow = p_grow; VS::get_singleton()->material_set_param(_get_material(), shader_names->grow, p_grow); } float SpatialMaterial::get_grow() const { return grow; } static Plane _get_texture_mask(SpatialMaterial::TextureChannel p_channel) { static const Plane masks[5] = { Plane(1, 0, 0, 0), Plane(0, 1, 0, 0), Plane(0, 0, 1, 0), Plane(0, 0, 0, 1), Plane(0.3333333, 0.3333333, 0.3333333, 0), }; return masks[p_channel]; } void SpatialMaterial::set_metallic_texture_channel(TextureChannel p_channel) { ERR_FAIL_INDEX(p_channel, 5); metallic_texture_channel = p_channel; VS::get_singleton()->material_set_param(_get_material(), shader_names->metallic_texture_channel, _get_texture_mask(p_channel)); } SpatialMaterial::TextureChannel SpatialMaterial::get_metallic_texture_channel() const { return metallic_texture_channel; } void SpatialMaterial::set_roughness_texture_channel(TextureChannel p_channel) { ERR_FAIL_INDEX(p_channel, 5); roughness_texture_channel = p_channel; VS::get_singleton()->material_set_param(_get_material(), shader_names->roughness_texture_channel, _get_texture_mask(p_channel)); } SpatialMaterial::TextureChannel SpatialMaterial::get_roughness_texture_channel() const { return roughness_texture_channel; } void SpatialMaterial::set_ao_texture_channel(TextureChannel p_channel) { ao_texture_channel = p_channel; VS::get_singleton()->material_set_param(_get_material(), shader_names->ao_texture_channel, _get_texture_mask(p_channel)); } SpatialMaterial::TextureChannel SpatialMaterial::get_ao_texture_channel() const { return ao_texture_channel; } void SpatialMaterial::set_refraction_texture_channel(TextureChannel p_channel) { refraction_texture_channel = p_channel; VS::get_singleton()->material_set_param(_get_material(), shader_names->refraction_texture_channel, _get_texture_mask(p_channel)); } SpatialMaterial::TextureChannel SpatialMaterial::get_refraction_texture_channel() const { return refraction_texture_channel; } RID SpatialMaterial::get_material_rid_for_2d(bool p_shaded, bool p_transparent, bool p_double_sided, bool p_cut_alpha, bool p_opaque_prepass) { int version = 0; if (p_shaded) version = 1; if (p_transparent) version |= 2; if (p_cut_alpha) version |= 4; if (p_opaque_prepass) version |= 8; if (p_double_sided) version |= 16; if (materials_for_2d[version].is_valid()) { return materials_for_2d[version]->get_rid(); } Ref<SpatialMaterial> material; material.instance(); material->set_flag(FLAG_UNSHADED, !p_shaded); material->set_feature(FEATURE_TRANSPARENT, p_transparent); material->set_cull_mode(p_double_sided ? CULL_DISABLED : CULL_BACK); material->set_depth_draw_mode(p_opaque_prepass ? DEPTH_DRAW_ALPHA_OPAQUE_PREPASS : DEPTH_DRAW_OPAQUE_ONLY); material->set_flag(FLAG_SRGB_VERTEX_COLOR, true); material->set_flag(FLAG_ALBEDO_FROM_VERTEX_COLOR, true); material->set_flag(FLAG_USE_ALPHA_SCISSOR, p_cut_alpha); materials_for_2d[version] = material; return materials_for_2d[version]->get_rid(); } void SpatialMaterial::set_on_top_of_alpha() { set_feature(FEATURE_TRANSPARENT, true); set_render_priority(RENDER_PRIORITY_MAX); set_flag(FLAG_DISABLE_DEPTH_TEST, true); } void SpatialMaterial::set_proximity_fade(bool p_enable) { proximity_fade_enabled = p_enable; _queue_shader_change(); _change_notify(); } bool SpatialMaterial::is_proximity_fade_enabled() const { return proximity_fade_enabled; } void SpatialMaterial::set_proximity_fade_distance(float p_distance) { proximity_fade_distance = p_distance; VS::get_singleton()->material_set_param(_get_material(), shader_names->proximity_fade_distance, p_distance); } float SpatialMaterial::get_proximity_fade_distance() const { return proximity_fade_distance; } void SpatialMaterial::set_distance_fade(DistanceFadeMode p_mode) { distance_fade = p_mode; _queue_shader_change(); _change_notify(); } SpatialMaterial::DistanceFadeMode SpatialMaterial::get_distance_fade() const { return distance_fade; } void SpatialMaterial::set_distance_fade_max_distance(float p_distance) { distance_fade_max_distance = p_distance; VS::get_singleton()->material_set_param(_get_material(), shader_names->distance_fade_max, distance_fade_max_distance); } float SpatialMaterial::get_distance_fade_max_distance() const { return distance_fade_max_distance; } void SpatialMaterial::set_distance_fade_min_distance(float p_distance) { distance_fade_min_distance = p_distance; VS::get_singleton()->material_set_param(_get_material(), shader_names->distance_fade_min, distance_fade_min_distance); } float SpatialMaterial::get_distance_fade_min_distance() const { return distance_fade_min_distance; } void SpatialMaterial::set_emission_operator(EmissionOperator p_op) { if (emission_op == p_op) return; emission_op = p_op; _queue_shader_change(); } SpatialMaterial::EmissionOperator SpatialMaterial::get_emission_operator() const { return emission_op; } RID SpatialMaterial::get_shader_rid() const { ERR_FAIL_COND_V(!shader_map.has(current_key), RID()); return shader_map[current_key].shader; } Shader::Mode SpatialMaterial::get_shader_mode() const { return Shader::MODE_SPATIAL; } void SpatialMaterial::_bind_methods() { ClassDB::bind_method(D_METHOD("set_albedo", "albedo"), &SpatialMaterial::set_albedo); ClassDB::bind_method(D_METHOD("get_albedo"), &SpatialMaterial::get_albedo); ClassDB::bind_method(D_METHOD("set_specular", "specular"), &SpatialMaterial::set_specular); ClassDB::bind_method(D_METHOD("get_specular"), &SpatialMaterial::get_specular); ClassDB::bind_method(D_METHOD("set_metallic", "metallic"), &SpatialMaterial::set_metallic); ClassDB::bind_method(D_METHOD("get_metallic"), &SpatialMaterial::get_metallic); ClassDB::bind_method(D_METHOD("set_roughness", "roughness"), &SpatialMaterial::set_roughness); ClassDB::bind_method(D_METHOD("get_roughness"), &SpatialMaterial::get_roughness); ClassDB::bind_method(D_METHOD("set_emission", "emission"), &SpatialMaterial::set_emission); ClassDB::bind_method(D_METHOD("get_emission"), &SpatialMaterial::get_emission); ClassDB::bind_method(D_METHOD("set_emission_energy", "emission_energy"), &SpatialMaterial::set_emission_energy); ClassDB::bind_method(D_METHOD("get_emission_energy"), &SpatialMaterial::get_emission_energy); ClassDB::bind_method(D_METHOD("set_normal_scale", "normal_scale"), &SpatialMaterial::set_normal_scale); ClassDB::bind_method(D_METHOD("get_normal_scale"), &SpatialMaterial::get_normal_scale); ClassDB::bind_method(D_METHOD("set_rim", "rim"), &SpatialMaterial::set_rim); ClassDB::bind_method(D_METHOD("get_rim"), &SpatialMaterial::get_rim); ClassDB::bind_method(D_METHOD("set_rim_tint", "rim_tint"), &SpatialMaterial::set_rim_tint); ClassDB::bind_method(D_METHOD("get_rim_tint"), &SpatialMaterial::get_rim_tint); ClassDB::bind_method(D_METHOD("set_clearcoat", "clearcoat"), &SpatialMaterial::set_clearcoat); ClassDB::bind_method(D_METHOD("get_clearcoat"), &SpatialMaterial::get_clearcoat); ClassDB::bind_method(D_METHOD("set_clearcoat_gloss", "clearcoat_gloss"), &SpatialMaterial::set_clearcoat_gloss); ClassDB::bind_method(D_METHOD("get_clearcoat_gloss"), &SpatialMaterial::get_clearcoat_gloss); ClassDB::bind_method(D_METHOD("set_anisotropy", "anisotropy"), &SpatialMaterial::set_anisotropy); ClassDB::bind_method(D_METHOD("get_anisotropy"), &SpatialMaterial::get_anisotropy); ClassDB::bind_method(D_METHOD("set_depth_scale", "depth_scale"), &SpatialMaterial::set_depth_scale); ClassDB::bind_method(D_METHOD("get_depth_scale"), &SpatialMaterial::get_depth_scale); ClassDB::bind_method(D_METHOD("set_subsurface_scattering_strength", "strength"), &SpatialMaterial::set_subsurface_scattering_strength); ClassDB::bind_method(D_METHOD("get_subsurface_scattering_strength"), &SpatialMaterial::get_subsurface_scattering_strength); ClassDB::bind_method(D_METHOD("set_transmission", "transmission"), &SpatialMaterial::set_transmission); ClassDB::bind_method(D_METHOD("get_transmission"), &SpatialMaterial::get_transmission); ClassDB::bind_method(D_METHOD("set_refraction", "refraction"), &SpatialMaterial::set_refraction); ClassDB::bind_method(D_METHOD("get_refraction"), &SpatialMaterial::get_refraction); ClassDB::bind_method(D_METHOD("set_line_width", "line_width"), &SpatialMaterial::set_line_width); ClassDB::bind_method(D_METHOD("get_line_width"), &SpatialMaterial::get_line_width); ClassDB::bind_method(D_METHOD("set_point_size", "point_size"), &SpatialMaterial::set_point_size); ClassDB::bind_method(D_METHOD("get_point_size"), &SpatialMaterial::get_point_size); ClassDB::bind_method(D_METHOD("set_detail_uv", "detail_uv"), &SpatialMaterial::set_detail_uv); ClassDB::bind_method(D_METHOD("get_detail_uv"), &SpatialMaterial::get_detail_uv); ClassDB::bind_method(D_METHOD("set_blend_mode", "blend_mode"), &SpatialMaterial::set_blend_mode); ClassDB::bind_method(D_METHOD("get_blend_mode"), &SpatialMaterial::get_blend_mode); ClassDB::bind_method(D_METHOD("set_depth_draw_mode", "depth_draw_mode"), &SpatialMaterial::set_depth_draw_mode); ClassDB::bind_method(D_METHOD("get_depth_draw_mode"), &SpatialMaterial::get_depth_draw_mode); ClassDB::bind_method(D_METHOD("set_cull_mode", "cull_mode"), &SpatialMaterial::set_cull_mode); ClassDB::bind_method(D_METHOD("get_cull_mode"), &SpatialMaterial::get_cull_mode); ClassDB::bind_method(D_METHOD("set_diffuse_mode", "diffuse_mode"), &SpatialMaterial::set_diffuse_mode); ClassDB::bind_method(D_METHOD("get_diffuse_mode"), &SpatialMaterial::get_diffuse_mode); ClassDB::bind_method(D_METHOD("set_specular_mode", "specular_mode"), &SpatialMaterial::set_specular_mode); ClassDB::bind_method(D_METHOD("get_specular_mode"), &SpatialMaterial::get_specular_mode); ClassDB::bind_method(D_METHOD("set_flag", "flag", "enable"), &SpatialMaterial::set_flag); ClassDB::bind_method(D_METHOD("get_flag", "flag"), &SpatialMaterial::get_flag); ClassDB::bind_method(D_METHOD("set_feature", "feature", "enable"), &SpatialMaterial::set_feature); ClassDB::bind_method(D_METHOD("get_feature", "feature"), &SpatialMaterial::get_feature); ClassDB::bind_method(D_METHOD("set_texture", "param", "texture"), &SpatialMaterial::set_texture); ClassDB::bind_method(D_METHOD("get_texture", "param"), &SpatialMaterial::get_texture); ClassDB::bind_method(D_METHOD("set_detail_blend_mode", "detail_blend_mode"), &SpatialMaterial::set_detail_blend_mode); ClassDB::bind_method(D_METHOD("get_detail_blend_mode"), &SpatialMaterial::get_detail_blend_mode); ClassDB::bind_method(D_METHOD("set_uv1_scale", "scale"), &SpatialMaterial::set_uv1_scale); ClassDB::bind_method(D_METHOD("get_uv1_scale"), &SpatialMaterial::get_uv1_scale); ClassDB::bind_method(D_METHOD("set_uv1_offset", "offset"), &SpatialMaterial::set_uv1_offset); ClassDB::bind_method(D_METHOD("get_uv1_offset"), &SpatialMaterial::get_uv1_offset); ClassDB::bind_method(D_METHOD("set_uv1_triplanar_blend_sharpness", "sharpness"), &SpatialMaterial::set_uv1_triplanar_blend_sharpness); ClassDB::bind_method(D_METHOD("get_uv1_triplanar_blend_sharpness"), &SpatialMaterial::get_uv1_triplanar_blend_sharpness); ClassDB::bind_method(D_METHOD("set_uv2_scale", "scale"), &SpatialMaterial::set_uv2_scale); ClassDB::bind_method(D_METHOD("get_uv2_scale"), &SpatialMaterial::get_uv2_scale); ClassDB::bind_method(D_METHOD("set_uv2_offset", "offset"), &SpatialMaterial::set_uv2_offset); ClassDB::bind_method(D_METHOD("get_uv2_offset"), &SpatialMaterial::get_uv2_offset); ClassDB::bind_method(D_METHOD("set_uv2_triplanar_blend_sharpness", "sharpness"), &SpatialMaterial::set_uv2_triplanar_blend_sharpness); ClassDB::bind_method(D_METHOD("get_uv2_triplanar_blend_sharpness"), &SpatialMaterial::get_uv2_triplanar_blend_sharpness); ClassDB::bind_method(D_METHOD("set_billboard_mode", "mode"), &SpatialMaterial::set_billboard_mode); ClassDB::bind_method(D_METHOD("get_billboard_mode"), &SpatialMaterial::get_billboard_mode); ClassDB::bind_method(D_METHOD("set_particles_anim_h_frames", "frames"), &SpatialMaterial::set_particles_anim_h_frames); ClassDB::bind_method(D_METHOD("get_particles_anim_h_frames"), &SpatialMaterial::get_particles_anim_h_frames); ClassDB::bind_method(D_METHOD("set_particles_anim_v_frames", "frames"), &SpatialMaterial::set_particles_anim_v_frames); ClassDB::bind_method(D_METHOD("get_particles_anim_v_frames"), &SpatialMaterial::get_particles_anim_v_frames); ClassDB::bind_method(D_METHOD("set_particles_anim_loop", "loop"), &SpatialMaterial::set_particles_anim_loop); ClassDB::bind_method(D_METHOD("get_particles_anim_loop"), &SpatialMaterial::get_particles_anim_loop); ClassDB::bind_method(D_METHOD("set_depth_deep_parallax", "enable"), &SpatialMaterial::set_depth_deep_parallax); ClassDB::bind_method(D_METHOD("is_depth_deep_parallax_enabled"), &SpatialMaterial::is_depth_deep_parallax_enabled); ClassDB::bind_method(D_METHOD("set_depth_deep_parallax_min_layers", "layer"), &SpatialMaterial::set_depth_deep_parallax_min_layers); ClassDB::bind_method(D_METHOD("get_depth_deep_parallax_min_layers"), &SpatialMaterial::get_depth_deep_parallax_min_layers); ClassDB::bind_method(D_METHOD("set_depth_deep_parallax_max_layers", "layer"), &SpatialMaterial::set_depth_deep_parallax_max_layers); ClassDB::bind_method(D_METHOD("get_depth_deep_parallax_max_layers"), &SpatialMaterial::get_depth_deep_parallax_max_layers); ClassDB::bind_method(D_METHOD("set_depth_deep_parallax_flip_tangent", "flip"), &SpatialMaterial::set_depth_deep_parallax_flip_tangent); ClassDB::bind_method(D_METHOD("get_depth_deep_parallax_flip_tangent"), &SpatialMaterial::get_depth_deep_parallax_flip_tangent); ClassDB::bind_method(D_METHOD("set_depth_deep_parallax_flip_binormal", "flip"), &SpatialMaterial::set_depth_deep_parallax_flip_binormal); ClassDB::bind_method(D_METHOD("get_depth_deep_parallax_flip_binormal"), &SpatialMaterial::get_depth_deep_parallax_flip_binormal); ClassDB::bind_method(D_METHOD("set_grow", "amount"), &SpatialMaterial::set_grow); ClassDB::bind_method(D_METHOD("get_grow"), &SpatialMaterial::get_grow); ClassDB::bind_method(D_METHOD("set_emission_operator", "operator"), &SpatialMaterial::set_emission_operator); ClassDB::bind_method(D_METHOD("get_emission_operator"), &SpatialMaterial::get_emission_operator); ClassDB::bind_method(D_METHOD("set_ao_light_affect", "amount"), &SpatialMaterial::set_ao_light_affect); ClassDB::bind_method(D_METHOD("get_ao_light_affect"), &SpatialMaterial::get_ao_light_affect); ClassDB::bind_method(D_METHOD("set_alpha_scissor_threshold", "threshold"), &SpatialMaterial::set_alpha_scissor_threshold); ClassDB::bind_method(D_METHOD("get_alpha_scissor_threshold"), &SpatialMaterial::get_alpha_scissor_threshold); ClassDB::bind_method(D_METHOD("set_grow_enabled", "enable"), &SpatialMaterial::set_grow_enabled); ClassDB::bind_method(D_METHOD("is_grow_enabled"), &SpatialMaterial::is_grow_enabled); ClassDB::bind_method(D_METHOD("set_metallic_texture_channel", "channel"), &SpatialMaterial::set_metallic_texture_channel); ClassDB::bind_method(D_METHOD("get_metallic_texture_channel"), &SpatialMaterial::get_metallic_texture_channel); ClassDB::bind_method(D_METHOD("set_roughness_texture_channel", "channel"), &SpatialMaterial::set_roughness_texture_channel); ClassDB::bind_method(D_METHOD("get_roughness_texture_channel"), &SpatialMaterial::get_roughness_texture_channel); ClassDB::bind_method(D_METHOD("set_ao_texture_channel", "channel"), &SpatialMaterial::set_ao_texture_channel); ClassDB::bind_method(D_METHOD("get_ao_texture_channel"), &SpatialMaterial::get_ao_texture_channel); ClassDB::bind_method(D_METHOD("set_refraction_texture_channel", "channel"), &SpatialMaterial::set_refraction_texture_channel); ClassDB::bind_method(D_METHOD("get_refraction_texture_channel"), &SpatialMaterial::get_refraction_texture_channel); ClassDB::bind_method(D_METHOD("set_proximity_fade", "enabled"), &SpatialMaterial::set_proximity_fade); ClassDB::bind_method(D_METHOD("is_proximity_fade_enabled"), &SpatialMaterial::is_proximity_fade_enabled); ClassDB::bind_method(D_METHOD("set_proximity_fade_distance", "distance"), &SpatialMaterial::set_proximity_fade_distance); ClassDB::bind_method(D_METHOD("get_proximity_fade_distance"), &SpatialMaterial::get_proximity_fade_distance); ClassDB::bind_method(D_METHOD("set_distance_fade", "mode"), &SpatialMaterial::set_distance_fade); ClassDB::bind_method(D_METHOD("get_distance_fade"), &SpatialMaterial::get_distance_fade); ClassDB::bind_method(D_METHOD("set_distance_fade_max_distance", "distance"), &SpatialMaterial::set_distance_fade_max_distance); ClassDB::bind_method(D_METHOD("get_distance_fade_max_distance"), &SpatialMaterial::get_distance_fade_max_distance); ClassDB::bind_method(D_METHOD("set_distance_fade_min_distance", "distance"), &SpatialMaterial::set_distance_fade_min_distance); ClassDB::bind_method(D_METHOD("get_distance_fade_min_distance"), &SpatialMaterial::get_distance_fade_min_distance); ADD_GROUP("Flags", "flags_"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "flags_transparent"), "set_feature", "get_feature", FEATURE_TRANSPARENT); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "flags_unshaded"), "set_flag", "get_flag", FLAG_UNSHADED); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "flags_vertex_lighting"), "set_flag", "get_flag", FLAG_USE_VERTEX_LIGHTING); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "flags_no_depth_test"), "set_flag", "get_flag", FLAG_DISABLE_DEPTH_TEST); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "flags_use_point_size"), "set_flag", "get_flag", FLAG_USE_POINT_SIZE); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "flags_world_triplanar"), "set_flag", "get_flag", FLAG_TRIPLANAR_USE_WORLD); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "flags_fixed_size"), "set_flag", "get_flag", FLAG_FIXED_SIZE); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "flags_albedo_tex_force_srgb"), "set_flag", "get_flag", FLAG_ALBEDO_TEXTURE_FORCE_SRGB); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "flags_do_not_receive_shadows"), "set_flag", "get_flag", FLAG_DONT_RECEIVE_SHADOWS); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "flags_disable_ambient_light"), "set_flag", "get_flag", FLAG_DISABLE_AMBIENT_LIGHT); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "flags_ensure_correct_normals"), "set_flag", "get_flag", FLAG_ENSURE_CORRECT_NORMALS); ADD_GROUP("Vertex Color", "vertex_color"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "vertex_color_use_as_albedo"), "set_flag", "get_flag", FLAG_ALBEDO_FROM_VERTEX_COLOR); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "vertex_color_is_srgb"), "set_flag", "get_flag", FLAG_SRGB_VERTEX_COLOR); ADD_GROUP("Parameters", "params_"); ADD_PROPERTY(PropertyInfo(Variant::INT, "params_diffuse_mode", PROPERTY_HINT_ENUM, "Burley,Lambert,Lambert Wrap,Oren Nayar,Toon"), "set_diffuse_mode", "get_diffuse_mode"); ADD_PROPERTY(PropertyInfo(Variant::INT, "params_specular_mode", PROPERTY_HINT_ENUM, "SchlickGGX,Blinn,Phong,Toon,Disabled"), "set_specular_mode", "get_specular_mode"); ADD_PROPERTY(PropertyInfo(Variant::INT, "params_blend_mode", PROPERTY_HINT_ENUM, "Mix,Add,Sub,Mul"), "set_blend_mode", "get_blend_mode"); ADD_PROPERTY(PropertyInfo(Variant::INT, "params_cull_mode", PROPERTY_HINT_ENUM, "Back,Front,Disabled"), "set_cull_mode", "get_cull_mode"); ADD_PROPERTY(PropertyInfo(Variant::INT, "params_depth_draw_mode", PROPERTY_HINT_ENUM, "Opaque Only,Always,Never,Opaque Pre-Pass"), "set_depth_draw_mode", "get_depth_draw_mode"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "params_line_width", PROPERTY_HINT_RANGE, "0.1,128,0.1"), "set_line_width", "get_line_width"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "params_point_size", PROPERTY_HINT_RANGE, "0.1,128,0.1"), "set_point_size", "get_point_size"); ADD_PROPERTY(PropertyInfo(Variant::INT, "params_billboard_mode", PROPERTY_HINT_ENUM, "Disabled,Enabled,Y-Billboard,Particle Billboard"), "set_billboard_mode", "get_billboard_mode"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "params_billboard_keep_scale"), "set_flag", "get_flag", FLAG_BILLBOARD_KEEP_SCALE); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "params_grow"), "set_grow_enabled", "is_grow_enabled"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "params_grow_amount", PROPERTY_HINT_RANGE, "-16,10,0.01"), "set_grow", "get_grow"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "params_use_alpha_scissor"), "set_flag", "get_flag", FLAG_USE_ALPHA_SCISSOR); ADD_PROPERTY(PropertyInfo(Variant::REAL, "params_alpha_scissor_threshold", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_alpha_scissor_threshold", "get_alpha_scissor_threshold"); ADD_GROUP("Particles Anim", "particles_anim_"); ADD_PROPERTY(PropertyInfo(Variant::INT, "particles_anim_h_frames", PROPERTY_HINT_RANGE, "1,128,1"), "set_particles_anim_h_frames", "get_particles_anim_h_frames"); ADD_PROPERTY(PropertyInfo(Variant::INT, "particles_anim_v_frames", PROPERTY_HINT_RANGE, "1,128,1"), "set_particles_anim_v_frames", "get_particles_anim_v_frames"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "particles_anim_loop"), "set_particles_anim_loop", "get_particles_anim_loop"); ADD_GROUP("Albedo", "albedo_"); ADD_PROPERTY(PropertyInfo(Variant::COLOR, "albedo_color"), "set_albedo", "get_albedo"); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "albedo_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_ALBEDO); ADD_GROUP("Metallic", "metallic_"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "metallic", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_metallic", "get_metallic"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "metallic_specular", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_specular", "get_specular"); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "metallic_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_METALLIC); ADD_PROPERTY(PropertyInfo(Variant::INT, "metallic_texture_channel", PROPERTY_HINT_ENUM, "Red,Green,Blue,Alpha,Gray"), "set_metallic_texture_channel", "get_metallic_texture_channel"); ADD_GROUP("Roughness", "roughness_"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "roughness", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_roughness", "get_roughness"); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "roughness_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_ROUGHNESS); ADD_PROPERTY(PropertyInfo(Variant::INT, "roughness_texture_channel", PROPERTY_HINT_ENUM, "Red,Green,Blue,Alpha,Gray"), "set_roughness_texture_channel", "get_roughness_texture_channel"); ADD_GROUP("Emission", "emission_"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "emission_enabled"), "set_feature", "get_feature", FEATURE_EMISSION); ADD_PROPERTY(PropertyInfo(Variant::COLOR, "emission", PROPERTY_HINT_COLOR_NO_ALPHA), "set_emission", "get_emission"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "emission_energy", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_emission_energy", "get_emission_energy"); ADD_PROPERTY(PropertyInfo(Variant::INT, "emission_operator", PROPERTY_HINT_ENUM, "Add,Multiply"), "set_emission_operator", "get_emission_operator"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "emission_on_uv2"), "set_flag", "get_flag", FLAG_EMISSION_ON_UV2); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "emission_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_EMISSION); ADD_GROUP("NormalMap", "normal_"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "normal_enabled"), "set_feature", "get_feature", FEATURE_NORMAL_MAPPING); ADD_PROPERTY(PropertyInfo(Variant::REAL, "normal_scale", PROPERTY_HINT_RANGE, "-16,16,0.01"), "set_normal_scale", "get_normal_scale"); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "normal_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_NORMAL); ADD_GROUP("Rim", "rim_"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "rim_enabled"), "set_feature", "get_feature", FEATURE_RIM); ADD_PROPERTY(PropertyInfo(Variant::REAL, "rim", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_rim", "get_rim"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "rim_tint", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_rim_tint", "get_rim_tint"); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "rim_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_RIM); ADD_GROUP("Clearcoat", "clearcoat_"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "clearcoat_enabled"), "set_feature", "get_feature", FEATURE_CLEARCOAT); ADD_PROPERTY(PropertyInfo(Variant::REAL, "clearcoat", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_clearcoat", "get_clearcoat"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "clearcoat_gloss", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_clearcoat_gloss", "get_clearcoat_gloss"); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "clearcoat_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_CLEARCOAT); ADD_GROUP("Anisotropy", "anisotropy_"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "anisotropy_enabled"), "set_feature", "get_feature", FEATURE_ANISOTROPY); ADD_PROPERTY(PropertyInfo(Variant::REAL, "anisotropy", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_anisotropy", "get_anisotropy"); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "anisotropy_flowmap", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_FLOWMAP); ADD_GROUP("Ambient Occlusion", "ao_"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "ao_enabled"), "set_feature", "get_feature", FEATURE_AMBIENT_OCCLUSION); ADD_PROPERTY(PropertyInfo(Variant::REAL, "ao_light_affect", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_ao_light_affect", "get_ao_light_affect"); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "ao_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_AMBIENT_OCCLUSION); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "ao_on_uv2"), "set_flag", "get_flag", FLAG_AO_ON_UV2); ADD_PROPERTY(PropertyInfo(Variant::INT, "ao_texture_channel", PROPERTY_HINT_ENUM, "Red,Green,Blue,Alpha,Gray"), "set_ao_texture_channel", "get_ao_texture_channel"); ADD_GROUP("Depth", "depth_"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "depth_enabled"), "set_feature", "get_feature", FEATURE_DEPTH_MAPPING); ADD_PROPERTY(PropertyInfo(Variant::REAL, "depth_scale", PROPERTY_HINT_RANGE, "-16,16,0.01"), "set_depth_scale", "get_depth_scale"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "depth_deep_parallax"), "set_depth_deep_parallax", "is_depth_deep_parallax_enabled"); ADD_PROPERTY(PropertyInfo(Variant::INT, "depth_min_layers", PROPERTY_HINT_RANGE, "1,32,1"), "set_depth_deep_parallax_min_layers", "get_depth_deep_parallax_min_layers"); ADD_PROPERTY(PropertyInfo(Variant::INT, "depth_max_layers", PROPERTY_HINT_RANGE, "1,32,1"), "set_depth_deep_parallax_max_layers", "get_depth_deep_parallax_max_layers"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "depth_flip_tangent"), "set_depth_deep_parallax_flip_tangent", "get_depth_deep_parallax_flip_tangent"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "depth_flip_binormal"), "set_depth_deep_parallax_flip_binormal", "get_depth_deep_parallax_flip_binormal"); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "depth_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_DEPTH); ADD_GROUP("Subsurf Scatter", "subsurf_scatter_"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "subsurf_scatter_enabled"), "set_feature", "get_feature", FEATURE_SUBSURACE_SCATTERING); ADD_PROPERTY(PropertyInfo(Variant::REAL, "subsurf_scatter_strength", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_subsurface_scattering_strength", "get_subsurface_scattering_strength"); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "subsurf_scatter_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_SUBSURFACE_SCATTERING); ADD_GROUP("Transmission", "transmission_"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "transmission_enabled"), "set_feature", "get_feature", FEATURE_TRANSMISSION); ADD_PROPERTY(PropertyInfo(Variant::COLOR, "transmission", PROPERTY_HINT_COLOR_NO_ALPHA), "set_transmission", "get_transmission"); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "transmission_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_TRANSMISSION); ADD_GROUP("Refraction", "refraction_"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "refraction_enabled"), "set_feature", "get_feature", FEATURE_REFRACTION); ADD_PROPERTY(PropertyInfo(Variant::REAL, "refraction_scale", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_refraction", "get_refraction"); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "refraction_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_REFRACTION); ADD_PROPERTY(PropertyInfo(Variant::INT, "refraction_texture_channel", PROPERTY_HINT_ENUM, "Red,Green,Blue,Alpha,Gray"), "set_refraction_texture_channel", "get_refraction_texture_channel"); ADD_GROUP("Detail", "detail_"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "detail_enabled"), "set_feature", "get_feature", FEATURE_DETAIL); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "detail_mask", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_DETAIL_MASK); ADD_PROPERTY(PropertyInfo(Variant::INT, "detail_blend_mode", PROPERTY_HINT_ENUM, "Mix,Add,Sub,Mul"), "set_detail_blend_mode", "get_detail_blend_mode"); ADD_PROPERTY(PropertyInfo(Variant::INT, "detail_uv_layer", PROPERTY_HINT_ENUM, "UV1,UV2"), "set_detail_uv", "get_detail_uv"); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "detail_albedo", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_DETAIL_ALBEDO); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "detail_normal", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_DETAIL_NORMAL); ADD_GROUP("UV1", "uv1_"); ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "uv1_scale"), "set_uv1_scale", "get_uv1_scale"); ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "uv1_offset"), "set_uv1_offset", "get_uv1_offset"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "uv1_triplanar"), "set_flag", "get_flag", FLAG_UV1_USE_TRIPLANAR); ADD_PROPERTY(PropertyInfo(Variant::REAL, "uv1_triplanar_sharpness", PROPERTY_HINT_EXP_EASING), "set_uv1_triplanar_blend_sharpness", "get_uv1_triplanar_blend_sharpness"); ADD_GROUP("UV2", "uv2_"); ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "uv2_scale"), "set_uv2_scale", "get_uv2_scale"); ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "uv2_offset"), "set_uv2_offset", "get_uv2_offset"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "uv2_triplanar"), "set_flag", "get_flag", FLAG_UV2_USE_TRIPLANAR); ADD_PROPERTY(PropertyInfo(Variant::REAL, "uv2_triplanar_sharpness", PROPERTY_HINT_EXP_EASING), "set_uv2_triplanar_blend_sharpness", "get_uv2_triplanar_blend_sharpness"); ADD_GROUP("Proximity Fade", "proximity_fade_"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "proximity_fade_enable"), "set_proximity_fade", "is_proximity_fade_enabled"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "proximity_fade_distance", PROPERTY_HINT_RANGE, "0,4096,0.1"), "set_proximity_fade_distance", "get_proximity_fade_distance"); ADD_GROUP("Distance Fade", "distance_fade_"); ADD_PROPERTY(PropertyInfo(Variant::INT, "distance_fade_mode", PROPERTY_HINT_ENUM, "Disabled,PixelAlpha,PixelDither,ObjectDither"), "set_distance_fade", "get_distance_fade"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "distance_fade_min_distance", PROPERTY_HINT_RANGE, "0,4096,0.1"), "set_distance_fade_min_distance", "get_distance_fade_min_distance"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "distance_fade_max_distance", PROPERTY_HINT_RANGE, "0,4096,0.1"), "set_distance_fade_max_distance", "get_distance_fade_max_distance"); BIND_ENUM_CONSTANT(TEXTURE_ALBEDO); BIND_ENUM_CONSTANT(TEXTURE_METALLIC); BIND_ENUM_CONSTANT(TEXTURE_ROUGHNESS); BIND_ENUM_CONSTANT(TEXTURE_EMISSION); BIND_ENUM_CONSTANT(TEXTURE_NORMAL); BIND_ENUM_CONSTANT(TEXTURE_RIM); BIND_ENUM_CONSTANT(TEXTURE_CLEARCOAT); BIND_ENUM_CONSTANT(TEXTURE_FLOWMAP); BIND_ENUM_CONSTANT(TEXTURE_AMBIENT_OCCLUSION); BIND_ENUM_CONSTANT(TEXTURE_DEPTH); BIND_ENUM_CONSTANT(TEXTURE_SUBSURFACE_SCATTERING); BIND_ENUM_CONSTANT(TEXTURE_TRANSMISSION); BIND_ENUM_CONSTANT(TEXTURE_REFRACTION); BIND_ENUM_CONSTANT(TEXTURE_DETAIL_MASK); BIND_ENUM_CONSTANT(TEXTURE_DETAIL_ALBEDO); BIND_ENUM_CONSTANT(TEXTURE_DETAIL_NORMAL); BIND_ENUM_CONSTANT(TEXTURE_MAX); BIND_ENUM_CONSTANT(DETAIL_UV_1); BIND_ENUM_CONSTANT(DETAIL_UV_2); BIND_ENUM_CONSTANT(FEATURE_TRANSPARENT); BIND_ENUM_CONSTANT(FEATURE_EMISSION); BIND_ENUM_CONSTANT(FEATURE_NORMAL_MAPPING); BIND_ENUM_CONSTANT(FEATURE_RIM); BIND_ENUM_CONSTANT(FEATURE_CLEARCOAT); BIND_ENUM_CONSTANT(FEATURE_ANISOTROPY); BIND_ENUM_CONSTANT(FEATURE_AMBIENT_OCCLUSION); BIND_ENUM_CONSTANT(FEATURE_DEPTH_MAPPING); BIND_ENUM_CONSTANT(FEATURE_SUBSURACE_SCATTERING); BIND_ENUM_CONSTANT(FEATURE_TRANSMISSION); BIND_ENUM_CONSTANT(FEATURE_REFRACTION); BIND_ENUM_CONSTANT(FEATURE_DETAIL); BIND_ENUM_CONSTANT(FEATURE_MAX); BIND_ENUM_CONSTANT(BLEND_MODE_MIX); BIND_ENUM_CONSTANT(BLEND_MODE_ADD); BIND_ENUM_CONSTANT(BLEND_MODE_SUB); BIND_ENUM_CONSTANT(BLEND_MODE_MUL); BIND_ENUM_CONSTANT(DEPTH_DRAW_OPAQUE_ONLY); BIND_ENUM_CONSTANT(DEPTH_DRAW_ALWAYS); BIND_ENUM_CONSTANT(DEPTH_DRAW_DISABLED); BIND_ENUM_CONSTANT(DEPTH_DRAW_ALPHA_OPAQUE_PREPASS); BIND_ENUM_CONSTANT(CULL_BACK); BIND_ENUM_CONSTANT(CULL_FRONT); BIND_ENUM_CONSTANT(CULL_DISABLED); BIND_ENUM_CONSTANT(FLAG_UNSHADED); BIND_ENUM_CONSTANT(FLAG_USE_VERTEX_LIGHTING); BIND_ENUM_CONSTANT(FLAG_DISABLE_DEPTH_TEST); BIND_ENUM_CONSTANT(FLAG_ALBEDO_FROM_VERTEX_COLOR); BIND_ENUM_CONSTANT(FLAG_SRGB_VERTEX_COLOR); BIND_ENUM_CONSTANT(FLAG_USE_POINT_SIZE); BIND_ENUM_CONSTANT(FLAG_FIXED_SIZE); BIND_ENUM_CONSTANT(FLAG_BILLBOARD_KEEP_SCALE); BIND_ENUM_CONSTANT(FLAG_UV1_USE_TRIPLANAR); BIND_ENUM_CONSTANT(FLAG_UV2_USE_TRIPLANAR); BIND_ENUM_CONSTANT(FLAG_AO_ON_UV2); BIND_ENUM_CONSTANT(FLAG_EMISSION_ON_UV2); BIND_ENUM_CONSTANT(FLAG_USE_ALPHA_SCISSOR); BIND_ENUM_CONSTANT(FLAG_TRIPLANAR_USE_WORLD); BIND_ENUM_CONSTANT(FLAG_ALBEDO_TEXTURE_FORCE_SRGB); BIND_ENUM_CONSTANT(FLAG_DONT_RECEIVE_SHADOWS); BIND_ENUM_CONSTANT(FLAG_DISABLE_AMBIENT_LIGHT); BIND_ENUM_CONSTANT(FLAG_ENSURE_CORRECT_NORMALS); BIND_ENUM_CONSTANT(FLAG_MAX); BIND_ENUM_CONSTANT(DIFFUSE_BURLEY); BIND_ENUM_CONSTANT(DIFFUSE_LAMBERT); BIND_ENUM_CONSTANT(DIFFUSE_LAMBERT_WRAP); BIND_ENUM_CONSTANT(DIFFUSE_OREN_NAYAR); BIND_ENUM_CONSTANT(DIFFUSE_TOON); BIND_ENUM_CONSTANT(SPECULAR_SCHLICK_GGX); BIND_ENUM_CONSTANT(SPECULAR_BLINN); BIND_ENUM_CONSTANT(SPECULAR_PHONG); BIND_ENUM_CONSTANT(SPECULAR_TOON); BIND_ENUM_CONSTANT(SPECULAR_DISABLED); BIND_ENUM_CONSTANT(BILLBOARD_DISABLED); BIND_ENUM_CONSTANT(BILLBOARD_ENABLED); BIND_ENUM_CONSTANT(BILLBOARD_FIXED_Y); BIND_ENUM_CONSTANT(BILLBOARD_PARTICLES); BIND_ENUM_CONSTANT(TEXTURE_CHANNEL_RED); BIND_ENUM_CONSTANT(TEXTURE_CHANNEL_GREEN); BIND_ENUM_CONSTANT(TEXTURE_CHANNEL_BLUE); BIND_ENUM_CONSTANT(TEXTURE_CHANNEL_ALPHA); BIND_ENUM_CONSTANT(TEXTURE_CHANNEL_GRAYSCALE); BIND_ENUM_CONSTANT(EMISSION_OP_ADD); BIND_ENUM_CONSTANT(EMISSION_OP_MULTIPLY); BIND_ENUM_CONSTANT(DISTANCE_FADE_DISABLED); BIND_ENUM_CONSTANT(DISTANCE_FADE_PIXEL_ALPHA); BIND_ENUM_CONSTANT(DISTANCE_FADE_PIXEL_DITHER); BIND_ENUM_CONSTANT(DISTANCE_FADE_OBJECT_DITHER); } SpatialMaterial::SpatialMaterial() : element(this) { // Initialize to the same values as the shader set_albedo(Color(1.0, 1.0, 1.0, 1.0)); set_specular(0.5); set_roughness(1.0); set_metallic(0.0); set_emission(Color(0, 0, 0)); set_emission_energy(1.0); set_normal_scale(1); set_rim(1.0); set_rim_tint(0.5); set_clearcoat(1); set_clearcoat_gloss(0.5); set_anisotropy(0); set_depth_scale(0.05); set_subsurface_scattering_strength(0); set_transmission(Color(0, 0, 0)); set_refraction(0.05); set_line_width(1); set_point_size(1); set_uv1_offset(Vector3(0, 0, 0)); set_uv1_scale(Vector3(1, 1, 1)); set_uv1_triplanar_blend_sharpness(1); set_uv2_offset(Vector3(0, 0, 0)); set_uv2_scale(Vector3(1, 1, 1)); set_uv2_triplanar_blend_sharpness(1); set_billboard_mode(BILLBOARD_DISABLED); set_particles_anim_h_frames(1); set_particles_anim_v_frames(1); set_particles_anim_loop(false); set_alpha_scissor_threshold(0.98); emission_op = EMISSION_OP_ADD; proximity_fade_enabled = false; distance_fade = DISTANCE_FADE_DISABLED; set_proximity_fade_distance(1); set_distance_fade_min_distance(0); set_distance_fade_max_distance(10); set_ao_light_affect(0.0); set_metallic_texture_channel(TEXTURE_CHANNEL_RED); set_roughness_texture_channel(TEXTURE_CHANNEL_RED); set_ao_texture_channel(TEXTURE_CHANNEL_RED); set_refraction_texture_channel(TEXTURE_CHANNEL_RED); grow_enabled = false; set_grow(0.0); deep_parallax = false; depth_parallax_flip_tangent = false; depth_parallax_flip_binormal = false; set_depth_deep_parallax_min_layers(8); set_depth_deep_parallax_max_layers(32); set_depth_deep_parallax_flip_tangent(false); //also sets binormal detail_uv = DETAIL_UV_1; blend_mode = BLEND_MODE_MIX; detail_blend_mode = BLEND_MODE_MIX; depth_draw_mode = DEPTH_DRAW_OPAQUE_ONLY; cull_mode = CULL_BACK; for (int i = 0; i < FLAG_MAX; i++) { flags[i] = 0; } diffuse_mode = DIFFUSE_BURLEY; specular_mode = SPECULAR_SCHLICK_GGX; for (int i = 0; i < FEATURE_MAX; i++) { features[i] = false; } current_key.key = 0; current_key.invalid_key = 1; _queue_shader_change(); } SpatialMaterial::~SpatialMaterial() { if (material_mutex) material_mutex->lock(); if (shader_map.has(current_key)) { shader_map[current_key].users--; if (shader_map[current_key].users == 0) { //deallocate shader, as it's no longer in use VS::get_singleton()->free(shader_map[current_key].shader); shader_map.erase(current_key); } VS::get_singleton()->material_set_shader(_get_material(), RID()); } if (material_mutex) material_mutex->unlock(); }
39.245044
215
0.75424
etalot
f6dd69da04cd2566f5d5204fac775a433b884129
231
cpp
C++
tests/007-argc-argv.cpp
yanlinlin82/icpp
4e3127a87201aef6bf96b97082a23d35ca4fe230
[ "MIT" ]
1
2020-05-07T23:07:12.000Z
2020-05-07T23:07:12.000Z
tests/007-argc-argv.cpp
yanlinlin82/icpp
4e3127a87201aef6bf96b97082a23d35ca4fe230
[ "MIT" ]
null
null
null
tests/007-argc-argv.cpp
yanlinlin82/icpp
4e3127a87201aef6bf96b97082a23d35ca4fe230
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(int argc, const char** argv) { cout << "argc = " << argc << endl; for (int i = 0; i < argc; ++i) { cout << "argv[" << i << "] = \"" << argv[i] << "\"" << endl; } return 0; }
19.25
62
0.493506
yanlinlin82
f6ddecd89fdffa5fca2e93bfc7172d8c86ac2b75
1,433
cpp
C++
libcaf_core/test/optional.cpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
null
null
null
libcaf_core/test/optional.cpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
null
null
null
libcaf_core/test/optional.cpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
null
null
null
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #define CAF_SUITE optional #include "core-test.hpp" #include "caf/optional.hpp" using namespace caf; namespace { struct qwertz { qwertz(int x, int y) : x_(x), y_(y) { // nop } int x_; int y_; }; bool operator==(const qwertz& lhs, const qwertz& rhs) { return lhs.x_ == rhs.x_ && lhs.y_ == rhs.y_; } } // namespace CAF_PUSH_DEPRECATED_WARNING CAF_TEST(empty) { optional<int> x; optional<int> y; CHECK(x == y); CHECK(!(x != y)); } CAF_TEST(equality) { optional<int> x = 42; optional<int> y = 7; CHECK(x != y); CHECK(!(x == y)); } CAF_TEST(ordering) { optional<int> x = 42; optional<int> y = 7; CHECK(x > y); CHECK(x >= y); CHECK(y < x); CHECK(y <= x); CHECK(!(y > x)); CHECK(!(y >= x)); CHECK(!(x < y)); CHECK(!(x <= y)); CHECK(x < 4711); CHECK(4711 > x); CHECK(4711 >= x); CHECK(!(x > 4711)); CHECK(!(x >= 4711)); CHECK(!(4211 < x)); CHECK(!(4211 <= x)); } CAF_TEST(custom_type_none) { optional<qwertz> x; CHECK(x == none); } CAF_TEST(custom_type_engaged) { qwertz obj{1, 2}; optional<qwertz> x = obj; CHECK(x != none); CHECK(obj == x); CHECK(x == obj); CHECK(obj == *x); CHECK(*x == obj); } CAF_POP_WARNINGS
17.691358
77
0.597348
seewpx
f6de6a9317688df27141e919ac7dfead3f911666
6,379
cpp
C++
controls.extend/SGroupList.cpp
denphon/soui
455909ede62a37ded1c1737c65c7cfbc29eae9bd
[ "MIT" ]
null
null
null
controls.extend/SGroupList.cpp
denphon/soui
455909ede62a37ded1c1737c65c7cfbc29eae9bd
[ "MIT" ]
null
null
null
controls.extend/SGroupList.cpp
denphon/soui
455909ede62a37ded1c1737c65c7cfbc29eae9bd
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "SGroupList.h" namespace SOUI { using namespace GroupListStuct; SGroupList::SGroupList():m_pSelectedItem(NULL) { GetEventSet()->addEvent(EVENTID(EventGroupListInitGroup)); GetEventSet()->addEvent(EVENTID(EventGroupListInitItem)); GetEventSet()->addEvent(EVENTID(EventGroupListItemCheck)); GetEventSet()->addEvent(EVENTID(EventGroupStateChanged)); } SGroupList::~SGroupList() { } BOOL SGroupList::CreateChildren(pugi::xml_node xmlNode) { pugi::xml_node groupTemplate = xmlNode.child(L"groupTemplate"); pugi::xml_node itemTemplate = xmlNode.child(L"itemTemplate"); SASSERT(groupTemplate && itemTemplate); m_groupTemplate = m_xmlDoc.root().append_copy(groupTemplate); m_itemTemplate = m_xmlDoc.root().append_copy(itemTemplate); pugi::xml_node xmlData = xmlNode.child(L"data"); if (xmlData) { pugi::xml_node xmlGroup = xmlData.child(L"group"); while (xmlGroup) { SStringT strText = S_CW2T(xmlGroup.attribute(L"text").as_string()); SStringW strName = xmlGroup.attribute(L"name").as_string(); SWindow *pGroup = InsertGroup(-1, strName, strText, xmlGroup.attribute(L"icon").as_int(), xmlGroup.attribute(L"id").as_int()); pugi::xml_node xmlItem = xmlGroup.child(L"item"); while (xmlItem) { SStringT strText = S_CW2T(xmlItem.attribute(L"text").as_string()); SStringW strName = xmlItem.attribute(L"name").as_string(); InsertItem(pGroup, -1, strName, strText, xmlItem.attribute(L"icon").as_int(), xmlItem.attribute(L"id").as_int()); xmlItem = xmlItem.next_sibling(L"item"); } xmlGroup = xmlGroup.next_sibling(L"group"); } } return TRUE; } void SGroupList::OnViewSizeChanged(CSize szOld, CSize szNew) { __super::OnViewSizeChanged(szOld, szNew); } void SGroupList::OnDestroy() { SWindow *pGroup = GetWindow(GSW_FIRSTCHILD); while (pGroup) { GroupInfo *pGroupInfo = (GroupInfo *)pGroup->GetUserData(); delete pGroupInfo; SWindow *pContainer = pGroup->FindChildByName(L"container"); SASSERT(pContainer); SWindow *pItem = pContainer->GetWindow(GSW_FIRSTCHILD); while (pItem) { ItemInfo *pItemInfo = (ItemInfo*)pItem->GetUserData(); delete pItemInfo; pItem = pItem->GetWindow(GSW_NEXTSIBLING); } pGroup = pGroup->GetWindow(GSW_NEXTSIBLING); } __super::OnDestroy(); } bool SGroupList::SelectPage(int nID) { SWindow *pItem = FindChildByID(nID); if(!pItem) return false; EventCmd evt(pItem); OnItemClick(&evt); return true; } SWindow* SGroupList::InsertGroup(int iGroup,const SStringW & name, const SStringT & text, int iIcon, int nID) { SWindow *pInsertAfter = ICWND_FIRST; if (iGroup < 0) { pInsertAfter = ICWND_LAST; } else { for (int i = 0; i < iGroup; i++) { if (pInsertAfter == ICWND_FIRST) pInsertAfter = GetWindow(GSW_FIRSTCHILD); else pInsertAfter = pInsertAfter->GetWindow(GSW_NEXTSIBLING); if (!pInsertAfter) { pInsertAfter = ICWND_LAST; break; } } } SWindow *pGroup = SApplication::getSingletonPtr()->CreateWindowByName(m_groupTemplate.attribute(L"class_name").as_string(L"window")); SASSERT(pGroup); InsertChild(pGroup, pInsertAfter); pGroup->InitFromXml(m_groupTemplate); pGroup->SetName(name); pGroup->SetID(nID); GroupInfo *pItemInfo = new GroupInfo; pItemInfo->bCollapsed = false; pItemInfo->strText = text; pItemInfo->strName = name; pItemInfo->iIcon = iIcon; pItemInfo->id = nID; pGroup->SetUserData((ULONG_PTR)pItemInfo); pGroup->FindChildByName(L"container")->SetVisible(!pItemInfo->bCollapsed); EventGroupListInitGroup evt(this); evt.pItem = pGroup->FindChildByName(L"title"); evt.pGroupInfo = pItemInfo; FireEvent(evt); evt.pItem->GetEventSet()->subscribeEvent(EventCmd::EventID, Subscriber(&SGroupList::OnGroupClick, this)); RequestRelayout(); return pGroup; } SWindow * SGroupList::InsertItem(SWindow * pGroup, int iItem,const SStringW & name, const SStringT & text, int iIcon, int nID) { SWindow *pItemContainer = pGroup->FindChildByName(L"container"); SWindow *pInsertAfter = ICWND_FIRST; if (iItem < 0) { pInsertAfter = ICWND_LAST; } else { for (int i = 0; i < iItem; i++) { if (pInsertAfter == ICWND_FIRST) pInsertAfter = pItemContainer->GetWindow(GSW_FIRSTCHILD); else pInsertAfter = pInsertAfter->GetWindow(GSW_NEXTSIBLING); if (!pInsertAfter) { pInsertAfter = ICWND_LAST; break; } } } SWindow *pItem = SApplication::getSingletonPtr()->CreateWindowByName(m_itemTemplate.attribute(L"class_name").as_string()); SASSERT(pItem); pItemContainer->InsertChild(pItem, pInsertAfter); pItem->InitFromXml(m_itemTemplate); pItem->SetName(name); pItem->SetID(nID); ItemInfo *pItemInfo = new ItemInfo; pItemInfo->strText = text; pItemInfo->strName = name; pItemInfo->iIcon = iIcon; pItemInfo->id = nID; pItem->SetUserData((ULONG_PTR)pItemInfo); EventGroupListInitItem evt(this); evt.pItem = pItem; evt.pItemInfo = pItemInfo; FireEvent(evt); evt.pItem->GetEventSet()->subscribeEvent(EventCmd::EventID, Subscriber(&SGroupList::OnItemClick, this)); RequestRelayout(); return pItem; } bool SGroupList::OnGroupClick(EventArgs * e) { e->bubbleUp = false; SWindow *pSender = sobj_cast<SWindow>(e->sender); GroupInfo *pInfo = (GroupInfo*)pSender->GetParent()->GetUserData(); pInfo->bCollapsed = !pInfo->bCollapsed; pSender->GetParent()->FindChildByName(L"container")->SetVisible(!pInfo->bCollapsed); EventGroupStateChanged evt(this); evt.pItem = pSender->GetParent(); evt.pGroupInfo = pInfo; FireEvent(evt); RequestRelayout(); return true; } bool SGroupList::OnItemClick(EventArgs * e) { SWindow *pSender = sobj_cast<SWindow>(e->sender); if (m_pSelectedItem != pSender) { pSender->SetCheck(TRUE); if (m_pSelectedItem) { m_pSelectedItem->SetCheck(FALSE); } m_pSelectedItem = pSender; EventGroupListItemCheck evt(this); evt.pItem = pSender; evt.pItemInfo = (ItemInfo*)pSender->GetUserData(); FireEvent(evt); } e->bubbleUp = false; return true; } }
28.477679
136
0.677536
denphon
f6e014b66ab47d8aa7d46fc8a08212f071e52b77
1,426
cpp
C++
src/AST_Implementaciones/PosfijoDecremento.cpp
AlejandroRM94/Compilador_C_minimo
6c69987749233876c9f7fc0cde9c479f0d3ba531
[ "MIT" ]
null
null
null
src/AST_Implementaciones/PosfijoDecremento.cpp
AlejandroRM94/Compilador_C_minimo
6c69987749233876c9f7fc0cde9c479f0d3ba531
[ "MIT" ]
null
null
null
src/AST_Implementaciones/PosfijoDecremento.cpp
AlejandroRM94/Compilador_C_minimo
6c69987749233876c9f7fc0cde9c479f0d3ba531
[ "MIT" ]
null
null
null
#include "../AST_Tipos.h" PosfijoDecremento::PosfijoDecremento( Identificador* exp ) { this->exp = exp; } PosfijoDecremento::~PosfijoDecremento( ) { delete exp; } TipoDato PosfijoDecremento::analizarTipo() { return exp->analizarTipo(); } string PosfijoDecremento::toString() { stringstream ss; ss << "<POSFIJO_DECREMENTO>" << endl; if( exp != nullptr ) { ss << exp->toString( ); } ss << "</POSFIJO_DECREMENTO>" << endl; return ss.str(); } string PosfijoDecremento::generarCodigo(){ stringstream ss; int pos = manejadorVariables->buscar(exp->simbolo); //Obtiene la variable ss << TABULADOR << "movl" << TABULADOR; if(pos>=0){ ss << "-" <<pos << "(%rbp)"; }else{ ss << simbolo << "(%rip)"; } ss << "," << TABULADOR << "%r10d" << endl; //Entrega el valor ss << TABULADOR << "movl" << TABULADOR << "%r10d," << TABULADOR << "%eax" << endl; //Incrementa su valor y lo guarda en la variable correspondiente ss << TABULADOR << "subl" << TABULADOR << "$1," << TABULADOR << "%r10d" << endl; ss << TABULADOR << "movl" << TABULADOR << "%r10d," << TABULADOR; if(pos>=0){ ss << "-" <<pos << "(%rbp)"; }else{ ss << simbolo << "(%rip)"; } ss << endl; return ss.str(); } bool PosfijoDecremento::analizarTipoConstante() { return false; } int PosfijoDecremento::evaluar() { return 0; }
23
86
0.568724
AlejandroRM94
f6e2f09d350e2f3d24e4d1d00da22b7980ea000c
3,654
cpp
C++
src/main.cpp
Smorodov/SpatialSubspaceRotation
41453a151b6e107b7177821bf84ef7d7b7be7f57
[ "MIT" ]
5
2019-11-18T11:05:00.000Z
2021-11-25T14:14:13.000Z
src/main.cpp
Smorodov/SpatialSubspaceRotation
41453a151b6e107b7177821bf84ef7d7b7be7f57
[ "MIT" ]
null
null
null
src/main.cpp
Smorodov/SpatialSubspaceRotation
41453a151b6e107b7177821bf84ef7d7b7be7f57
[ "MIT" ]
2
2019-11-18T11:05:53.000Z
2019-11-18T14:56:49.000Z
#include <algorithm> #include <set> #include <opencv2/opencv.hpp> #include "SpatialSubspaceRotation.h" /// /// \brief generateSkinMap /// \param src /// \param dst /// void generateSkinMap(cv::Mat& src, cv::Mat& dst) { cv::cvtColor(src, dst, cv::COLOR_BGR2YCrCb); cv::Mat mask; cv::inRange(dst, cv::Scalar(0, 133, 98), cv::Scalar(255, 177, 142), mask); dst = mask.clone(); } /// /// \brief extractPixels /// \param img_src /// \param values /// void extractPixels(cv::Mat& img_src, cv::Mat& values) { cv::Mat bin; size_t pixelsInImage = (img_src.rows * img_src.cols); generateSkinMap(img_src, bin); int NPx = cv::countNonZero(bin); values = cv::Mat::zeros(NPx, 3, CV_64FC1); int n = 0; for (int j = 0; j < img_src.rows; ++j) { for (int k = 0; k < img_src.cols; ++k) { if (bin.at<uchar>(j, k) > 0) { values.at<double>(n, 0) = img_src.at<cv::Vec3b>(j, k)[2]; // R values.at<double>(n, 1) = img_src.at<cv::Vec3b>(j, k)[1]; // G values.at<double>(n, 2) = img_src.at<cv::Vec3b>(j, k)[0]; // B ++n; } } } } /// /// \brief main /// \param argc /// \param argv /// \return /// int main(int argc, char** argv) { cv::Mat img_src; cv::Mat plot = cv::Mat::zeros(600, 1024, CV_8UC3); std::string fileName = "0"; if (argc > 1) { fileName = argv[1]; } cv::VideoCapture cap; if (fileName.length() == 1) cap.open(atoi(fileName.c_str())); else cap.open(fileName); SpatialSubspaceRotation ssr(10, 2, 5); double pulse = 0; double pulse_prev = 0; int f = 0; int k = 0; while (k != 27) { cap >> img_src; double start = static_cast<double>(cv::getTickCount()); std::cout << " f : " << std::to_string(f) << std::endl; if (img_src.empty()) { cap.set(cv::CAP_PROP_POS_FRAMES, 0); continue; } cv::Mat values; extractPixels(img_src, values); if (values.empty()) { continue; } pulse_prev = pulse; pulse = ssr.Step(values); if (f >= plot.cols) { f = 0; plot.setTo(cv::Scalar::all(0)); } cv::Mat spectline = ssr.GetSpectLine(); if (!spectline.empty()) { cv::applyColorMap(spectline, spectline, cv::COLORMAP_JET); spectline.copyTo(plot(cv::Rect(f, 0, 1, ssr.GetFFTWindowSize()/2))); } int y1 = cvRound(pulse_prev * 1000 + 300); int y2 = cvRound(pulse * 1000 + 300); cv::line(plot, cv::Point(f-1, y1), cv::Point(f, y2), cv::Scalar::all(255), 1); { cv::imshow("img_src", img_src); cv::imshow("plot", plot); k = cv::waitKey(5); } ++f; double end = static_cast<double>(cv::getTickCount()); double time_cost = (end - start) / cv::getTickFrequency() * 1000; std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now(); std::chrono::duration<double> time_span = std::chrono::duration<double>(0); while (time_span.count() < (1000.0 / ssr.GetFrameRate() - time_cost) / 1000.0) { time_span = std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::steady_clock::now() - t1); } double end2 = static_cast<double>(cv::getTickCount()); time_cost = (end2 - start) / cv::getTickFrequency() * 1000; std::cout << "pulse = " << pulse << ", time cost: " << time_cost << "ms" << std::endl; } return 0; }
27.066667
121
0.527367
Smorodov
f6e968abb7b5415701ce5c9bf9462a454066e538
654
hpp
C++
assignment-8 Indexing/Range.hpp
Arda-Bati/RDBMS-Homeworks
e3b121b5d8587552cc7177228ba5a5bea5c2cf68
[ "Apache-2.0" ]
1
2021-04-01T23:45:48.000Z
2021-04-01T23:45:48.000Z
assignment-8 Indexing/Range.hpp
Arda-Bati/Relational-Database
e3b121b5d8587552cc7177228ba5a5bea5c2cf68
[ "Apache-2.0" ]
null
null
null
assignment-8 Indexing/Range.hpp
Arda-Bati/Relational-Database
e3b121b5d8587552cc7177228ba5a5bea5c2cf68
[ "Apache-2.0" ]
null
null
null
// // Range.hpp // Database3 // // Created by rick gessner on 4/12/19. // Copyright © 2019 rick gessner. All rights reserved. // #ifndef Range_h #define Range_h namespace ECE141 { template<class T> struct Range { T* b = nullptr; T* e = nullptr; Range()=default; Range(T* s, T* f):b(s),e(f){} Range(T* s, std::size_t l):Range(s, s+l){} T* begin() const{ return b; } T* end() const{ return e; } T& operator[](std::size_t i)const{ return begin()[i]; } std::size_t size() const { return end()-begin(); } bool empty() const { return begin()==end(); } }; } #endif /* Range_h */
21.096774
60
0.551988
Arda-Bati
f6ead0147466a65a9b1bc333377caed1dee31f57
6,590
cpp
C++
src/backend/DepthCamera.cpp
maoLB/Kintinuous
e327d2ea06d04885f6d8f422ff95db2933f370d1
[ "BSD-4-Clause-UC" ]
854
2015-10-23T17:49:29.000Z
2022-03-28T11:23:37.000Z
src/backend/DepthCamera.cpp
FranticPink/Kintinuous
2043f5b85619f4cbd1c4404058dafc67d338af84
[ "BSD-4-Clause-UC" ]
63
2015-11-03T15:59:16.000Z
2021-10-10T11:13:25.000Z
src/backend/DepthCamera.cpp
FranticPink/Kintinuous
2043f5b85619f4cbd1c4404058dafc67d338af84
[ "BSD-4-Clause-UC" ]
303
2015-10-30T12:13:41.000Z
2022-03-16T08:10:06.000Z
/* * This file is part of Kintinuous. * * Copyright (C) 2015 The National University of Ireland Maynooth and * Massachusetts Institute of Technology * * The use of the code within this file and all code within files that * make up the software that is Kintinuous is permitted for * non-commercial purposes only. The full terms and conditions that * apply to the code within this file are detailed within the LICENSE.txt * file and at <http://www.cs.nuim.ie/research/vision/data/kintinuous/code.php> * unless explicitly stated. By downloading this file you agree to * comply with these terms. * * If you wish to use any of this code for commercial purposes then * please email commercialisation@nuim.ie. * * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2011, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include "DepthCamera.h" DepthCamera::DepthCamera(cv::Mat * calibration) : depthIntrinsics(calibration), principalPoint(depthIntrinsics->at<double>(0, 2), depthIntrinsics->at<double>(1, 2)) { } DepthCamera::~DepthCamera() { } void DepthCamera::projectInlierMatches(std::vector<std::pair<int2, int2> > inliers, std::vector<Eigen::Vector3d> & inl1, std::vector<Eigen::Vector3d> & inl2, unsigned short * depth1, unsigned short * depth2) { for(unsigned int i = 0; i < inliers.size(); i++) { float depthFirst = (float)depth1[inliers.at(i).first.y * Resolution::get().width() + inliers.at(i).first.x] / 1000.f; float depthSecond = (float)depth2[inliers.at(i).second.y * Resolution::get().width() + inliers.at(i).second.x] / 1000.f; if(!depthFirst || !depthSecond) { continue; } Eigen::Vector3d firstProj(depthFirst * (inliers.at(i).first.x - principalPoint.x) * (1 / depthIntrinsics->at<double>(0, 0)), depthFirst * (inliers.at(i).first.y - principalPoint.y) * (1 / depthIntrinsics->at<double>(1, 1)), depthFirst); Eigen::Vector3d secondProj(depthSecond * (inliers.at(i).second.x - principalPoint.x) * (1 / depthIntrinsics->at<double>(0, 0)), depthSecond * (inliers.at(i).second.y - principalPoint.y) * (1 / depthIntrinsics->at<double>(1, 1)), depthSecond); inl1.push_back(firstProj); inl2.push_back(secondProj); } } void DepthCamera::computeVertexMap(cv::Mat & depthMap, cv::Mat & vertexMap) { vertexMap.create(depthMap.rows, depthMap.cols, CV_32FC3); Eigen::Isometry3f m; m.setIdentity(); m(0,0) = depthIntrinsics->at<double>(0,0); m(0,2) = depthIntrinsics->at<double>(0,2); m(1,1) = depthIntrinsics->at<double>(1,1); m(1,2) = depthIntrinsics->at<double>(1,2); Eigen::Projective3f K = m; Eigen::Projective3f Kinv = K.inverse(); for(int row = 0; row < depthMap.rows; row++) { unsigned short * depthRow = (unsigned short *)depthMap.ptr(row); float * vertexRow = (float *)vertexMap.ptr(row); for(int col = 0; col < depthMap.cols; col++) { if(depthRow[col] == 0) { vertexRow[col * 3] = 100000; vertexRow[col * 3 + 1] = 100000; vertexRow[col * 3 + 2] = 100000; } else { Eigen::Vector4f vertex; vertex(0) = col * (float)depthRow[col]; vertex(1) = row * (float)depthRow[col]; vertex(2) = (float)depthRow[col]; vertex(3) = 1; Eigen::Vector4f pixel; pixel = Kinv * vertex; vertexRow[col * 3] = pixel(0) / 1000.0; vertexRow[col * 3 + 1] = pixel(1) / 1000.0; vertexRow[col * 3 + 2] = pixel(2) / 1000.0; } } } } pcl::PointCloud<pcl::PointXYZ>::Ptr DepthCamera::convertToXYZPointCloud(unsigned short * depth_image, float maxDist) { pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud <pcl::PointXYZ>); for(int i = 0; i < Resolution::get().width(); i++) { for(int j = 0; j < Resolution::get().height(); j++) { if(depth_image[j * Resolution::get().width() + i] != 0 && depth_image[j * Resolution::get().width() + i] < maxDist * 1000) { pcl::PointXYZ pt; pt.z = depth_image[j * Resolution::get().width() + i] * 0.001f; pt.x = (static_cast<float>(i) - depthIntrinsics->at<double>(0, 2)) * pt.z * (1.0f / depthIntrinsics->at<double>(0, 0)); pt.y = (static_cast<float>(j) - depthIntrinsics->at<double>(1, 2)) * pt.z * (1.0f / depthIntrinsics->at<double>(1, 1)); cloud->push_back(pt); } } } return cloud; }
40.182927
135
0.606222
maoLB
f6ec5cf04d9a8356be51684364409d40028ab288
3,607
cpp
C++
Stp/Json/JsonValueTest.cpp
markazmierczak/Polonite
240f099cafc5c38dc1ae1cc6fc5773e13f65e9de
[ "MIT" ]
1
2019-07-11T12:47:52.000Z
2019-07-11T12:47:52.000Z
Stp/Json/JsonValueTest.cpp
Polonite/Polonite
240f099cafc5c38dc1ae1cc6fc5773e13f65e9de
[ "MIT" ]
null
null
null
Stp/Json/JsonValueTest.cpp
Polonite/Polonite
240f099cafc5c38dc1ae1cc6fc5773e13f65e9de
[ "MIT" ]
1
2019-07-11T12:47:53.000Z
2019-07-11T12:47:53.000Z
// Copyright 2017 Polonite Authors. All rights reserved. // Distributed under MIT license that can be found in the LICENSE file. #include "Json/JsonValue.h" #include "Base/Test/GTest.h" #include "Json/JsonArray.h" #include "Json/JsonObject.h" namespace stp { TEST(JsonValueTest, Basic) { // Test basic object getting/setting JsonObject settings; StringSpan homepage = "http://google.com"; ASSERT_FALSE(settings.tryGetWithPath("global.homepage", homepage)); ASSERT_EQ("http://google.com", homepage); ASSERT_FALSE(settings.tryGetWithPath("global")); settings.SetWithPath("global", true); ASSERT_TRUE(settings.tryGetWithPath("global")); settings.SetWithPath("global.homepage", "http://scurvy.com"); ASSERT_TRUE(settings.tryGetWithPath("global")); homepage = "http://google.com"; ASSERT_TRUE(settings.tryGetObjectWithPath("global")); ASSERT_TRUE(settings.tryGetWithPath("global.homepage", homepage)); ASSERT_EQ("http://scurvy.com", homepage); // Test storing an object in an array. JsonArray* toolbar_bookmarks = settings.tryGetArrayWithPath("global.toolbar.bookmarks"); ASSERT_FALSE(toolbar_bookmarks); JsonArray new_toolbar_bookmarks; settings.SetWithPath("global.toolbar.bookmarks", move(new_toolbar_bookmarks)); toolbar_bookmarks = settings.tryGetArrayWithPath("global.toolbar.bookmarks"); ASSERT_TRUE(toolbar_bookmarks); JsonObject new_bookmark; new_bookmark.SetWithPath("name", "Froogle"); new_bookmark.SetWithPath("url", "http://froogle.com"); toolbar_bookmarks->add(move(new_bookmark)); JsonArray* bookmark_array = settings.tryGetArrayWithPath("global.toolbar.bookmarks"); ASSERT_TRUE(bookmark_array); ASSERT_EQ(1, bookmark_array->size()); JsonObject* bookmark = bookmark_array->tryGetObject(0); ASSERT_TRUE(bookmark); StringSpan bookmark_name = "Unnamed"; ASSERT_TRUE(bookmark->tryGetWithPath("name", bookmark_name)); ASSERT_EQ("Froogle", bookmark_name); StringSpan bookmark_url; ASSERT_TRUE(bookmark->tryGetWithPath("url", bookmark_url)); ASSERT_EQ("http://froogle.com", bookmark_url); } TEST(JsonValueTest, Array) { JsonArray mixed_array; mixed_array.set(0, JsonValue(true)); mixed_array.set(1, JsonValue(42)); mixed_array.set(2, JsonValue(88.8)); mixed_array.set(3, JsonValue("foo")); ASSERT_EQ(4, mixed_array.size()); bool bool_value = false; int int_value = 0; double double_value = 0.0; StringSpan string_value; JsonValue* value = mixed_array.tryGet(4); ASSERT_FALSE(value); ASSERT_FALSE(mixed_array.tryGet(0, int_value)); ASSERT_EQ(0, int_value); ASSERT_FALSE(mixed_array.tryGet(1, bool_value)); ASSERT_FALSE(bool_value); ASSERT_FALSE(mixed_array.tryGet(2, string_value)); ASSERT_EQ("", string_value); ASSERT_FALSE(mixed_array.tryGet(2, int_value)); ASSERT_EQ(0, int_value); ASSERT_FALSE(mixed_array.tryGet(3, bool_value)); ASSERT_FALSE(bool_value); ASSERT_TRUE(mixed_array.tryGet(0, bool_value)); ASSERT_TRUE(bool_value); ASSERT_TRUE(mixed_array.tryGet(1, int_value)); ASSERT_EQ(42, int_value); // implicit conversion from Integer to Double should be possible. ASSERT_TRUE(mixed_array.tryGet(1, double_value)); ASSERT_EQ(42, double_value); ASSERT_TRUE(mixed_array.tryGet(2, double_value)); ASSERT_EQ(88.8, double_value); ASSERT_TRUE(mixed_array.tryGet(3, string_value)); ASSERT_EQ("foo", string_value); JsonValue sought_value(42); JsonValue not_found_value(false); // Attempt to search in the mixed array. ASSERT_TRUE(mixed_array.contains(sought_value)); ASSERT_FALSE(mixed_array.contains(not_found_value)); } } // namespace stp
34.682692
90
0.757693
markazmierczak
f6eca2630520edcef0dd554eef0443fc4715d904
12,295
cpp
C++
tests/cfloat/conversion/normalization.cpp
shikharvashistha/universal
5c20504504f067412958fa61ea3839cf86c3d6f7
[ "MIT" ]
null
null
null
tests/cfloat/conversion/normalization.cpp
shikharvashistha/universal
5c20504504f067412958fa61ea3839cf86c3d6f7
[ "MIT" ]
null
null
null
tests/cfloat/conversion/normalization.cpp
shikharvashistha/universal
5c20504504f067412958fa61ea3839cf86c3d6f7
[ "MIT" ]
null
null
null
// normalization.cpp: test suite runner for normalization tests of classic cfloats // // Copyright (C) 2017-2021 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include <universal/utility/directives.hpp> // minimum set of include files to reflect source code dependencies // Configure the cfloat template environment // first: enable general or specialized configurations #define CFLOAT_FAST_SPECIALIZATION // second: enable/disable arithmetic exceptions #define CFLOAT_THROW_ARITHMETIC_EXCEPTION 0 // third: enable trace conversion #define TRACE_CONVERSION 0 #include <universal/number/cfloat/cfloat_impl.hpp> #include <universal/number/cfloat/manipulators.hpp> #include <universal/number/cfloat/math_functions.hpp> #include <universal/verification/test_suite_conversion.hpp> #include <universal/verification/cfloat_test_suite.hpp> namespace sw::universal { /// <summary> /// verify that normalization represents the same value /// </summary> /// <typeparam name="bt">block storage type of representation</typeparam> /// <param name="bReportIndividualTestCases">if true print individual test cases</param> /// <returns></returns> template<typename cfloatConfiguration> int VerifyCfloatNormalization(bool bReportIndividualTestCases) { using namespace std; using namespace sw::universal; constexpr size_t nbits = cfloatConfiguration::nbits; constexpr size_t es = cfloatConfiguration::es; using bt = typename cfloatConfiguration::BlockType; constexpr size_t fhbits = nbits - es; cfloat<nbits, es, bt> a; blocktriple<fhbits> b; // representing significant int nrOfTestFailures{ 0 }; for (size_t i = 0; i < 64; ++i) { a.setbits(i); if (a.iszero() || a.isinf() || a.isnan()) { // special values are not normalizable b.setzero(); } else { a.normalize(b); if (double(a) != double(b)) { ++nrOfTestFailures; if (bReportIndividualTestCases) cout << "FAIL: " << to_binary(a) << " : " << a << " != " << to_triple(b) << " : " << b << '\n'; } } } return nrOfTestFailures; } } // conditional compile flags #define MANUAL_TESTING 1 #define STRESS_TESTING 0 int main(int argc, char** argv) try { using namespace std; using namespace sw::universal; print_cmd_line(argc, argv); int nrOfFailedTestCases = 0; std::string tag = "cfloat normalization: "; #if MANUAL_TESTING // cfloat<> is a linear floating-point // to track conversion in more detail std::cout << std::setprecision(8); std::cerr << std::setprecision(8); { constexpr size_t nbits = 10; constexpr size_t es = 4; constexpr size_t fbits = nbits - 1ull - es; cfloat<nbits, es, uint8_t> a; blocktriple<fbits + 1> b; // representing significant a = 0.015625f; // a.normalize(b); cout << to_binary(a) << " : " << a << " : scale " << a.scale() << " : " << to_triple(b) << " : " << b << endl; } #ifdef LATER nrOfFailedTestCases += VerifyCfloatNormalization< cfloat<3, 1, uint8_t> >(true); nrOfFailedTestCases += VerifyCfloatNormalization< cfloat<4, 1, uint8_t> >(true); return 0; nrOfFailedTestCases += VerifyCfloatNormalization< cfloat<5, 1, uint8_t> >(true); nrOfFailedTestCases += VerifyCfloatNormalization< cfloat<6, 1, uint8_t> >(true); nrOfFailedTestCases += VerifyCfloatNormalization< cfloat<7, 1, uint8_t> >(true); nrOfFailedTestCases += VerifyCfloatNormalization< cfloat<8, 1, uint8_t> >(true); nrOfFailedTestCases += VerifyCfloatNormalization< cfloat<9, 1, uint8_t> >(true); #endif std::cout << "failed tests: " << nrOfFailedTestCases << endl; nrOfFailedTestCases = 0; // in manual testing we ignore failures for the regression system #if STRESS_TESTING // manual exhaustive test #endif #else // !MANUAL_TESTING bool bReportIndividualTestCases = false; cout << "cfloat normalization validation" << endl; // es = 1 nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<3, 1> >(bReportIndividualTestCases), tag, "cfloat<3,1>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<4, 1> >(bReportIndividualTestCases), tag, "cfloat<4,1>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<5, 1> >(bReportIndividualTestCases), tag, "cfloat<5,1>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<6, 1> >(bReportIndividualTestCases), tag, "cfloat<6,1>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<7, 1> >(bReportIndividualTestCases), tag, "cfloat<7,1>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<8, 1> >(bReportIndividualTestCases), tag, "cfloat<8,1>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<9, 1> >(bReportIndividualTestCases), tag, "cfloat<9,1>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<10, 1> >(bReportIndividualTestCases), tag, "cfloat<10,1>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<12, 1> >(bReportIndividualTestCases), tag, "cfloat<12,1>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<16, 1> >(bReportIndividualTestCases), tag, "cfloat<16,1>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<18, 1> >(bReportIndividualTestCases), tag, "cfloat<18,1>"); // 3 blocks // es = 2 nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<4, 2> >(bReportIndividualTestCases), tag, "cfloat<4,2>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<5, 2> >(bReportIndividualTestCases), tag, "cfloat<5,2>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<6, 2> >(bReportIndividualTestCases), tag, "cfloat<6,2>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<7, 2> >(bReportIndividualTestCases), tag, "cfloat<7,2>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<8, 2> >(bReportIndividualTestCases), tag, "cfloat<8,2>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<10, 2> >(bReportIndividualTestCases), tag, "cfloat<10,2>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<12, 2> >(bReportIndividualTestCases), tag, "cfloat<12,2>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<14, 2> >(bReportIndividualTestCases), tag, "cfloat<14,2>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<16, 2> >(bReportIndividualTestCases), tag, "cfloat<16,2>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<18, 2> >(bReportIndividualTestCases), tag, "cfloat<18,2>"); // 3 blocks // es = 3 nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<5, 3> >(bReportIndividualTestCases), tag, "cfloat<5,3>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<6, 3> >(bReportIndividualTestCases), tag, "cfloat<6,3>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<7, 3> >(bReportIndividualTestCases), tag, "cfloat<7,3>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<8, 3> >(bReportIndividualTestCases), tag, "cfloat<8,3>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<10, 3> >(bReportIndividualTestCases), tag, "cfloat<10,3>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<12, 3> >(bReportIndividualTestCases), tag, "cfloat<12,3>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<14, 3> >(bReportIndividualTestCases), tag, "cfloat<14,3>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<18, 3> >(bReportIndividualTestCases), tag, "cfloat<18,3>"); // 3 blocks // es = 4 nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<6, 4> >(bReportIndividualTestCases), tag, "cfloat<6,4>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<7, 4> >(bReportIndividualTestCases), tag, "cfloat<7,4>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<8, 4> >(bReportIndividualTestCases), tag, "cfloat<8,4>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<10, 4> >(bReportIndividualTestCases), tag, "cfloat<10,4>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<12, 4> >(bReportIndividualTestCases), tag, "cfloat<12,4>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<14, 4> >(bReportIndividualTestCases), tag, "cfloat<14,4>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<18, 4> >(bReportIndividualTestCases), tag, "cfloat<18,4>"); // 3 blocks // es = 5 nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<7, 5> >(bReportIndividualTestCases), tag, "cfloat<7,5>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<8, 5> >(bReportIndividualTestCases), tag, "cfloat<8,5>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<10, 5> >(bReportIndividualTestCases), tag, "cfloat<10,5>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<12, 5> >(bReportIndividualTestCases), tag, "cfloat<12,5>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<14, 5> >(bReportIndividualTestCases), tag, "cfloat<14,5>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<18, 5> >(bReportIndividualTestCases), tag, "cfloat<18,5>"); // 3 blocks // es = 6 nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<8, 6> >(bReportIndividualTestCases), tag, "cfloat<8,6>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<9, 6> >(bReportIndividualTestCases), tag, "cfloat<9,6>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<10, 6> >(bReportIndividualTestCases), tag, "cfloat<10,6>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<12, 6> >(bReportIndividualTestCases), tag, "cfloat<12,6>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<14, 6> >(bReportIndividualTestCases), tag, "cfloat<14,6>"); // es = 7 nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat< 9, 7> >(bReportIndividualTestCases), tag, "cfloat<9,7>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<10, 7> >(bReportIndividualTestCases), tag, "cfloat<10,7>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<12, 7> >(bReportIndividualTestCases), tag, "cfloat<12,7>"); nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<14, 7> >(bReportIndividualTestCases), tag, "cfloat<14,7>"); // still failing // es = 8 // nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<11, 8> >(bReportIndividualTestCases), tag, "cfloat<11,8>"); // nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<12, 8> >(bReportIndividualTestCases), tag, "cfloat<12,8>"); // nrOfFailedTestCases = ReportTestResult(VerifyCfloatNormalization< cfloat<14, 8> >(bReportIndividualTestCases), tag, "cfloat<14,8>"); #if STRESS_TESTING #endif // STRESS_TESTING #endif // MANUAL_TESTING return (nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS); } catch (char const* msg) { std::cerr << "Caught exception: " << msg << std::endl; return EXIT_FAILURE; } catch (const sw::universal::cfloat_arithmetic_exception& err) { std::cerr << "Uncaught cfloat arithmetic exception: " << err.what() << std::endl; return EXIT_FAILURE; } catch (const sw::universal::cfloat_internal_exception& err) { std::cerr << "Uncaught cfloat internal exception: " << err.what() << std::endl; return EXIT_FAILURE; } catch (const std::runtime_error& err) { std::cerr << "Uncaught runtime exception: " << err.what() << std::endl; return EXIT_FAILURE; } catch (...) { std::cerr << "Caught unknown exception" << std::endl; return EXIT_FAILURE; } /* To generate: GenerateFixedPointComparisonTable<4, 0>(std::string("-")); GenerateFixedPointComparisonTable<4, 1>(std::string("-")); GenerateFixedPointComparisonTable<4, 2>(std::string("-")); */
52.097458
147
0.755754
shikharvashistha
f6ed6aa2ef053df1fef354dae9223128be09d326
295
hpp
C++
Source/Hyper/include/Hyper/Identifier.hpp
SkillerRaptor/HyperLang
c7bcabf90462247e388861b4255fe61e74c32fca
[ "MIT" ]
13
2021-08-08T19:17:22.000Z
2022-02-17T10:52:07.000Z
Source/Hyper/include/Hyper/Identifier.hpp
SkillerRaptor/HyperLang
c7bcabf90462247e388861b4255fe61e74c32fca
[ "MIT" ]
null
null
null
Source/Hyper/include/Hyper/Identifier.hpp
SkillerRaptor/HyperLang
c7bcabf90462247e388861b4255fe61e74c32fca
[ "MIT" ]
null
null
null
/* * Copyright (c) 2020-2021, SkillerRaptor <skillerraptor@protonmail.com> * * SPDX-License-Identifier: MIT */ #pragma once #include "Hyper/SourceRange.hpp" #include <string> namespace Hyper { struct Identifier { std::string value; SourceRange range = {}; }; } // namespace Hyper
14.047619
72
0.691525
SkillerRaptor
f6eea5b500cd524c8b06b779f0859fe398fce131
1,712
cpp
C++
Examples/ScalarField/Main_ScalarField.cpp
boxuange/GRChombo
4baece8164eef6fae5e1b29d929ef324d9e8081b
[ "BSD-3-Clause" ]
42
2018-02-01T20:58:05.000Z
2022-03-20T07:26:31.000Z
Examples/ScalarField/Main_ScalarField.cpp
boxuange/GRChombo
4baece8164eef6fae5e1b29d929ef324d9e8081b
[ "BSD-3-Clause" ]
140
2018-02-12T13:43:13.000Z
2022-03-23T14:56:19.000Z
Examples/ScalarField/Main_ScalarField.cpp
boxuange/GRChombo
4baece8164eef6fae5e1b29d929ef324d9e8081b
[ "BSD-3-Clause" ]
40
2018-01-29T15:36:52.000Z
2022-03-30T02:45:54.000Z
/* GRChombo * Copyright 2012 The GRChombo collaboration. * Please refer to LICENSE in GRChombo's root directory. */ // Chombo includes #include "parstream.H" //Gives us pout() // System includes #include <iostream> // Our general includes #include "DefaultLevelFactory.hpp" #include "GRAMR.hpp" #include "GRParmParse.hpp" #include "SetupFunctions.hpp" #include "SimulationParameters.hpp" // Problem specific includes: #include "ScalarFieldLevel.hpp" // Chombo namespace #include "UsingNamespace.H" int runGRChombo(int argc, char *argv[]) { // Load the parameter file and construct the SimulationParameter class // To add more parameters edit the SimulationParameters file. char *in_file = argv[1]; GRParmParse pp(argc - 2, argv + 2, NULL, in_file); SimulationParameters sim_params(pp); if (sim_params.just_check_params) return 0; // The line below selects the problem that is simulated // (To simulate a different problem, define a new child of AMRLevel // and an associated LevelFactory) GRAMR gr_amr; DefaultLevelFactory<ScalarFieldLevel> scalar_field_level_fact(gr_amr, sim_params); setupAMRObject(gr_amr, scalar_field_level_fact); // Engage! Run the evolution gr_amr.run(sim_params.stop_time, sim_params.max_steps); gr_amr.conclude(); return 0; } int main(int argc, char *argv[]) { mainSetup(argc, argv); int status = runGRChombo(argc, argv); if (status == 0) pout() << "GRChombo finished." << std::endl; else pout() << "GRChombo failed with return code " << status << std::endl; mainFinalize(); return status; }
26.338462
78
0.67465
boxuange
f6f21795f48b20138971572845720c78eee3fcaf
521
cpp
C++
docs/assets/examples/bind-values.cpp
gkgoat1/lexy
9c600fa906e81efbb3e34b8951ebc56809f2a0df
[ "BSL-1.0" ]
527
2020-12-01T14:23:50.000Z
2022-03-31T11:30:24.000Z
docs/assets/examples/bind-values.cpp
ExternalRepositories/lexy
edc6bd4aabd6f0ecbddba6f2bbf9bd2c6e4fa61d
[ "BSL-1.0" ]
44
2020-12-01T18:39:38.000Z
2022-03-08T00:22:39.000Z
docs/assets/examples/bind-values.cpp
ExternalRepositories/lexy
edc6bd4aabd6f0ecbddba6f2bbf9bd2c6e4fa61d
[ "BSL-1.0" ]
24
2020-12-02T01:45:53.000Z
2022-03-22T21:31:31.000Z
#include <cstdio> #include <lexy/callback.hpp> //{ constexpr auto my_callback = lexy::callback<int>([](int factor, int i) { return factor * i; }, [](int factor, int a, int b) { return factor * (a + b); }); // Bind the first parameter and forward the rest unchanged. constexpr auto bound = lexy::bind(my_callback, 2, lexy::values); //} int main() { std::printf("one argument: %d\n", bound(11)); // 2 * 11 std::printf("two arguments: %d\n", bound(11, 42)); // 2 * (11 + 42) }
27.421053
85
0.579655
gkgoat1
f6f2233008c0b87ff57025fe9693118df8ec36d1
2,898
cc
C++
cinn/optim/transform_polyfor_to_for_test.cc
T8T9/CINN
3d5641c4dea370c6666255bc517c56b826a62773
[ "Apache-2.0" ]
null
null
null
cinn/optim/transform_polyfor_to_for_test.cc
T8T9/CINN
3d5641c4dea370c6666255bc517c56b826a62773
[ "Apache-2.0" ]
null
null
null
cinn/optim/transform_polyfor_to_for_test.cc
T8T9/CINN
3d5641c4dea370c6666255bc517c56b826a62773
[ "Apache-2.0" ]
null
null
null
#include "cinn/optim/transform_polyfor_to_for.h" #include <gtest/gtest.h> #include "cinn/cinn.h" namespace cinn { namespace optim { TEST(Expr, basic) { using namespace ir; // NOLINT Expr M(512); Expr K(200); Expr N(500); Placeholder<float> A("A", {M, K}); Placeholder<float> B("B", {K, N}); // C = A * B Var k(K.as_int32(), "k0"); Tensor C = Compute( {M, N}, [&](Var i, Var j) { return lang::ReduceSum(A(i, k) * B(k, j), {k}); }, "C"); auto stages = CreateStages({C}); { stages[C]->Split("i", 8); stages[C]->Split("j", 8); } // Code gen auto func = Lower("matmul", stages, {A, B, C}); Target target; target.arch = Target::Arch ::X86; target.bits = Target::Bit ::k32; target.os = Target::OS ::Linux; { ir::Module::Builder builder("module1", target); builder.AddFunction(func); CodeGenC codegen(target); codegen.SetInlineBuiltinCodes(false); auto out = codegen.Compile(builder.Build(), CodeGenC::OutputKind::CImpl); std::cout << "out:\n" << out; } optim::TransformPolyForToFor(&func->body); { ir::Module::Builder builder("module1", target); builder.AddFunction(func); CodeGenC codegen(target); codegen.SetInlineBuiltinCodes(false); auto out = codegen.Compile(builder.Build(), CodeGenC::OutputKind::CImpl); std::cout << "out:\n" << out; auto target_out = R"ROC( #include <cinn_runtime.h> #include <stdio.h> void matmul(void* _args, int32_t num_args) { const cinn_buffer_t* _A = cinn_pod_value_to_buffer_p(&(((cinn_pod_value_t*)(_args))[0])); const cinn_buffer_t* _B = cinn_pod_value_to_buffer_p(&(((cinn_pod_value_t*)(_args))[1])); cinn_buffer_t* _C = cinn_pod_value_to_buffer_p(&(((cinn_pod_value_t*)(_args))[2])); cinn_buffer_malloc((void*)(0), _C); const float* A = ((const float*)(_A->memory)); const float* B = ((const float*)(_B->memory)); float* C = ((float*)(_C->memory)); float* C__reduce_init = ((float*)(_C->memory)); for (int32_t i = 0; i < 512; i += 1) { for (int32_t j = 0; j < 500; j += 1) { C__reduce_init[((500 * i) + j)] = 0; }; }; for (int32_t i_outer = 0; i_outer < 64; i_outer += 1) { for (int32_t i_inner = 0; i_inner < 8; i_inner += 1) { for (int32_t j_outer = 0; j_outer < 63; j_outer += 1) { for (int32_t j_inner = 0; j_inner < (1 + cinn_min(7, (499 + (-8 * j_outer)))); j_inner += 1) { for (int32_t k0 = 0; k0 < 200; k0 += 1) { C[((500 * i_inner) + ((4000 * i_outer) + ((8 * j_outer) + j_inner)))] = (C[((500 * i_inner) + ((4000 * i_outer) + ((8 * j_outer) + j_inner)))] + (A[((200 * i_inner) + ((1600 * i_outer) + k0))] * B[((8 * j_outer) + ((500 * k0) + j_inner))])); }; }; }; }; }; cinn_buffer_free((void*)(0), _C); } )ROC"; EXPECT_EQ(utils::Trim(target_out), utils::Trim(out)); } } } // namespace optim } // namespace cinn
28.98
253
0.584886
T8T9