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
b3300a31507ffdad377a2a6fa8d98adf15252013
1,050
cpp
C++
src/firmware/cpu/led.cpp
vagran/hydroponics
e0fd187f5b96646ac71526bda50dbe3ad0c0249f
[ "BSD-3-Clause" ]
26
2015-10-11T18:07:41.000Z
2022-01-17T19:49:37.000Z
src/firmware/cpu/led.cpp
vagran/hydroponics
e0fd187f5b96646ac71526bda50dbe3ad0c0249f
[ "BSD-3-Clause" ]
null
null
null
src/firmware/cpu/led.cpp
vagran/hydroponics
e0fd187f5b96646ac71526bda50dbe3ad0c0249f
[ "BSD-3-Clause" ]
1
2019-02-24T04:11:21.000Z
2019-02-24T04:11:21.000Z
/* This file is a part of 'hydroponics' project. * Copyright (c) 2015, Artyom Lebedev <artyom.lebedev@gmail.com> * All rights reserved. * See LICENSE file for copyright details. */ /** @file led.cpp */ #include "cpu.h" using namespace adk; Led led; Led::Led() { AVR_BIT_SET8(AVR_REG_DDR(LED_PORT), LED_PIN); mode = static_cast<u8>(Mode::STANDBY); patPos = 0; pattern = Pattern::STANDBY; } void Led::Initialize() { scheduler.ScheduleTask(_Animator, ANIMATION_PERIOD); } u16 Led::_Animator() { return led.Animator(); } u16 Led::Animator() { if (pattern & (1 << patPos)) { AVR_BIT_SET8(AVR_REG_PORT(LED_PORT), LED_PIN); } else { AVR_BIT_CLR8(AVR_REG_PORT(LED_PORT), LED_PIN); } patPos++; return ANIMATION_PERIOD; } void Led::SetMode(Mode mode) { this->mode = static_cast<u8>(mode); switch (mode) { case Mode::STANDBY: pattern = Pattern::STANDBY; break; case Mode::FAILURE: pattern = Pattern::FAILURE; break; } patPos = 0; }
17.213115
64
0.626667
vagran
b3309a268b396a955a2a57ad8fc2b320d3b562af
1,552
cpp
C++
gym/index00_09/ioi2021_00/RB.cpp
daklqw/IOI2021-training
4f21cef8eec47330e3db77a3d90cbe2309fa8294
[ "Apache-2.0" ]
6
2020-10-12T05:07:03.000Z
2021-09-11T14:54:58.000Z
gym/index00_09/ioi2021_00/RB.cpp
daklqw/IOI2021-training
4f21cef8eec47330e3db77a3d90cbe2309fa8294
[ "Apache-2.0" ]
null
null
null
gym/index00_09/ioi2021_00/RB.cpp
daklqw/IOI2021-training
4f21cef8eec47330e3db77a3d90cbe2309fa8294
[ "Apache-2.0" ]
2
2021-02-09T02:06:31.000Z
2021-10-06T01:25:08.000Z
#include <bits/stdc++.h> const int MAXN = 1e5 + 10; void bye() { std::cout << "Impossible" << std::endl; exit(0); } int n, P, noB, noG, G1, G2, B1, B2, Gex, Bex; int main() { std::ios_base::sync_with_stdio(false), std::cin.tie(0); std::cin >> n >> noB >> noG; noB = n - noB; noG = n - noG; if (noB == 0 && noG == n) { for (int i = 0; i < n; ++i) std::cout << 'B'; std::cout << '\n'; return 0; } if (noB == n && noG == 0) { for (int i = 0; i < n; ++i) std::cout << 'G'; std::cout << '\n'; return 0; } if (noB + noG > n || (n - noB - noG) % 2 != 0) bye(); int g2b2 = (n - noB - noG) / 2; for (P = 1; P * 2 <= n; ++P) { int g1b1 = P * 2 - g2b2; int gexbex = noB + noG - g1b1; if (g1b1 < 0 || gexbex < 0) continue; bool can = false; for (int j = 0; j != 4; ++j) { int L = std::max(std::max(noG - gexbex, g1b1 - P), 0); int R = std::min(std::min(noG, g1b1), P); if (j & 1) { L = std::max(L, g1b1 - noB); R = std::min(R, g1b1 - noB); } else R = std::min(R, P - 1); if (j & 2) { L = std::max(L, noG); R = std::min(R, noG); } else L = std::max(L, g1b1 - P + 1); if (L <= R) { can = true; G1 = L, G2 = P - L; B1 = g1b1 - G1, B2 = P - B1; Bex = noG - G1; Gex = noB - B1; break; } } if (can) break; } if (P * 2 > n) bye(); for (int i = 1; i <= P; ++i) { int c = i <= G2 ? 2 + (i == 1) * Gex : G1 > 0; while (c --> 0) std::cout << 'G'; c = i <= B2 ? 2 + (i == 1) * Bex : B1 > 0; while (c --> 0) std::cout << 'B'; } std::cout << '\n'; return 0; }
24.634921
57
0.438789
daklqw
b335d3719f573fc295a28ac589275becf20bc892
1,679
cpp
C++
ProjectEuler/pe213.cpp
wang12d/ProgrammingPractices
c7a150eb1aeb0e30a30bc77a25aba940b99ce773
[ "MIT" ]
null
null
null
ProjectEuler/pe213.cpp
wang12d/ProgrammingPractices
c7a150eb1aeb0e30a30bc77a25aba940b99ce773
[ "MIT" ]
null
null
null
ProjectEuler/pe213.cpp
wang12d/ProgrammingPractices
c7a150eb1aeb0e30a30bc77a25aba940b99ce773
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using std::cout; using std::endl; using std::vector; int main(int argc, char** argv) { const int grid{30}; const int bells{50}; vector<vector<double>> emptyGrid(grid, vector<double>(grid, 1.0)); for (int i = 0; i < grid; ++i) { for (int j = 0; j < grid; ++j) { vector<vector<double>> flea(grid, vector<double>(grid, 0.0)); flea[i][j] = 1; for (int b = 0; b < bells; ++b) { vector<vector<double>> nextPos(grid, vector<double>(grid, 0.0)); for (int i = 0; i < grid; ++i) { for (int j = 0; j < grid; ++j) { if (flea[i][j] == 0) continue; int dire{4}; if (i == 0 || i == grid-1) dire--; if (j == 0 || j == grid-1) dire--; double prob{1.0/dire}; double nextProb{flea[i][j]*prob}; if (j != grid-1) nextPos[i][j+1] += nextProb; if (j != 0) nextPos[i][j-1] += nextProb; if (i != 0) nextPos[i-1][j] += nextProb; if (i != grid-1) nextPos[i+1][j] += nextProb; } } flea = std::move(nextPos); } for (int i = 0; i < grid; ++i) { for (int j = 0; j < grid; ++j) { emptyGrid[i][j] *= (1-flea[i][j]); } } } } double res{.0}; for (auto &v: emptyGrid) { for (auto &u: v) { res += u; } } cout << std::fixed << std::setprecision(6) << res << endl; }
34.979167
80
0.387731
wang12d
b33c37c8882954616a472056e96df77ee546adac
2,261
cpp
C++
src/childsarequest.cpp
OpenIKEv2/libopenikev2
9d91225e5917cbc9afc83db37dfe4905c5501d01
[ "Apache-2.0" ]
7
2017-02-27T17:52:26.000Z
2021-12-15T06:03:26.000Z
src/childsarequest.cpp
David-WL/libopenikev2
9d91225e5917cbc9afc83db37dfe4905c5501d01
[ "Apache-2.0" ]
5
2017-03-02T20:16:41.000Z
2017-11-04T08:23:13.000Z
src/childsarequest.cpp
David-WL/libopenikev2
9d91225e5917cbc9afc83db37dfe4905c5501d01
[ "Apache-2.0" ]
3
2017-04-12T00:25:25.000Z
2021-09-23T09:13:27.000Z
/*************************************************************************** * Copyright (C) 2005 by * * Alejandro Perez Mendez alex@um.es * * Pedro J. Fernandez Ruiz pedroj@um.es * * * * This software may be modified and distributed under the terms * * of the Apache license. See the LICENSE file for details. * ***************************************************************************/ #include "childsarequest.h" namespace openikev2 { ChildSaRequest::ChildSaRequest( Enums::PROTOCOL_ID ipsec_protocol, Enums::IPSEC_MODE mode, auto_ptr< Payload_TS > my_traffic_selector, auto_ptr< Payload_TS > peer_traffic_selector ) { this->ipsec_protocol = ipsec_protocol; this->mode = mode; this->my_traffic_selector = my_traffic_selector; this->peer_traffic_selector = peer_traffic_selector; } ChildSaRequest::ChildSaRequest( const ChildSaRequest & other ) { this->ipsec_protocol = other.ipsec_protocol; this->mode = other.mode; this->my_traffic_selector.reset( new Payload_TSi( *other.my_traffic_selector ) ); this->peer_traffic_selector.reset( new Payload_TSr( *other.peer_traffic_selector ) ); } ChildSaRequest::~ChildSaRequest() { } auto_ptr< ChildSaRequest > ChildSaRequest::clone() { return auto_ptr<ChildSaRequest> ( new ChildSaRequest( *this ) ); } string ChildSaRequest::toStringTab( uint8_t tabs ) const { ostringstream oss; // Prints object name oss << Printable::generateTabs( tabs ) << "CHILD_SA_REQUEST{\n"; oss << Printable::generateTabs( tabs + 1 ) << "ipsec protocol=[" << Enums::PROTOCOL_ID_STR( this->ipsec_protocol ) << "]\n"; oss << Printable::generateTabs( tabs + 1 ) << "mode=[" << Enums::IPSEC_MODE_STR( this->mode ) << "]\n"; oss << this->my_traffic_selector->toStringTab( tabs + 1 ); oss << this->peer_traffic_selector->toStringTab( tabs + 1 ); oss << Printable::generateTabs( tabs ) << "}\n"; return oss.str(); } }
40.375
187
0.551968
OpenIKEv2
b3416925e4bc9bb3abdd3983c11703a531a91d9b
5,267
cpp
C++
base/files/version_info.cpp
luciouskami/libbase
89dc13b0eab4d6a48e74c99254b025a15b875ee0
[ "BSD-3-Clause" ]
6
2021-09-24T06:18:14.000Z
2022-03-21T20:44:21.000Z
base/files/version_info.cpp
luciouskami/libbase
89dc13b0eab4d6a48e74c99254b025a15b875ee0
[ "BSD-3-Clause" ]
null
null
null
base/files/version_info.cpp
luciouskami/libbase
89dc13b0eab4d6a48e74c99254b025a15b875ee0
[ "BSD-3-Clause" ]
2
2021-09-23T06:01:55.000Z
2021-09-24T06:18:15.000Z
// Copyright 2021 The Tapirus-Team Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/universal.inl" namespace base::files { namespace { struct LanguageAndCodePage { WORD language; WORD code_page; }; // Returns the \VarFileInfo\Translation value extracted from the // VS_VERSION_INFO resource in |data|. LanguageAndCodePage* GetTranslate(const void* data) { static constexpr wchar_t kTranslation[] = L"\\VarFileInfo\\Translation"; LPVOID translate = nullptr; UINT dummy_size = 0; if (::VerQueryValueW(data, kTranslation, &translate, &dummy_size)) return static_cast<LanguageAndCodePage*>(translate); return nullptr; } const VS_FIXEDFILEINFO& GetVsFixedFileInfo(const void* data) { static constexpr wchar_t kRoot[] = L"\\"; LPVOID fixed_file_info = nullptr; UINT dummy_size = 0; ::VerQueryValueW(data, kRoot, &fixed_file_info, &dummy_size); return *static_cast<VS_FIXEDFILEINFO*>(fixed_file_info); } } // namespace std::unique_ptr<FileVersionInfo> FileVersionInfo::New(_In_ const std::filesystem::path& file_path) { DWORD dummy = 0; const wchar_t* path = file_path.c_str(); const DWORD length = ::GetFileVersionInfoSizeW(path, &dummy); if (length == 0) return nullptr; std::vector<uint8_t> data(length, 0); if (!::GetFileVersionInfoW(path, 0, length, data.data())) return nullptr; const auto translate = GetTranslate(data.data()); if (!translate) return nullptr; return std::unique_ptr<FileVersionInfo>(new FileVersionInfo( std::move(data), translate->language, translate->code_page)); } FileVersionInfo::FileVersionInfo(std::vector<uint8_t>&& data, WORD language, WORD code_page) : _OwnedData(std::move(data)) , _Data(_OwnedData.data()) , _Language(language) , _CodePage(code_page) , _FixedFileInfo(GetVsFixedFileInfo(_Data)) { } FileVersionInfo::FileVersionInfo(void* data, WORD language, WORD code_page) : _Data(data) , _Language(language) , _CodePage(code_page) , _FixedFileInfo(GetVsFixedFileInfo(_Data)) { } std::wstring FileVersionInfo::GetCompanyName() const { return GetStringValue(L"CompanyName"); } std::wstring FileVersionInfo::GetCompanyShortName() const { return GetStringValue(L"CompanyShortName"); } std::wstring FileVersionInfo::GetProductName() const { return GetStringValue(L"ProductName"); } std::wstring FileVersionInfo::GetProductShortName() const { return GetStringValue(L"ProductShortName"); } std::wstring FileVersionInfo::GetInternalName() const { return GetStringValue(L"InternalName"); } std::wstring FileVersionInfo::GetProductVersion() const { return GetStringValue(L"ProductVersion"); } std::wstring FileVersionInfo::GetSpecialBuild() const { return GetStringValue(L"SpecialBuild"); } std::wstring FileVersionInfo::GetOriginalFileName() const { return GetStringValue(L"OriginalFilename"); } std::wstring FileVersionInfo::GetFileDescription() const { return GetStringValue(L"FileDescription"); } std::wstring FileVersionInfo::GetFileVersion() const { return GetStringValue(L"FileVersion"); } bool FileVersionInfo::GetValue(_In_ const wchar_t* name, _Out_ std::wstring* value) const { value->clear(); const struct LanguageAndCodePage lang_codepages[] = { // Use the language and codepage from the DLL. { _Language, _CodePage }, // Use the default language and codepage from the DLL. { ::GetUserDefaultLangID(), _CodePage }, // Use the language from the DLL and Latin codepage (most common). { _Language, 1252 }, // Use the default language and Latin codepage (most common). { ::GetUserDefaultLangID(), 1252 }, }; for (const auto& lang_codepage : lang_codepages) { wchar_t sub_block[MAX_PATH]{}; _snwprintf_s(sub_block, _countof(sub_block), _countof(sub_block), L"\\StringFileInfo\\%04x%04x\\%ls", lang_codepage.language, lang_codepage.code_page, name); LPVOID value_ptr = nullptr; uint32_t size = 0; BOOL r = ::VerQueryValueW(_Data, sub_block, &value_ptr, &size); if (r && value_ptr && size) { value->assign(static_cast<wchar_t*>(value_ptr), size - 1); return true; } } return false; } std::wstring FileVersionInfo::GetStringValue(_In_ const wchar_t* name) const { std::wstring str; GetValue(name, &str); return std::move(str); } }
29.261111
102
0.606987
luciouskami
b342c3749a0cbaad2bf8f77d204d12b624832070
2,615
cpp
C++
src/gpu/d3d/GrD3DAttachment.cpp
NearTox/Skia
8b7e0616161fff86ecbd8938b90600d72b8d5c1d
[ "BSD-3-Clause" ]
null
null
null
src/gpu/d3d/GrD3DAttachment.cpp
NearTox/Skia
8b7e0616161fff86ecbd8938b90600d72b8d5c1d
[ "BSD-3-Clause" ]
null
null
null
src/gpu/d3d/GrD3DAttachment.cpp
NearTox/Skia
8b7e0616161fff86ecbd8938b90600d72b8d5c1d
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2020 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/gpu/d3d/GrD3DAttachment.h" #include "src/gpu/d3d/GrD3DGpu.h" GrD3DAttachment::GrD3DAttachment( GrD3DGpu* gpu, SkISize dimensions, UsageFlags supportedUsages, DXGI_FORMAT format, const D3D12_RESOURCE_DESC& desc, const GrD3DTextureResourceInfo& info, sk_sp<GrD3DResourceState> state, const GrD3DDescriptorHeap::CPUHandle& view) : GrAttachment(gpu, dimensions, supportedUsages, desc.SampleDesc.Count, GrProtected::kNo), GrD3DTextureResource(info, state), fView(view), fFormat(format) { this->registerWithCache(SkBudgeted::kYes); } sk_sp<GrD3DAttachment> GrD3DAttachment::MakeStencil( GrD3DGpu* gpu, SkISize dimensions, int sampleCnt, DXGI_FORMAT format) { D3D12_RESOURCE_DESC resourceDesc = {}; resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; resourceDesc.Alignment = 0; // default alignment resourceDesc.Width = dimensions.width(); resourceDesc.Height = dimensions.height(); resourceDesc.DepthOrArraySize = 1; resourceDesc.MipLevels = 1; resourceDesc.Format = format; resourceDesc.SampleDesc.Count = sampleCnt; resourceDesc.SampleDesc.Quality = DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN; resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; // use driver-selected swizzle resourceDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; D3D12_CLEAR_VALUE clearValue = {}; clearValue.Format = format; clearValue.DepthStencil.Depth = 0; clearValue.DepthStencil.Stencil = 0; GrD3DTextureResourceInfo info; if (!GrD3DTextureResource::InitTextureResourceInfo( gpu, resourceDesc, D3D12_RESOURCE_STATE_DEPTH_WRITE, GrProtected::kNo, &clearValue, &info)) { return nullptr; } GrD3DDescriptorHeap::CPUHandle view = gpu->resourceProvider().createDepthStencilView(info.fResource.get()); sk_sp<GrD3DResourceState> state(new GrD3DResourceState(info.fResourceState)); return sk_sp<GrD3DAttachment>(new GrD3DAttachment( gpu, dimensions, UsageFlags::kStencilAttachment, format, resourceDesc, info, std::move(state), view)); } void GrD3DAttachment::onRelease() { GrD3DGpu* gpu = this->getD3DGpu(); this->releaseResource(gpu); GrAttachment::onRelease(); } void GrD3DAttachment::onAbandon() { GrD3DGpu* gpu = this->getD3DGpu(); this->releaseResource(gpu); GrAttachment::onAbandon(); } GrD3DGpu* GrD3DAttachment::getD3DGpu() const { SkASSERT(!this->wasDestroyed()); return static_cast<GrD3DGpu*>(this->getGpu()); }
33.961039
100
0.754876
NearTox
b3451c655d4efa665a9a50d125b5aa897f757543
708
cpp
C++
test/tests/models/tx/Test_TxBody.cpp
ltc-mweb/libmw
e4c487e5e90a17d2121d1e7f1cd65d4793a5c7ac
[ "MIT" ]
24
2020-10-01T10:15:22.000Z
2022-02-01T20:07:47.000Z
test/tests/models/tx/Test_TxBody.cpp
Dogecoin2-0/MimbleWimble
e4c487e5e90a17d2121d1e7f1cd65d4793a5c7ac
[ "MIT" ]
29
2020-10-11T00:43:51.000Z
2021-07-01T22:39:06.000Z
test/tests/models/tx/Test_TxBody.cpp
Dogecoin2-0/MimbleWimble
e4c487e5e90a17d2121d1e7f1cd65d4793a5c7ac
[ "MIT" ]
5
2020-10-02T13:17:50.000Z
2021-05-30T03:26:49.000Z
#include <catch.hpp> #include <test_framework/TxBuilder.h> TEST_CASE("Tx Body") { const uint64_t pegInAmount = 123; const uint64_t fee = 5; mw::Transaction::CPtr tx = test::TxBuilder() .AddInput(20).AddInput(30, EOutputFeatures::PEGGED_IN) .AddOutput(45).AddOutput(pegInAmount, EOutputFeatures::PEGGED_IN) .AddPlainKernel(fee).AddPeginKernel(pegInAmount) .Build().GetTransaction(); const TxBody& txBody = tx->GetBody(); txBody.Validate(); // // Serialization // Deserializer deserializer(txBody.Serialized()); REQUIRE(txBody == deserializer.Read<TxBody>()); // // Getters // REQUIRE(txBody.GetTotalFee() == fee); }
24.413793
73
0.648305
ltc-mweb
b3452d368e6018349aa361ab2078add4b1e52ef9
1,434
cpp
C++
compiler-information/sizeofs.cpp
mstankus/my-common-cpp
8b3e282e6fd987bf53886a262a96daf9bd9e8a6e
[ "MIT" ]
null
null
null
compiler-information/sizeofs.cpp
mstankus/my-common-cpp
8b3e282e6fd987bf53886a262a96daf9bd9e8a6e
[ "MIT" ]
null
null
null
compiler-information/sizeofs.cpp
mstankus/my-common-cpp
8b3e282e6fd987bf53886a262a96daf9bd9e8a6e
[ "MIT" ]
null
null
null
#include <iostream> #include <stdint.h> #include <string> #include <string_view> #include <memory> template<typename T> void print_type(const char * s) { auto i = strlen(s); std::cout << s; for(;i<30;++i) std::cout << ' '; std::cout << ": " << sizeof(T) << " bytes (x" << CHAR_BIT << " = " << sizeof(T)*CHAR_BIT << " bits)" << '\n'; } void sizeofs() { print_type<char>("char_t"); print_type<int8_t>("int8_t"); print_type<int16_t>("int16_t"); print_type<int32_t>("int32_t"); print_type<int64_t>("int32_t"); std::cout << '\n'; print_type<int>("int"); print_type<long>("long"); print_type<long long>("long long"); print_type<std::size_t>("std::size_t"); std::cout << '\n'; print_type<float>("float"); print_type<long double>("long double"); print_type<bool>("bool"); print_type<bool[32]>("bool[32]"); std::cout << '\n'; print_type<std::string>("std::string"); print_type<std::string>("std::string_view"); std::cout << '\n'; print_type<std::string>("std::shared_ptr<int>"); print_type<std::string>("std::shared_ptr<std::string>"); std::cout << '\n'; print_type<std::string>("std::unique_ptr<int>"); print_type<std::string>("std::unique_ptr<std::string>"); std::cout << '\n'; print_type<const char *>("const char *"); print_type<char * const>("char * const"); print_type<const char * const>("const char * const"); print_type<char *>("char *"); }
28.68
58
0.608089
mstankus
b34e50004f84421e0de4048fad863e41aac457e4
1,830
cpp
C++
Tree/LargestBSTInBinaryTree/LargestBSTInBinaryTree.cpp
PrachieNaik/DSA
083522bb3c8a0694adec1f2856d4d4cd0fb51722
[ "MIT" ]
null
null
null
Tree/LargestBSTInBinaryTree/LargestBSTInBinaryTree.cpp
PrachieNaik/DSA
083522bb3c8a0694adec1f2856d4d4cd0fb51722
[ "MIT" ]
null
null
null
Tree/LargestBSTInBinaryTree/LargestBSTInBinaryTree.cpp
PrachieNaik/DSA
083522bb3c8a0694adec1f2856d4d4cd0fb51722
[ "MIT" ]
null
null
null
/* Problem statement: Given a Binary Tree, write a function that returns the size of the largest subtree which is also a Binary Search Tree (BST). If the complete Binary Tree is BST, then return the size of the whole tree. Examples: Input: 5 / \ 2 4 / \ 1 3 Output: 3 The following subtree is the maximum size BST subtree 2 / \ 1 3 Input: 50 / \ 30 60 / \ / \ 5 20 45 70 / \ 65 80 Output: 5 The following subtree is the maximum size BST subtree 60 / \ 45 70 / \ 65 80 Approach: A Tree is BST if following is true for every node x. The largest value in left subtree (of x) is smaller than value of x. The smallest value in right subtree (of x) is greater than value of x. We traverse tree in bottom up manner. For every traversed node, we return maximum and minimum values in subtree rooted with it. If any node follows above properties and size of it's bst is greater then overall max size bst we update the answer. */ struct Info { int size; bool isbst; int mx; int mn; }; Info solve(Node* root,int& a) { if(root == NULL) { Info t; t.size = 0; t.isbst = true; t.mx = INT_MIN; t.mn = INT_MAX; return t; } Info left = solve(root->left,a); Info right = solve(root->right,a); Info ans; ans.mx = max(root->data,max(left.mx,right.mx)); ans.mn = min(root->data,min(left.mn,right.mn)); ans.size = 1 + left.size + right.size; ans.isbst = left.isbst && right.isbst && left.mx < root->data && right.mn > root->data; if(ans.isbst) { a = max(a,ans.size); } return ans; } int largestBst(Node *root) { int a = 0; solve(root,a); return a; }
21.785714
150
0.58306
PrachieNaik
b35c7901846ceb3acf3c65710f4cbd544f5f1747
517
cpp
C++
2017/day20/tests/TestClass.cpp
alexandru-andronache/adventofcode
ee41d82bae8b705818fda5bd43e9962bb0686fec
[ "Apache-2.0" ]
3
2021-07-01T14:31:06.000Z
2022-03-29T20:41:21.000Z
2017/day20/tests/TestClass.cpp
alexandru-andronache/adventofcode
ee41d82bae8b705818fda5bd43e9962bb0686fec
[ "Apache-2.0" ]
null
null
null
2017/day20/tests/TestClass.cpp
alexandru-andronache/adventofcode
ee41d82bae8b705818fda5bd43e9962bb0686fec
[ "Apache-2.0" ]
null
null
null
#include "TestClass.h" #include "../test.h" namespace aoc2017_day20 { TEST_F(Tests2017Day20, part_1_test) { ASSERT_EQ(part_1("../2017/day20/input_test.in"), 0); } TEST_F(Tests2017Day20, part_1_real_test) { ASSERT_EQ(part_1("../2017/day20/input.in"), 243); } TEST_F(Tests2017Day20, part_2_test) { ASSERT_EQ(part_2("../2017/day20/input_test2.in"), 1); } TEST_F(Tests2017Day20, part_2_real_test) { ASSERT_EQ(part_2("../2017/day20/input.in"), 648); } }
24.619048
61
0.634429
alexandru-andronache
b35d93aeff923a803a36c700560d87857cbe4ddd
4,635
cpp
C++
CPP/RhinoCppTest/cmdRhinoCppTest.cpp
hrntsm/study-language
922578a5321d70c26b935e6052f400125e15649c
[ "MIT" ]
1
2022-02-06T10:50:42.000Z
2022-02-06T10:50:42.000Z
CPP/RhinoCppTest/cmdRhinoCppTest.cpp
hrntsm/study-language
922578a5321d70c26b935e6052f400125e15649c
[ "MIT" ]
null
null
null
CPP/RhinoCppTest/cmdRhinoCppTest.cpp
hrntsm/study-language
922578a5321d70c26b935e6052f400125e15649c
[ "MIT" ]
null
null
null
// cmdRhinoCppTest.cpp : command file // #include "StdAfx.h" #include "RhinoCppTestPlugIn.h" //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // // BEGIN RhinoCppTest command // #pragma region RhinoCppTest command // Do NOT put the definition of class CCommandRhinoCppTest in a header // file. There is only ONE instance of a CCommandRhinoCppTest class // and that instance is the static theRhinoCppTestCommand that appears // immediately below the class definition. class CCommandRhinoCppTest : public CRhinoCommand { public: // The one and only instance of CCommandRhinoCppTest is created below. // No copy constructor or operator= is required. // Values of member variables persist for the duration of the application. // CCommandRhinoCppTest::CCommandRhinoCppTest() // is called exactly once when static theRhinoCppTestCommand is created. CCommandRhinoCppTest() = default; // CCommandRhinoCppTest::~CCommandRhinoCppTest() // is called exactly once when static theRhinoCppTestCommand is destroyed. // The destructor should not make any calls to the Rhino SDK. // If your command has persistent settings, then override // CRhinoCommand::SaveProfile and CRhinoCommand::LoadProfile. ~CCommandRhinoCppTest() = default; // Returns a unique UUID for this command. // If you try to use an id that is already being used, then // your command will not work. Use GUIDGEN.EXE to make unique UUID. UUID CommandUUID() override { // {1FF2D8F4-6A39-4CB9-9E14-459CFF171DC0} static const GUID RhinoCppTestCommand_UUID = { 0x1FF2D8F4, 0x6A39, 0x4CB9, { 0x9E, 0x14, 0x45, 0x9C, 0xFF, 0x17, 0x1D, 0xC0 } }; return RhinoCppTestCommand_UUID; } // Returns the English command name. // If you want to provide a localized command name, then override // CRhinoCommand::LocalCommandName. const wchar_t* EnglishCommandName() override { return L"RhinoCppTest"; } // Rhino calls RunCommand to run the command. CRhinoCommand::result RunCommand(const CRhinoCommandContext& context) override; }; // The one and only CCommandRhinoCppTest object // Do NOT create any other instance of a CCommandRhinoCppTest class. static class CCommandRhinoCppTest theRhinoCppTestCommand; CRhinoCommand::result CCommandRhinoCppTest::RunCommand(const CRhinoCommandContext& context) { ON_Plane plane = ON_xy_plane; double height = 10.0; double radius = 5.0; bool bCapBottom = FALSE; CRhinoGetOption ro; ro.SetCommandPrompt(L"Command options"); ro.AcceptNothing(); for (;;) { ro.ClearCommandOptions(); int hval_option_index = ro.AddCommandOptionNumber( RHCMDOPTNAME(L"Height"), &height, L"height value", FALSE, 1.0, 10, 0 ); int rval_option_index = ro.AddCommandOptionNumber( RHCMDOPTNAME(L"Radius"), &radius, L"radius value", FALSE, 0.1, 10.0 ); int bval_option_index = ro.AddCommandOptionToggle( RHCMDOPTNAME(L"CapBottom"), RHCMDOPTVALUE(L"False"), RHCMDOPTVALUE(L"True"), bCapBottom, &bCapBottom ); int test_option_index = ro.AddCommandOption( RHCMDOPTNAME(L"Test") ); CRhinoGet::result res = ro.GetOption(); if (res == CRhinoGet::nothing) break; if (res == CRhinoGet::cancel) return CRhinoCommand::cancel; if (res != CRhinoGet::option) return CRhinoCommand::failure; const CRhinoCommandOption* option = ro.Option(); if (nullptr == option) return CRhinoCommand::failure; int option_index = option->m_option_index; if (option_index == hval_option_index) continue; // nothing to do if (option_index == rval_option_index) continue; // nothing to do } ON_Cone cone(plane, height, radius); if (cone.IsValid()) { ON_Brep* cone_brep = ON_BrepCone(cone, bCapBottom); if (cone_brep) { CRhinoBrepObject *cone_objct = new CRhinoBrepObject(); cone_objct->SetBrep(cone_brep); context.m_doc.AddObject(cone_objct); context.m_doc.Redraw(); } } // CRhinoGet::result res = go.GetOption(); //if (option_index == bval_option_index) // continue; // nothing to do //} return CRhinoCommand::success; } #pragma endregion // // END RhinoCppTest command // //////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////
32.640845
112
0.640561
hrntsm
b35f78eafd42b72306306256eb38f4b0fe653e6e
608
hpp
C++
Includes/Rosetta/Common/Macros.hpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
62
2017-08-21T14:11:00.000Z
2018-04-23T16:09:02.000Z
Includes/Rosetta/Common/Macros.hpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
37
2017-08-21T11:13:07.000Z
2018-04-30T08:58:41.000Z
Includes/Rosetta/Common/Macros.hpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
10
2017-08-21T03:44:12.000Z
2018-01-10T22:29:10.000Z
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #ifndef ROSETTASTONE_MACROS_HPP #define ROSETTASTONE_MACROS_HPP #if defined(_WIN32) || defined(_WIN64) #define ROSETTASTONE_WINDOWS #elif defined(__APPLE__) #define ROSETTASTONE_APPLE #ifndef ROSETTASTONE_IOS #define ROSETTASTONE_MACOSX #endif #elif defined(linux) || defined(__linux__) #define ROSETTASTONE_LINUX #endif #endif // ROSETTASTONE_MACROS_HPP
27.636364
75
0.807566
Hearthstonepp
b36074ad600f715170ff1014ffe071e602c7bf66
847
hpp
C++
include/poike/core/DescriptorPool.hpp
florianvazelle/poike
2ff7313c994b888dd83e22a0a9703c08b4a3a361
[ "MIT" ]
null
null
null
include/poike/core/DescriptorPool.hpp
florianvazelle/poike
2ff7313c994b888dd83e22a0a9703c08b4a3a361
[ "MIT" ]
null
null
null
include/poike/core/DescriptorPool.hpp
florianvazelle/poike
2ff7313c994b888dd83e22a0a9703c08b4a3a361
[ "MIT" ]
null
null
null
/** * @file DescriptorPool.hpp * @brief Define DescriptorPool class */ #ifndef DESCRIPTORPOOL_HPP #define DESCRIPTORPOOL_HPP // clang-format off #include <poike/core/VulkanHeader.hpp> // for VkDescriptorPool, VkDescriptorPoolCr... #include <poike/meta/NoCopy.hpp> // for NoCopy namespace poike { class Device; } // clang-format on namespace poike { class DescriptorPool : public NoCopy { public: DescriptorPool(const Device& device, const VkDescriptorPoolCreateInfo& poolInfo); ~DescriptorPool(); inline const VkDescriptorPool& handle() const { return m_pool; }; void cleanup(); void recreate(); private: VkDescriptorPool m_pool; const Device& m_device; const VkDescriptorPoolCreateInfo& m_poolInfo; void createDescriptorPool(); }; } // namespace poike #endif // DESCRIPTORPOOL_HPP
22.891892
86
0.72137
florianvazelle
b369c2af8870330e1d3ea774be3354eb3b00d166
1,003
hpp
C++
include/fastbuffers/type_traits.hpp
kcwl/fastbuffers
0ff82bdb43a3f616b69ae6a60790d85297fc7a15
[ "MIT" ]
1
2022-01-17T14:41:52.000Z
2022-01-17T14:41:52.000Z
include/fastbuffers/type_traits.hpp
kcwl/fastbuffers
0ff82bdb43a3f616b69ae6a60790d85297fc7a15
[ "MIT" ]
null
null
null
include/fastbuffers/type_traits.hpp
kcwl/fastbuffers
0ff82bdb43a3f616b69ae6a60790d85297fc7a15
[ "MIT" ]
null
null
null
#pragma once #include <functional> #include <tuple> namespace fastbuffers { template<typename _Ty, typename _ = void> struct is_container : std::false_type {}; template<typename _Ty> struct is_container<_Ty, std::void_t<typename _Ty::value_type, typename _Ty::size_type, typename _Ty::allocator_type, typename _Ty::iterator, typename _Ty::const_iterator, decltype(std::declval<_Ty>().size()), decltype(std::declval<_Ty>().begin()), decltype(std::declval<_Ty>().end()), decltype(std::declval<_Ty>().cbegin()), decltype(std::declval<_Ty>().cend())>> : std::true_type{}; template<typename _Ty> constexpr static bool is_container_v = is_container<std::remove_cvref_t<_Ty>>::value; template<typename _Ty> struct is_pod : std::false_type {}; template<typename _Ty> requires(std::is_standard_layout_v<_Ty> && std::is_trivial_v<_Ty>) struct is_pod<_Ty> : std::true_type{}; template<typename _Ty> constexpr static bool is_pod_v = is_pod<std::remove_cvref_t<_Ty>>::value; }
27.108108
86
0.725823
kcwl
b370e8ff0450150eae99ee4b91da6ed9dc4e24ae
343
cpp
C++
graph/dfs.cpp
fredbr/algorithm-implementations
19da93dc4632cbba91f6014e821f9b08b4e00248
[ "CC0-1.0" ]
13
2018-08-23T22:11:23.000Z
2021-06-10T04:15:09.000Z
graph/dfs.cpp
fredbr/algorithm-implementations
19da93dc4632cbba91f6014e821f9b08b4e00248
[ "CC0-1.0" ]
null
null
null
graph/dfs.cpp
fredbr/algorithm-implementations
19da93dc4632cbba91f6014e821f9b08b4e00248
[ "CC0-1.0" ]
3
2019-09-06T17:44:38.000Z
2019-09-10T12:41:35.000Z
#include <bits/stdc++.h> using namespace std; const int maxn = 101010; vector<int> v[maxn]; int vis[maxn]; // if general graph int dfs(int x) { vis[x] = 1; // body for (int u : v[x]) if (!vis[u]) dfs(u); // after } // if tree int dfs(int x, int p) { // body for (int u : v[x]) { if (u == p) continue; dfs(u, x); } // after }
11.827586
24
0.54519
fredbr
b3791827c409dbbe0afa86e0cb705a842f3cb8f8
888
cpp
C++
Strings/Anagrams_Bitset.cpp
rsghotra/InterviewQuestions
41dadd4c523bc267e4ec4b238e6a98749f655915
[ "Apache-2.0" ]
null
null
null
Strings/Anagrams_Bitset.cpp
rsghotra/InterviewQuestions
41dadd4c523bc267e4ec4b238e6a98749f655915
[ "Apache-2.0" ]
null
null
null
Strings/Anagrams_Bitset.cpp
rsghotra/InterviewQuestions
41dadd4c523bc267e4ec4b238e6a98749f655915
[ "Apache-2.0" ]
1
2020-12-08T23:52:00.000Z
2020-12-08T23:52:00.000Z
#include<iostream> using namespace std; //anagrams using Bitset /* Algorithm: 1. Traverse over str1 and perform merging on the Hash 2. Traverse over second and perform masking to see if the bit was set */ void Anagrams_Bitset(string str1, string str2) { if(str1.length() != str2.length()) { cout << "Not Anagrams" << endl; return; } int H = 0; int a; for(int i=0; i < str1.length(); i++) { a = 1; a = a << str1[i] - 97; H = H | a; } for(int j = 0; j < str2.length(); j++) { a = 1; a = a << str2[j] - 97; if((H&a) == 0) { cout << "Not Anagrams" << endl; return; } } cout << "Anagrams" << endl; } int main() { //assumimg no duplicacates string str1 = "medicab"; string str2 = "decimal"; Anagrams_Bitset(str1, str2); }
21.658537
77
0.506757
rsghotra
b3881eaa8e0e69a7ee5bb33a570ed3af054b8c71
1,772
hpp
C++
sdl/graehl/shared/pointer_traits.hpp
sdl-research/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
29
2015-01-26T21:49:51.000Z
2021-06-18T18:09:42.000Z
sdl/graehl/shared/pointer_traits.hpp
hypergraphs/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
1
2016-04-18T17:20:37.000Z
2016-04-23T07:36:38.000Z
sdl/graehl/shared/pointer_traits.hpp
hypergraphs/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
7
2015-06-11T14:48:13.000Z
2017-08-12T16:06:19.000Z
// Copyright 2014 Jonathan Graehl-http://graehl.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** \file C++11 or boost: N2982 std::pointer_traits<PointerType>::element_type which lives in <memory> template <class U> struct rebind_pointer { typedef U* type; }; //! <b>Returns</b>: addressof(r) //! static pointer pointer_to(reference r) { return boost::intrusive::detail::addressof(r); } //! <b>Returns</b>: static_cast<pointer>(uptr) //! template<class U> static pointer static_cast_from(U *uptr) { return static_cast<pointer>(uptr); } //! <b>Returns</b>: const_cast<pointer>(uptr) //! template<class U> static pointer const_cast_from(U *uptr) { return const_cast<pointer>(uptr); } //! <b>Returns</b>: dynamic_cast<pointer>(uptr) //! template<class U> static pointer dynamic_cast_from(U *uptr) { return dynamic_cast<pointer>(uptr); } */ #ifndef POINTER_TRAITS_JG201266_HPP #define POINTER_TRAITS_JG201266_HPP #pragma once #include <graehl/shared/cpp11.hpp> #if GRAEHL_CPP11 #include <memory> namespace graehl { using std::pointer_traits; } #else #include <boost/intrusive/pointer_traits.hpp> namespace graehl { using boost::intrusive::pointer_traits; } #endif #endif
26.447761
96
0.708239
sdl-research
b3893852a8292b050016ba5516792a4f3a4c7712
6,609
cpp
C++
src/core/blocks/strings.cpp
Kryptos-FR/chainblocks
67160c535237a90cfe8a059db487d054d2714a3c
[ "BSD-3-Clause" ]
15
2019-10-30T18:21:52.000Z
2021-06-22T06:06:15.000Z
src/core/blocks/strings.cpp
Kryptos-FR/chainblocks
67160c535237a90cfe8a059db487d054d2714a3c
[ "BSD-3-Clause" ]
103
2021-06-26T17:09:43.000Z
2022-03-30T12:05:18.000Z
src/core/blocks/strings.cpp
Kryptos-FR/chainblocks
67160c535237a90cfe8a059db487d054d2714a3c
[ "BSD-3-Clause" ]
8
2021-07-27T14:45:26.000Z
2022-03-01T08:07:18.000Z
/* SPDX-License-Identifier: BSD-3-Clause */ /* Copyright © 2019 Fragcolor Pte. Ltd. */ #include "../../../deps/utf8.h/utf8.h" #include "shared.hpp" #include <regex> namespace chainblocks { namespace Regex { struct Common { static inline Parameters params{ {"Regex", CBCCSTR("The regular expression."), {CoreInfo::StringType}}}; std::regex _re; std::string _re_str; std::string _subject; static CBTypesInfo inputTypes() { return CoreInfo::StringType; } static CBParametersInfo parameters() { return CBParametersInfo(params); } void setParam(int index, const CBVar &value) { switch (index) { case 0: _re_str = value.payload.stringValue; _re.assign(_re_str); break; default: break; } } CBVar getParam(int index) { switch (index) { case 0: return Var(_re_str); default: return Var::Empty; } } }; struct Match : public Common { IterableSeq _output; std::vector<std::string> _pool; static CBTypesInfo outputTypes() { return CoreInfo::StringSeqType; } CBVar activate(CBContext *context, const CBVar &input) { std::smatch match; _subject.assign(input.payload.stringValue, CBSTRLEN(input)); if (std::regex_match(_subject, match, _re)) { auto size = match.size(); _pool.resize(size); _output.resize(size); for (size_t i = 0; i < size; i++) { _pool[i].assign(match[i].str()); _output[i] = Var(_pool[i]); } } else { _pool.clear(); _output.clear(); } return Var(CBSeq(_output)); } }; struct Search : public Common { IterableSeq _output; std::vector<std::string> _pool; static CBTypesInfo outputTypes() { return CoreInfo::StringSeqType; } CBVar activate(CBContext *context, const CBVar &input) { std::smatch match; _subject.assign(input.payload.stringValue, CBSTRLEN(input)); _pool.clear(); _output.clear(); while (std::regex_search(_subject, match, _re)) { auto size = match.size(); for (size_t i = 0; i < size; i++) { _pool.emplace_back(match[i].str()); } _subject.assign(match.suffix()); } for (auto &s : _pool) { _output.push_back(Var(s)); } return Var(CBSeq(_output)); } }; struct Replace : public Common { ParamVar _replacement; std::string _replacementStr; std::string _output; static inline Parameters params{ Common::params, {{"Replacement", CBCCSTR("The replacement expression."), {CoreInfo::StringType, CoreInfo::StringVarType}}}}; static CBParametersInfo parameters() { return params; } static CBTypesInfo outputTypes() { return CoreInfo::StringType; } void setParam(int index, const CBVar &value) { switch (index) { case 1: _replacement = value; break; default: Common::setParam(index, value); break; } } CBVar getParam(int index) { switch (index) { case 1: return _replacement; default: return Common::getParam(index); } } void warmup(CBContext *context) { _replacement.warmup(context); } void cleanup() { _replacement.cleanup(); } CBVar activate(CBContext *context, const CBVar &input) { _subject.assign(input.payload.stringValue, CBSTRLEN(input)); _replacementStr.assign(_replacement.get().payload.stringValue, CBSTRLEN(_replacement.get())); _output.assign(std::regex_replace(_subject, _re, _replacementStr)); return Var(_output); } }; struct ToUpper { static CBTypesInfo inputTypes() { return CoreInfo::StringType; } static CBTypesInfo outputTypes() { return CoreInfo::StringType; } CBVar activate(CBContext *context, const CBVar &input) { utf8upr(const_cast<char *>(input.payload.stringValue)); return input; } }; struct ToLower { static CBTypesInfo inputTypes() { return CoreInfo::StringType; } static CBTypesInfo outputTypes() { return CoreInfo::StringType; } CBVar activate(CBContext *context, const CBVar &input) { utf8lwr(const_cast<char *>(input.payload.stringValue)); return input; } }; struct Trim { static CBTypesInfo inputTypes() { return CoreInfo::StringType; } static CBTypesInfo outputTypes() { return CoreInfo::StringType; } static std::string_view trim(std::string_view s) { s.remove_prefix(std::min(s.find_first_not_of(" \t\r\v\n"), s.size())); s.remove_suffix( std::min(s.size() - s.find_last_not_of(" \t\r\v\n") - 1, s.size())); return s; } CBVar activate(CBContext *context, const CBVar &input) { auto sv = CBSTRVIEW(input); auto tsv = trim(sv); return Var(tsv); } }; struct Parser { std::string _cache; }; struct ParseInt : public Parser { static CBTypesInfo inputTypes() { return CoreInfo::StringType; } static CBTypesInfo outputTypes() { return CoreInfo::IntType; } int _base{10}; static inline Parameters params{ {"Base", CBCCSTR("Numerical base (radix) that determines the valid characters " "and their interpretation."), {CoreInfo::IntType}}}; CBParametersInfo parameters() { return params; } void setParam(int index, const CBVar &value) { _base = value.payload.intValue; } CBVar getParam(int index) { return Var(_base); } CBVar activate(CBContext *context, const CBVar &input) { char *str = const_cast<char *>(input.payload.stringValue); const auto len = CBSTRLEN(input); _cache.assign(str, len); size_t parsed; auto v = int64_t(std::stoul(_cache, &parsed, _base)); if (parsed != len) { throw ActivationError("ParseInt: Invalid integer string"); } return Var(v); } }; struct ParseFloat : public Parser { static CBTypesInfo inputTypes() { return CoreInfo::StringType; } static CBTypesInfo outputTypes() { return CoreInfo::FloatType; } CBVar activate(CBContext *context, const CBVar &input) { char *str = const_cast<char *>(input.payload.stringValue); const auto len = CBSTRLEN(input); _cache.assign(str, len); size_t parsed; auto v = std::stod(_cache, &parsed); if (parsed != len) { throw ActivationError("ParseFloat: Invalid float string"); } return Var(v); } }; void registerBlocks() { REGISTER_CBLOCK("Regex.Replace", Replace); REGISTER_CBLOCK("Regex.Search", Search); REGISTER_CBLOCK("Regex.Match", Match); REGISTER_CBLOCK("String.ToUpper", ToUpper); REGISTER_CBLOCK("String.ToLower", ToLower); REGISTER_CBLOCK("ParseInt", ParseInt); REGISTER_CBLOCK("ParseFloat", ParseFloat); REGISTER_CBLOCK("String.Trim", Trim); } } // namespace Regex } // namespace chainblocks
27.309917
77
0.659404
Kryptos-FR
b3a762edecc8b0b0f823da8a18bd6e851d8780bb
7,816
cpp
C++
SDLTests/StandardNodes.cpp
rileyzzz/NodeBackend
eb3e36d5482f238024a7b0a3123d0c247ba6fba3
[ "MIT" ]
3
2020-08-01T22:29:41.000Z
2022-01-13T07:53:35.000Z
SDLTests/StandardNodes.cpp
rileyzzz/NodeBackend
eb3e36d5482f238024a7b0a3123d0c247ba6fba3
[ "MIT" ]
null
null
null
SDLTests/StandardNodes.cpp
rileyzzz/NodeBackend
eb3e36d5482f238024a7b0a3123d0c247ba6fba3
[ "MIT" ]
1
2021-09-19T20:20:32.000Z
2021-09-19T20:20:32.000Z
#include "StandardNodes.h" #include <math.h> #include "NodeHelpers.h" #include <thread> #include <algorithm> namespace NodeEdit { //Calculations ======================================== //Math Data* NodeMath::Add(std::vector<Data*> Inputs) { NodeNumeric* input1 = (NodeNumeric*)Inputs[0]; double value1 = input1->value; NodeNumeric* input2 = (NodeNumeric*)Inputs[1]; double value2 = input2->value; return new NodeFloat(value1 + value2); } Data* NodeMath::Subtract(std::vector<Data*> Inputs) { NodeNumeric* input1 = (NodeNumeric*)Inputs[0]; double value1 = input1->value; NodeNumeric* input2 = (NodeNumeric*)Inputs[1]; double value2 = input2->value; return new NodeFloat(value1 - value2); } Data* NodeMath::Multiply(std::vector<Data*> Inputs) { NodeNumeric* input1 = (NodeNumeric*)Inputs[0]; double value1 = input1->value; NodeNumeric* input2 = (NodeNumeric*)Inputs[1]; double value2 = input2->value; return new NodeFloat(value1 * value2); } Data* NodeMath::Divide(std::vector<Data*> Inputs) { NodeNumeric* input1 = (NodeNumeric*)Inputs[0]; double value1 = input1->value; NodeNumeric* input2 = (NodeNumeric*)Inputs[1]; double value2 = input2->value; return new NodeFloat(value1 / value2); } Data* NodeMath::Mod(std::vector<Data*> Inputs) { NodeNumeric* input1 = (NodeNumeric*)Inputs[0]; int value1 = input1->value; NodeNumeric* input2 = (NodeNumeric*)Inputs[1]; int value2 = input2->value; return new NodeInteger(value1 % value2); } Data* NodeMath::Abs(std::vector<Data*> Inputs) { NodeNumeric* input1 = (NodeNumeric*)Inputs[0]; double value1 = input1->value; return new NodeFloat(std::abs(value1)); } Data* NodeMath::Sqrt(std::vector<Data*> Inputs) { NodeNumeric* input1 = (NodeNumeric*)Inputs[0]; double value1 = input1->value; return new NodeFloat(std::sqrt(value1)); } Data* NodeMath::Round(std::vector<Data*> Inputs) { NodeNumeric* input1 = (NodeNumeric*)Inputs[0]; double value1 = input1->value; return new NodeFloat(std::round(value1)); } Data* NodeMath::Floor(std::vector<Data*> Inputs) { NodeNumeric* input1 = (NodeNumeric*)Inputs[0]; double value1 = input1->value; return new NodeFloat(std::floor(value1)); } Data* NodeMath::Ceil(std::vector<Data*> Inputs) { NodeNumeric* input1 = (NodeNumeric*)Inputs[0]; double value1 = input1->value; return new NodeFloat(std::ceil(value1)); } Data* NodeMath::Log(std::vector<Data*> Inputs) { NodeNumeric* input1 = (NodeNumeric*)Inputs[0]; double value1 = input1->value; return new NodeFloat(std::log(value1)); } Data* NodeMath::Pow(std::vector<Data*> Inputs) { NodeNumeric* input1 = (NodeNumeric*)Inputs[0]; double value1 = input1->value; NodeNumeric* input2 = (NodeNumeric*)Inputs[1]; double value2 = input2->value; return new NodeFloat(std::pow(value1, value2)); } Data* NodeMath::Negate(std::vector<Data*> Inputs) { NodeNumeric* input1 = (NodeNumeric*)Inputs[0]; double value1 = input1->value; return new NodeFloat(-value1); } //Trig Data* NodeTrig::Sin(std::vector<Data*> Inputs) { NodeNumeric* input1 = (NodeNumeric*)Inputs[0]; double value1 = input1->value; return new NodeFloat(std::sin(value1)); } Data* NodeTrig::Cos(std::vector<Data*> Inputs) { NodeNumeric* input1 = (NodeNumeric*)Inputs[0]; double value1 = input1->value; return new NodeFloat(std::cos(value1)); } Data* NodeTrig::Tan(std::vector<Data*> Inputs) { NodeNumeric* input1 = (NodeNumeric*)Inputs[0]; double value1 = input1->value; return new NodeFloat(std::tan(value1)); } Data* NodeTrig::Asin(std::vector<Data*> Inputs) { NodeNumeric* input1 = (NodeNumeric*)Inputs[0]; double value1 = input1->value; return new NodeFloat(std::asin(value1)); } Data* NodeTrig::Acos(std::vector<Data*> Inputs) { NodeNumeric* input1 = (NodeNumeric*)Inputs[0]; double value1 = input1->value; return new NodeFloat(std::acos(value1)); } Data* NodeTrig::Atan(std::vector<Data*> Inputs) { NodeNumeric* input1 = (NodeNumeric*)Inputs[0]; double value1 = input1->value; return new NodeFloat(std::atan(value1)); } //Comparison Data* NodeComparison::And(std::vector<Data*> Inputs) { NodeBoolean* input1 = (NodeBoolean*)Inputs[0]; NodeBoolean* input2 = (NodeBoolean*)Inputs[1]; return new NodeBoolean(input1->value && input2->value); } Data* NodeComparison::Or(std::vector<Data*> Inputs) { NodeBoolean* input1 = (NodeBoolean*)Inputs[0]; NodeBoolean* input2 = (NodeBoolean*)Inputs[1]; return new NodeBoolean(input1->value || input2->value); } Data* NodeComparison::Not(std::vector<Data*> Inputs) { NodeBoolean* input1 = (NodeBoolean*)Inputs[0]; return new NodeBoolean(!input1->value); } //Casting Data* NodeCast::BooltoInt(std::vector<Data*> Inputs) { NodeBoolean* input1 = (NodeBoolean*)Inputs[0]; return new NodeInteger(input1->value); } Data* NodeCast::InttoBool(std::vector<Data*> Inputs) { NodeInteger* input1 = (NodeInteger*)Inputs[0]; return new NodeBoolean(input1->value); } Data* NodeCast::InttoFloat(std::vector<Data*> Inputs) { NodeInteger* input1 = (NodeInteger*)Inputs[0]; return new NodeFloat(input1->value); } Data* NodeCast::WeirdtoFloat(std::vector<Data*> Inputs) { NodeWeird<double>* convert = (NodeWeird<double>*)Inputs[0]; return new NodeFloat(convert->value); } Data* NodeCast::FloattoWeird(std::vector<Data*> Inputs) { NodeFloat* input1 = (NodeFloat*)Inputs[0]; return new NodeWeird<double>(input1->value); } Data* NodeCast::WeirdtoString(std::vector<Data*> Inputs) { NodeWeird<const char*>* convert = (NodeWeird<const char*>*)Inputs[0]; return new NodeString(convert->value); } Data* NodeCast::StringtoWeird(std::vector<Data*> Inputs) { NodeString* input1 = (NodeString*)Inputs[0]; return new NodeWeird<const char*>(input1->value); } //Actions ======================================== //Debug std::deque<ConsoleMessage> NodeDebug::console; void NodeDebug::MessageThread(NodeString* input) { ConsoleMessage NewMessage; NewMessage.message = input->value; NewMessage.messageLength = 2; console.push_front(NewMessage); std::this_thread::sleep_for(std::chrono::seconds(NewMessage.messageLength)); } bool NodeDebug::Print(std::vector<Data*> Inputs) { NodeString* input = (NodeString*)Inputs[0]; //std::cout << input->value << "\n"; ConsoleMessage NewMessage; NewMessage.message = input->value; NewMessage.messageLength = 2; console.push_front(NewMessage); //std::thread t(MessageThread, input); //t.detach(); return true; } //Inputs ======================================== time_t NodeInput::start = clock(); Data* NodeInput::Time() { //std::chrono::system_clock::now().time_since_epoch().count() NodeFloat* curtime = new NodeFloat(difftime(clock(), start)); return curtime; } }
29.055762
84
0.596725
rileyzzz
b3b071b16484de90d1663094843c80545192c815
4,490
hpp
C++
include/bugspray/reporter/constexpr_reporter.hpp
jan-moeller/bugspray
77777526f4445283b5f48b6f11ef82c84fdb167b
[ "MIT" ]
null
null
null
include/bugspray/reporter/constexpr_reporter.hpp
jan-moeller/bugspray
77777526f4445283b5f48b6f11ef82c84fdb167b
[ "MIT" ]
null
null
null
include/bugspray/reporter/constexpr_reporter.hpp
jan-moeller/bugspray
77777526f4445283b5f48b6f11ef82c84fdb167b
[ "MIT" ]
null
null
null
// // MIT License // // Copyright (c) 2022 Jan Möller // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #ifndef BUGSPRAY_CONSTEXPR_REPORTER_HPP #define BUGSPRAY_CONSTEXPR_REPORTER_HPP #include "bugspray/reporter/reporter.hpp" #include "bugspray/to_string/to_string_integral.hpp" #include "bugspray/utility/structural_string.hpp" #include <algorithm> #include <array> /* * Reporter to be used for constexpr evaluation. It stores the first n messages of the first failed assertion in a * constexpr-friendly way. It assumes that compilation will abort after the first assertion failed, and therefore only * one assertion is ever logged as a failure. */ namespace bs { struct constexpr_reporter : reporter { #if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER) // TODO: check if gcc bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=93413 is fixed constexpr ~constexpr_reporter(){}; #endif constexpr void enter_test_case(std::string_view /*name*/, std::span<std::string_view const> /*tags*/, source_location /*sloc*/) noexcept override { } constexpr void leave_test_case() noexcept override {} constexpr void start_run(section_path const& /*target*/) noexcept override {} constexpr void stop_run() noexcept override {} constexpr void enter_section(std::string_view /*name*/, source_location /*sloc*/) noexcept override {} constexpr void leave_section() noexcept override {} constexpr void log_assertion(std::string_view assertion, source_location sloc, std::string_view expansion, std::span<bs::string const> messages, bool result) noexcept override { if (!result) m_messages = compose_messages(assertion, sloc, expansion, messages); } constexpr void finalize() noexcept override {} [[nodiscard]] constexpr auto messages() const noexcept { return m_messages; } private: static constexpr std::size_t s_max_message_length = 1024; structural_string<s_max_message_length> m_messages; constexpr auto compose_messages(std::string_view assertion, source_location sloc, std::string_view expansion, std::span<bs::string const> messages) -> structural_string<s_max_message_length> { structural_string<s_max_message_length> result; std::size_t cur_idx = 0; auto append = [&result, &cur_idx](auto&& s) { auto const length_available = s_max_message_length - cur_idx; auto const length_to_copy = std::min(s.size(), length_available); std::ranges::copy_n(s.begin(), length_to_copy, result.value + cur_idx); cur_idx += length_to_copy; }; append(bs::string{sloc.file_name} + ':' + to_string(sloc.line) + ": " + bs::string{assertion}); if (!expansion.empty()) append(bs::string{" ### WITH EXPANSION: "} + bs::string{expansion}); for (auto&& m : messages) append(bs::string{" ### WITH: "} + m); return result; } }; } // namespace bs #endif // BUGSPRAY_CONSTEXPR_REPORTER_HPP
41.192661
118
0.649889
jan-moeller
a2a55c6bae62178f17452ef3db002a0a7086da77
533
cpp
C++
src/food.cpp
ASjet/GreedySnake
c07a22ede63a8c4f42bc6af2d8c8c95cd46b0311
[ "MIT" ]
1
2020-05-30T07:15:18.000Z
2020-05-30T07:15:18.000Z
src/food.cpp
ITFS777/GreedySnake
c07a22ede63a8c4f42bc6af2d8c8c95cd46b0311
[ "MIT" ]
null
null
null
src/food.cpp
ITFS777/GreedySnake
c07a22ede63a8c4f42bc6af2d8c8c95cd46b0311
[ "MIT" ]
null
null
null
#include <cstdlib> #include <ctime> #include "point.h" #include "food.h" #include "snake.h" //////////////////////////////////////////////////////////////////////////////// Food Food::print(void) const { pos.print(); return *this; } //////////////////////////////////////////////////////////////////////////////// Food Food::fresh(Snake snake) { srand((unsigned)time(NULL)); do pos.setPos((rand() % width) + 1, (rand() % height) + 1); while (snake.inBody(pos, 0)); pos.print("■"); return *this; }
25.380952
80
0.409006
ASjet
a2a7fce9d8dea14b694f253871c331d44bfcee65
10,803
cpp
C++
evo-X-Scriptdev2/scripts/northrend/ulduar/ulduar/boss_ignis.cpp
Gigelf-evo-X/evo-X
d0e68294d8cacfc7fb3aed5572f51d09a47136b9
[ "OpenSSL" ]
1
2019-01-19T06:35:40.000Z
2019-01-19T06:35:40.000Z
evo-X-Scriptdev2/scripts/northrend/ulduar/ulduar/boss_ignis.cpp
Gigelf-evo-X/evo-X
d0e68294d8cacfc7fb3aed5572f51d09a47136b9
[ "OpenSSL" ]
null
null
null
evo-X-Scriptdev2/scripts/northrend/ulduar/ulduar/boss_ignis.cpp
Gigelf-evo-X/evo-X
d0e68294d8cacfc7fb3aed5572f51d09a47136b9
[ "OpenSSL" ]
null
null
null
/* Copyright (C) 2006 - 2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: boss_ignis SD%Complete: 85% SDComment: slag pot damage missing. missing bringing adds to water part SDCategory: Ulduar EndScriptData */ #include "precompiled.h" #include "ulduar.h" enum { //yells //ignis the furnace master SPELL_FLAME_JETS = 62680, SPELL_FLAME_JETS_H = 63472, SPELL_SLAG_POT = 62717, SPELL_SLAG_POT_H = 63477, SPELL_SLAG_POT_DMG = 65722, SPELL_SLAG_POT_DMG_H = 65723, SPELL_SCORCH = 62546, SPELL_SCORCH_H = 63474, BUFF_STRENGHT_OF_CREATOR = 64473, SPELL_HASTE = 66045, //iron construct SPELL_HEAT = 65667, SPELL_MOLTEN = 62373, SPELL_BRITTLE = 62382, SPELL_SHATTER = 62383, //scorch target AURA_SCORCH = 62548, AURA_SCORCH_H = 63476, //NPC ids MOB_IRON_CONSTRUCT = 33121, MOB_SCORCH_TARGET = 33221, }; // scorch target struct MANGOS_DLL_DECL mob_scorch_targetAI : public ScriptedAI { mob_scorch_targetAI(Creature* pCreature) : ScriptedAI(pCreature) { Reset(); SetCombatMovement(false); m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); } ScriptedInstance* m_pInstance; bool m_bIsRegularMode; uint32 Death_Timer; uint32 Range_Check_Timer; void Reset() { Death_Timer = 55000; Range_Check_Timer = 1000; m_creature->SetDisplayId(11686); m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); DoCast(m_creature, m_bIsRegularMode ? AURA_SCORCH : AURA_SCORCH_H); } void UpdateAI(const uint32 diff) { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) m_creature->DealDamage(m_creature, m_creature->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); if (Death_Timer < diff) { m_creature->DealDamage(m_creature, m_creature->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); }else Death_Timer -= diff; } }; CreatureAI* GetAI_mob_scorch_target(Creature* pCreature) { return new mob_scorch_targetAI(pCreature); } // iron construct struct MANGOS_DLL_DECL mob_iron_constructAI : public ScriptedAI { mob_iron_constructAI(Creature* pCreature) : ScriptedAI(pCreature) { Reset(); m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); } ScriptedInstance* m_pInstance; uint32 Death_Timer; uint32 Aura_Check_Timer; bool brittle; bool shatter; void Reset() { shatter = false; brittle = false; Aura_Check_Timer = 1000; } void JustDied(Unit* pKiller) { if (!m_pInstance) return; if (Creature* pTemp = ((Creature*)Unit::GetUnit((*m_creature), m_pInstance->GetData64(DATA_IGNIS)))) if (pTemp->isAlive()) if (pTemp->HasAura(BUFF_STRENGHT_OF_CREATOR)) { if (pTemp->GetAura(BUFF_STRENGHT_OF_CREATOR, EFFECT_INDEX_0)->GetStackAmount() == 1) pTemp->RemoveAurasDueToSpell(BUFF_STRENGHT_OF_CREATOR); else pTemp->GetAura(BUFF_STRENGHT_OF_CREATOR, EFFECT_INDEX_0)->modStackAmount(-1); } } void DamageTaken(Unit *done_by, uint32 &damage) { if (brittle) if (damage>5000){ DoCast(m_creature, SPELL_SHATTER); shatter = true; Death_Timer = 1000; } } void UpdateAI(const uint32 diff) { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; if (Death_Timer < diff && shatter) { m_creature->DealDamage(m_creature, m_creature->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); }else Death_Timer -= diff; if (m_creature->HasAura(SPELL_BRITTLE, EFFECT_INDEX_0)) brittle = true; else brittle = false; if (Aura_Check_Timer < diff) { if(Aura* aura = m_creature->GetAura(SPELL_HEAT, EFFECT_INDEX_0)) if(aura->GetStackAmount() > 19) { DoCast(m_creature, SPELL_BRITTLE); //TODO: change brittle = true; } Aura_Check_Timer = 1000; }else Aura_Check_Timer -= diff; if (!shatter && !brittle) DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_mob_iron_construct(Creature* pCreature) { return new mob_iron_constructAI(pCreature); } //ignis the furnace master struct MANGOS_DLL_DECL boss_ignisAI : public ScriptedAI { boss_ignisAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); m_bIsRegularMode = pCreature->GetMap()->IsRegularDifficulty(); Reset(); } ScriptedInstance* m_pInstance; bool m_bIsRegularMode; std::list<uint64> m_lIronConstructGUIDList; uint32 Flame_Jets_Timer; uint32 Slag_Pot_Timer; uint32 Slag_Pot_Dmg_Timer; uint32 Scorch_Timer; uint32 Summon_Timer; uint32 PotDmgCount; uint64 m_uiPotTarget; void Reset() { m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE); Flame_Jets_Timer = 20000; Slag_Pot_Timer = 25000; Slag_Pot_Dmg_Timer = 26000; Scorch_Timer = 14000; Summon_Timer = 10000; PotDmgCount = 0; m_uiPotTarget = 0; m_lIronConstructGUIDList.clear(); } void JustDied(Unit* pKiller) { //death yell if (m_pInstance) m_pInstance->SetData(TYPE_IGNIS, DONE); if (!m_lIronConstructGUIDList.empty()) { for(std::list<uint64>::iterator itr = m_lIronConstructGUIDList.begin(); itr != m_lIronConstructGUIDList.end(); ++itr) if (Creature* pTemp = (Creature*)Unit::GetUnit(*m_creature, *itr)) pTemp->ForcedDespawn(); } } void Aggro(Unit* pWho) { if (m_pInstance) m_pInstance->SetData(TYPE_IGNIS, IN_PROGRESS); //aggro yell } void JustReachedHome() { if (m_pInstance) m_pInstance->SetData(TYPE_IGNIS, FAIL); } void UpdateAI(const uint32 diff) { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; if (Flame_Jets_Timer < diff) { //flame jets yell DoCast(m_creature, m_bIsRegularMode ? SPELL_FLAME_JETS : SPELL_FLAME_JETS_H); Flame_Jets_Timer = 30000; }else Flame_Jets_Timer -= diff; if (Slag_Pot_Timer < diff) { //slag pot yell if (Unit* target = SelectUnit(SELECT_TARGET_RANDOM,1)){ DoCast(target, m_bIsRegularMode ? SPELL_SLAG_POT : SPELL_SLAG_POT_H); m_uiPotTarget = target->GetGUID(); } Slag_Pot_Timer = 30000; Slag_Pot_Dmg_Timer = 1000; PotDmgCount = 0; }else Slag_Pot_Timer -= diff; if (Slag_Pot_Dmg_Timer < diff) { if (Unit* pPotTarget = Unit::GetUnit(*m_creature, m_uiPotTarget)){ if (PotDmgCount < 10) DoCast(pPotTarget, m_bIsRegularMode ? SPELL_SLAG_POT_DMG : SPELL_SLAG_POT_DMG_H); else if (PotDmgCount == 10) DoCast(pPotTarget, SPELL_HASTE); } ++PotDmgCount; Slag_Pot_Dmg_Timer = 1000; }else Slag_Pot_Dmg_Timer -= diff; if (Summon_Timer < diff) { //summon yell if (Creature* pTemp = m_creature->SummonCreature(MOB_IRON_CONSTRUCT, 0.0f, 0.0f, 0.0f, 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 10000)) if (Unit* pTarget = SelectUnit(SELECT_TARGET_RANDOM,0)) { pTemp->AddThreat(pTarget,0.0f); pTemp->AI()->AttackStart(pTarget); m_lIronConstructGUIDList.push_back(pTemp->GetGUID()); } Summon_Timer = 40000; if (m_creature->HasAura(BUFF_STRENGHT_OF_CREATOR)) m_creature->GetAura(BUFF_STRENGHT_OF_CREATOR, EFFECT_INDEX_0)->modStackAmount(+1); else DoCast(m_creature, BUFF_STRENGHT_OF_CREATOR); }else Summon_Timer -= diff; if (Scorch_Timer < diff) { DoCast(m_creature->getVictim(), SPELL_SCORCH); if (Creature* pTemp = m_creature->SummonCreature(MOB_SCORCH_TARGET, m_creature->getVictim()->GetPositionX(), m_creature->getVictim()->GetPositionY(), m_creature->getVictim()->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 10000)) { pTemp->AddThreat(m_creature->getVictim(),0.0f); pTemp->AI()->AttackStart(m_creature->getVictim()); } Scorch_Timer = 28000; }else Scorch_Timer -= diff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_boss_ignis(Creature* pCreature) { return new boss_ignisAI(pCreature); } void AddSC_boss_ignis() { Script* NewScript; NewScript = new Script; NewScript->Name = "boss_ignis"; NewScript->GetAI = GetAI_boss_ignis; NewScript->RegisterSelf(); NewScript = new Script; NewScript->Name = "mob_scorch_target"; NewScript->GetAI = &GetAI_mob_scorch_target; NewScript->RegisterSelf(); NewScript = new Script; NewScript->Name = "mob_iron_construct"; NewScript->GetAI = &GetAI_mob_iron_construct; NewScript->RegisterSelf(); }
31.961538
253
0.608442
Gigelf-evo-X
a2ad196f127e4447cff98506db5e576c64049d15
2,193
cpp
C++
examples/common/audio_output.cpp
anokta/barelyMusician
cf2b7440f0fa248b2bd9ff3440d9fc1209c5219d
[ "MIT" ]
5
2015-02-13T18:28:06.000Z
2021-11-11T05:04:53.000Z
examples/common/audio_output.cpp
anokta/barelyMusician
cf2b7440f0fa248b2bd9ff3440d9fc1209c5219d
[ "MIT" ]
null
null
null
examples/common/audio_output.cpp
anokta/barelyMusician
cf2b7440f0fa248b2bd9ff3440d9fc1209c5219d
[ "MIT" ]
null
null
null
#include "examples/common/audio_output.h" #include <cassert> #include <utility> #include "portaudio.h" namespace barely::examples { AudioOutput::AudioOutput() noexcept : process_callback_(nullptr), stream_(nullptr) { Pa_Initialize(); } AudioOutput::~AudioOutput() noexcept { Pa_Terminate(); } void AudioOutput::Start(int sample_rate, int num_channels, int num_frames) noexcept { assert(sample_rate >= 0); assert(num_channels >= 0); assert(num_frames >= 0); if (stream_) { // Stop the existing |stream_| first. Stop(); } PaStreamParameters output_parameters; output_parameters.device = Pa_GetDefaultOutputDevice(); assert(output_parameters.device != paNoDevice); output_parameters.channelCount = num_channels; output_parameters.sampleFormat = paFloat32; output_parameters.suggestedLatency = Pa_GetDeviceInfo(output_parameters.device)->defaultLowOutputLatency; output_parameters.hostApiSpecificStreamInfo = nullptr; const auto callback = [](const void* /*input_buffer*/, void* output_buffer, unsigned long /*frames_per_buffer*/, const PaStreamCallbackTimeInfo* /*time_info*/, PaStreamCallbackFlags /*status_flags*/, void* user_data) noexcept { if (user_data) { // Access the audio process callback via |user_data| (to avoid capturing // |process_callback_|). const auto& process_callback = *reinterpret_cast<ProcessCallback*>(user_data); process_callback(reinterpret_cast<float*>(output_buffer)); } return static_cast<int>(paContinue); }; Pa_OpenStream(&stream_, nullptr, &output_parameters, sample_rate, num_frames, paClipOff, callback, reinterpret_cast<void*>(&process_callback_)); Pa_StartStream(stream_); } void AudioOutput::Stop() noexcept { if (stream_) { Pa_StopStream(stream_); Pa_CloseStream(stream_); } stream_ = nullptr; } void AudioOutput::SetProcessCallback( ProcessCallback process_callback) noexcept { process_callback_ = std::move(process_callback); } } // namespace barely::examples
30.887324
79
0.686731
anokta
a2ae8beea84e23d19d4c779dae5cd9103e24ca5b
286,617
cpp
C++
TissueFolding/SourceCode/Simulation.cpp
meldatozluoglu/TissueFolding_Lite
2b436d7004a75c73f44202f31826557f5fb9f900
[ "Unlicense" ]
2
2019-06-18T14:13:41.000Z
2021-01-25T16:18:45.000Z
TissueFolding/SourceCode/Simulation.cpp
meldatozluoglu/TissueFolding_Lite
2b436d7004a75c73f44202f31826557f5fb9f900
[ "Unlicense" ]
null
null
null
TissueFolding/SourceCode/Simulation.cpp
meldatozluoglu/TissueFolding_Lite
2b436d7004a75c73f44202f31826557f5fb9f900
[ "Unlicense" ]
2
2021-05-06T11:38:53.000Z
2021-07-28T12:26:51.000Z
#include "Simulation.h" #include "Prism.h" #include "RandomGenerator.h" #include <string.h> #include <vector> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> Simulation::Simulation(){ savedStepwise = true; currElementId = 0; ModInp = std::make_unique<ModelInputObject>(); SystemCentre[0]=0.0; SystemCentre[1]=0.0; SystemCentre[2]=0.0; TissueHeight = 0.0; TissueHeightDiscretisationLayers= 1; timestep = 0; currSimTimeSec = 0; reachedEndOfSaveFile = false; thereIsPeripodialMembrane = false; needPeripodialforInputConsistency = false; conservingColumnVolumes = false; boundingBoxSize[0]=1000.0; boundingBoxSize[1]=1000.0; boundingBoxSize[2]=1000.0; ContinueFromSave = false; growthRotationUpdateFrequency = 60.0/dt; nElements = 0; nNodes = 0; if (growthRotationUpdateFrequency<1) {growthRotationUpdateFrequency =1;} setDefaultParameters(); implicitPacking = true; thereIsAdhesion = false; collapseNodesOnAdhesion = false; thereNodeCollapsing = false; thereIsEmergentEllipseMarking = false; thereIsArtificaialRelaxation = false; artificialRelaxationTime = -1; relaxECMInArtificialRelaxation = false; checkedForCollapsedNodesOnFoldingOnce = false; } Simulation::~Simulation(){ std::cout<<"destructor for simulation called"<<std::endl; } void Simulation::setDefaultParameters(){ dt = 0.01; //sec SimLength = dt; //10 sec of simulation saveImages = false; //do not save simulation images by default saveData = false; //do not save simulation data by default imageSaveInterval = 60.0/dt; //save images every minute dataSaveInterval = 60.0/dt; //save data every minute saveDirectory = "Not-Set"; //the directory to save the images and data points saveScreenshotsDirectory = "Not-Set"; //the directory to save the images and data points saveDirectoryToDisplayString = "Not-Set"; //the file whcih will be read and displayed - no simulation EApical = 250.0; EBasal = 250.0; EMid = 250.0; PeripodialElasticity = 10000.0; EColumnarECM = 10000.0; EPeripodialECM = 10000.0; poisson = 0.3; discProperApicalViscosity = 10000.0; discProperBasalViscosity = 10000.0; for (int i=0; i<3; ++i){ zeroExternalViscosity[i] = true; } noiseOnPysProp.fill(0); // The default input is a calculated mesh of width 4 elements, each element being 2.0 unit high // and having 1.0 unit sides of the triangles. MeshType = 2; Row = 4; Column = Row-2; SideLength=1.0; zHeight = 2.0; ApicalNodeFixWithExternalViscosity = false; BasalNodeFixWithExternalViscosity = false; NotumNodeFixWithExternalViscosity = false; for (int i=0; i<5; ++i){ CircumferentialNodeFixWithHighExternalViscosity[i] = false; for (int j=0; j<3; j++){ CircumferentialNodeFix[i][j] = false; ApicalNodeFix[j] = false; BasalNodeFix[j] = false; NotumNodeFix[j] = false; fixingExternalViscosity[j] = 0; } } notumFixingRange[0] = 1.1; notumFixingRange[1] = -0.1; nGrowthFunctions = 0; GridGrowthsPinnedOnInitialMesh = false; nGrowthPinning = 0; gridGrowthsInterpolationType = 1; nShapeChangeFunctions = 0; TensionCompressionSaved = true; GrowthSaved = true; GrowthRateSaved = true; ForcesSaved = true; PackingSaved = true; growthRedistributionSaved = true; nodeBindingSaved = true; physicalPropertiesSaved = true; collapseAndAdhesionSaved = true; PeripodialElasticity = 0.0; peripodialApicalViscosity = discProperApicalViscosity; peripodialBasalViscosity = discProperBasalViscosity; dorsalTipIndex = 0; ventralTipIndex = 1; anteriorTipIndex = 0; posteriorTipIndex = 0; stretcherAttached = false; distanceIndex = false; StretchDistanceStep = 0.0; DVClamp = true; StretchInitialTime = -100; StretchEndTime = -100; PipetteSuction = false; PipetteInitialStep= -100; nPipetteSuctionSteps = 0; ApicalSuction = true; TissueStuckOnGlassDuringPipetteAspiration = true; pipetteCentre[0] = 0.0; pipetteCentre[1] = 0.0; pipetteCentre[2] = 0.0; pipetteDepth = 0.0; pipetteInnerRadius =0.0; SuctionPressure[0] = 0.0; SuctionPressure[1] = 0.0; SuctionPressure[2] = 0.0; pipetteInnerRadiusSq = pipetteInnerRadius*pipetteInnerRadius; pipetteThickness = 11.7; effectLimitsInZ[0] = pipetteCentre[2] - pipetteDepth; effectLimitsInZ[1] = pipetteCentre[2] + pipetteDepth; boundingBox[0][0] = 1000.0; //left x boundingBox[0][1] = 1000.0; //low y boundingBox[0][2] = 1000.0; //bottom z boundingBox[1][0] = -1000.0; //right x boundingBox[1][1] = -1000.0; //high y boundingBox[1][2] = -1000.0; //top z symmetricY = false; symmetricX = false; addingRandomForces = false; randomForceMean = 0.0; randomForceVar = 0.0; packingDetectionThreshold = 5.5; packingThreshold = 6.0; softPeriphery = false; softDepth = 0.0; softnessFraction = 0.0; softPeripheryBooleans[0] = false; //apical softPeripheryBooleans[1] = false; //basal softPeripheryBooleans[2] = false; //columnar softPeripheryBooleans[3] = false; //peripodial thereIsPlasticDeformation = false; plasticDeformationAppliedToPeripodial = false; plasticDeformationAppliedToColumnar = false; volumeConservedInPlasticDeformation = false; plasticDeformationHalfLife = 0.0; zRemodellingLowerThreshold = 0.5; zRemodellingUpperThreshold = 2.0; BaseLinkerZoneParametersOnPeripodialness = true; LinkerZoneApicalElasticity = 0.0; LinkerZoneBasalYoungsModulus = 0.0; linkerZoneApicalViscosity = discProperApicalViscosity; linkerZoneBasalViscosity = discProperBasalViscosity; extendExternalViscosityToInnerTissue = false; externalViscosityDPApical = 0.0; externalViscosityDPBasal = 0.0; externalViscosityPMApical = 0.0; externalViscosityPMBasal = 0.0; externalViscosityLZApical = 0.0; externalViscosityLZBasal = 0.0; thereIsECMChange = false; thereIsExplicitECM = false; lateralECMThickness = 0.0; ECMRenawalHalfLife = 0.0; thereIsExplicitActin = false; nMarkerEllipseRanges = 0; ThereIsStiffnessPerturbation = false; encloseTissueBetweenSurfaces = false; zEnclosementBoundaries[0] = -1000; zEnclosementBoundaries[1] = 1000; initialZEnclosementBoundaries[0] = -1000; initialZEnclosementBoundaries[1] = 1000; finalZEnclosementBoundaries[0] = -1000; finalZEnclosementBoundaries[1] = 1000; thereIsCircumferenceXYBinding= false; notumECMChangeInitTime = 10000000.0; notumECMChangeEndTime = 0.0; notumECMChangeFraction =1.0; hingeECMChangeInitTime = 10000000.0; hingeECMChangeEndTime = 0.0; hingeECMChangeFraction =1.0; pouchECMChangeInitTime = 10000000.0; pouchECMChangeEndTime = 0.0; pouchECMChangeFraction =1.0; boundLateralElements = false; } bool Simulation::readExecutableInputs(int argc, char **argv){ int i = 1; bool Success = true; while(i<argc){ const char *inptype = argv[i]; if (std::string(inptype) == "-mode"){ /** * The mode of simulation can be "DisplaySave","SimulationOnTheGo" or "ContinueFromSave". As the *nemas suggest, "DisplaySave" option will dsplay a simulation from saved files, without running the *simulation. "SimulationOnTheGo" will start a fresh simulation and "ContinueFromSave" will continue simulating *from a save file.\n * */ Success = readModeOfSim(i, argc, argv); } else if (std::string(inptype) == "-i"){ /** * The tag "-i" defines the input file, this should be a modelinput file * detailing the parameters of the simulation.\n */ Success = readParameters(i, argc, argv); } else if (std::string(inptype) == "-od"){ /** * If the input file requires saving, then an output direcotry should be specified with the "-od" tag. */ Success = readOutputDirectory(i, argc, argv); } else if (std::string(inptype) == "-dInput"){ /** * In case of simulations contining from save or when the tool is called to display an existing simulation, * the input directory should be specified, with the tag "-dInput". */ Success = readSaveDirectoryToDisplay(i, argc, argv); } else { std::cerr<<"Please enter a valid option key: {-mode,-i, -od, -dInput}, current string: "<<inptype<<std::endl; return false; } i++; if (!Success){ return Success; } } Success = checkInputConsistency(); return Success; } bool Simulation::readModeOfSim(int& i, int argc, char **argv){ i++; if (i >= argc){ std::cerr<<" input the mode of simulation: {DisplaySave, SimulationOnTheGo, ContinueFromSave, Default}"<<std::endl; return false; } const char* inpstring = argv[i]; if (std::string(inpstring) == "DisplaySave"){ DisplaySave = true; return true; } else if (std::string(inpstring) == "SimulationOnTheGo" || string(inpstring) == "Default"){ DisplaySave = false; return true; } else if (std::string(inpstring) == "ContinueFromSave"){ ContinueFromSave = true; DisplaySave = false; return true; } else{ std::cerr<<"Please provide input mode: -mode {DisplaySave, SimulationOnTheGo, ContinueFromSave, Default}"; return false; } } bool Simulation::readParameters(int& i, int argc, char **argv){ i++; if (i >= argc){ std::cerr<<" input the model input file"<<std::endl; return false; } ModInp->Sim=shared_from_this(); ModInp->parameterFileName = argv[i]; bool Success = ModInp->readParameters(); if (!Success){ return Success; } return true; } bool Simulation::readSaveDirectoryToDisplay(int& i, int argc, char **argv){ i++; if (i >= argc){ std::cerr<<" input the save directory, contents of which will be displayed"<<std::endl; return false; } const char* inpstring = argv[i]; saveDirectoryToDisplayString = string(inpstring); return true; } bool Simulation::readOutputDirectory(int& i, int argc, char **argv){ /** * This function will read in the save directory. The boolean for saving files will * not be toggles. If your model input file states no saving, then the error and output files * will be directed into this directory, but the frame saving must be toggled independently. */ i++; if (i >= argc){ std::cerr<<" input the save directory"<<std::endl; return false; } const char* inpstring = argv[i]; saveDirectory= string(inpstring); return true; } bool Simulation::readFinalSimulationStep(){ bool success = openFilesToDisplay(); if (!success){ return false; } /** * The data save interval and time step from the model input file * are backed up, then the properties of the saved system are read. */ double timeStepCurrentSim = dt; int dataSaveIntervalCurrentSim = dataSaveInterval; //reading system properties: success = readSystemSummaryFromSave(); if (!success){ return false; } string currline; while(reachedEndOfSaveFile == false){ /** * Each frame is then read until the end of Simulation is reached. For each fraom first * line is discarded as it is the header. */ //skipping the header: getline(saveFileToDisplayMesh,currline); //std::cerr<<" currline in read last step: "<<currline<<std::endl; if(saveFileToDisplayMesh.eof()){ reachedEndOfSaveFile = true; break; } /** * If end of file is not reached, the node data is read. */ success = readNodeDataToContinueFromSave(); std::cout<<"dt after readNodeDataToContinueFromSave "<<dt<<" timeStepCurrentSim: "<<timeStepCurrentSim<<" dataSaveInterval: "<<dataSaveInterval<<" dataSaveIntervalCurrentSim: "<<dataSaveIntervalCurrentSim<<std::endl; if (!success){ return false; } /** * If node data is successfully read, then element data is read. */ readElementDataToContinueFromSave(); /** * Depending on which properties are saved, all the trmainder physocal porperies and * states of the tissue are read. */ if (TensionCompressionSaved){ readTensionCompressionToContinueFromSave(); } if (GrowthSaved){ readGrowthToContinueFromSave(); } if (GrowthRateSaved){ readGrowthRateToContinueFromSave(); } if (physicalPropertiesSaved){ readPhysicalPropToContinueFromSave(); } if (growthRedistributionSaved){ readGrowthRedistributionToContinueFromSave(); } //std::cout<<" reading node binding"<<std::endl; if (nodeBindingSaved){ readNodeBindingToContinueFromSave(); } /** * The time step are iterated with the save time step read from the save summary. */ timestep = timestep + dataSaveInterval; currSimTimeSec += dt*dataSaveInterval; std::cout<<"current time step "<<timestep<<" currSimTimeSec: "<<currSimTimeSec<<std::endl; /** * Finally the footer is skipped. */ //skipping the footer: getline(saveFileToDisplayMesh,currline); while (currline.empty() && !saveFileToDisplayMesh.eof()){ //skipping empty line getline(saveFileToDisplayMesh,currline); } /** * Now with all this information, we will save the file again, as such, we can keep all the Simulation * in a continuous file and dont work on appending folders later. This reduces significant amount of book keeping, * specifically for the simulations that are run on high throughput servers at muliple steps. */ //Now I will save it again: std::cout<<"saving"<<std::endl; saveStep(); } /** * One the last step is reached, the element positions, volumes, physical properties, nodal masses, and other geometry dependent properties such as * the shape function derivatives, and bounding box are updated. */ std::cout<<"carry out updates"<<std::endl; updateElementVolumesAndTissuePlacements(); updateElasticPropertiesForAllNodes(); clearNodeMassLists(); assignNodeMasses(); assignConnectedElementsAndWeightsToNodes(); calculateShapeFunctionDerivatives(); updateElementPositions(); calculateBoundingBox(); /** * Finally, the data save interval and time step from the model input of the current simulation are * instated back. */ dataSaveInterval = dataSaveIntervalCurrentSim; dt = timeStepCurrentSim; return true; } void Simulation::updateMasterSlaveNodesInBinding(){ for (const auto& itNode : Nodes){ for (int dim = 0; dim<3; ++dim){ if (itNode->slaveTo[dim] > -1){ int slaveDof = itNode->Id*3+dim; int masterDof = itNode->slaveTo[dim]*3+dim; std::vector <int> fix; fix.push_back(slaveDof); fix.push_back(masterDof); NRSolver->slaveMasterList.push_back(fix); NRSolver->boundNodesWithSlaveMasterDefinition = true; } } } } bool Simulation::checkInputConsistency(){ if (ContinueFromSave && saveDirectoryToDisplayString == "Not-Set"){ std::cerr <<"The mode is set to continue from saved simulation, please provide an input directory containing the saved profile, using -dInput"<<std::endl; return false; } if (saveData || saveImages){ if (saveDirectory == "Not-Set"){ std::cerr <<"Modelinput file requires saving, please provide output directory, using -od tag"<<std::endl; return false; } } if (DisplaySave){ if (saveDirectoryToDisplayString == "Not-Set"){ std::cerr <<"The mode is set to display from save, please provide an input directory, using -dInput"<<std::endl; return false; } } for (int i=0; i<nGrowthFunctions; ++i){ if(GrowthFunctions[i]->applyToPeripodialMembrane){ std::cerr<<"There is no peripodial membrane, while growth function "<<i<<" is applicable to peropodial membrane, further checks needed"<<std::endl; needPeripodialforInputConsistency = true; } } return true; } bool Simulation::initiateSystem(){ bool Success = openFiles(); if (!Success){ return Success; } if (MeshType == 2){ /** * If the mesh type is 2, then a mesh with selected number of rows and columns will be initiated. *This is the default option is no input file is provided to the system. */ Success = initiateMesh(MeshType, Row, Column, SideLength, zHeight); } else if(MeshType == 4){ /** * Most commonly used input mesh type requires an input mesh file. */ Success = initiateMesh(MeshType); } if (!Success){ return Success; } if (symmetricY || symmetricX){ /** * If there is symetricity in the system, a checkpoint for circumferential node definitions * is in place. The symmetricity boundary should not be considered as at the outer circumference. */ clearCircumferenceDataFromSymmetricityLine(); } /** * Then the existance of the peripodial membrane in the system is checked. */ Success = checkIfThereIsPeripodialMembrane(); /** * The tissue height is calculated and the tissue bounding box is obtained. Then the relative z positions * of the elements are calculated. */ Success = calculateTissueHeight(); //Calculating how many layers the columnar layer has, and what the actual height is. calculateBoundingBox(); assignInitialZPositions(); if (!Success){ return Success; } /** * At this point consistency is checked again to see if the model inputs necessiate a peripodial membane, and if they do, if * it has been implemented. */ if (needPeripodialforInputConsistency){ if (!thereIsPeripodialMembrane){ std::cerr<<"There is no peripodial membrane but at least one growth function desires one"<<std::endl; Success = false; } } /** * If the model inputs enable an explicit definition of extracellular matrix, this is labelled on the * mesh here via Simulation#setUpECMMimicingElements. */ if (thereIsExplicitECM){ setUpECMMimicingElements(); } /** * If the model inputs enable an explicit definition of an actin rich top layer, this is labelled on the * mesh here via Simulation#setUpActinMimicingElements. */ if (thereIsExplicitActin){ setUpActinMimicingElements(); } /** * Then element neighbourhoods are filled in. */ setBasalNeighboursForApicalElements(); fillInNodeNeighbourhood(); fillInElementColumnLists(); /** * The simulation can fix degrees of freedom for certain nodes, as boundary condition. These * node fixing options are set up via function Simulation#checkForNodeFixing. */ checkForNodeFixing(); /** * The tip nodes are assigned via Simulation#assignTips. */ assignTips(); if (!Success){ return Success; } /** * If all the initiation setup conpleted without errors up to this point, then the mesh is characterised with flags, and now * the actual physical parametrs are set up. First the system forces matrix is set with the sytem node size, via function * Simulation#initiateSystemForces. Then the system center is calcualted, and physical parameters are assigned to the elements via * Simulation#assignPhysicalParameters. \n */ initiateSystemForces(); calculateSystemCentre(); assignPhysicalParameters(); /** * Once the viscoelastic properties are set, thje system is checked against zero external viscosity. If there is no external * viscosity in the system, then additional boundry conditions should e implemented to reach a unique solution in the NR iteration to * solve for nodal displacements. Oncce viscosities are updated, the node massess, and the surfaces that are expoed the the external * friction are set in Simulation#assignNodeMasses, Simulation#assignElementalSurfaceAreaIndices, and * Simulation#assignConnectedElementsAndWeightsToNodes functions. */ checkForZeroExternalViscosity(); calculateShapeFunctionDerivatives(); assignNodeMasses(); assignElementalSurfaceAreaIndices(); assignConnectedElementsAndWeightsToNodes(); alignTissueDVToXPositive(); /** * Then the boiunding box of the tissue is calculated and the relative positions are set. */ calculateBoundingBox(); calculateDVDistance(); for (auto &itElement : Elements){ itElement->calculateRelativePosInBoundingBox(boundingBox[0][0],boundingBox[0][1],boundingBoxSize[0],boundingBoxSize[1]); } updateRelativePositionsToApicalPositioning(); for(const auto& itElement : Elements){ itElement->setInitialRelativePosInBoundingBox(); } /** * If there are any additional manipulations, they are implemented next. Thee include growth mutant induction, experiemtal stretcher attachement, * experimental pippete aspiration setup, and setting up symettic axes of the tissue to have fixed boundaries, and assigningn labelling by * ellipse bands for further manipulation if these are implemented. */ induceClones(); if (stretcherAttached){ setStretch(); } std::cout<<"setting the pipette"<<std::endl; //setUpAFM(); if(PipetteSuction){ setupPipetteExperiment(); } if (symmetricY){ setupYsymmetricity(); } if (symmetricX){ setupXsymmetricity(); } assignIfElementsAreInsideEllipseBands(); /** * If the simultion is continuing from an already saved setup (Simualtion#ContinueFromSave = true), the last * frame of the save is read via Simulation#readFinalSimulationStep. */ if (ContinueFromSave){ cout<<"Reading Final SimulationStep: "<<std::endl; Success = readFinalSimulationStep(); if (!Success){ return Success; } } /** * If data is being saved, then the simulation summary will be written next. */ if (saveData){ cout<<"writing the summary current simulation parameters"<<std::endl; writeSimulationSummary(); writeSpecificNodeTypes(); } /** * Fianlly, the Newton Raphson solver object is initiated, and node DoF bonding as boundary condition is checked. */ nNodes = Nodes.size(); nElements = Elements.size(); NRSolver = make_unique<NewtonRaphsonSolver>(Nodes[0]->nDim,nNodes); if (ContinueFromSave){ updateMasterSlaveNodesInBinding(); } checkForNodeBinding(); std::cout<<" system initiated"<<std::endl; return Success; } void Simulation::checkForNodeBinding(){ /** * If the model inputs require node binding to eliminate rotation at tissue boundary (Simulation#thereIsCircumferenceXYBinding = true), * then this is implemented in here. The nodes are updated via Simulation#bindCircumferenceXY, and the NR solver data is updated. */ if (thereIsCircumferenceXYBinding){ bool thereIsBinding = bindCircumferenceXY(); if (thereIsBinding){ NRSolver->boundNodesWithSlaveMasterDefinition = true; } } } bool Simulation::areNodesToCollapseOnLateralECM(int slaveNodeId, int masterNodeId){ if(Nodes[slaveNodeId]->hasLateralElementOwner || Nodes[masterNodeId]->hasLateralElementOwner){ cout<<"binding nodes: "<<slaveNodeId<<" "<<masterNodeId<<" on single element collapse, but will not collapse nodes, as they are too close on lateral element"<<std::endl; return true; } int nElement = Nodes[slaveNodeId]->connectedElementIds.size(); for (int elementCounter = 0; elementCounter<nElement; elementCounter++){ int elementId = Nodes[slaveNodeId]->connectedElementIds[elementCounter]; if (Elements[elementId]->isECMMimimcingAtCircumference){ cout<<"binding nodes: "<<slaveNodeId<<" "<<masterNodeId<<" on single element collapse, but will not collapse nodes, as they are too close on circumferential element - slave"<<std::endl; return true; } } nElement = Nodes[masterNodeId]->connectedElementIds.size(); for (int elementCounter = 0; elementCounter<nElement; elementCounter++){ int elementId = Nodes[masterNodeId]->connectedElementIds[elementCounter]; if (Elements[elementId]->isECMMimimcingAtCircumference){ cout<<"binding nodes: "<<slaveNodeId<<" "<<masterNodeId<<" on single element collapse, but will not collapse nodes, as they are too close on circumferential element - master"<<std::endl; return true; } } return false; } bool Simulation::checkEdgeLenghtsForBindingPotentiallyUnstableElements(){ /** * This function checks the side lengths of elements, and if they are shrinking below the collapse threshold, the * nodes of the element are collapsed to avoid flipping. */ bool thereIsBinding = false; size_t dim = 3; vector<int> masterIdsBulk,slaveIdsBulk; if (boundLateralElements == false){ /** * During the check, the corner ECM elements are treated specially. These elements are very thin, they are prone to flips, * therefore their apical and basal surfaces are bound to convert them effectively into sheet elements. * They are bound without collapse as they are very thin. This is carried out once at * the beginning of the simulation, and the operation is flagged with Simulation#boundLateralElements boolean. */ for (auto &itElement : Elements){ boundLateralElements = true; //cout<<"checking element "<<(*itElement)->Id<<std::endl; /** * The length is checked with ShapeBase#checkEdgeLenghtsForBinding. */ itElement->checkEdgeLenghtsForBinding(masterIdsBulk,slaveIdsBulk); int selectedPair[2] = {0,0}; if(itElement->isECMMimimcingAtCircumference && itElement->tissuePlacement == 0){ /** Then in the following loop the corner ECM elements are listed to be bound. */ const std::vector<int>& nodeIds = itElement->getNodeIds(); std::array<double,3> vec {0.0}; for (int idim =0; idim<3; idim++){ vec[idim] = Nodes[nodeIds[0]]->Position[idim]-Nodes[nodeIds[1]]->Position[idim]; } double L = itElement->normaliseVector3D(vec); if (L < 0.5){ selectedPair[0] = 0; selectedPair[1] = 1; } else{ for (size_t idim =0; idim<3; idim++){ vec[idim] = Nodes[nodeIds[0]]->Position[idim]-Nodes[nodeIds[2]]->Position[idim]; } double L = itElement->normaliseVector3D(vec); if (L < 0.5){ selectedPair[0] = 0; selectedPair[1] = 2; } else{ selectedPair[0] = 1; selectedPair[1] = 2; } } masterIdsBulk.push_back(nodeIds[selectedPair[0]]); slaveIdsBulk.push_back(nodeIds[selectedPair[1]]); masterIdsBulk.push_back(nodeIds[selectedPair[0]+3]); slaveIdsBulk.push_back(nodeIds[selectedPair[1]+3]); for (size_t i=1; i < TissueHeightDiscretisationLayers;++i){ int idOfElementOnSameColumn = itElement->elementsIdsOnSameColumn[i]; const std::vector<int>& nodeIdsOfElementOnSameColumn = Elements[idOfElementOnSameColumn]->getNodeIds(); masterIdsBulk.push_back(nodeIdsOfElementOnSameColumn[selectedPair[0]]); slaveIdsBulk.push_back(nodeIdsOfElementOnSameColumn[selectedPair[1]]); masterIdsBulk.push_back(nodeIdsOfElementOnSameColumn[selectedPair[0]+3]); slaveIdsBulk.push_back(nodeIdsOfElementOnSameColumn[selectedPair[1]+3]); } } } } /** * Once the potential collapse list is obtained, the duplicates are cleaned. */ vector<int> masterIds,slaveIds; size_t n = masterIdsBulk.size(); for (size_t i=0;i<n;++i){ bool duplicate = false; size_t nMaster = masterIds.size(); for (size_t j=0; j<nMaster; ++j){ if (masterIdsBulk[i] == masterIds[j] && slaveIdsBulk[i] == slaveIds[j]){ duplicate = true; } if (masterIdsBulk[i] == slaveIds[j] && slaveIdsBulk[i] == masterIds[j]){ duplicate = true; } } if (!duplicate){ masterIds.push_back(masterIdsBulk[i]); slaveIds.push_back(slaveIdsBulk[i]); } } /** * In the clean list, the node degree of freedom couples are checked to see if they are already bound, or already flagged as masters or slaves * to other degrees of freedoms. The collapse is managed by function Node#collapseOnNode. */ //Now go through the list, check if the binding is feasible: n = masterIds.size(); for (size_t idMasterSlaveCouple=0;idMasterSlaveCouple<n;++idMasterSlaveCouple){ int masterNodeId = masterIds[idMasterSlaveCouple]; int slaveNodeId = slaveIds[idMasterSlaveCouple]; if (binary_search(Nodes[masterNodeId]->collapsedWith.begin(), Nodes[masterNodeId]->collapsedWith.end(),slaveNodeId)){ //the couple is already collapsed; continue; } bool nodesHaveLateralOwners = areNodesToCollapseOnLateralECM(slaveNodeId,masterNodeId); if(!nodesHaveLateralOwners){ cout<<"the nodes do not have lateral owners, continue to collapse"<<std::endl; Nodes[slaveNodeId]->collapseOnNode(Nodes, masterNodeId); } for(size_t i=0; i<dim; ++i){ /** The fixed node degree of freedoms of the master node are reflected on the slave. */ if (Nodes[masterNodeId]->FixedPos[i]){ Nodes[slaveNodeId]->FixedPos[i]=true; } //not using an else, as the slave could be fixed in given dimension independent of the master if (!Nodes[slaveNodeId]->FixedPos[i]){ int dofmaster = masterNodeId*dim+i; int dofslave = slaveNodeId*dim+i; /** * If the slave is alrady slave to another node (Node#slaveTo is not set to -1, the default non-slave indice), then the master of this processed couple is set to * be the slave of the existing master of the slave, and all three degree of freedoms are bound to each other. */ if (Nodes[slaveNodeId]->slaveTo[i] > -1){ /** * One possiblity is that the potential slave is already a slave to the potential master, then nothing is needed to be done. */ if(Nodes[slaveNodeId]->slaveTo[i] == masterNodeId || Nodes[slaveNodeId]->slaveTo[i] == Nodes[masterNodeId]->slaveTo[i] ){ continue; } dofslave = Nodes[slaveNodeId]->slaveTo[i]*dim+i; slaveNodeId = Nodes[slaveNodeId]->slaveTo[i]; } /** * If the potential master node is already a slave to another node, then the potential master is moved to * the original master of the potential master DoF in function NewtonRaphsonSolver#checkMasterUpdate. */ NRSolver->checkMasterUpdate(dofmaster,masterNodeId); /** * In this last check point, if the original couple was flipped such that the potential master vas the slave of the potential slave, * then now both master and slave nodes are equal to the initial potential slave id ( as it has been the master prior to this step). * Then again, nothing needs to be implemented, slave master coupling is already in place. */ if (dofmaster != dofslave){ /** * If this is not the case and the implementation shoulf continue, the next check point is for duplicate couples, to check * if this couple already exists, via NewtonRaphsonSolver#checkIfCombinationExists. */ bool continueAddition = NRSolver->checkIfCombinationExists(dofslave,dofmaster); if (continueAddition){ /** * If the couple is not implemented, then the check for the status of the slave is carried out, if the slave is already master of * other nodes, the coupling is checked and corrected in function NewtonRaphsonSolver#checkIfSlaveIsAlreadyMasterOfOthers. If the * function updates the node couple, then the potential slave was a master, and now is a slave to the potential master. * All slaves of the potential master are moved on to the potential master. \n */ bool madeChange = NRSolver->checkIfSlaveIsAlreadyMasterOfOthers(dofslave,dofmaster); if (madeChange){ for (size_t nodeIt = 0 ; nodeIt<nNodes; ++nodeIt){ if(Nodes[nodeIt]->slaveTo[i]==slaveNodeId){ Nodes[nodeIt]->slaveTo[i]=masterNodeId; } } } vector <int> fixDOF; fixDOF.push_back(dofslave); fixDOF.push_back(dofmaster); NRSolver->slaveMasterList.push_back(fixDOF); Nodes[slaveNodeId]->slaveTo[i] = masterNodeId; Nodes[masterNodeId]->isMaster[i] = true; thereIsBinding = true; } } } } } if(thereIsBinding){ /** * After finalisation of all node binding checks, if there has been binding, then node positions are updated to bring the positions of * the collapsed nodes together.\m * Please note there is no hierarchy between master and slaves, the choice siply defines which array of the * sparse matrix will be utilised in solving the cumulative forces of all master-slave groups. */ updateElementPositions(); } return thereIsBinding; } bool Simulation::bindCircumferenceXY(){ /** * This is a boundary condition setup function, where a special case of node binding is implemented. For each column of nodes art tissue * circumference, the x and y degrees of freedom of each node is bound. The most basal (bottom - min z) node is declared as the master of the * remaining nodes, and they slaves. Please note there is no hierarchy between master and slaves, the choice siply defines which array of the * sparse matrix will be utilised in solving the cumulative forces of all master-slave groups. */ bool thereIsBinding = false; size_t dim = 3; vector <int> nodeIds; for (size_t i=0; i<nNodes; ++i){ if (Nodes[i]->tissuePlacement == 0){ //basal node if (Nodes[i]->atCircumference){ //at basal circumference: nodeIds.push_back(i); } } } size_t n = nodeIds.size(); for (size_t i=0; i<n; ++i){ int masterNodeId = nodeIds[i]; int dofXmaster = masterNodeId*dim; int dofYmaster = masterNodeId*dim+1; int currNodeId = masterNodeId; bool reachedTop = false; int a = 0; while (!reachedTop && a<5){ a++; int nConnectedElements = Nodes[currNodeId]->connectedElementIds.size(); for (int j=0;j<nConnectedElements;++j){ int elementId = Nodes[currNodeId]->connectedElementIds[j]; bool IsBasalOwner = Elements[elementId]->IsThisNodeMyBasal(currNodeId); if (IsBasalOwner){ int slaveNodeId = Elements[elementId]->getCorrecpondingApical(currNodeId); if (Nodes[masterNodeId]->FixedPos[0]){ //master node is fixed in X, slave needs to be fixed as well, and no need for binding calculations. Nodes[slaveNodeId]->FixedPos[0]=true; } if (Nodes[masterNodeId]->FixedPos[1]){ Nodes[slaveNodeId]->FixedPos[1]=true; } //If the DoF is fixed rigidly by node fixing functions, then I //will not make it a slave of any node. Making it a slave leads to displacement //I would need to check for fixed nodes and correct my forces/jacobian twice. //First fix jacobian and forces, then bind nodes, then fix jacobian again to //clear up all the fixed nodes that were slaves and bound to other nodes. //If I do the binding first,without the first fixing I will carry the load of the fixed node onto the master node unnecessarily //Simpler and cleaner to not make them slaves at all. if (!Nodes[slaveNodeId]->FixedPos[0]){ int dofXslave = slaveNodeId*dim; vector <int> fixX; fixX.push_back(dofXslave); fixX.push_back(dofXmaster); NRSolver->slaveMasterList.push_back(fixX); Nodes[slaveNodeId]->slaveTo[0] = masterNodeId; Nodes[masterNodeId]->isMaster[0] = true; thereIsBinding = true; } if (!Nodes[slaveNodeId]->FixedPos[1]){ int dofYslave = slaveNodeId*dim+1; vector <int> fixY; fixY.push_back(dofYslave); fixY.push_back(dofYmaster); NRSolver->slaveMasterList.push_back(fixY); Nodes[slaveNodeId]->slaveTo[1] = masterNodeId; Nodes[masterNodeId]->isMaster[1] = true; thereIsBinding = true; } currNodeId = slaveNodeId; break; } } if (!thereIsPeripodialMembrane && Nodes[currNodeId]->tissuePlacement == 1){ //there is no peripodial and I have reached apical nodes reachedTop = true; } if (thereIsPeripodialMembrane && Nodes[currNodeId]->tissuePlacement == 0){ //there is peripodial and I have reached basal nodes again reachedTop = true; } } } return thereIsBinding; } void Simulation::assignNodeMasses(){ /** * Masses to all nodes are asigned through thier owner elements via ShapeBase#assignVolumesToNodes. */ for(auto& itElement : Elements){ itElement->assignVolumesToNodes(Nodes); } } void Simulation::assignElementalSurfaceAreaIndices(){ /** * Exposed surface indices to all elements are asigned via ShapeBase#assignExposedSurfaceAreaIndices. */ //not using range based loops here to ensure openMP comaptibility #pragma omp parallel for for(std::vector<std::unique_ptr<ShapeBase>>::iterator itElement = Elements.begin(); itElement < Elements.end(); ++itElement){ (*itElement)->assignExposedSurfaceAreaIndices(Nodes); } } void Simulation::assignConnectedElementsAndWeightsToNodes(){ /** * All connected elements are asigned nodes via ShapeBase#assignElementToConnectedNodes. */ for(auto& itElement : Elements){ itElement->assignElementToConnectedNodes(Nodes); } } bool Simulation::openFiles(){ bool Success; if (saveData){ //Mesh information at each step: string saveFileString = saveDirectory +"/Save_Frame"; const char* name_saveFileMesh = saveFileString.c_str(); saveFileMesh.open(name_saveFileMesh, ofstream::out); if (saveFileMesh.good() && saveFileMesh.is_open()){ Success = true; } else{ std::cerr<<"could not open file: "<<name_saveFileMesh<<std::endl; Success = false; } saveFileString = saveDirectory +"Save_Summary"; const char* name_saveFileSimulationSummary = saveFileString.c_str(); saveFileSimulationSummary.open(name_saveFileSimulationSummary, ofstream::out); if (saveFileSimulationSummary.good() && saveFileSimulationSummary.is_open()){ Success = true; } else{ std::cerr<<"could not open file: "<<name_saveFileSimulationSummary<<std::endl; Success = false; } //tension compression information at each step: saveFileString = saveDirectory +"/Save_TensionCompression"; const char* name_saveFileTenComp = saveFileString.c_str(); cout<<"opening the file" <<name_saveFileTenComp<<std::endl; saveFileTensionCompression.open(name_saveFileTenComp, ofstream::binary); if (saveFileTensionCompression.good() && saveFileTensionCompression.is_open()){ Success = true; } else{ std::cerr<<"could not open file: "<<name_saveFileTenComp<<std::endl; Success = false; } //Growth information at each step (Fg): saveFileString = saveDirectory +"/Save_Growth"; const char* name_saveFileGrowth = saveFileString.c_str(); cout<<"opening the file" <<name_saveFileGrowth<<std::endl; saveFileGrowth.open(name_saveFileGrowth, ofstream::binary); if (saveFileGrowth.good() && saveFileGrowth.is_open()){ Success = true; } else{ std::cerr<<"could not open file: "<<name_saveFileGrowth<<std::endl; Success = false; } //Growth rate information at each step (rx,ry,rz, (as in exp(rx*dt) )for display purposes only): saveFileString = saveDirectory +"/Save_GrowthRate"; const char* name_saveFileGrowthRate = saveFileString.c_str(); cout<<"opening the file" <<name_saveFileGrowthRate<<std::endl; saveFileGrowthRate.open(name_saveFileGrowthRate, ofstream::binary); if (saveFileGrowthRate.good() && saveFileGrowthRate.is_open()){ Success = true; } else{ std::cerr<<"could not open file: "<<name_saveFileGrowthRate<<std::endl; Success = false; } //opening the physical property information file: saveFileString = saveDirectory +"/Save_PhysicalProp"; const char* name_saveFilePhysicalProp = saveFileString.c_str(); saveFilePhysicalProp.open(name_saveFilePhysicalProp, ofstream::binary); if (saveFilePhysicalProp.good() && saveFilePhysicalProp.is_open()){ Success = true; } else{ std::cerr<<"could not open file: "<<name_saveFilePhysicalProp<<std::endl; Success = false; } //opening the specific Node/Element Type file: saveFileString = saveDirectory +"/Save_SpecificElementAndNodeTypes"; const char* name_saveFileSpecificType = saveFileString.c_str(); saveFileSpecificType.open(name_saveFileSpecificType, ofstream::binary); if (saveFileSpecificType.good() && saveFileSpecificType.is_open()){ Success = true; } else{ std::cerr<<"could not open file: "<<name_saveFileSpecificType<<std::endl; Success = false; } //opeining the growth redistribution information file: saveFileString = saveDirectory +"/Save_GrowthRedistribution"; const char* name_saveFileGrowRedist = saveFileString.c_str(); cout<<"opening the file" <<name_saveFileGrowRedist<<std::endl; saveFileGrowthRedistribution.open(name_saveFileGrowRedist, ofstream::binary); if (saveFileGrowthRedistribution.good() && saveFileGrowthRedistribution.is_open()){ Success = true; } else{ std::cerr<<"could not open file: "<<name_saveFileGrowRedist<<std::endl; Success = false; } //node binding information at each step: saveFileString = saveDirectory +"/Save_NodeBinding"; const char* name_saveFileNodeBind = saveFileString.c_str(); cout<<"opening the file" <<name_saveFileNodeBind<<std::endl; //saveFileNodeBinding.open(name_saveFileNodeBind, ofstream::binary); saveFileNodeBinding.open(name_saveFileNodeBind, ofstream::out); if (saveFileNodeBinding.good() && saveFileNodeBinding.is_open()){ Success = true; } else{ std::cerr<<"could not open file: "<<name_saveFileNodeBind<<std::endl; Success = false; } } if (saveDirectory == "Not-Set"){ std::cerr<<"Output directory is not set, outputting on Out file in current directory"<<std::endl; outputFileString = "./Out"; } else { outputFileString = saveDirectory +"/Out"; } const char* name_outputFile = outputFileString.c_str(); outputFile.open(name_outputFile, ofstream::out); if (outputFile.good() && outputFile.is_open()){ Success = true; } else{ std::cerr<<"could not open file: "<<name_outputFile<<std::endl; Success = false; } return Success; } void Simulation::writeSimulationSummary(){ saveFileSimulationSummary<<"TimeStep(sec): "; saveFileSimulationSummary<<dt<<std::endl; saveFileSimulationSummary<<"DataSaveInterval(sec): "; saveFileSimulationSummary<<dataSaveInterval*dt<<std::endl; saveFileSimulationSummary<<"ModelinputName: "; saveFileSimulationSummary<<ModInp->parameterFileName<<std::endl<<std::endl; saveFileSimulationSummary<<"Mesh_Type: "; saveFileSimulationSummary<<MeshType<<std::endl; saveFileSimulationSummary<<" Symmetricity-x: "<<symmetricX<<" Symmetricity-y: "<<symmetricY<<std::endl; writeMeshFileSummary(); writeGrowthRatesSummary(); writeECMSummary(); writeActinSummary(); writeExperimentalSummary(); } void Simulation::writeSpecificNodeTypes(){ //Counting the number of elements and nodes for, actin elements, ECM mimicing elements size_t counterForActinMimicingElements = 0; size_t counterForECMMimicingElements = 0; for(const auto& itElement : Elements){ if (itElement->isActinMimicing){ counterForActinMimicingElements++; } if (itElement->isECMMimicing){ counterForECMMimicingElements++; } } //Writing explicit actin layer: saveFileSpecificType.write((char*) &counterForActinMimicingElements, sizeof counterForActinMimicingElements); for (const auto& itElement : Elements){ if (itElement->isActinMimicing){ saveFileSpecificType.write((char*) & itElement->Id, sizeof itElement->Id); } } //Writing explicit ECM layer: saveFileSpecificType.write((char*) &counterForECMMimicingElements, sizeof counterForECMMimicingElements); for (const auto& itElement : Elements){ if (itElement->isECMMimicing){ saveFileSpecificType.write((char*) & itElement->Id, sizeof itElement->Id); } } saveFileSpecificType.close(); } void Simulation::writeMeshFileSummary(){ if ( MeshType == 2){ saveFileSimulationSummary<<" Row: "; saveFileSimulationSummary<<Row; saveFileSimulationSummary<<" Column: "; saveFileSimulationSummary<<Column; saveFileSimulationSummary<<" SideLength: "; saveFileSimulationSummary<<SideLength; saveFileSimulationSummary<<" zHeight: "; saveFileSimulationSummary<<zHeight; saveFileSimulationSummary<<std::endl; } if ( MeshType == 4){ saveFileSimulationSummary<<" MeshFileName: "; saveFileSimulationSummary<<inputMeshFileName; saveFileSimulationSummary<<std::endl; } } void Simulation::writeGrowthRatesSummary(){ saveFileSimulationSummary<<std::endl; for (int i=0; i<nGrowthFunctions; ++i){ if(GrowthFunctions[i]->Type == 3){ //grid based function does not need dt in summary GrowthFunctions[i]->writeSummary(saveFileSimulationSummary); } else{ GrowthFunctions[i]->writeSummary(saveFileSimulationSummary,dt); } } } void Simulation::writeECMSummary(){ saveFileSimulationSummary<<std::endl; saveFileSimulationSummary<<"There is explicit ECM: "<<thereIsExplicitECM<<std::endl; if (thereIsExplicitECM){ writeECMProperties(); } } void Simulation::writeECMProperties(){ saveFileSimulationSummary<<" Columnar ECM Stiffness(Pa): "<<EColumnarECM<<std::endl; saveFileSimulationSummary<<" Peripodial ECM Stiffness(Pa): "<<EPeripodialECM<<std::endl; saveFileSimulationSummary<<" ECM remodelling half life (hour): "<<ECMRenawalHalfLife/3600.0<<std::endl; saveFileSimulationSummary<<" Is there perturbation to the ECM: "<<thereIsECMChange<<std::endl; if (thereIsECMChange){ int n = ECMChangeBeginTimeInSec.size(); saveFileSimulationSummary<<"there are "<<n<<" ECM perturbations"<<std::endl; for (int ECMperturbationIndex =0;ECMperturbationIndex<n; ++ECMperturbationIndex ){ saveFileSimulationSummary<<" stiffness alteration begins at "<<ECMChangeBeginTimeInSec[ECMperturbationIndex]/3600.0<<" hrs and ends at "<<ECMChangeEndTimeInSec[ECMperturbationIndex]/3600.0<<std::endl; saveFileSimulationSummary<<" final fraction of ECM stiffness "<<ECMStiffnessChangeFraction[ECMperturbationIndex]<<" times original values."<<std::endl; saveFileSimulationSummary<<" final fraction of ECM renewal time "<<ECMRenewalHalfLifeTargetFraction[ECMperturbationIndex]<<" times original values."<<std::endl; saveFileSimulationSummary<<" final fraction of ECM viscosity "<<ECMViscosityChangeFraction[ECMperturbationIndex]<<" times original values."<<std::endl; saveFileSimulationSummary<<" stiffness alteration applied to apical ECM: " <<changeApicalECM[ECMperturbationIndex]<<std::endl; saveFileSimulationSummary<<" stiffness alteration applied to basal ECM: " <<changeBasalECM[ECMperturbationIndex]<<std::endl; saveFileSimulationSummary<<" stiffness alteration applied to ellipse bands: "; for (int i=0; i<numberOfECMChangeEllipseBands[ECMperturbationIndex]; ++i){ saveFileSimulationSummary<<" "<<ECMChangeEllipseBandIds[ECMperturbationIndex][i]; } saveFileSimulationSummary<<std::endl; } } } void Simulation::writeActinSummary(){ saveFileSimulationSummary<<std::endl; saveFileSimulationSummary<<"There is explicit actin: "<<thereIsExplicitActin<<std::endl; } void Simulation::writeExperimentalSummary(){ writePipetteSumary(); } void Simulation::writePipetteSumary(){ saveFileSimulationSummary<<std::endl; saveFileSimulationSummary<<"There is pipette aspiration: "<<PipetteSuction<<std::endl; if (PipetteSuction){ saveFileSimulationSummary<<" is the tissue stuck on the glass: "<<TissueStuckOnGlassDuringPipetteAspiration<<std::endl; saveFileSimulationSummary<<" suction on apical side: "<<ApicalSuction<<std::endl; saveFileSimulationSummary<<" pipette position [centre(x,y,z), effective pippette suction depth, microns]: "<<pipetteCentre[0]<<" "<<pipetteCentre[1]<<" "<<pipetteCentre[2]<<" "<<pipetteDepth<<std::endl; saveFileSimulationSummary<<" pipette radia [inner & outer(microns)]: "<<pipetteInnerRadius<<" "<<pipetteInnerRadius+pipetteThickness<<std::endl; saveFileSimulationSummary<<" Steps for pipette suction "<<nPipetteSuctionSteps<<std::endl; saveFileSimulationSummary<<" suction times (sec): "; for (int i=0; i<nPipetteSuctionSteps; ++i){ saveFileSimulationSummary<<pipetteSuctionTimes[i]<<" "; } saveFileSimulationSummary<<std::endl; saveFileSimulationSummary<<" suction pressures (Pa): "; for (int i=0; i<nPipetteSuctionSteps; ++i){ saveFileSimulationSummary<<pipetteSuctionPressures[i]<<" "; } } } bool Simulation::openFilesToDisplay(){ string saveFileString = saveDirectoryToDisplayString +"/Save_Frame"; const char* name_saveFileToDisplayMesh = saveFileString.c_str(); saveFileToDisplayMesh.open(name_saveFileToDisplayMesh, ifstream::in); if (!(saveFileToDisplayMesh.good() && saveFileToDisplayMesh.is_open())){ std::cerr<<"Cannot open the save file to display: "<<name_saveFileToDisplayMesh<<std::endl; return false; } saveFileString = saveDirectoryToDisplayString +"/Save_Summary"; const char* name_saveFileToDisplaySimSum = saveFileString.c_str();; saveFileToDisplaySimSum.open(name_saveFileToDisplaySimSum, ifstream::in); if (!(saveFileToDisplaySimSum.good() && saveFileToDisplaySimSum.is_open())){ std::cerr<<"Cannot open the simulation summary: "<<name_saveFileToDisplaySimSum<<std::endl; return false; } saveFileString = saveDirectoryToDisplayString +"/Save_SpecificElementAndNodeTypes"; const char* name_saveSpecificElementAndNodeTypes = saveFileString.c_str();; saveFileToDisplaySpecificNodeTypes.open(name_saveSpecificElementAndNodeTypes, ifstream::in); specificElementTypesRecorded = true; if (!(saveFileToDisplaySpecificNodeTypes.good() && saveFileToDisplaySpecificNodeTypes.is_open())){ std::cerr<<"Cannot open the specific node types: "<<name_saveSpecificElementAndNodeTypes<<std::endl; specificElementTypesRecorded = false; //return false; } saveFileString = saveDirectoryToDisplayString +"/Save_TensionCompression"; const char* name_saveFileToDisplayTenComp = saveFileString.c_str(); saveFileToDisplayTenComp.open(name_saveFileToDisplayTenComp, ifstream::in); if (!(saveFileToDisplayTenComp.good() && saveFileToDisplayTenComp.is_open())){ std::cerr<<"Cannot open the save file to display: "<<name_saveFileToDisplayTenComp<<std::endl; TensionCompressionSaved = false; } saveFileString = saveDirectoryToDisplayString +"/Save_Growth"; const char* name_saveFileToDisplayGrowth = saveFileString.c_str(); saveFileToDisplayGrowth.open(name_saveFileToDisplayGrowth, ifstream::in); if (!(saveFileToDisplayGrowth.good() && saveFileToDisplayGrowth.is_open())){ std::cerr<<"Cannot open the save file to display: "<<name_saveFileToDisplayGrowth<<std::endl; GrowthSaved = false; } saveFileString = saveDirectoryToDisplayString +"/Save_GrowthRate"; const char* name_saveFileToDisplayGrowthRate = saveFileString.c_str(); saveFileToDisplayGrowthRate.open(name_saveFileToDisplayGrowthRate, ifstream::in); if (!(saveFileToDisplayGrowthRate.good() && saveFileToDisplayGrowthRate.is_open())){ std::cerr<<"Cannot open the save file to display: "<<name_saveFileToDisplayGrowthRate<<std::endl; GrowthRateSaved = false; } saveFileString = saveDirectoryToDisplayString +"/Save_PhysicalProp"; const char* name_saveFileToDisplayPhysicalProp = saveFileString.c_str();; saveFileToDisplayPhysicalProp.open(name_saveFileToDisplayPhysicalProp, ifstream::in); if (!(saveFileToDisplayPhysicalProp.good() && saveFileToDisplayPhysicalProp.is_open())){ std::cerr<<"Cannot open the save file to display: "<<name_saveFileToDisplayPhysicalProp<<std::endl; physicalPropertiesSaved = false; } saveFileString = saveDirectoryToDisplayString +"/Save_GrowthRedistribution"; const char* name_saveFileToDisplayGrowRedist = saveFileString.c_str(); saveFileToDisplayGrowthRedistribution.open(name_saveFileToDisplayGrowRedist, ifstream::in); if (!(saveFileToDisplayTenComp.good() && saveFileToDisplayTenComp.is_open())){ std::cerr<<"Cannot open the save file to display: "<<name_saveFileToDisplayGrowRedist<<std::endl; growthRedistributionSaved = false; } saveFileString = saveDirectoryToDisplayString +"/Save_NodeBinding"; const char* name_saveFileToDisplayNodeBinding = saveFileString.c_str(); saveFileToDisplayNodeBinding.open(name_saveFileToDisplayNodeBinding, ifstream::in); if (!(saveFileToDisplayNodeBinding.good() && saveFileToDisplayNodeBinding.is_open())){ std::cerr<<"Cannot open the save file to display: "<<name_saveFileToDisplayNodeBinding<<std::endl; nodeBindingSaved = false; } return true; } bool Simulation::initiateSavedSystem(){ /** * This function follows the logic of the Simulation#initiateSystem function, please refer to its documentation for details. * The element and node properties are read from saveed files where available. */ bool success = openFilesToDisplay(); if (!success){ return false; } //reading system properties: success = readSystemSummaryFromSave(); if (!success){ return false; } string currline; //skipping the header: getline(saveFileToDisplayMesh,currline); initiateNodesFromSave(); initiateElementsFromSave(); fillInNodeNeighbourhood(); assignPhysicalParameters(); initiateSystemForces(); if (specificElementTypesRecorded){ success = readSpecificNodeTypesFromSave(); } if (!success){ return false; } if (TensionCompressionSaved){ updateTensionCompressionFromSave(); } if (GrowthSaved){ updateGrowthFromSave(); } if (GrowthRateSaved){ updateGrowthRateFromSave(); } cout<<" reading forces"<<std::endl; if (growthRedistributionSaved){ updateGrowthRedistributionFromSave(); } if (nodeBindingSaved){ updateNodeBindingFromSave(); } updateElementVolumesAndTissuePlacements(); clearNodeMassLists(); assignNodeMasses(); assignConnectedElementsAndWeightsToNodes(); calculateShapeFunctionDerivatives(); updateElementPositions(); //skipping the footer: getline(saveFileToDisplayMesh,currline); while (currline.empty() && !saveFileToDisplayMesh.eof()){ //skipping empty line getline(saveFileToDisplayMesh,currline); } if(saveFileToDisplayMesh.eof()){ reachedEndOfSaveFile = true; return true; } return true; } bool Simulation::readSystemSummaryFromSave(){ string dummystring; if(saveFileToDisplaySimSum.eof()){ std::cerr<<"reached the end of summary file, expecting: TimeStep(sec):"<<std::endl; return false; } saveFileToDisplaySimSum >> dummystring; //reading "TimeStep(sec):" if(saveFileToDisplaySimSum.eof()){ std::cerr<<"reached the end of summary file, expecting: dt value"<<std::endl; return false; } saveFileToDisplaySimSum >> dt; if(saveFileToDisplaySimSum.eof()){ std::cerr<<"reached the end of summary file, expecting: DataSaveInterval(sec):"<<std::endl; return false; } saveFileToDisplaySimSum >> dummystring; //reading "DataSaveInterval(sec):" double dummydouble; if(saveFileToDisplaySimSum.eof()){ std::cerr<<"reached the end of summary file, expecting: save interval value"<<std::endl; return false; } saveFileToDisplaySimSum >> dummydouble; dataSaveInterval = (int) ceil(dummydouble/dt); if(saveFileToDisplaySimSum.eof()){ std::cerr<<"reached the end of summary file, expecting: ModelinputName:"<<std::endl; return false; } saveFileToDisplaySimSum >> dummystring; //reading "ModelinputName: " if(saveFileToDisplaySimSum.eof()){ std::cerr<<"reached the end of summary file, expecting name of the model input file"<<std::endl; return false; } saveFileToDisplaySimSum >> dummystring; //reading the model input file if(saveFileToDisplaySimSum.eof()){ std::cerr<<"reached the end of summary file, expecting: Mesh_Type:"<<std::endl; return false; } saveFileToDisplaySimSum >> dummystring; //reading "Mesh_Type: " if(saveFileToDisplaySimSum.eof()){ std::cerr<<"reached the end of summary file, expecting: the mesh type(int)"<<std::endl; return false; } int dummyint; saveFileToDisplaySimSum >> dummyint; //reading the mesh type if(saveFileToDisplaySimSum.eof()){ std::cerr<<"reached the end of summary file, expecting: Symmetricity-x:"<<std::endl; return false; } saveFileToDisplaySimSum >> dummystring; //reading "Symmetricity-x: " if(saveFileToDisplaySimSum.eof()){ std::cerr<<"reached the end of summary file, expecting: symmetricitX boolean:"<<std::endl; return false; } saveFileToDisplaySimSum >> symmetricX; if(saveFileToDisplaySimSum.eof()){ std::cerr<<"reached the end of summary file, expecting: Symmetricity-y:"<<std::endl; return false; } saveFileToDisplaySimSum >> dummystring; //reading "Symmetricity-y: " if(saveFileToDisplaySimSum.eof()){ std::cerr<<"reached the end of summary file, expecting: symmetricitY boolean:"<<std::endl; return false; } saveFileToDisplaySimSum >> symmetricY; cout<<"read the summary, symmetricity data: "<<symmetricX<<" "<<symmetricY<<std::endl; return true; } bool Simulation::readSpecificNodeTypesFromSave(){ int currElementId; size_t counterForActinMimicingElements; saveFileToDisplaySpecificNodeTypes.read((char*) &counterForActinMimicingElements, sizeof counterForActinMimicingElements); if (counterForActinMimicingElements>0){ thereIsExplicitActin = true; } for (size_t i=0; i<counterForActinMimicingElements; i++){ saveFileToDisplaySpecificNodeTypes.read((char*) &currElementId, sizeof currElementId); int currIndice = getElementArrayIndexFromId(currElementId); if (currIndice < 0){ std::cout<<" error in reading actin mimicking elements "<<std::endl; std::cerr<<" error in reading actin mimicking elements "<<std::endl; return false; } Elements[currIndice]->isActinMimicing = true; } //read in ECM layer to display: size_t counterForECMMimicingElements; saveFileToDisplaySpecificNodeTypes.read((char*) &counterForECMMimicingElements, sizeof counterForECMMimicingElements); if (counterForECMMimicingElements>0){ thereIsExplicitECM = true; } for (size_t i=0; i<counterForECMMimicingElements; i++){ saveFileToDisplaySpecificNodeTypes.read((char*) &currElementId, sizeof currElementId); int currIndice = getElementArrayIndexFromId(currElementId); if (currIndice < 0){ std::cout<<" error in reading ECM mimicking elements "<<std::endl; std::cerr<<" error in reading ECM mimicking elements "<<std::endl; return false; } Elements[currIndice]->isECMMimicing = true; } assigneElementsAtTheBorderOfECM(); assigneElementsAtTheBorderOfActin(); return true; } int Simulation::getElementArrayIndexFromId(int currId){ int currIndice = 0; for (const auto& itElement : Elements){ if (itElement->getId() == currId){ return currIndice; } currIndice++; } std::cerr<<"Error in getElementArrayIndexFromId, required element Id : "<<currId<<" returnin -10, inducing a crash"<<std::endl; return -10; } int Simulation::getNodeArrayIndexFromId(int currId){ int currIndice = 0; for (const auto& itNode : Nodes){ if (itNode->getId() == currId){ return currIndice; } currIndice++; } std::cerr<<"Error in getElementArrayIndexFromId, required node Id : "<<currId<<" returnin -10, inducing a crash"<<std::endl; return -10; } bool Simulation::readNodeDataToContinueFromSave(){ /** * The order of the node data is : \n * [number of nodes] \n * [pos_x] [pos_y] [pos_z] [Node#tissuePlacement] [Node#tissueType] [Node#atCircumference] */ size_t n; saveFileToDisplayMesh >> n; std::cout<<"number of nodes: "<<n<<std::endl; if(nNodes != n){ std::cerr<<"The node number from save file("<<n<<") and model input("<<Nodes.size()<<") are not consistent - cannot continue simulation from save"<<std::endl; return false; } for (size_t i=0; i<n; ++i){ int tissuePlacement, tissueType; bool atCircumference; saveFileToDisplayMesh >> Nodes[i]->Position[0]; saveFileToDisplayMesh >> Nodes[i]->Position[1]; saveFileToDisplayMesh >> Nodes[i]->Position[2]; saveFileToDisplayMesh >> tissuePlacement; saveFileToDisplayMesh >> tissueType; saveFileToDisplayMesh >> atCircumference; if (Nodes[i]->tissuePlacement != tissuePlacement || Nodes[i]->atCircumference != atCircumference || Nodes[i]->tissueType != tissueType ){ std::cerr<<"Node "<<i<<" properties are not consistent - cannot continue simulation from save "<<std::endl; return false; } } return true; } void Simulation::initiateNodesFromSave(){ saveFileToDisplayMesh >> nNodes; for (size_t i=0; i<nNodes; ++i){ std::array<double,3> pos = {0.0, 0.0, 0.0}; int tissuePlacement, tissueType; bool atCircumference; saveFileToDisplayMesh >> pos[0]; saveFileToDisplayMesh >> pos[1]; saveFileToDisplayMesh >> pos[2]; saveFileToDisplayMesh >> tissuePlacement; saveFileToDisplayMesh >> tissueType; saveFileToDisplayMesh >> atCircumference; std::unique_ptr<Node> tmp_nd = make_unique<Node>(i, 3, pos,tissuePlacement, tissueType); tmp_nd-> atCircumference = atCircumference; Nodes.push_back(std::move(tmp_nd)); } } void Simulation::initiateNodesFromMeshInput(){ size_t n; inputMeshFile >> n; for (size_t i=0; i<n; ++i){ std::array<double,3> pos = {0.0, 0.0, 0.0}; int tissuePos = -2; int tissueType = -2; int atCircumference; inputMeshFile >> pos[0]; inputMeshFile >> pos[1]; inputMeshFile >> pos[2]; inputMeshFile >> tissuePos; inputMeshFile >> tissueType; inputMeshFile >> atCircumference; std::unique_ptr<Node> tmp_nd = make_unique<Node>(i, 3, pos,tissuePos, tissueType); tmp_nd-> atCircumference = atCircumference; Nodes.push_back(std::move(tmp_nd)); nNodes = Nodes.size(); } } void Simulation::initiateElementsFromMeshInput(){ size_t n; inputMeshFile >> n; for (size_t i=0; i<n; ++i){ int shapeType; inputMeshFile >> shapeType; if (shapeType == 1){ initiatePrismFromMeshInput(); } else{ std::cerr<<"Element "<<i<<" of "<<n<<": Error in shape type, corrupt save file! - currShapeType: "<<shapeType<<std::endl; break; } } } void Simulation::initiateElementsFromSave(){ size_t n; saveFileToDisplayMesh >> n; cout<<"number of elements: "<<n<<std::endl; for (size_t i=0; i<n; ++i){ int shapeType; saveFileToDisplayMesh >> shapeType; if (shapeType == 1){ initiatePrismFromSave(); } else{ std::cerr<<"Error in shape type, corrupt save file! - currShapeType: "<<shapeType<<std::endl; } } cout<<"number of elements: "<<nElements<<std::endl; } bool Simulation::readElementDataToContinueFromSave(){ /** * The order of the element data is : \n * [number of elements] \n * [ShapeBase#ShapeType] [shape type specific data read by Simulation#readShapeData] */ size_t n; saveFileToDisplayMesh >> n; if (nElements != n){ std::cerr<<"The element number from save file and model input are not consistent - cannot continue simulation from save"<<std::endl; std::cerr<<"n: "<<n<<" nElements: "<<std::endl; return false; } for (size_t i=0; i<nElements; ++i){ int shapeType; saveFileToDisplayMesh >> shapeType; if (Elements[i]->getShapeType() != shapeType){ std::cerr<<"The element type from save file and model input are not consistent - cannot continue simulation from save"<<std::endl; return false; } if (shapeType == 1){ bool success = readShapeData(i); if (!success){ std::cerr<<"Error reading shape data, element: "<<i<<std::endl; return false; } } else if (shapeType == 4){ double height = 0.0; saveFileToDisplayMesh >> height; if (Elements[i]->ReferenceShape->height != height){ std::cerr<<"The element height from save file and model input are not consistent - cannot continue simulation from save"<<std::endl; return false; } bool success = readShapeData(i); if (!success){ std::cerr<<"Error reading shape data, element: "<<i<<std::endl; return false; } } else{ std::cerr<<"Error in shape type, corrupt save file! - currShapeType: "<<shapeType<<std::endl; } } return true; } void Simulation::initiatePrismFromSave(){ /** * Inserts a new prism at order k into elements vector, ShapeBase#NodeIds and reference shape positions * ShapeBase#updateShapeFromSave */ std::vector<int> NodeIds(6,0); std::unique_ptr<ShapeBase> PrismPnt01 = make_unique<Prism>(NodeIds, Nodes, currElementId); PrismPnt01->updateShapeFromSave(saveFileToDisplayMesh); Elements.push_back(std::move(PrismPnt01)); nElements = Elements.size(); currElementId++; } bool Simulation::readShapeData(int i){ /** * The order of the element shape specific information is : \n * [ShapeBase#IsAblated] [node ids read by ShapeBase#readNodeIdData] [reference positions read by ShapeBase#readReferencePositionData] */ bool IsAblated; saveFileToDisplayMesh >> IsAblated; if ( Elements[i]->IsAblated != IsAblated){ std::cerr<<"The element "<<i<<" ablation from save file and model input are not consistent - cannot continue simulation from save"<<std::endl; return false; } bool success = Elements[i]->readNodeIdData(saveFileToDisplayMesh); if (!success){ std::cerr<<"The element "<<i<<" node ids from save file and model input are not consistent - cannot continue simulation from save"<<std::endl; return false; } success = Elements[i]->readReferencePositionData(saveFileToDisplayMesh); if (!success){ std::cerr<<"The element "<<i<<" reference shape from save file and model input are not consistent - cannot continue simulation from save"<<std::endl; return false; } return true; } void Simulation::initiatePrismFromMeshInput(){ std::vector<int> NodeIds(6,0); for (size_t i =0 ;i<6; ++i){ int savedId; inputMeshFile >> savedId; NodeIds[i] = savedId; } std::unique_ptr<ShapeBase> PrismPnt01 = make_unique<Prism>(NodeIds, Nodes, currElementId); PrismPnt01->updateReferencePositionMatrixFromMeshInput(inputMeshFile); PrismPnt01->checkRotationConsistency3D(); Elements.push_back(std::move(PrismPnt01)); nElements = Elements.size(); currElementId++; } void Simulation::reInitiateSystemForces(){ SystemForces.clear(); PackingForces.clear(); for (size_t j=0;j<nNodes;++j){ SystemForces.push_back(std::array<double,3>{0.0}); PackingForces.push_back(std::array<double,3>{0.0}); } } void Simulation::updateTensionCompressionFromSave(){ for(const auto& itElement : Elements){ for (size_t j=0; j<6; ++j){ double S = gsl_matrix_get(itElement->Strain,j,0); saveFileToDisplayTenComp.read((char*) &S, sizeof S); gsl_matrix_set(itElement->Strain,j,0,S); } } } void Simulation::updateGrowthRedistributionFromSave(){ for(const auto& itElement : Elements){ bool thereIsDistribution = false; bool shrinksElement = false; saveFileToDisplayGrowthRedistribution.read((char*) &thereIsDistribution, sizeof thereIsDistribution); itElement->thereIsGrowthRedistribution = thereIsDistribution; saveFileToDisplayGrowthRedistribution.read((char*) &shrinksElement, sizeof shrinksElement); itElement->growthRedistributionShrinksElement = shrinksElement; } } void Simulation::updateNodeBindingFromSave(){ for(const auto& itNode : Nodes){ itNode->slaveTo[0] = -1; itNode->slaveTo[1] = -1; itNode->slaveTo[2] = -1; itNode->isMaster[0] = false; itNode->isMaster[1] = false; itNode->isMaster[2] = false; } size_t n = 0; //size Of Master-Slave List saveFileToDisplayNodeBinding>>n; for (size_t i=0; i<n; ++i){ int dofSlave, dofMaster; saveFileToDisplayNodeBinding>>dofSlave; saveFileToDisplayNodeBinding>>dofMaster; int dim = dofSlave % 3; int nodeSlave = (dofSlave - dim)/3; int nodeMaster = (dofMaster - dim)/3; Nodes[nodeSlave]->slaveTo[dim] = nodeMaster; Nodes[nodeMaster]->isMaster[dim] = true; } } void Simulation::updateGrowthFromSave(){ for(const auto& itElement : Elements){ gsl_matrix* currFg = gsl_matrix_calloc(3,3); for (size_t j=0; j<3; ++j){ for(size_t k=0; k<3; ++k){ double Fgjk; saveFileToDisplayGrowth.read((char*) &Fgjk, sizeof Fgjk); gsl_matrix_set(currFg,j,k,Fgjk); } } itElement->setFg(currFg); gsl_matrix_free(currFg); } } void Simulation::updateGrowthRateFromSave(){ /** For each element, the format is: \n * growth rate [r_x] [r_y] [r_z] \n * Then the shape information is updated with correct timestep length in ShapeBase#setGrowthRateViaInputTimeMultipliedMagnitude. */ for(const auto& itElement : Elements){ double rx=0.0,ry=0.0,rz=0.0; saveFileToDisplayGrowthRate.read((char*) &rx, sizeof rx); saveFileToDisplayGrowthRate.read((char*) &ry, sizeof ry); saveFileToDisplayGrowthRate.read((char*) &rz, sizeof rz); itElement->setGrowthRateViaInputTimeMultipliedMagnitude(rx,ry,rz); } } void Simulation::updatePhysicalPropFromSave(){ readPhysicalPropToContinueFromSave(); } void Simulation::readTensionCompressionToContinueFromSave(){ for(const auto& itElement : Elements){ for (size_t j=0; j<6; ++j){ double S; saveFileToDisplayTenComp.read((char*) &S, sizeof S); gsl_matrix_set(itElement->Strain,j,0,S); } } } void Simulation::readGrowthRedistributionToContinueFromSave(){ for(const auto& itElement : Elements){ bool thereIsDistribution = false; bool shrinksElement = false; saveFileToDisplayGrowthRedistribution.read((char*) &thereIsDistribution, sizeof thereIsDistribution); itElement->thereIsGrowthRedistribution = thereIsDistribution; saveFileToDisplayGrowthRedistribution.read((char*) &shrinksElement, sizeof shrinksElement); itElement->growthRedistributionShrinksElement = shrinksElement; } } void Simulation::readNodeBindingToContinueFromSave(){ //clear all first: for(const auto& itNode : Nodes){ itNode->slaveTo[0] = -1; itNode->slaveTo[1] = -1; itNode->slaveTo[2] = -1; itNode->isMaster[0] = false; itNode->isMaster[1] = false; itNode->isMaster[2] = false; } size_t n = 0; //size Of Master-Slave List saveFileToDisplayNodeBinding>>n; for (size_t i=0; i<n; ++i){ int dofSlave, dofMaster; saveFileToDisplayNodeBinding>>dofSlave; saveFileToDisplayNodeBinding>>dofMaster; int dim = dofSlave % 3; int nodeSlave = (dofSlave - dim)/3; int nodeMaster = (dofMaster - dim)/3; Nodes[nodeSlave]->slaveTo[dim] = nodeMaster; Nodes[nodeMaster]->isMaster[dim] = true; } } void Simulation::readGrowthToContinueFromSave(){ updateGrowthFromSave(); } void Simulation::readGrowthRateToContinueFromSave(){ updateGrowthRateFromSave(); } void Simulation::readPhysicalPropToContinueFromSave(){ /** * For each element, the format is: \n * [Young's modulus] [internal viscosity] [zRemodelling] \n * The values are assigned to elemetns via functions: ShapeBase#setYoungsModulus, * ShapeBase#setViscosity, ShapeBase#setZRemodellingSoFar. \n * Then for each node: \n * [external viscosity_x] [external viscosity_y] [external viscosity_z] */ double E; double internalViscposity; double externalViscosity[3]; double zRemodelling; for(const auto& itElement : Elements){ saveFileToDisplayPhysicalProp.read((char*) &E, sizeof E); saveFileToDisplayPhysicalProp.read((char*) &internalViscposity, sizeof internalViscposity); saveFileToDisplayPhysicalProp.read((char*) &zRemodelling, sizeof zRemodelling); itElement->setYoungsModulus(E); itElement->setViscosity(internalViscposity); itElement->setZRemodellingSoFar(zRemodelling); } for (const auto& itNode : Nodes){ for (size_t i=0; i<3; ++i){ saveFileToDisplayPhysicalProp.read((char*) &externalViscosity[i], sizeof externalViscosity[i]); itNode->externalViscosity[i] = externalViscosity[i]; } } } void Simulation::initiatePrismFromSaveForUpdate(int k){ /** * Inserts a new prism at order k into elements vector, ShapeBase#NodeIds and reference shape positions * ShapeBase#updateShapeFromSave */ std::vector<int> NodeIds(6,0); std::unique_ptr<ShapeBase> PrismPnt01 = make_unique<Prism>(NodeIds, Nodes, currElementId); PrismPnt01->updateShapeFromSave(saveFileToDisplayMesh); std::vector<std::unique_ptr<ShapeBase>>::iterator it = Elements.begin(); it += k; Elements.insert(it,std::move(PrismPnt01)); nElements = Elements.size(); currElementId++; } void Simulation::updateOneStepFromSave(){ string currline; getline(saveFileToDisplayMesh,currline); if(saveFileToDisplayMesh.eof()){ reachedEndOfSaveFile = true; return; } if (implicitPacking){ resetForces(true); // reset packing forces } else{ resetForces(false); // do not reset packing forces } updateNodeNumberFromSave(); updateNodePositionsFromSave(); updateElementStatesFromSave(); for(const auto& itElement : Elements){ //This is updating positions from save. itElement->updatePositions(Nodes); } if (TensionCompressionSaved){ updateTensionCompressionFromSave(); } if (GrowthSaved){ updateGrowthFromSave(); } if (GrowthRateSaved){ updateGrowthRateFromSave(); } if(physicalPropertiesSaved){ updatePhysicalPropFromSave(); } if (growthRedistributionSaved){ updateGrowthRedistributionFromSave(); } if (nodeBindingSaved){ updateNodeBindingFromSave(); } clearNodeMassLists(); assignNodeMasses(); assignConnectedElementsAndWeightsToNodes(); calculateBoundingBox(); //skipping the footer: string currline2; getline(saveFileToDisplayMesh,currline2); getline(saveFileToDisplayMesh,currline2); while (currline.empty() && !saveFileToDisplayMesh.eof()){ //skipping empty line getline(saveFileToDisplayMesh,currline2); } timestep = timestep + dataSaveInterval; currSimTimeSec += dt*dataSaveInterval; } void Simulation::updateNodeNumberFromSave(){ size_t n; saveFileToDisplayMesh>> n; size_t currNodeNumber = Nodes.size(); if (n>currNodeNumber){ for (size_t i = 0; i<(n-currNodeNumber); ++i){ std::array<double,3> pos = {0.0, 0.0, 0.0}; /** This function only initiates the node where necessary, the positions will be read and updated in * Simulaition#updateNodePositionsFromSave. */ std::unique_ptr<Node> tmp_nd = make_unique<Node>(i, 3, pos,-1, -1); Nodes.push_back(std::move(tmp_nd)); nNodes = Nodes.size(); } } else{ //shorten the vector until node numbers match for (size_t i = 0; i<(currNodeNumber-n); ++i){ Nodes.pop_back(); } } n = Nodes.size(); if ( n != nNodes){ //the node number is change, I updated the node list, now I need to fix system forces: reInitiateSystemForces(); } } void Simulation::updateElementStatesFromSave(){ size_t n; saveFileToDisplayMesh >> n; size_t currElementNumber = Elements.size(); while(currElementNumber>n){ /** If the elements list is longer than necessary, elements will be removed from list via Simulation#removeElementFromEndOfList. */ removeElementFromEndOfList(); currElementNumber = Elements.size(); } for (size_t i=0; i<currElementNumber; ++i){ /** * Once existing element list size is shorter or equal to the size on save file, * the shape properties will be updated from the save files. The format is * detailed in Simulartion#readElementDataToContinueFromSave. */ int shapeType; saveFileToDisplayMesh >> shapeType; int currShapeType = Elements[i]->getShapeType(); if (shapeType == currShapeType || shapeType == 2 || shapeType ==4){ if (shapeType ==4){ double height; saveFileToDisplayMesh >> height; } Elements[i]->updateShapeFromSave(saveFileToDisplayMesh); } else{ /** * If the element type does not match the one read from save a new element is initiated and inseted here * (Simulation#initiatePrismFromSaveForUpdate), followed by * an element removed from the end of the list (Simulation#removeElementFromEndOfList) to preserve element * number consistency. */ if (shapeType == 1){ //the new shape is a prism, I will add it now; initiatePrismFromSaveForUpdate(i); } removeElementFromEndOfList(); currElementNumber = Elements.size(); } } while(n>currElementNumber){ /** * If there are more elements saved than I have in my elemetn list new elements will be initiated and updated. * (Simulation#initiatePrismFromSaveForUpdate). */ int shapeType; saveFileToDisplayMesh >> shapeType; if (shapeType == 1){ int i = Elements.size()-1; /** * Only the initiation will be carried out in this function, the * positions will be updated in Simulation#updatePositions called via Simulation#updateOneStepFromSave. */ initiatePrismFromSaveForUpdate(i); currElementNumber = Elements.size(); } } } void Simulation::removeElementFromEndOfList(){ Elements.pop_back(); nElements = Elements.size(); } void Simulation::updateNodePositionsFromSave(){ /** The formatting is detailed in , Simulation#readNodeDataToContinueFromSave, * the main difference is that the node numebr is already read once this function is called. */ for (size_t i=0; i<nNodes; ++i){ saveFileToDisplayMesh >> Nodes[i]->Position[0]; saveFileToDisplayMesh >> Nodes[i]->Position[1]; saveFileToDisplayMesh >> Nodes[i]->Position[2]; saveFileToDisplayMesh >> Nodes[i]->tissuePlacement; saveFileToDisplayMesh >> Nodes[i]->tissueType; saveFileToDisplayMesh >> Nodes[i]->atCircumference; } } bool Simulation::initiateMesh(int MeshType, int Row, int Column, float SideLength, float zHeight){ if ( MeshType == 1 ){ std::cerr<<"Error: Too many arguments for a single element system"<<std::endl; return false; } if ( MeshType == 2){ /** * This call will initiate the nodes first, with the selected side length and height via * Simulation#initiateNodesByRowAndColumn, then the elemetns will be initiated * via Simulation#initiateElementsByRowAndColumn accordingly. */ initiateNodesByRowAndColumn(Row,Column,SideLength,zHeight); initiateElementsByRowAndColumn(Row,Column); } else if ( MeshType == 3 ){ std::cerr<<"Error: Wrong set of arguments for mesh triangulation"<<std::endl; return false; } else if ( MeshType ==4 ){ std::cerr<<"Error: Too many arguments for reading the mesh from file"<<std::endl; return false; } else { std::cerr<<"Error: Mesh Type not recognised"<<std::endl; return false; } return true; } bool Simulation::initiateMesh(int MeshType){ if ( MeshType == 1 ){ std::cerr<<"Error: Too many arguments for a single element system"<<std::endl; return false; } if ( MeshType == 2){ std::cerr<<"Error: Too few arguments for mesh by dimensions"<<std::endl; return false; } else if ( MeshType == 3 ){ std::cerr<<"Error: Wrong set of arguments for mesh triangulation"<<std::endl; return false; } else if ( MeshType ==4 ){ /** * The mesh information will be read form the file read into Simulation#inputMeshFileName parameter. * The nodes and elements will be initiated through functions Simulation#initiateNodesFromMeshInput and * Simulation#initiateElementsFromMeshInput. Then if the tissue type weights are recorded, then they will be read in * via Simulation#readInTissueWeights, the recorded value is peripodialness weight, ShapeBase#peripodialGrowthWeight. * The input maseh file will be closed at teh end of the function. */ const char* name_inputMeshFile = inputMeshFileName.c_str();; inputMeshFile.open(name_inputMeshFile, ifstream::in); if (!(inputMeshFile.good() && inputMeshFile.is_open())){ std::cerr<<"Cannot open the input mesh file: "<<name_inputMeshFile<<std::endl; return false; } initiateNodesFromMeshInput(); initiateElementsFromMeshInput(); std::cout<<" nNodes: "<<nNodes<<" nEle: "<<nElements<<std::endl; bool areTissueWeightsRecorded = checkIfTissueWeightsRecorded(); if (areTissueWeightsRecorded){ readInTissueWeights(); } inputMeshFile.close(); } else { std::cerr<<"Error: Mesh Type not recognised"<<std::endl; return false; } return true; } bool Simulation::checkIfTissueWeightsRecorded(){ bool tissueWeightsRecorded; saveFileToDisplayMesh >> tissueWeightsRecorded; return tissueWeightsRecorded; } void Simulation::readInTissueWeights(){ /** * The tissue type weigths for all elemetns are read from mesh input, via the function * ShapeBase#setGrowthWeightsViaTissuePlacement. The recorded value is * peripodialness weight, ShapeBase#peripodialGrowthWeight. */ double wPeri; for (const auto& itElement : Elements){ inputMeshFile >> wPeri; itElement->setGrowthWeightsViaTissuePlacement(wPeri); //peripodialness weight is recorded } } void Simulation::clearCircumferenceDataFromSymmetricityLine(){ /** * The input mesh can be specified to be symmetric in x, y or both x&y axes. This means the actual * tissue of interest is a larger, but symmetric tissue. Examples are one half of the fly winf, where the * tissue is assummed to be symmetric in its long axis, or simulations of a circular tissue pathc, where * only one quadrant of the tissue is simulated. The mesh input file most likely will report the borders of * the symmetrticity axes to be at circumference. But in real terms, these nodes are not at the circumference, * they are not exposed to the outer world, they are part of a continuing tissue. The circumference flags * should thenbe cleaned from these nodes prior to simulation intiation. \n * * First, the tips are detected. * The y-symmetry is at the y=0 line and similarly x-symmetry is at the x=0 line. Therefore, any node recorded to be * at circumference, but is part of a symmetric tissue and within the relevant distance limit, they should have their * Node#atCircumference flag set to false. The nodes at the tip should be an exception, as the nodes at the tips of the tissue, * will still be at the circumference, although they are at the limits of the symetricity line. One specific case is the * origin in case of x&y symmetry. The origin will be a tissue tip, but will reside at t he centre of the tissue, * therefore should not be symmetric. * */ if (symmetricY){ double xTipPos = -1000, xTipNeg = 1000; for (const auto& itNode : Nodes){ if (itNode->Position[0] > xTipPos ){ xTipPos = itNode->Position[0]; } if (itNode->Position[0] < xTipNeg ){ xTipNeg = itNode->Position[0]; } } double yLimPos = 0.1; double yLimNeg = (-1.0)*yLimPos; for (const auto& itNode : Nodes){ double x = itNode->Position[0]; double y = itNode->Position[1]; if ( y < yLimPos){ if ( y > yLimNeg){ itNode->atSymmetricityBorder = true; fixY(itNode.get(),false); //this is for symmetricity, the fixing has to be hard fixing, not with external viscosity under any condition bool atTip = false; if ( x < xTipPos+yLimPos && x >xTipPos+yLimNeg){ atTip = true; } if (!symmetricX){ //This if clause is checking the x-tip at the negative end. //As described above, the node should still be a circumference node, //if it is at the line of symmetry, but at the tip as well. //BUT, if there is also xSymmetry, this "negative end tip" will //be the tip at the x symmetry line. (If I am modelling a quarter of a circle, //with x and y symmetry, this will point be the centre of the circle.) //Under these conditions, it is not actually at the tip. It should be //removed from circumference node list. //Therefore, I am carrying the atTip? check for the negative end only if //there is no x-symmetry. if ( x > xTipNeg+yLimNeg && x < xTipNeg+yLimPos){ atTip = true; } } if (!atTip){ //removing node from list: itNode->atCircumference = false; } } } } } if (symmetricX){ double yTipPos = -1000, yTipNeg = 1000; for (const auto& itNode : Nodes){ if (itNode->Position[0] > yTipPos ){ yTipPos = itNode->Position[1]; } if (itNode->Position[0] < yTipNeg ){ yTipNeg = itNode->Position[1]; } } double xLimPos = 0.1; double xLimNeg = (-1.0)*xLimPos; for (const auto& itNode : Nodes){ double x = itNode->Position[0]; double y = itNode->Position[1]; if ( x < xLimPos){ if ( x > xLimNeg){ itNode->atSymmetricityBorder = true; fixX(itNode.get(),false); //this is for symmetricity, the fixing has to be hard fixing, not with external viscosity under any condition //the node is indeed at the border, BUT, I will remove it only if it is not at the tip: bool atTip = false; if ( y < yTipPos+xLimPos && y >yTipPos+xLimNeg){ atTip = true; } if ( y > yTipNeg+xLimNeg && y < yTipNeg+xLimPos){ atTip = true; } if (!atTip){ itNode->atCircumference = false; } } } } } } void Simulation::getAverageSideLength(double& periAverageSideLength, double& colAverageSideLength){ double dsumPeri =0.0, dsumCol = 0.0; int colCounter =0, periCounter=0; double packingDetectionThresholdGridCounter[10][5]; for (size_t i=0; i<10;++i){ for (size_t j=0;j<5;++j){ packingDetectionThresholdGrid[i][j] = 0.0; packingDetectionThresholdGridCounter[i][j] = 0.0; } } for (auto &itElement : Elements){ if (itElement->tissueType==0){ //element belongs to columnar layer double currValue = itElement->getApicalSideLengthAverage(); if(currValue>0){ /** * There may be alements with fully collapsed areas, where currValue will be zero. * These are not counted in averaging the side length, as the zero length is not relevant for packing * distance calculations. */ dsumCol += currValue; colCounter++; } if(itElement->tissuePlacement == 0 || itElement->spansWholeTissue){ currValue = itElement->getBasalSideLengthAverage(); if(currValue>0){ dsumCol += currValue; colCounter++; } } /** The local side length data is recorded in a * 10x5 grid, Simulation#packingDetectionThresholdGrid. */ std::array<double,2> reletivePos = itElement->getRelativePosInBoundingBox(); int relX = floor(reletivePos[0]); int relY = floor(reletivePos[1]/2.0); if (relX < 0) {relX = 0;} if (relX > 9) {relX = 9;} if (relY < 0) {relY = 0;} if (relY > 4) {relY = 4;} packingDetectionThresholdGrid[relX][relY]+=currValue; packingDetectionThresholdGridCounter[relX][relY]++; } else{ dsumPeri += itElement->getApicalSideLengthAverage(); periCounter++; } } colAverageSideLength = dsumCol / (double)colCounter; for (size_t i=0; i<10;++i){ for (size_t j=0;j<5;++j){ if(packingDetectionThresholdGridCounter[i][j]>0){ packingDetectionThresholdGrid[i][j] /= packingDetectionThresholdGridCounter[i][j]; } } } if (periCounter>0){ periAverageSideLength = dsumPeri / (double)periCounter; } } bool Simulation::isColumnarLayer3D(){ bool ColumnarLayer3D = false; for (auto &itElement : Elements){ if (itElement->ShapeDim == 3){ ColumnarLayer3D = true; break; } } return ColumnarLayer3D; } bool Simulation::calculateTissueHeight(){ /** * First check will be if the tissue is made up of 3D elements. If the tissue is 3D, then the height * will be calculated accordingly. If the tissue is made up of 2D elements, then the * height will simply be the assigned heigt of the elements, ReferenceShapeBase#height. \n */ bool ColumnarLayer3D = isColumnarLayer3D(); TissueHeight = 0; if (ColumnarLayer3D){ /** * The calculation for tissue height will find the first basal node on Simulation#Nodes. */ //Find the first basal node on the Nodes List //Find the first element that has this node on the elements list //Move apically through the elements until you reach the apical surface - an apical node //Find a basal node: int currNodeId=0; bool foundNode = false; for (auto& itNode : Nodes){ if(itNode->tissueType == 0 && itNode->tissuePlacement == 0){ //Columnar node is basal foundNode = true; currNodeId = itNode->Id; break; } } if (!foundNode){ return false; } //Find an element using the basal node, and move on the elements apically, until you reach the apical surface: bool foundElement = true; TissueHeightDiscretisationLayers = 0; double currentH =0; /** * Then the first element on Simulation#Elements that utilises the found node as a basal node will be identified. * Once the element is identified, an apical node of this element will be selected as the current search node, * the Simulation#TissueHeight and Simulation#TissueHeightDiscretisationLayers will be incremented up, and * the search will continue to find the first element to utilise the new search node as its apicel. The loopo * will continue until and apical node is readhed (Node#tissuePlacement == 1). */ while(Nodes[currNodeId]->tissuePlacement != 1 && foundElement){ //while the node is not apical, and I could find the next element foundElement = false; for (auto &itElement : Elements){ bool IsBasalOwner = itElement->IsThisNodeMyBasal(currNodeId); if (IsBasalOwner){ foundElement = true; currentH = itElement->getElementHeight(); currNodeId = itElement->getCorrecpondingApical(currNodeId); //have the next node break; } } TissueHeight += currentH; TissueHeightDiscretisationLayers++; } if (!foundElement){ return false; } } else{ TissueHeight = Elements[0]->ReferenceShape->height; if (TissueHeight == 0){ std::cerr<<"The coulmanr layer is 2D, but the tissue height of the elements is not assigned properly, cannot obtain TissueHeight"<<std::endl; return false; } } return true; } void Simulation::assignInitialZPositions(){ for (auto &itElement : Elements){ itElement->setInitialZPosition(boundingBox[0][2], TissueHeight); //minimum z of the tissue and the tissue height given as input } } void Simulation::calculateShapeFunctionDerivatives(){ for (auto &itElement : Elements){ itElement->calculateElementShapeFunctionDerivatives(); } } void Simulation::fixAllD(Node* currNode, bool fixWithViscosity){ for (size_t j =0 ; j<currNode->nDim; ++j){ if(fixWithViscosity){ currNode->externalViscosity[j] = fixingExternalViscosity[j]; currNode->externalViscositySetInFixing[j] = true; } else{ currNode->FixedPos[j]=true; } } } void Simulation::fixAllD(int i, bool fixWithViscosity){ for (size_t j =0 ; j<Nodes[i]->nDim; ++j){ if(fixWithViscosity){ Nodes[i]->externalViscosity[j] = fixingExternalViscosity[j]; Nodes[i]->externalViscositySetInFixing[j] = true; } else{ Nodes[i]->FixedPos[j]=true; } } } void Simulation::fixX(Node* currNode, bool fixWithViscosity){ if(currNode->nDim>0){ if(fixWithViscosity){ currNode->externalViscosity[0] = fixingExternalViscosity[0]; currNode->externalViscositySetInFixing[0] = true; } else{ currNode->FixedPos[0]=true; } } else{ std::cerr<<"ERROR: Node : "<<currNode->Id<<" does not have x-dimension"<<std::endl; } } void Simulation::fixX(int i, bool fixWithViscosity){ if(Nodes[i]->nDim>0){ if(fixWithViscosity){ Nodes[i]->externalViscosity[0] = fixingExternalViscosity[0]; Nodes[i]->externalViscositySetInFixing[0] = true; } else{ Nodes[i]->FixedPos[0]=true; } } else{ std::cerr<<"ERROR: Node : "<<Nodes[i]->Id<<" does not have x-dimension"<<std::endl; } } void Simulation::fixY(Node* currNode, bool fixWithViscosity){ if(currNode->nDim>1){ if(fixWithViscosity){ currNode->externalViscosity[1] = fixingExternalViscosity[1]; currNode->externalViscositySetInFixing[1] = true; } else{ currNode->FixedPos[1]=true; } } else{ std::cerr<<"ERROR: Node : "<<currNode->Id<<" does not have y-dimension"<<std::endl; } } void Simulation::fixY(int i, bool fixWithViscosity){ if(Nodes[i]->nDim>1){ if(fixWithViscosity){ Nodes[i]->externalViscosity[1] = fixingExternalViscosity[1]; Nodes[i]->externalViscositySetInFixing[1] = true; } else{ Nodes[i]->FixedPos[1]=true; } } else{ std::cerr<<"ERROR: Node : "<<Nodes[i]->Id<<" does not have y-dimension"<<std::endl; } } void Simulation::fixZ(Node* currNode, bool fixWithViscosity){ if(currNode->nDim>2){ if(fixWithViscosity){ currNode->externalViscosity[2] = fixingExternalViscosity[2]; currNode->externalViscositySetInFixing[2] = true; } else{ currNode->FixedPos[2]=true; } } else{ std::cerr<<"ERROR: Node : "<<currNode->Id<<" does not have z-dimension"<<std::endl; } } void Simulation::fixZ(int i, bool fixWithViscosity){ if(Nodes[i]->nDim>2){ if(fixWithViscosity){ Nodes[i]->externalViscosity[2] = fixingExternalViscosity[2]; Nodes[i]->externalViscositySetInFixing[2] = true; } else{ Nodes[i]->FixedPos[2]=true; } } else{ std::cerr<<"ERROR: Node : "<<Nodes[i]->Id<<" does not have z-dimension"<<std::endl; } } void Simulation::zeroForcesOnNode(size_t i){ /** * The forces corresponding to node indexed at input i on Simulation#Nodes will be set to zero. */ double ForceBalance[3]; ForceBalance[0] = SystemForces[i][0]; ForceBalance[1] = SystemForces[i][1]; ForceBalance[2] = SystemForces[i][2]; for (size_t i=0;i<nNodes;++i){ SystemForces[i][0]-=ForceBalance[0]; SystemForces[i][1]-=ForceBalance[1]; SystemForces[i][2]-=ForceBalance[2]; } } void Simulation::initiateSystemForces(){ for (size_t j=0;j<nNodes;++j){ //3 dimensions SystemForces.push_back(std::array<double,3>{0.0}); PackingForces.push_back(std::array<double,3>{0.0}); } } void Simulation::initiateNodesByRowAndColumn(size_t Row, size_t Column, float SideLength, float zHeight){ dorsalTipIndex = Row; ventralTipIndex = 0; /** * This function will place nodes in space to form the tirangles to genreate a hexagonal mesh of input rows and * columns at its widest point. First in a simple geometric calculaion, the height of of the equilateral triangle * with the input side length is calculated. Then the nodes will be placed at a h difference in y for each column. * The nodes position in x will be shifted by half the side length between columns. */ double sqrt3 = 1.7321; float h = sqrt3/2*SideLength; // height of triangle vector <double> xPos, yPos; vector <int> NodesToFix; int toprowcounter = 0; //number of nodes at the terminating end, the top row. I will need this to add the sideway prisms; for (size_t ColCount = 0; ColCount < Column+1; ++ColCount){ double CurrY = ColCount*h; int CurrRowNum = Row + 1 - ColCount; double RowOffset = 0.5*SideLength*ColCount; for ( int RowCount = 1; RowCount<CurrRowNum+1; ++RowCount){ double CurrX = RowOffset + RowCount * SideLength; xPos.push_back(CurrX); yPos.push_back(CurrY); if (RowCount ==1 || RowCount == CurrRowNum || ColCount == Column){ NodesToFix.push_back(xPos.size()-1); if(ColCount == Column){ toprowcounter++; } } } if (ColCount>0){ CurrY = (-1.0)*CurrY; for ( int RowCount = 1; RowCount<CurrRowNum+1; ++RowCount){ double CurrX = RowOffset + RowCount * SideLength; xPos.push_back(CurrX); yPos.push_back(CurrY); if (RowCount ==1 || RowCount == CurrRowNum || ColCount == Column){ NodesToFix.push_back(xPos.size()-1); } } } } size_t n = xPos.size(); std::array<double,3> pos = {0.0, 0.0, 0.0}; for (size_t i =0; i< n; ++i){ pos[0] = xPos[i]; pos[1] = yPos[i]; pos[2] = 0.0; std::unique_ptr<Node> tmp_nd = make_unique<Node>(i, 3, pos,0,0); Nodes.push_back(std::move(tmp_nd)); nNodes = Nodes.size(); } //Adding the apical level, all will form columnar elements: for (size_t i =0; i< n; ++i){ pos[0] = xPos[i]; pos[1] = yPos[i]; pos[2] = zHeight; std::unique_ptr<Node> tmp_nd = make_unique<Node>(n+i, 3, pos,1,0); Nodes.push_back(std::move(tmp_nd)); nNodes = Nodes.size(); } } void Simulation::setLinkerCircumference(){ double maxX = -100, ZofTip = -100; for (auto& itNode : Nodes){ if (itNode->tissueType == 2){ //The node is linker, is the x position higher than already recorded? if (itNode->Position[0]> maxX){ maxX = itNode->Position[0]; ZofTip = itNode->Position[2]; } } } double thres = 0.2; //cout<<"Setting circumference, maxX: "<<maxX<<" Z of tip: "<<ZofTip<<std::endl; //Now I have the maxX, and the corresponding z height. //Declare all linkers at the basal/or apical surface are the circumferential nodes: for (auto & itNode : Nodes){ if (itNode->tissueType == 2){ //The node is linker, if it is apical or basal, it can be circumferntial: if ( itNode->tissuePlacement == 0 || itNode->tissuePlacement == 1 ){ //The node is linker, if it is in the range of the height of the tip then it is circumferential if ( itNode->Position[2] < ZofTip+thres && itNode->Position[2] > ZofTip-thres ){ itNode->atCircumference = true; } } } } } void Simulation::checkForNodeFixing(){ /** * The Simulation#CircumferentialNodeFix array gives fixing options as booleans for [5options][in 3D] : \n * [option = 0] : apical circumference fixing options [fix_x][ix_y][fix_z]. \n * [option = 1] : basal circumference fixing options [fix_x][ix_y][fix_z]. \n * [option = 2] : linker apical circumference fixing options [fix_x][ix_y][fix_z]. \n * [option = 3] : linker basal circumference fixing options [fix_x][ix_y][fix_z]. \n * [option = 4] : ALL circumference fixing options [fix_x][ix_y][fix_z]. \n * \n * First check point will be for checking if there is circumferential fixing for any part of the tissue. */ //Are there any circumferential node fixing options enabled: bool thereIsCircumFix = false; if (!thereIsCircumFix){ for (size_t i=0;i<5; ++i){ for (size_t j=0;j<3; ++j){ if (CircumferentialNodeFix[i][j] == true){ thereIsCircumFix = true; break; } } if (thereIsCircumFix){ break; } } } /** If there is any fixing option active in any dimention, then the detailed check will continue. */ if (thereIsCircumFix){ for (auto& itNode : Nodes){ if ( itNode->atCircumference){ /** The node is protected from fixing if it is at peripodial tissue. */ bool doNotFix = false; if (itNode->tissueType == 1){ //the node is peripodial, no not fix this node doNotFix = true; } if (!doNotFix){ //Node is at the circumference, now checking for all possibilities: // if i == 0 , I am checking for apical circumference // if i == 1 , I am checking for basal circumference // if i == 2 , I am checking for the linker apical circumference // if i == 3 , I am checking for the linker basal circumference // if i == 4 , I am checking for all circumference /** Then checking all options against Node#tissuePlacement and Node#tissueType, the node fixing is assigned accordingly, * through functions Node#fixX, Node#fixY, Node#fixZ. */ for (size_t i=0;i<5; ++i){ if ( (i == 0 && itNode->tissuePlacement == 1 ) || //tissuePlacement == 1 is apical (i == 1 && itNode->tissuePlacement == 0 ) || //tissuePlacement == 0 is basal (i == 2 && itNode->tissueType == 2 && itNode->tissuePlacement == 1 ) || //tissuePlacement == 1 is apical (i == 3 && itNode->tissueType == 2 && itNode->tissuePlacement == 0 ) || //tissuePlacement == 0 is basal (i == 4)){ //tissuePlacement is irrelevant, fixing all //The node is at circumference; if if (CircumferentialNodeFix[i][0]){ fixX(itNode.get(),CircumferentialNodeFixWithHighExternalViscosity[i]); } if (CircumferentialNodeFix[i][1]){ fixY(itNode.get(),CircumferentialNodeFixWithHighExternalViscosity[i]); } if (CircumferentialNodeFix[i][2]){ fixZ(itNode.get(),CircumferentialNodeFixWithHighExternalViscosity[i]); } } } } } } } /** Once checking the circumference fixing is complete, then fixing whole surfaces are checked, * (Simulation#BasalNodeFix and Simulation#ApicalNodeFix) for instance when the tissue is stuck * on glass for a pipette aspiration experiment. */ if (BasalNodeFix[0] || BasalNodeFix[1] || BasalNodeFix[2] ){ for (auto& itNode : Nodes){ if ( itNode->tissuePlacement == 0){ if (BasalNodeFix[0]){ fixX(itNode.get(), BasalNodeFixWithExternalViscosity); } if (BasalNodeFix[1]){ fixY(itNode.get(), BasalNodeFixWithExternalViscosity); } if (BasalNodeFix[2]){ fixZ(itNode.get(), BasalNodeFixWithExternalViscosity); } } } } if (ApicalNodeFix[0] || ApicalNodeFix[1] || ApicalNodeFix[2]){ for (auto & itNode : Nodes){ if ( itNode->tissuePlacement == 1){ if (ApicalNodeFix[0]){ fixX(itNode.get(), ApicalNodeFixWithExternalViscosity); } if (ApicalNodeFix[1]){ fixY(itNode.get(), ApicalNodeFixWithExternalViscosity); } if (ApicalNodeFix[2]){ fixZ(itNode.get(), ApicalNodeFixWithExternalViscosity); } } } } /** The tissue can be fixed basally through tissue domain specification, specifically for th notum, * which is set by tissue relative position and the parameters * Siumulation#notumFixingRange and Simulation#NotumNodeFix. */ if (NotumNodeFix[0] || NotumNodeFix[1] || NotumNodeFix[2]){ for (auto& itNode : Nodes){ if ( itNode->tissuePlacement == 0){ double boundingBoxXMin = boundingBox[0][0]; double boundingBoxLength = boundingBoxSize[0]; double relativeXPos = (itNode->Position[0] - boundingBoxXMin)/boundingBoxLength; if ( relativeXPos >= notumFixingRange[0] && relativeXPos <= notumFixingRange[1]){ if (NotumNodeFix[0]){ fixX(itNode.get(), NotumNodeFixWithExternalViscosity); } if (NotumNodeFix[1]){ fixY(itNode.get(), NotumNodeFixWithExternalViscosity); } if (NotumNodeFix[2]){ fixZ(itNode.get(), NotumNodeFixWithExternalViscosity); } } } } } } void Simulation::induceClones(){ /** * Growth of a subset of elemetns can be manipulated as mutant clones. These are set with * positional information from model input file, and the mutation growth influence type, which can be * an absolute growth value input, or scaling the existing growth rate. */ for (size_t i=0;i<numberOfClones; ++i){ double inMicronsX = cloneInformationX[i]*boundingBoxSize[0] + boundingBox[0][0]; double inMicronsY = cloneInformationY[i]*boundingBoxSize[1] + boundingBox[0][1]; double inMicronsRadius = cloneInformationR[i]; //cout<<" clone: "<<i<<" position: "<<inMicronsX<<" "<<inMicronsY<<" radius: "<<inMicronsRadius<<std::endl; double r2 = inMicronsRadius*inMicronsRadius; double growthRateORFold = cloneInformationGrowth[i]; for(const auto& itElement : Elements){ if (!itElement->isECMMimicing){ std::array<double,3> c = itElement->getCentre(); double dx = inMicronsX - c[0]; double dy = inMicronsY - c[1]; double d2 = dx*dx + dy*dy; if (d2 < r2){ //cout<<"mutating element: "<<(*itElement)->Id<<std::endl; if (cloneInformationUsingAbsolueGrowth[i]){ itElement->mutateElement(0,growthRateORFold); //the mutation is absolute, using an absolute value } else{ itElement->mutateElement(growthRateORFold,0); //the mutation is not absolute, using relative values } } } } } } void Simulation::initiateElementsByRowAndColumn(size_t Row, size_t Column){ int xinit1 = 0; int xinit2 = xinit1+Row+1; int xinit3 = 0; int xinit4 = xinit1+2*(Row+1)-1; size_t n = Nodes.size() /2.0; //initialising the tissue elements: for (size_t ColCount = 0; ColCount < Column; ++ColCount){ size_t CurrRowNum = Row + 1 - ColCount; for (size_t RowCount = 0; RowCount<CurrRowNum-1; ++RowCount ){ std::vector<int> NodeIds(6,0); NodeIds[0] = xinit1+RowCount; NodeIds[1] = xinit1+RowCount+1; NodeIds[2] = xinit2+RowCount; NodeIds[3] = NodeIds[0] + n; NodeIds[4] = NodeIds[1] + n; NodeIds[5] = NodeIds[2] + n; std::unique_ptr<ShapeBase> PrismPnt01 = make_unique<Prism>(NodeIds, Nodes, currElementId); Elements.push_back(std::move(PrismPnt01)); nElements = Elements.size(); currElementId++; NodeIds[0] = xinit3+RowCount; NodeIds[1] = xinit4+RowCount; NodeIds[2] = xinit3+RowCount+1; NodeIds[3] = NodeIds[0] + n; NodeIds[4] = NodeIds[1] + n; NodeIds[5] = NodeIds[2] + n; std::unique_ptr<ShapeBase> PrismPnt02 = make_unique<Prism>(NodeIds, Nodes, currElementId); Elements.push_back(std::move(PrismPnt02)); nElements = Elements.size(); currElementId++; } for (size_t RowCount = 0; RowCount<CurrRowNum-2; ++RowCount ){ std::vector<int> NodeIds(6,0); NodeIds[0] = xinit2+RowCount; NodeIds[1] = xinit1+RowCount+1; NodeIds[2] = xinit2+RowCount+1; NodeIds[3] = NodeIds[0] + n; NodeIds[4] = NodeIds[1] + n; NodeIds[5] = NodeIds[2] + n; std::unique_ptr<ShapeBase> PrismPnt01 = make_unique<Prism>(NodeIds, Nodes, currElementId); Elements.push_back(std::move(PrismPnt01)); nElements = Elements.size(); currElementId++; NodeIds[0] = xinit4+RowCount; NodeIds[1] = xinit4+RowCount+1; NodeIds[2] = xinit3+RowCount+1; NodeIds[3] = NodeIds[0] + n; NodeIds[4] = NodeIds[1] + n; NodeIds[5] = NodeIds[2] + n; std::unique_ptr<ShapeBase> PrismPnt02 = make_unique<Prism>(NodeIds, Nodes, currElementId); Elements.push_back(std::move(PrismPnt02)); nElements = Elements.size(); currElementId++; } xinit1 = xinit2; xinit2 = xinit4 + CurrRowNum-1; xinit3 = xinit4; xinit4 = xinit2 + CurrRowNum-2; } } void Simulation::calculateSystemCentre(){ for (size_t i = 0; i< nNodes; ++i){ for (size_t j =0; j<Nodes[i]->nDim; ++j){ SystemCentre[j] += Nodes[i]->Position[j]; } } SystemCentre[0]= SystemCentre[0]/nNodes; SystemCentre[1]= SystemCentre[1]/nNodes; SystemCentre[2]= SystemCentre[2]/nNodes; } void Simulation::addSoftPeriphery(std::vector<double>& fractions){ /** * The elemetns within the range of soft periphery are identified first with their * distance from the nearest circumference node. This calculation will be noisy as the * side length of elements and node positions sill influence the cut-off, but this is * an acceptable noise given the noise in biological systems. \n * The array of booleans states: * [applied ot apical side] [applied to basal side] [applied to columnar tissue] [applied to peripodial tissue] */ double t2 = softDepth*softDepth; double midlineFraction = 0.0; double currSoftnessFraction = softnessFraction; double tissueTypeMultiplier = 1; if (softPeripheryBooleans[0] && softPeripheryBooleans[1]){ midlineFraction = softnessFraction; } else if (softPeripheryBooleans[0] || softPeripheryBooleans[1]){ midlineFraction = 1.0 - (1.0-softnessFraction)*0.5; } for(const auto& itNode : Nodes){ if ( itNode->atCircumference ){ //this node is at circumference, I will calculate the distance of all elements to this node //if an element is close enough, update the fraction matrix set above: for(const auto& itElement : Elements){ bool applyToThisElement = true; if ( itElement->tissuePlacement == 1 && !softPeripheryBooleans[0]){ //element is apical, the softness is NOT applied to apical applyToThisElement = false; } if (itElement->tissuePlacement == 0 && !softPeripheryBooleans[1]){ //element is basal, the softness is NOT applied to apical applyToThisElement = false; } if (itElement->tissueType == 0 && !softPeripheryBooleans[2]){ //element is columnar, the softness is NOT applied to columnar applyToThisElement = false; } if (itElement->tissueType == 1 && !softPeripheryBooleans[3]){ //element is peripodial, the softness is NOT applied to peripodial applyToThisElement = false; } if ( applyToThisElement ){ //scaling the softness fraction if necessary: currSoftnessFraction = softnessFraction; if (itElement->tissuePlacement == 2 ){ //element is on the midline currSoftnessFraction= midlineFraction; } //scaling the tissue type multiplier if necessary (important for linker elements: if (itElement->tissueType == 2 ){ // element is on the linker zone if (softPeripheryBooleans[2] && softPeripheryBooleans[3]){ //softness is applied to both peripodial and columnar zones, the linkers should not be scaling anything tissueTypeMultiplier = 1.0; }else if (softPeripheryBooleans[2] ){ //softness only applied to columnar layer: tissueTypeMultiplier = itElement->getColumnarness(); } else if (softPeripheryBooleans[3] ){ //softness only applied to peripodial layer: tissueTypeMultiplier = itElement->getPeripodialness(); } } else{ //element is not linker tissueTypeMultiplier = 1; } currSoftnessFraction = 1.0 - (1.0-currSoftnessFraction)*tissueTypeMultiplier; std::array<double,3> c = itElement->getCentre(); double dx = c[0]-itNode->Position[0]; double dy = c[1]-itNode->Position[1]; //double dz = c[2]-(*itNode1)->Position[2]; double d = dx*dx + dy*dy; if (d<t2){ d = pow(d,0.5); double f = currSoftnessFraction + (1.0 - currSoftnessFraction)*d/softDepth; if ((softnessFraction< 1.0 && f < fractions[itElement->Id]) ||(softnessFraction> 1.0 && f > fractions[itElement->Id])){ fractions[itElement->Id] = f; } } } } } } } void Simulation::assignPhysicalParameters(){ /** This funcition starts by generating the array of stiffness fractions to allow for perturbation implementation at the same time with the * setting up of all elastic properties. */ std::vector<double> fractions; for (size_t i=0; i<nElements; ++i){ fractions.push_back(1.0); } if(softPeriphery){ /** If there is a soft periphery implemented in the system, this is scaled here by modigying the fractions array via function * Simulation#addSoftPeriphery. */ addSoftPeriphery(fractions); } for(const auto& itElement : Elements){ /** If there is noise on the physical proerties, this is randomly assigned first. */ double r = (rand() % 200) / 100.0; //random number between 0.00 and 2.00 r = r - 1.0; //random number between -1.00 and 1.00 float noise1 = r*noiseOnPysProp[0]; //percent noise on current element r = (rand() % 200) / 100.0; r = r - 1.0; float noise2 = r*noiseOnPysProp[1]; /** The input Young's moduli are scaled for the stiffness scaling of the current element. * The noise is added on at the same step, and the Poission's ratio is set to zero for ECM mimicking elements. * Then the elastic properties of the elemetn are set and necessary tensors updated via ShapeBase#setElasticProperties and * ShapeBase#setViscosity functions. */ if (itElement->tissueType == 0){ //Element is on the columnar layer double currEApical = fractions[itElement->Id] * EApical*(1 + noise1/100.0); double currEBasal = fractions[itElement->Id] * EBasal*(1 + noise1/100.0); double currEMid = fractions[itElement->Id] * EMid*(1 + noise1/100.0); double currEECM = fractions[itElement->Id] * EColumnarECM*(1 + noise1/100.0); double currPoisson = poisson*(1 + noise2/100); if(itElement->isECMMimicing){ //the Poisson ratio is zero so that the ECM layer will not thin! currPoisson = 0; } itElement->setElasticProperties(currEApical,currEBasal,currEMid,currEECM,currPoisson); itElement->setViscosity(discProperApicalViscosity,discProperBasalViscosity,discProperMidlineViscosity); } else if (itElement->tissueType == 1){ //Element is on the peripodial membrane double currEApical = fractions[itElement->Id] * PeripodialElasticity*(1 + noise1/100.0); double currEBasal = currEApical; double currEMid = currEApical; double currEECM = fractions[itElement->Id] * EPeripodialECM*(1 + noise1/100.0); double currPoisson = poisson*(1 + noise2/100); if(itElement->isECMMimicing){ //the Poisson ratio is zero so that the ECM layer will not thin! currPoisson = 0; } itElement->setElasticProperties(currEApical,currEBasal,currEMid,currEECM, currPoisson); itElement->setViscosity(peripodialApicalViscosity,peripodialBasalViscosity,peripodialMidlineViscosity); } else if (itElement->tissueType == 2 ){ //Element is on the linker Zone, //The elastic properties of the linker zone ECM are always based on the //peripodialness factor. double currPeripodialECME = fractions[itElement->Id] * EPeripodialECM*(1 + noise1/100.0); double currColumnarECME = fractions[itElement->Id] * EColumnarECM*(1 + noise1/100.0); double periWeight = itElement->getPeripodialness(); double colWeight = itElement->getColumnarness(); double currEECM = colWeight * currColumnarECME + periWeight * currPeripodialECME; if (BaseLinkerZoneParametersOnPeripodialness){ //I will weight the values: double currPeripodialE = fractions[itElement->Id] * PeripodialElasticity * (1 + noise1/100.0); double currEApical = fractions[itElement->Id] * EApical * (1 + noise1/100.0); double currEBasal = fractions[itElement->Id] * EBasal * (1 + noise1/100.0); double currEMid = fractions[itElement->Id] * EMid * (1 + noise1/100.0); double currPoisson = poisson*(1 + noise2/100); currEApical = colWeight * currEApical + periWeight * currPeripodialE; currEBasal = colWeight * currEBasal + periWeight * currPeripodialE; currEMid = colWeight * currEMid + periWeight * currPeripodialE; itElement->setElasticProperties(currEApical,currEBasal,currEMid,currEECM, currPoisson); double currViscApical = colWeight * discProperApicalViscosity + periWeight * peripodialApicalViscosity; double currViscBasal = colWeight * discProperBasalViscosity + periWeight * peripodialBasalViscosity; itElement->setViscosity(currViscApical,currViscBasal); //There is no midline in the linker zone. } else{ //I have the inputs provided: double currEApical = fractions[itElement->Id] * LinkerZoneApicalElasticity*(1 + noise1/100.0); double currEBasal = fractions[itElement->Id] * LinkerZoneBasalYoungsModulus*(1 + noise1/100.0); double currEMid = fractions[itElement->Id] * 0.5 * (LinkerZoneApicalElasticity+LinkerZoneBasalYoungsModulus)*(1 + noise1/100.0); double currPoisson = poisson*(1 + noise2/100); if(itElement->isECMMimicing){ //the Poisson ratio is zero so that the ECM layer will not thin! currPoisson = 0; } itElement->setElasticProperties(currEApical,currEBasal,currEMid,currEECM, currPoisson); itElement->setViscosity(linkerZoneApicalViscosity,linkerZoneBasalViscosity,linkerZoneMidlineViscosity); } } } /** Once all elemental properties are set, the nodal viscosities are asssigned through their owenr elements. */ for(const auto& itNode : Nodes){ double r = (rand() % 200) / 100.0; r = r - 1.0; float noise3 = r*noiseOnPysProp[1]; noise3 = (1 + noise3/100.0); if (itNode->tissueType == 2 ){ //linker, the viscosity can be averaged, or based on indivudual set of parameters: if (BaseLinkerZoneParametersOnPeripodialness){ //take average of the two: double currExternalViscApical = 0.5*(externalViscosityDPApical + externalViscosityPMApical); double currExternalViscBasal = 0.5*(externalViscosityDPBasal + externalViscosityPMBasal); itNode->setExternalViscosity(currExternalViscApical,currExternalViscBasal, extendExternalViscosityToInnerTissue); } else{ itNode->setExternalViscosity(externalViscosityLZApical*noise3, externalViscosityLZBasal*noise3, extendExternalViscosityToInnerTissue); } } else if (itNode->tissueType == 0){ //disc proper itNode->setExternalViscosity(externalViscosityDPApical*noise3, externalViscosityDPBasal*noise3, extendExternalViscosityToInnerTissue); } else if (itNode->tissueType == 1){ itNode->setExternalViscosity(externalViscosityPMApical*noise3, externalViscosityPMBasal*noise3, extendExternalViscosityToInnerTissue); } } } void Simulation::checkForZeroExternalViscosity(){ /** * Among all nodes, if there is at least one node with external viscosity in a given dimension, then the * viscosity is not zero in that dimension. */ for (const auto& itNode : Nodes){ for (size_t i=0; i<3; ++i){ if (itNode->externalViscosity[i] > 0){ zeroExternalViscosity[i] = false; } } } /** * If after checking all nodes, there is at least one dimension of x, y & z that has zero viscosity, at * least one degree of freedom in that dimension should be fixed to have a unique displacement * solution to the system in the given dimension. In other words, if no node feels external resistanc ein x, then * the forces can fix the relative movement of all nodes in x, but nothing prevents the tissue rigid body displacement * in x, therefore resulting in infinite number of solutions. */ if (zeroExternalViscosity[0] || zeroExternalViscosity[1] || zeroExternalViscosity[2]){ //At least one of the dimensions have zero viscosity if(nNodes < 3) { std::cerr<<"Cannot run zero viscosity simulation with less than 3 nodes, run simulation at your own risk!"<<std::endl; } if (!symmetricY){ bool sufficientXFix = false; bool sufficientYFix = false; bool sufficientZFix = false; for (size_t a=0; a<3; ++a){ //if zeroExternalViscosity[0] is false, it means there is already sufficient x fix //OR, if I spotted sufficientXFix in previous nodes, it persists, //OR, there is circumferential fix on x dimension sufficientXFix = sufficientXFix || !zeroExternalViscosity[0] || CircumferentialNodeFix[a][0]; sufficientYFix = sufficientYFix || !zeroExternalViscosity[1] || CircumferentialNodeFix[a][1]; sufficientZFix = sufficientZFix || !zeroExternalViscosity[2] || CircumferentialNodeFix[a][2]; } //if there are no z fixe on the circumference, check the whole surfaces: if (!sufficientXFix){ sufficientXFix = sufficientXFix || !zeroExternalViscosity[0] || BasalNodeFix[0] ; sufficientXFix = sufficientXFix || !zeroExternalViscosity[0] || ApicalNodeFix[0] ; } if (!sufficientYFix){ sufficientYFix = sufficientYFix || !zeroExternalViscosity[1] || BasalNodeFix[1] ; sufficientYFix = sufficientYFix || !zeroExternalViscosity[1] || ApicalNodeFix[1] ; } if (!sufficientZFix){ sufficientZFix = sufficientZFix || !zeroExternalViscosity[2] || BasalNodeFix[2]; sufficientZFix = sufficientZFix || !zeroExternalViscosity[2] || ApicalNodeFix[2]; } if (!sufficientXFix){ Nodes[ventralTipIndex]->FixedPos[0] = true; } if (!sufficientYFix){ Nodes[ventralTipIndex]->FixedPos[1] = true; } if (!sufficientZFix){ Nodes[ventralTipIndex]->FixedPos[2] = true; } if (!sufficientYFix){ Nodes[dorsalTipIndex]->FixedPos[1] = true; } if (!sufficientZFix){ Nodes[dorsalTipIndex]->FixedPos[2] = true; } if (!sufficientZFix){ //if there is symmetricity, then the mid-line nodes will be fixed in y, and I do not need to fix the third node. // in fact, fixing the position of the third node in z will cause problems. if (dorsalTipIndex != 1 && ventralTipIndex!= 1 ){ Nodes[1]->FixedPos[2] = true; } else if (dorsalTipIndex != 2 && ventralTipIndex!= 2 ){ Nodes[2]->FixedPos[2] = true; } else if (dorsalTipIndex != 3 && ventralTipIndex!= 3 ){ Nodes[3]->FixedPos[2] = true; } } } else{ //There is symmetricity, then there is y fix, if there are any node fixes, on the surfaces in z, then I do not need to do fix z: bool sufficientZFix = false; for (size_t a=0; a<3; ++a){ sufficientZFix = sufficientZFix || !zeroExternalViscosity[2] || CircumferentialNodeFix[a][2]; } //if there are no z fixe on the circumferenece, check the whole surfaces: if (!sufficientZFix){ sufficientZFix = sufficientZFix || !zeroExternalViscosity[2] || BasalNodeFix[2]; sufficientZFix = sufficientZFix || !zeroExternalViscosity[2] || ApicalNodeFix[2]; } bool sufficientXFix = false; for (size_t a=0; a<3; ++a){ sufficientXFix = sufficientXFix || !zeroExternalViscosity[0] || CircumferentialNodeFix[a][0] ; } //if there are no x fixes on the circumferenece, check the whole surfaces: if (!sufficientXFix){ sufficientXFix = sufficientXFix || !zeroExternalViscosity[0] || BasalNodeFix[0] ; sufficientXFix = sufficientXFix || !zeroExternalViscosity[0] || ApicalNodeFix[0] ; } //there is no circumference or surface fixing of suffieint nature, then I should fix the nodes: if (!sufficientXFix){ Nodes[ventralTipIndex]->FixedPos[0] = true; } Nodes[ventralTipIndex]->FixedPos[1] = true; if (!sufficientZFix){ Nodes[ventralTipIndex]->FixedPos[2] = true; Nodes[dorsalTipIndex]->FixedPos[2] = true; } } } } void Simulation::fixNode0InPosition(double x, double y, double z){ double dx = Nodes[0]->Position[0]-x; double dy = Nodes[0]->Position[1]-y; double dz = Nodes[0]->Position[2]-z; for (const auto& itNode : Nodes){ itNode->Position[0] -=dx; itNode->Position[1] -=dy; itNode->Position[2] -=dz; } for(const auto& itElement : Elements){ itElement->updatePositions(Nodes); } } void Simulation::manualPerturbationToInitialSetup(bool deform, bool rotate){ /** * This function allows the developer to add manual perturbations to initial setup. * The simple positonal perturbations are self-explanatory, the function is used * to test the response of any system to impulse perturbations. It also allows for * rigid body rotation adn translations. */ //cout<<" inside manual perturbation, timestep "<<timestep<<std::endl; if(timestep==0){ double scaleX = 2.0; double scaleY = 1.0; double scaleZ = 1.0; double PI = 3.14159265359; double tetX = 0 *PI/180.0; double tetY = 45 *PI/180.0; double tetZ = 0 *PI/180.0; int axisToRotateOn = 1; //0: rotate around x axis, 1: around y-axis, and 2: around z-axis. if(deform){ for (const auto& itNode : Nodes){ itNode->Position[0] *=scaleX; itNode->Position[1] *=scaleY; itNode->Position[2] *=scaleZ; } } if (rotate){ std::cerr<<"Rotating system"<<std::endl; double R[3][3] = {{1,0,0},{0,1,0},{0,0,1}}; if (axisToRotateOn == 0){ double c = cos(tetX); double s = sin(tetX); //Rx = {{1,0,0},{0,c,-s},{0,s,c}}; R[1][1] = c; R[1][2] = -s; R[2][1] = s; R[2][2] = c; } else if(axisToRotateOn == 1){ double c = cos(tetY); double s = sin(tetY); //Ry = {{c,0,s},{0,1,0},{-s,0,c}}; R[0][0] = c; R[0][2] = s; R[2][0] = -s; R[2][2] = c; } else if(axisToRotateOn == 2){ double c = cos(tetZ); double s = sin(tetZ); //Rz = {{c,-s,0},{s,c,0},{0,0,1}}; R[0][0] = c; R[0][1] = -s; R[1][0] = s; R[1][1] = c; } for (const auto& itNode : Nodes){ double x = itNode->Position[0]*R[0][0] + itNode->Position[1]*R[0][1] + itNode->Position[2]*R[0][2]; double y = itNode->Position[0]*R[1][0] + itNode->Position[1]*R[1][1] + itNode->Position[2]*R[1][2]; double z = itNode->Position[0]*R[2][0] + itNode->Position[1]*R[2][1] + itNode->Position[2]*R[2][2]; itNode->Position[0]=x; itNode->Position[1]=y; itNode->Position[2]=z; } } for(const auto& itElement : Elements){ itElement->updatePositions(Nodes); } } } void Simulation::updateGrowthRotationMatrices(){ /** * Growth rotation matrices are updated for each element via ShapeBase#CalculateGrowthRotationByF. */ for(const auto & itElement : Elements){ itElement->CalculateGrowthRotationByF(); } } std::array<double,3> Simulation::calculateNewNodePosForPeripodialNodeAddition(int nodeId0, int nodeId1, int nodeId2, double sideThickness){ std::array<double,3> vec1{0.0}; if (symmetricY && nodeId1 == -100){ vec1[0] = -1.0; } else if (symmetricY && nodeId2 == -100){ vec1[0] = 1.0; } else{ std::array<double,3> vec2{0.0}; for (size_t j=0; j<Nodes[nodeId0]->nDim; j++){ vec1[j] = (Nodes[nodeId0]->Position[j] - Nodes[nodeId1]->Position[j]); vec2[j] = (Nodes[nodeId0]->Position[j] - Nodes[nodeId2]->Position[j]); } (void) Elements[0]->normaliseVector3D(vec1); (void) Elements[0]->normaliseVector3D(vec2); vec1[0] += vec2[0]; vec1[1] += vec2[1]; vec1[2] += vec2[2]; double vec1Mag2 = vec1[0]*vec1[0] + vec1[1]*vec1[1] + vec1[2]*vec1[2]; if (vec1Mag2 < 1E-5){ //the two nodes are linear, the resulting vector is of zero length. //I will rotate one of the vectors 90 degrees and it will be pointing in the correct orientation, the actual direction can be fixed in the below loop: //this vector is already normalised, I am skipping the normalisation step vec1[0] = -1.0*vec2[1]; vec1[1] = vec2[0]; } else{ (void) Elements[0]->normaliseVector3D(vec1); } //now I have the vector to point out from the base node 0. BUT, this will point outwards only if the tissue curvature is convex at all points //I need to check if it actually is pointing out, as the experimentally driven tissues can be concave at points. //the cross produc of vec[2] and the vector to the cell centre should have the opposite sign with the corss product of my orientation vector and vector 2. std::array<double,3> vecCentre{0.0}; vecCentre[0] = SystemCentre[0] - Nodes[nodeId0]->Position[0]; vecCentre[1] = SystemCentre[1] - Nodes[nodeId0]->Position[1]; vecCentre[2] = SystemCentre[2] - Nodes[nodeId0]->Position[2]; (void) Elements[0]->normaliseVector3D(vecCentre); std::array<double,3> cross1 = Elements[0]->crossProduct3D(vec2,vecCentre); (void) Elements[0]->normaliseVector3D(cross1); std::array<double,3> cross2 = Elements[0]->crossProduct3D(vec2,vec1); (void) Elements[0]->normaliseVector3D(cross2); double dotp = Elements[0]->dotProduct3D(cross1,cross2); if (dotp >0 ){ //the vectors are pointing to the same direction! Need to rotate vec1 180 degrees: vec1[0] *= -1.0; vec1[1] *= -1.0; vec1[2] *= -1.0; } } std::array<double,3> pos{0.0}; pos[0] = Nodes[nodeId0]->Position[0] + vec1[0]*sideThickness; pos[1] = Nodes[nodeId0]->Position[1] + vec1[1]*sideThickness; pos[2] = Nodes[nodeId0]->Position[2]; return pos; } std::array<double,3> Simulation::calculateNewNodePosForPeripodialNodeAddition(int nodeId0, int nodeId1, double sideThickness){ std::array<double,3> vec0{0.0}; std::array<double,3> midpoint{0.0}; for (size_t j=0; j<Nodes[nodeId0]->nDim; j++){ vec0[j] = (Nodes[nodeId1]->Position[j] - Nodes[nodeId0]->Position[j])/2.0; midpoint[j] = Nodes[nodeId0]->Position[j] + vec0[j]; } (void) Elements[0]->normaliseVector3D(vec0); //The list is sorted counter-cock-wise, to point out, I will rotate normalised vector v0 -90 degrees on z axis: // (x,y,z) -> (y,-x,z); // then I will add this vector to the calculated mid point to gt the new node's position. std::array<double,3> pos {0.0}; pos[0] = midpoint[0] + vec0[1]*sideThickness; pos[1] = midpoint[1] - vec0[0]*sideThickness; pos[2] = midpoint[2]; return pos; } bool Simulation::checkIfThereIsPeripodialMembrane(){ bool Success = true; for(const auto& itNode : Nodes){ if (itNode->tissueType == 1){ thereIsPeripodialMembrane = true; //I have not added the peripodial membrane as yet, //if there is one, it came from the input mesh //Then I want to set up the circumferencial input properly. setLinkerCircumference(); break; } } return Success; } void Simulation::checkForExperimentalSetupsBeforeIteration(){ if (stretcherAttached){ //moveClampedNodesForStretcher(); } } void Simulation::checkForExperimentalSetupsWithinIteration(){ } void Simulation::checkForExperimentalSetupsAfterIteration(){ } void Simulation::calculateStiffnessChangeRatesForActin(int idOfCurrentStiffnessPerturbation){ /** * If the actin layer has perturbations, the elements are checked if they are influenced via * ShapeBase#isActinStiffnessChangeAppliedToElement and * rates are set in this function via ShapeBase#calculateStiffnessPerturbationRate. */ startedStiffnessPerturbation[idOfCurrentStiffnessPerturbation] = true; //not using range based loops here to ensure openMP comaptibility #pragma omp parallel for for(std::vector<std::unique_ptr<ShapeBase>>::iterator itElement = Elements.begin(); itElement <Elements.end(); ++itElement){ bool applyToThisElement = (*itElement)->isActinStiffnessChangeAppliedToElement(ThereIsWholeTissueStiffnessPerturbation[idOfCurrentStiffnessPerturbation], ThereIsApicalStiffnessPerturbation[idOfCurrentStiffnessPerturbation], ThereIsBasalStiffnessPerturbation[idOfCurrentStiffnessPerturbation], ThereIsBasolateralWithApicalRelaxationStiffnessPerturbation[idOfCurrentStiffnessPerturbation],ThereIsBasolateralStiffnessPerturbation[idOfCurrentStiffnessPerturbation], stiffnessPerturbationEllipseBandIds[idOfCurrentStiffnessPerturbation], numberOfStiffnessPerturbationAppliesEllipseBands[idOfCurrentStiffnessPerturbation]); if (applyToThisElement){ (*itElement)->calculateStiffnessPerturbationRate(ThereIsBasolateralWithApicalRelaxationStiffnessPerturbation[idOfCurrentStiffnessPerturbation], stiffnessPerturbationBeginTimeInSec[idOfCurrentStiffnessPerturbation],stiffnessPerturbationEndTimeInSec[idOfCurrentStiffnessPerturbation], stiffnessChangedToFractionOfOriginal[idOfCurrentStiffnessPerturbation]); } } } void Simulation::updateStiffnessChangeForActin(int idOfCurrentStiffnessPerturbation){ /** * If the actin layer has perturbations, the elements are checked if they are influenced via * ShapeBase#isActinStiffnessChangeAppliedToElement, the ShapeBase#stiffnessMultiplier is altered via * ShapeBase#updateStiffnessMultiplier and elastic property tensors are updated * via ShapeBase#updateElasticProperties. */ //not using range based loops here to ensure openMP comaptibility #pragma omp parallel for for(std::vector<std::unique_ptr<ShapeBase>>::iterator itElement = Elements.begin(); itElement <Elements.end(); ++itElement){ bool applyToThisElement = (*itElement)->isActinStiffnessChangeAppliedToElement(ThereIsWholeTissueStiffnessPerturbation[idOfCurrentStiffnessPerturbation], ThereIsApicalStiffnessPerturbation[idOfCurrentStiffnessPerturbation], ThereIsBasalStiffnessPerturbation[idOfCurrentStiffnessPerturbation], ThereIsBasolateralWithApicalRelaxationStiffnessPerturbation[idOfCurrentStiffnessPerturbation], ThereIsBasolateralStiffnessPerturbation[idOfCurrentStiffnessPerturbation], stiffnessPerturbationEllipseBandIds[idOfCurrentStiffnessPerturbation], numberOfStiffnessPerturbationAppliesEllipseBands[idOfCurrentStiffnessPerturbation]); if (applyToThisElement){ (*itElement)->updateStiffnessMultiplier(dt); (*itElement)->updateElasticProperties(); } } } void Simulation::checkStiffnessPerturbation(){ /** * For all input stiffness perturbaitons, the perturbation activity time is checked from the Simulation#currSimTimeSec * being between the selected Simulation#stiffnessPerturbationBeginTimeInSec and Simulation#stiffnessPerturbationEndTimeInSec. * If this is the first time the perturbation is being called (checked via Simulation#startedStiffnessPerturbation flag) then * the rate is calculated via Simulation#calculateStiffnessChangeRatesForActin. Then stiffnesses are uodated via * Simulation#updateStiffnessChangeForActin. */ int n = stiffnessPerturbationBeginTimeInSec.size(); for (int idOfCurrentStiffnessPerturbation=0; idOfCurrentStiffnessPerturbation<n; ++idOfCurrentStiffnessPerturbation){ if (currSimTimeSec >=stiffnessPerturbationBeginTimeInSec[idOfCurrentStiffnessPerturbation] && currSimTimeSec <stiffnessPerturbationEndTimeInSec[idOfCurrentStiffnessPerturbation]){ if (startedStiffnessPerturbation[idOfCurrentStiffnessPerturbation] == false){ calculateStiffnessChangeRatesForActin(idOfCurrentStiffnessPerturbation); } updateStiffnessChangeForActin(idOfCurrentStiffnessPerturbation); } } } void Simulation::updateChangeForExplicitECM(int idOfCurrentECMPerturbation){ /** * If the ECM has perturbationson elasticity, the elements are checked if they are influenced via * ShapeBase#isECMChangeAppliedToElement, the ShapeBase#stiffnessMultiplier is altered via * ShapeBase#updateStiffnessMultiplier and elastic property tensors are updated * via ShapeBase#updateElasticProperties. */ //not using range based loops here to ensure openMP comaptibility #pragma omp parallel for for(std::vector<std::unique_ptr<ShapeBase>>::iterator itElement = Elements.begin(); itElement <Elements.end(); ++itElement){ bool applyToThisElement = (*itElement)->isECMChangeAppliedToElement(changeApicalECM[idOfCurrentECMPerturbation], changeBasalECM[idOfCurrentECMPerturbation], ECMChangeEllipseBandIds[idOfCurrentECMPerturbation], numberOfECMChangeEllipseBands[idOfCurrentECMPerturbation]); if (applyToThisElement){ (*itElement)->updateStiffnessMultiplier(dt); (*itElement)->updateElasticProperties(); } } } void Simulation::updateChangeForViscosityBasedECMDefinition(int idOfCurrentECMPerturbation){ /** * If the ECM has perturbations on viscosity, the nodes are checked if they are influenced via * Node#tissuePlacement and Simulation#changeBasalECM - Simulation#changeApicalECM boolean arrays, * as well as the marker ellipse Ids. The visocisties of each node are updated via * Node#ECMViscosityChangePerHour and the time step Simulation#dt (in sec). Once new viscosity is * calculated, it is capped to be positive and at most equal to the maximum external viscosity. */ //not using range based loops here to ensure openMP comaptibility #pragma omp parallel for for (std::vector<std::unique_ptr<Node>>::iterator itNode = Nodes.begin(); itNode<Nodes.end(); ++itNode){ if(((*itNode)->tissuePlacement == 0 && changeBasalECM[idOfCurrentECMPerturbation] ) || ((*itNode)->tissuePlacement == 1 && changeApicalECM[idOfCurrentECMPerturbation] )){ if((*itNode)->insideEllipseBand){ for (int ECMReductionRangeCounter =0; ECMReductionRangeCounter<numberOfECMChangeEllipseBands[idOfCurrentECMPerturbation]; ++ECMReductionRangeCounter){ if ((*itNode)->coveringEllipseBandId == ECMChangeEllipseBandIds[idOfCurrentECMPerturbation][ECMReductionRangeCounter]){ for (size_t i =0; i<(*itNode)->nDim; ++i){ double viscosityChange = (*itNode)->ECMViscosityChangePerHour[i]/3600*dt; double newViscosity = (*itNode)->externalViscosity[i] - viscosityChange; //avoiding setting negative viscosity! if (newViscosity>(*itNode)->maximumExternalViscosity[i]){ (*itNode)->externalViscosity[i] =(*itNode)->maximumExternalViscosity[i]; } else if(newViscosity<(*itNode)->minimumExternalViscosity[i]){ (*itNode)->externalViscosity[i] =(*itNode)->minimumExternalViscosity[i]; } else{ (*itNode)->externalViscosity[i] = newViscosity; } } } } } } } } void Simulation::calculateChangeRatesForECM(int idOfCurrentECMPerturbation){ /** * If the ECM has perturbations, the elements are checked if they are influenced via * ShapeBase#isECMChangeAppliedToElement and * rates are set in this function via ShapeBase#calculateStiffnessPerturbationRate. */ changedECM[idOfCurrentECMPerturbation] = true; //this will not be used for emergent ecm perturbations //this is the first time step I am changing the ECM stiffness. //I need to calculate rates first. //If there is explicit ECM, I will calculate the young modulus change via elements. //If there is no explicit ECM, the viscosity reflects the ECM stiffness, and I will change the viscosity on a nodal basis. if( thereIsExplicitECM){ //not using range based loops here to ensure openMP comaptibility #pragma omp parallel for for(std::vector<std::unique_ptr<ShapeBase>>::iterator itElement = Elements.begin(); itElement <Elements.end(); ++itElement){ bool applyToThisElement = (*itElement)->isECMChangeAppliedToElement(changeApicalECM[idOfCurrentECMPerturbation], changeBasalECM[idOfCurrentECMPerturbation], ECMChangeEllipseBandIds[idOfCurrentECMPerturbation], numberOfECMChangeEllipseBands[idOfCurrentECMPerturbation]); if (applyToThisElement){ //the first input is used for checking basolateral stiffenning combined with apical relaxation //the ECM does not have such options. Will give the boolean as false and continue. (*itElement)->calculateStiffnessPerturbationRate(false, ECMChangeBeginTimeInSec[idOfCurrentECMPerturbation],ECMChangeEndTimeInSec[idOfCurrentECMPerturbation], ECMStiffnessChangeFraction[idOfCurrentECMPerturbation]); } } //now I need to check for the viscosity based calculation: //not using range based loops here to ensure openMP comaptibility /** * For each node, the applicability of ECM change is checked via Node#isECMChangeAppliedToNode, and the rate * Node#ECMViscosityChangePerHour per dimension is calculated via the change fraction Simulation#ECMViscosityChangeFraction, the * total time of applied change obtined from Simulation#ECMChangeBeginTimeInSec and Simulation#ECMChangeEndTimeInSec. */ #pragma omp parallel for for (std::vector<std::unique_ptr<Node>>::iterator itNode = Nodes.begin(); itNode<Nodes.end(); ++itNode){ bool applyToThisNode = (*itNode)->isECMChangeAppliedToNode(changeApicalECM[idOfCurrentECMPerturbation], changeBasalECM[idOfCurrentECMPerturbation], ECMChangeEllipseBandIds[idOfCurrentECMPerturbation], numberOfECMChangeEllipseBands[idOfCurrentECMPerturbation]); if(applyToThisNode){ double timeDifferenceInHours = (ECMChangeEndTimeInSec[idOfCurrentECMPerturbation] - ECMChangeBeginTimeInSec[idOfCurrentECMPerturbation])/3600; for (int i=0; i<3; ++i){ (*itNode)->ECMViscosityChangePerHour[i] = (*itNode)->initialExternalViscosity[i]*(1-ECMViscosityChangeFraction[idOfCurrentECMPerturbation])/timeDifferenceInHours; if ((*itNode)->ECMViscosityChangePerHour[i]<0){ (*itNode)->maximumExternalViscosity[i] = (*itNode)->initialExternalViscosity[i]*ECMViscosityChangeFraction[idOfCurrentECMPerturbation]; } else{ (*itNode)->minimumExternalViscosity[i] = (*itNode)->initialExternalViscosity[i]*ECMViscosityChangeFraction[idOfCurrentECMPerturbation]; } } } } } else{ /** * The viscosity based ECM perturbation can be applied for ECM definitions beyond explicit ECM, and this is purely on nodal viscosity basis. */ double timeDifferenceInHours = (ECMChangeEndTimeInSec[idOfCurrentECMPerturbation] - ECMChangeBeginTimeInSec[idOfCurrentECMPerturbation])/3600; //not using range based loops here to ensure openMP comaptibility #pragma omp parallel for for (std::vector<std::unique_ptr<Node>>::iterator itNode = Nodes.begin(); itNode<Nodes.end(); ++itNode){ bool applyToThisNode = (*itNode)->isECMChangeAppliedToNode(changeApicalECM[idOfCurrentECMPerturbation], changeBasalECM[idOfCurrentECMPerturbation], ECMChangeEllipseBandIds[idOfCurrentECMPerturbation], numberOfECMChangeEllipseBands[idOfCurrentECMPerturbation]); if(applyToThisNode){ for (int i=0; i<3; ++i){ (*itNode)->ECMViscosityChangePerHour[i] = (*itNode)->initialExternalViscosity[i]*(1-ECMViscosityChangeFraction[idOfCurrentECMPerturbation])/timeDifferenceInHours; if ((*itNode)->ECMViscosityChangePerHour[i]<0){ (*itNode)->maximumExternalViscosity[i] = (*itNode)->initialExternalViscosity[i]*ECMViscosityChangeFraction[idOfCurrentECMPerturbation]; } else{ (*itNode)->minimumExternalViscosity[i] = (*itNode)->initialExternalViscosity[i]*ECMViscosityChangeFraction[idOfCurrentECMPerturbation]; } } } } } } void Simulation::updateECMRenewalHalflifeMultiplier(int idOfCurrentECMPerturbation){ /** * If there is perturbation on ECM renewal halflife, the type of perturbation emergence is checked, * if the perturbation initiation is emergend based on topology (active at fold grove basal sides), then * the rate is calculated from the total application time. */ if(thereIsExplicitECM){ if (ECMChangeTypeIsEmergent[idOfCurrentECMPerturbation]){ double totalTimeChange = ECMChangeEndTimeInSec[idOfCurrentECMPerturbation] - ECMChangeBeginTimeInSec[idOfCurrentECMPerturbation]; double incrementPerSec = (ECMRenewalHalfLifeTargetFraction[idOfCurrentECMPerturbation] - 1.0) / totalTimeChange; //not using range based loops here to ensure openMP comaptibility #pragma omp parallel for for(std::vector<std::unique_ptr<ShapeBase>>::iterator itElement = Elements.begin(); itElement <Elements.end(); ++itElement){ if ((*itElement)->isECMMimicing){ bool applyToThisElement = (*itElement)->isECMChangeAppliedToElement(changeApicalECM[idOfCurrentECMPerturbation], changeBasalECM[idOfCurrentECMPerturbation], ECMChangeEllipseBandIds[idOfCurrentECMPerturbation], numberOfECMChangeEllipseBands[idOfCurrentECMPerturbation]); if (applyToThisElement){ (*itElement)->plasticDeformationHalfLifeMultiplier += incrementPerSec*dt; if (incrementPerSec<0 && (*itElement)->plasticDeformationHalfLifeMultiplier < ECMRenewalHalfLifeTargetFraction[idOfCurrentECMPerturbation]){ (*itElement)->plasticDeformationHalfLifeMultiplier = ECMRenewalHalfLifeTargetFraction[idOfCurrentECMPerturbation]; } if (incrementPerSec>0 && (*itElement)->plasticDeformationHalfLifeMultiplier > ECMRenewalHalfLifeTargetFraction[idOfCurrentECMPerturbation]){ (*itElement)->plasticDeformationHalfLifeMultiplier = ECMRenewalHalfLifeTargetFraction[idOfCurrentECMPerturbation]; } } } } } else{ if (currSimTimeSec>ECMChangeBeginTimeInSec[idOfCurrentECMPerturbation]){ //perturbation on ECM renewal half life started double currECMRenewaHalfLifeMultiplier = 1.0; if (currSimTimeSec>=ECMChangeEndTimeInSec[idOfCurrentECMPerturbation]){ currECMRenewaHalfLifeMultiplier = ECMRenewalHalfLifeTargetFraction[idOfCurrentECMPerturbation]; } else{ double totalTimeChange = ECMChangeEndTimeInSec[idOfCurrentECMPerturbation] - ECMChangeBeginTimeInSec[idOfCurrentECMPerturbation]; double currTimeChange = currSimTimeSec - ECMChangeBeginTimeInSec[idOfCurrentECMPerturbation]; currECMRenewaHalfLifeMultiplier = 1 + (ECMRenewalHalfLifeTargetFraction[idOfCurrentECMPerturbation] - 1.0) * currTimeChange / totalTimeChange; } //not using range based loops here to ensure openMP comaptibility #pragma omp parallel for for(std::vector<std::unique_ptr<ShapeBase>>::iterator itElement = Elements.begin(); itElement <Elements.end(); ++itElement){ if ((*itElement)->isECMMimicing){ bool applyToThisElement = (*itElement)->isECMChangeAppliedToElement(changeApicalECM[idOfCurrentECMPerturbation], changeBasalECM[idOfCurrentECMPerturbation], ECMChangeEllipseBandIds[idOfCurrentECMPerturbation], numberOfECMChangeEllipseBands[idOfCurrentECMPerturbation]); if (applyToThisElement){ (*itElement)->plasticDeformationHalfLifeMultiplier = currECMRenewaHalfLifeMultiplier; } } } } } } } void Simulation::checkECMChange(){ /** * If there is explicit ECM, then first the compartment based perturbations are checked. * Then each perturbation based on tissue placement, such as apical, basal or emergnt with markers, are checked. * The stiffness, viscosity and half life updates are carried out via ShapeBase#updateStiffnessMultiplier, * ShapeBase#updateChangeForViscosityBasedECMDefinition, ShapeBase#updateChangeForExplicitECM and ShapeBase#updateECMRenewalHalflifeMultiplier. */ if( thereIsExplicitECM){ //not using range based loops here to ensure openMP comaptibility #pragma omp parallel for for(std::vector<std::unique_ptr<ShapeBase>>::iterator itElement = Elements.begin(); itElement <Elements.end(); ++itElement){ bool updateStiffness = false; if( (*itElement)->isECMMimicing && (*itElement)->tissuePlacement == 0 && (*itElement)->tissueType ==0 ){//columnar basal ecmmimicking element //check notum: if (notumECMChangeFraction != 1.0 && (*itElement)->compartmentType == 2){//notum: if (currSimTimeSec>= notumECMChangeInitTime && currSimTimeSec< notumECMChangeEndTime){ double currentFraction = 1.0 + (notumECMChangeFraction-1)*(*itElement)->compartmentIdentityFraction; (*itElement)->calculateStiffnessPerturbationRate(false, notumECMChangeInitTime,notumECMChangeEndTime, currentFraction); updateStiffness=true; } } //check hinge: if (hingeECMChangeFraction != 1.0 && (*itElement)->compartmentType == 1){//hinge: if (currSimTimeSec>= hingeECMChangeInitTime && currSimTimeSec< hingeECMChangeEndTime){ double currentFraction = 1.0 + (hingeECMChangeFraction-1)*(*itElement)->compartmentIdentityFraction; (*itElement)->calculateStiffnessPerturbationRate(false, hingeECMChangeInitTime,hingeECMChangeEndTime, currentFraction); updateStiffness=true; } } //check pouch: if (pouchECMChangeFraction != 1.0 && (*itElement)->compartmentType == 0){//pouch: if (currSimTimeSec>= pouchECMChangeInitTime && currSimTimeSec< pouchECMChangeEndTime){ double currentFraction = 1.0 + (pouchECMChangeFraction-1)*(*itElement)->compartmentIdentityFraction; (*itElement)->calculateStiffnessPerturbationRate(false, pouchECMChangeInitTime,pouchECMChangeEndTime, currentFraction); updateStiffness=true; } } } if (updateStiffness){ (*itElement)->updateStiffnessMultiplier(dt); (*itElement)->updateElasticProperties(); } } } //Now go through ellipses, ellipses overwrite the compartment based definitions int n = ECMChangeBeginTimeInSec.size(); for (int idOfCurrentECMPerturbation=0; idOfCurrentECMPerturbation<n; ++idOfCurrentECMPerturbation){ if (ECMChangeTypeIsEmergent[idOfCurrentECMPerturbation]){ if (currSimTimeSec >=ECMChangeBeginTimeInSec[idOfCurrentECMPerturbation]){ calculateChangeRatesForECM(idOfCurrentECMPerturbation); if( thereIsExplicitECM){ updateECMRenewalHalflifeMultiplier(idOfCurrentECMPerturbation); updateChangeForExplicitECM(idOfCurrentECMPerturbation); } updateChangeForViscosityBasedECMDefinition(idOfCurrentECMPerturbation); } } else{ if (currSimTimeSec >=ECMChangeBeginTimeInSec[idOfCurrentECMPerturbation] && currSimTimeSec <ECMChangeEndTimeInSec[idOfCurrentECMPerturbation]){ if (changedECM[idOfCurrentECMPerturbation] == false){ calculateChangeRatesForECM(idOfCurrentECMPerturbation); } if( thereIsExplicitECM){ updateECMRenewalHalflifeMultiplier(idOfCurrentECMPerturbation); updateChangeForExplicitECM(idOfCurrentECMPerturbation); } updateChangeForViscosityBasedECMDefinition(idOfCurrentECMPerturbation); } } } } void Simulation::checkEllipseAllocationWithCurvingNodes(){ /** * The emergent curved regions of the tissue are marked via ellipse ban ids. * These bands can be defined by the user, as such marker ellipse band Ids 100, 101 and 102 are reserved * for emergent band initiation. \n * - If a surface is on the apical fold initiation surface, then it acquires Id 100. \n * - If a surface is on the basal fold initiation, then is acquires Id 101. \n * - If there are emergent perturbations, and initiation of perturbation is conditional ( * tissue shape change perturbation starts only after the ECM is reduced below a certain fraction of its original value), then * the elements initially tagged 100 are updated to tag 102 once htis threshold (Simulation#shapeChangeECMLimit) is reached. The * function Simulation#checkForEllipseIdUpdateWithECMDegradation * will carry out this operation. */ int selectedEllipseBandId =100; for (const auto& itNode : Nodes){ if (itNode->onFoldInitiation){ if(itNode->coveringEllipseBandId != 100 && itNode->coveringEllipseBandId != 101){ if (itNode->tissuePlacement == 1){ //apical collapse: ECM relaxation, cell shortening, volume redistribution to shrink top selectedEllipseBandId = 100; } else{ //basal collapse, volume redistribution to shrink bottom selectedEllipseBandId = 101; } size_t n = itNode->connectedElementIds.size(); for (size_t i=0; i<n; ++i){ int currElementId = itNode->connectedElementIds[i]; if (Elements[currElementId]->coveringEllipseBandId == 100 || Elements[currElementId]->coveringEllipseBandId == 101 || Elements[currElementId]->isECMMimimcingAtCircumference){ continue; } bool changeEllipseId = Elements[currElementId]->hasEnoughNodesOnCurve(Nodes); if (changeEllipseId){ Elements[currElementId]->coveringEllipseBandId = selectedEllipseBandId; Elements[currElementId]->assignEllipseBandIdToWholeTissueColumn(TissueHeightDiscretisationLayers,Nodes,Elements); } } } } } } void Simulation::checkForLeftOutElementsInEllipseAssignment(){ /** * When elements are assigned emergent marker identities, their nodes will follow. * As a result, in densly folding regions, an element can have all its nodes assigned to a specific marker * by its neighbours, without itself being assigned to it. These elements themselves will be tagged via their nodes. */ for (const auto& itNode : Nodes){ if (itNode->checkOwnersforEllipseAsignment){ int currentEllipseId = itNode->coveringEllipseBandId; int n = itNode->connectedElementIds.size(); for (int i=0; i<n ; ++i){ int currElementId = itNode->connectedElementIds[i]; if (Elements[currElementId]->coveringEllipseBandId ==currentEllipseId ){ continue; } const std::vector<int>& nodeIds = Elements[currElementId]->getNodeIds(); bool hasNodeOutsideEllipse = false; for (auto currNodeId : nodeIds){ if (Nodes[currNodeId]->coveringEllipseBandId != currentEllipseId){ hasNodeOutsideEllipse = true; break; } } if (!hasNodeOutsideEllipse){ //the element does not have any nodes outside the ellipse //should assign to ellipse Elements[currElementId]->coveringEllipseBandId = currentEllipseId; Elements[currElementId]->assignEllipseBandIdToWholeTissueColumn(TissueHeightDiscretisationLayers,Nodes,Elements); } } } } } void Simulation::updateEllipseWithCollapse(){ /** * If there is an apical collapse of nodes, then this elemetn must be on a curving surface, thus the emergent marker ids are updated. * The element is not checked if it is already assigned to a fold via emergent mariking (ShapeBase#coveringEllipseBandId is 100 or 101). * Lateral ECM elements are not modified. If the element is not already assigned to an emergent marker group (on fold initiation), then * its collapse status is checked via ShapeBase#checkForCollapsedNodes. */ for (const auto& itEle : Elements){ if (itEle->coveringEllipseBandId == 100 || itEle->coveringEllipseBandId == 101 || itEle->isECMMimimcingAtCircumference){ continue; } if(itEle->tissuePlacement == 0 || itEle->tissuePlacement == 1 || (itEle->tissuePlacement == 2 && itEle->spansWholeTissue ) ){ itEle->checkForCollapsedNodes(TissueHeightDiscretisationLayers, Nodes, Elements); } } } void Simulation::checkForEllipseIdUpdateWithECMDegradation(){ /** * If there are emergent marker allocations, and initiation of a perturbation is conditional ( * tissue shape change perturbation starts only after the ECM is reduced below a certain fraction of its original value), then * the elements initially tagged 100 are updated to tag 102 once this threshold (Simulation#shapeChangeECMLimit) is reached. */ for (const auto& itEle : Elements){ if (itEle->isECMMimicing && itEle->coveringEllipseBandId == 100){ if (itEle->stiffnessMultiplier<shapeChangeECMLimit){ itEle->coveringEllipseBandId = 102; itEle->assignEllipseBandIdToWholeTissueColumn(TissueHeightDiscretisationLayers,Nodes,Elements); } } } } void Simulation::updateOnFoldNodesFromCollapse(){ /** * When an element collapses its nodes, it is a sign that it is residing on a fold. These elements * assign their nodes to be on folds, by flagging the boolean Node#onFold. */ if (checkedForCollapsedNodesOnFoldingOnce){ return; } //update detection threshold grid: double periAverageSideLength = 0,colAverageSideLength = 0; getAverageSideLength(periAverageSideLength, colAverageSideLength); if (thereIsPeripodialMembrane){ colAverageSideLength = (periAverageSideLength+colAverageSideLength)/2.0; } for (size_t i=0;i<10;++i){ for(size_t j=0;j<5;++j){ packingDetectionThresholdGrid[i][j] = 0.4 * packingDetectionThresholdGrid[i][j]; } } //check collapsed nodes, run this code only on initiation! for (auto& itNode : Nodes){ if ( itNode->collapsedWith.size()>0) { bool checkForFold = true; int collapsedId = itNode->collapsedWith[0]; if (collapsedId == itNode->Id){ if (itNode->collapsedWith.size()>1){ collapsedId = itNode->collapsedWith[1]; } else{ checkForFold=false; } } if (checkForFold){ assignFoldRegionAndReleasePeripodial(itNode.get(), Nodes[collapsedId].get()); } } } checkedForCollapsedNodesOnFoldingOnce = true; } void Simulation::checkForEmergentEllipseFormation(){ /** * The emergent marker ellipse Ids, reserved 100, 101 and 102, are assigned to * curved surfaces of hte tissue. This information can be obtained via * collapse of an elemental surface, or adhesion of two nodes. Once the * identity is assigned, it can be updated to mark ECM relaxation threshold. * The respnsible functions are Simulation#updateEllipseWithCollapse, * Simulation#updateOnFoldNodesFromCollapse, Simulation#checkEllipseAllocationWithCurvingNodes, * Simulation#checkForLeftOutElementsInEllipseAssignment and Simulation#checkForEllipseIdUpdateWithECMDegradation. */ updateEllipseWithCollapse(); updateOnFoldNodesFromCollapse(); checkEllipseAllocationWithCurvingNodes(); checkForLeftOutElementsInEllipseAssignment(); checkForEllipseIdUpdateWithECMDegradation(); } void Simulation::artificialRelax(){ /** * This function relaxes all accumulated forces on elements of the tissue by transfering the current elastic deformation * gradient onto growth gradient. The relaxation can optionally be extended to ECM, or be applied to only * cellular material of the tissue. */ for (const auto& itEle : Elements){ bool relaxElement = false; if (itEle->isECMMimicing){ if( relaxECMInArtificialRelaxation ){ relaxElement = true; } } else if(itEle->tissueType == 0 ){ relaxElement = true; } if (relaxElement){ itEle->relaxElasticForces(); } } } bool Simulation::runOneStep(){ /** * The core function in the Simulation class is the function to update the whole system from one time step to the next. */ bool Success = true; for (size_t i=0; i< nElements; ++i){ if (Elements[i]->tissuePlacement == 1 && Elements[i]->tissueType == 0){ Elements[i]->calculateApicalArea(); } } manualPerturbationToInitialSetup(false,false); //bool deform, bool rotate, optional perturbations at first time step, see the function documentation, /** * The process starts by resetting all forces of the current time step via Simulation#resetForces. Then emergent marker initiation is checked, * (Simulation#checkForEmergentEllipseFormation) as this could initiate physical property changes and should be carried out before the relavent updates. \n */ resetForces(true); // reset the packing forces together with all the rest of the forces here checkForEmergentEllipseFormation(); /** * Then the relative position updates of the tissue are carreid out. First the tissue long axis is aligned on * the x axis (Simulation#alignTissueDVToXPositive), then the bounsing box is calculated (ShapeBase#calculateBoundingBox), * and the relative positions of apical (top layer) elements are obtained (ShapeBase#calculateRelativePosInBoundingBox). The * relative positions of the midline and bottom elements are updated to be the same as the apical layer, as growth should * not differ in the z-axis, the relative positions should read the same grid point from growth maps. */ alignTissueDVToXPositive(); calculateBoundingBox(); calculateDVDistance(); for(const auto& itElement : Elements){ itElement->calculateRelativePosInBoundingBox(boundingBox[0][0],boundingBox[0][1],boundingBoxSize[0],boundingBoxSize[1]); } updateRelativePositionsToApicalPositioning(); /** * Any experimental setup, that requires an update prior to entring the NR iterations for the * time step are carried out by the function Simulation#checkForExperimentalSetupsBeforeIteration. This is folllowed by * any existing perturbation on physical properties, through functions Simulation#checkStiffnessPerturbation and * Simulation#checkECMChange. \n */ checkForExperimentalSetupsBeforeIteration(); if (ThereIsStiffnessPerturbation) { checkStiffnessPerturbation(); } if (thereIsECMChange) { checkECMChange(); } /** * Once the physical proerties are updated, the growth of each element is calculated. For growth functions based on reading * gorwht maps (the main attribute utilised in morphogenesis simulations), the relative position in usecan be updated less * frequently then each step, this update is checked in Simulation#checkForPinningPositionsUpdate. Then the rigid body rotations * around z axis are extracted to be eliminated through ShapeBase#updateGrowthRotationMatrices. For all growth functions and * induced mutant clones the growth is calculated in Simulation#calculateGrowth. Simularly, shape changes are updated via * Simulation#calculateShapeChange. \n */ if(nGrowthFunctions>0 || nShapeChangeFunctions >0 || numberOfClones >0 ){ checkForPinningPositionsUpdate(); updateGrowthRotationMatrices(); if(nGrowthFunctions>0 || numberOfClones > 0){ calculateGrowth(); } if(nShapeChangeFunctions>0){ calculateShapeChange(); } } /** * Based on user preferences, the volumes of the elements can be conserved individually (default), or the volume can be * conserved through the column, but volume exchange is allowed between elements of the same column, this is stated * by the boolean Simulation#conservingColumnVolumes and operation is handled by the function Simulation#conserveColumnVolume. \n */ if (conservingColumnVolumes){ conserveColumnVolume(); } /** * Following potential volume exchange, the remodelling (plastic deformation) is updated. All explicit ECM elements (ShapeBase#isECMMimicing = true) * do have remodelling by default. Remodelling of cellular elements (all the rest) can be defiend by the user preferences * and is defined in Simulation#thereIsPlasticDeformation. The remodelling function is Simulation#updatePlasticDeformation. */ if(thereIsPlasticDeformation || thereIsExplicitECM){ updatePlasticDeformation(); } /** * The growth, shape change, volume exchange and remodelling all induce theri effects eventually through growth of the elements. Once * all these options are covered, the elemetns are grown in ShapeBase#growShapeByFg, which updated the growth deformation gradient of the element. \n */ for(const auto &itElement: Elements){ itElement->growShapeByFg(); } /** * As the shape size is changed, nodal masses (volumes) (Simulation#updateNodeMasses) and * exposed surfaces (Simulation#updateNodeViscositySurfaces) are updated, then the * weight of each elements contribution on the nodes are updated (Simulation#updateElementToConnectedNodes). Then * the collapse nodes positions are updated, if the collapse is being carried out in stages. \n */ updateNodeMasses(); updateNodeViscositySurfaces(); updateElementToConnectedNodes(Nodes); updatePositionsOfNodesCollapsingInStages(); /** * Then packing to all posssible surfaces are detected, while the actual packing forces are calculated in the NR iterations as * they are position dependent. This initial check creates a list of potential packing nodes, to check only these through * the NR itaration, rather than checking all nodes at all times. Packing is checked against self contact (Simulation#detectPacingNodes) * then to enclosing surfaces (Simulation#detectPacingToEnclosingSurfacesNodes) and pipette (Simulation#detectPackingToPipette) * if they are implemented. \n */ detectPacingNodes(); if (encloseTissueBetweenSurfaces){ detectPacingToEnclosingSurfacesNodes(); } if (PipetteSuction){ detectPackingToPipette(); } if (addingRandomForces){ calculateRandomForces(); } /** * Then collapse of elemental surfaces are checked (Simulation#checkEdgeLenghtsForBindingPotentiallyUnstableElementss), * and the NR solver is notified if there are changes made. */ bool thereIsBinding = false; if (thereNodeCollapsing){ thereIsBinding = checkEdgeLenghtsForBindingPotentiallyUnstableElements(); } if (thereIsBinding){ NRSolver->boundNodesWithSlaveMasterDefinition = true; } /** * After the collapse check, the nodal adhesion is updated (Simulation#adhereNodes), makinguse of the detected packing, as any node couple close enough * to adhere must be close enough to activate self-contact. \n */ if (thereIsAdhesion){ thereIsBinding = adhereNodes(); } if (thereIsBinding){ NRSolver->boundNodesWithSlaveMasterDefinition = true; } /** * The actual positional updates are delegated to teh newton-Raphson solver object via function Simulation#updateStepNR. \n */ updateStepNR(); /** * Once the positions are updated, the bounding box is calculated again, the elements are checked agains flipping (Simulation#checkFlip). */ calculateBoundingBox(); //cout<<" step: "<<timestep<<" Pressure: "<<SuctionPressure[2]<<" Pa, maximum z-height: "<<boundingBox[1][2]<<" L/a: "<<(boundingBox[1][2]-50)/(2.0*pipetteRadius)<<std::endl; Success = checkFlip(); /** * If there is aftificail relaxation defined by the user, this is done at the end of the time step via Simulation#artificialRelax. */ if (thereIsArtificaialRelaxation && artificialRelaxationTime == currSimTimeSec){ artificialRelax(); } /** * Then the time step is updated, and the data is saved if necessary in Simulation#processDisplayDataAndSave. */ timestep++; currSimTimeSec += dt; if (Success){ processDisplayDataAndSave(); } return Success; } void Simulation::assignIfElementsAreInsideEllipseBands(){ for(const auto& itElement : Elements){ if ((itElement->tissueType == 0 || itElement->tissueType == 2)){ //The element is either a columnar or a linker element. //Peripodial elements are not counted in the ellipses, as the perturbations of // interest are not applied to them itElement->checkIfInsideEllipseBands(nMarkerEllipseRanges, markerEllipseBandXCentres,markerEllipseBandR1Ranges, markerEllipseBandR2Ranges, Nodes); } } } void Simulation::updateRelativePositionsToApicalPositioning(){ /** * All the elements of a single column are stored in ShapeBase#elementsIdsOnSameColumn vector for each element. * Going through the apical (top layer) elements of the tissue, the relative position of the apical element * is assigned to all the elements on the same column. */ for( const auto& itElement : Elements){ if ( itElement->tissuePlacement == 1 && itElement->tissueType == 0){//apical element of columnar layer std::array<double,2> ReletivePos = itElement->getRelativePosInBoundingBox(); for (size_t i=0; i < TissueHeightDiscretisationLayers-2;++i){ int idOfElementBelowThisApicalElement = itElement->elementsIdsOnSameColumn[i]; Elements[idOfElementBelowThisApicalElement]->setRelativePosInBoundingBox(ReletivePos[0],ReletivePos[1]); } } } } void Simulation::checkForPinningPositionsUpdate(){ if (GridGrowthsPinnedOnInitialMesh){ for (int i=0; i<nGrowthPinning; ++i){ if (currSimTimeSec >= growthPinUpdateTime[i] && !growthPinUpdateBools[i]){ updatePinningPositions(); growthPinUpdateBools[i] = true; } } } } void Simulation::updatePinningPositions(){ for( const auto& itElement : Elements){ itElement->setInitialRelativePosInBoundingBox(); } } bool Simulation::checkFlip(){ for(const auto& itElement : Elements){ if (itElement->isFlipped){ //there is a flipped element: outputFile<<"There is A flipped element: "<<itElement->Id<<std::endl; std::cerr<<"There is A flipped element: "<<itElement->Id<<std::endl; return false; } } return true; } void Simulation::wrapUpAtTheEndOfSimulation(){ alignTissueDVToXPositive(); } void Simulation::clearProjectedAreas(){ for (const auto& currNode : Nodes){ currNode->zProjectedArea = 0.0; } } void Simulation::correctzProjectedAreaForMidNodes(){ for (const auto& currNode : Nodes){ if (currNode->tissuePlacement == 2 ){ // the node is on midlayer /** * For the nodes in mid-line nodes the area is added from apical and basal surfaces of elemetns on both sides. * This is corrected in this function. !! A more efficient approach would be to calculate these areas only once!! */ currNode->zProjectedArea /= 2.0; } } } void Simulation::calculateZProjectedAreas(){ clearProjectedAreas(); for(const auto& itElement : Elements){ itElement->calculateZProjectedAreas(); itElement->assignZProjectedAreas(Nodes); } correctzProjectedAreaForMidNodes(); } void Simulation::updatePlasticDeformation(){ //not using range based loops here to ensure openMP comaptibility #pragma omp parallel for for(std::vector<std::unique_ptr<ShapeBase>>::iterator itElement = Elements.begin(); itElement <Elements.end(); ++itElement){ if (thereIsExplicitECM && (*itElement)->isECMMimicing){ /** * The ezplicitely defined ECM elements are always subject to non-volume econserving plastic deformation. * The remodelling is calculated by ShaopeBase#calculatePlasticDeformation3D. */ (*itElement)->calculatePlasticDeformation3D(false,dt,ECMRenawalHalfLife, 0.1, 10.0); } else if (thereIsPlasticDeformation){ /** * If there is user prefered remodelling on elements other than the ECM then the ShapeBase#tissueType is * chacked agains the parameters Simulation#plasticDeformationAppliedToColumnar and * Simulation#plasticDeformationAppliedToPeripodial. The parameters of the ShapeBase#calculatePlasticDeformation3D * are again defined by the user, such as the Simulation#volumeConservedInPlasticDeformation, Simulation#plasticDeformationHalfLife * Simulation#zRemodellingLowerThreshold and Simulation#zRemodellingUpperThreshold. See function documentation for further details. */ if(( ((*itElement)->tissueType == 0 || (*itElement)->tissueType == 2) && plasticDeformationAppliedToColumnar) || ( ((*itElement)->tissueType == 1 || (*itElement)->tissueType == 2) && plasticDeformationAppliedToPeripodial)) { (*itElement)->calculatePlasticDeformation3D(volumeConservedInPlasticDeformation,dt,plasticDeformationHalfLife, zRemodellingLowerThreshold, zRemodellingUpperThreshold); } } else{ /** * If there is no remodelling, then the elements plastic deformation increment is set to identity in ShapeBase#setPlasticDeformationIncrement. */ (*itElement)->setPlasticDeformationIncrement(1.0,1.0,1.0); } } } void Simulation::conserveColumnVolume(){ //not using range based loops here to ensure openMP comaptibility #pragma omp parallel for for(std::vector<std::unique_ptr<ShapeBase>>::iterator itElement = Elements.begin(); itElement <Elements.end(); ++itElement){ std::vector <int> elementIdsForRedistribution; if ((*itElement)->tissueType == 0 && (*itElement)->tissuePlacement == 1){ for (size_t i=0; i < TissueHeightDiscretisationLayers;++i){ int idOfElementOnSameColumn = (*itElement)->elementsIdsOnSameColumn[i]; if (Elements[idOfElementOnSameColumn]->tissueType != 0){ //must be columnar continue; } if (Elements[idOfElementOnSameColumn]->isECMMimicing){ //exclude ECM continue; } if (Elements[idOfElementOnSameColumn]->isActinMimicing){ //exclude top actin layer if there is one continue; } elementIdsForRedistribution.push_back(idOfElementOnSameColumn); } /** * The column-vise volume conservation requires volume redistribution amongst cell layer of the tissue, * and a diffusion based volume exchange where the most compressed elements give volume to least compressed. */ //now I have a list of elements that I would like to redistribute the volumes of: //get sum of ideal volumes: const int n = elementIdsForRedistribution.size(); double ratioOfCurrentVolumeToIdeal[n]; double sumIdealVolumes = 0; double sumCurrentVolumes = 0; for (int i=0; i < n;++i){ double idealVolume = Elements[elementIdsForRedistribution[i]]->GrownVolume; sumIdealVolumes += idealVolume; //get current volume from average detF: double currentVolume = Elements[elementIdsForRedistribution[i]]->getCurrentVolume(); if (currentVolume < 10E-10){ currentVolume = idealVolume; } ratioOfCurrentVolumeToIdeal[i]= currentVolume/idealVolume; sumCurrentVolumes += currentVolume; if (elementIdsForRedistribution[i] == 7009 || elementIdsForRedistribution[i] == 5207 || elementIdsForRedistribution[i] == 4622 || elementIdsForRedistribution[i] == 2820){ std::cout<<" redistributing element: "<<elementIdsForRedistribution[i]<<" idealVolume: "<<idealVolume<<" currentVolume: "<<currentVolume<<" ratio: "<<ratioOfCurrentVolumeToIdeal[i]<<std::endl; } } double redistributionFactors[n]; for (int i=0; i < n;++i){ //calculate redistribution factors: redistributionFactors[i] = sumIdealVolumes/sumCurrentVolumes *ratioOfCurrentVolumeToIdeal[i]; if (elementIdsForRedistribution[i] == 7009 || elementIdsForRedistribution[i] == 5207 || elementIdsForRedistribution[i] == 4622 || elementIdsForRedistribution[i] == 2820){ std::cout<<" redistributing element: "<<elementIdsForRedistribution[i]<<" redist factor: "<<redistributionFactors[i]<<std::endl; } //calculateGrowth: double uniformGrowthIncrement = pow(redistributionFactors[i],1.0/3.0); gsl_matrix* columnarFgIncrement = gsl_matrix_calloc(3,3); gsl_matrix* peripodialFgIncrement = gsl_matrix_calloc(3,3); gsl_matrix_set_identity(columnarFgIncrement); gsl_matrix_set_identity(peripodialFgIncrement); gsl_matrix_set(columnarFgIncrement,0,0,uniformGrowthIncrement); gsl_matrix_set(columnarFgIncrement,1,1,uniformGrowthIncrement); gsl_matrix_set(columnarFgIncrement,2,2,uniformGrowthIncrement); Elements[elementIdsForRedistribution[i]]->updateGrowthIncrement(columnarFgIncrement,peripodialFgIncrement); gsl_matrix_free(columnarFgIncrement); gsl_matrix_free(peripodialFgIncrement); } } } } void Simulation::updateStepNR(){ int iteratorK = 0; /** * The iteration will be carried out for 20 steps, if upon 20 trials the simulation have not converged, an error will be * generated. The iteration starts by clearing all force, displacement and Jacobian matrices of the NR solver in * NewtonRaphsonSolver#setMatricesToZeroAtTheBeginningOfIteration. Then the vector containing the positions of teh nodes at the * end of the previous time step "n", \f$ \boldsymbol{u_n} \f$ is calculated in NewtonRaphsonSolver#constructUnMatrix. The positions * of the current iteration "k", \f$ \boldsymbol{u_k} \f$ are initiated equal to \f$ \boldsymbol{u_n} \f$ via * NewtonRaphsonSolver#initialteUkMatrix. \n */ int maxIteration =20; bool converged = false; NRSolver->setMatricesToZeroAtTheBeginningOfIteration(); NRSolver->constructUnMatrix(Nodes); NRSolver->initialteUkMatrix(); while (!converged){ /** * While the system has not converged, all the forces are rest at the beginning of each iteration with Simulation#resetForces. * Then the matrices to be cumulated from scratch in each iteration are reset in NewtonRaphsonSolver#setMatricesToZeroInsideIteration(). * The displacement matrix per time step Simulation#dt is calculated for use in external viscous forces in * NewtonRaphsonSolver#calculateDisplacementMatrix. Then all the internal elemental and nodal forces are calculated in NewtonRaphsonSolver#calculateForcesAndJacobianMatrixNR. * The forces are moved from the elements and nodes to the system vectors in NewtonRaphsonSolver#writeForcesTogeAndgvInternal, the elastic and viscous * terms of the elemental Jacobians are mapped and added onto the system Jacobian in NewtonRaphsonSolver#writeImplicitElementalKToJacobian. * The external forces are calculated in NewtonRaphsonSolver#calculateExternalViscousForcesForNR and their derivatives are added to * the system Jacobian in NewtonRaphsonSolver#addImplicitKViscousExternalToJacobian. \n */ std::cout<<"iteration: "<<iteratorK<<std::endl; if (implicitPacking){ resetForces(true); // reset packing forces } else{ resetForces(false); // do not reset packing forces } NRSolver->setMatricesToZeroInsideIteration(); NRSolver->calculateDisplacementMatrix(dt); NRSolver->calculateForcesAndJacobianMatrixNR(Nodes, Elements, dt); //Writing elastic Forces and elastic Ke: NRSolver->writeForcesTogeAndgvInternal(Nodes, Elements, SystemForces); NRSolver->writeImplicitElementalKToJacobian(Elements); NRSolver->calculateExternalViscousForcesForNR(Nodes); NRSolver->addImplicitKViscousExternalToJacobian(Nodes,dt); /** * If the packing forces calculated implicitely (default) they are updated via Simulation#calculatePackingForcesImplicit3D and * the corresponding Jacobian update is carried out with Simulation#calculatePackingJacobian3D. The packing for enclosing surfaces and the pipette * are also carried out here (Simulation#calculatePackingForcesToEnclosingSurfacesImplicit3D, * Simulation#calculatePackingToEnclosingSurfacesJacobian3D, Simulation#calculatePackingToPipetteForcesImplicit3D * and Simulation#calculatePackingToPipetteJacobian3D). */ if (implicitPacking){ calculatePackingForcesImplicit3D(); calculatePackingJacobian3D(NRSolver->K); if (encloseTissueBetweenSurfaces){ calculatePackingForcesToEnclosingSurfacesImplicit3D(); calculatePackingToEnclosingSurfacesJacobian3D(NRSolver->K); } if (PipetteSuction){ calculatePackingToPipetteForcesImplicit3D(); calculatePackingToPipetteJacobian3D(NRSolver->K); } } /** * All the internal forces and the external viscous resistance forces are collated in NewtonRaphsonSolver#gSum * via NewtonRaphsonSolver#calculateSumOfInternalForces. The external forceas from the pipette suction if set up, all packing, * and random forces if assigned are collated in NewtonRaphsonSolver#gExt, and these are added to system forces in * NewtonRaphsonSolver#addExernalForces(). \n */ NRSolver->calculateSumOfInternalForces(); if (PipetteSuction && timestep >= PipetteInitialStep){ calculateZProjectedAreas(); addPipetteForces(NRSolver->gExt); } //packing can come from both encapsulation and tissue-tissue packing. I add the forces irrespective of adhesion. addPackingForces(NRSolver->gExt); if (addingRandomForces){ addRandomForces(NRSolver->gExt); } NRSolver->addExernalForces(); checkForExperimentalSetupsWithinIteration(); /** * Once all forces and their derivatives are collated in system forces and Jacobian, then degrees of freedom fixing is * reflected on these matrices in NewtonRaphsonSolver#calcutateFixedK and NewtonRaphsonSolver#calculateBoundKWithSlavesMasterDoF. */ NRSolver->calcutateFixedK(Nodes); NRSolver->calculateBoundKWithSlavesMasterDoF(); /** Then NewtonRaphsonSolver#solveForDeltaU function arranges the matrices and solves for the incremental displacements via * PARDISO sparse matrix solver. The convergence is checked via the norm of incremental displacements in * NewtonRaphsonSolver#checkConvergenceViaDeltaU, the position of the nodes in the iteration, \f $ \boldsymbol{u_k} \f $ are updated * in NewtonRaphsonSolver#updateUkInIteration. The nodal and elemental positions are updated (Simulation#updateElementPositionsinNR, * Simulation#updateNodePositionsNR) with the new node positions of the iteration. */ NRSolver->solveForDeltaU(); converged = NRSolver->checkConvergenceViaDeltaU(); NRSolver->updateUkInIteration(); updateElementPositionsinNR(NRSolver->uk); updateNodePositionsNR(NRSolver->uk); iteratorK ++; if (!converged && iteratorK > maxIteration){ std::cerr<<"Error: did not converge!!!"<<std::endl; converged = true; } } checkForExperimentalSetupsAfterIteration(); //Now the calculation is converged, I update the node positions with the latest positions uk: updateNodePositionsNR(NRSolver->uk); //Element positions are already up to date. std::cout<<"finished run one step"<<std::endl; if (PipetteSuction){ //find the max z: double zMax = -10000; int idMax = -10; for (const auto& itNode : Nodes){ if (itNode->Position[2] > zMax){ zMax = itNode->Position[2]; idMax = itNode->Id; } } std::cout<<"Pipette suction: "<<SuctionPressure[2]<<" max suction: "<<zMax<<" from node "<<idMax<<std::endl; } } void Simulation::calculateRandomForces(){ randomForces.clear(); randomForces=RandomGenerator::Obj().getNormRV( randomForceMean,randomForceVar, 3*nNodes ); //making the sum of forces zero: double sumRandomForceX = 0.0; double sumRandomForceY = 0.0; double sumRandomForceZ = 0.0; vector<double>::iterator itDouble; for (itDouble =randomForces.begin(); itDouble < randomForces.end(); itDouble = itDouble+3){ sumRandomForceX+= (*itDouble); sumRandomForceY+= (*(itDouble+1)); sumRandomForceZ+= (*(itDouble+2)); } sumRandomForceX /= nNodes; sumRandomForceY /= nNodes; sumRandomForceZ /= nNodes; for (itDouble =randomForces.begin(); itDouble < randomForces.end(); itDouble = itDouble+3){ (*itDouble) -= sumRandomForceX; (*(itDouble+1)) -= sumRandomForceY; (*(itDouble+2)) -= sumRandomForceZ; } } void Simulation::addRandomForces(gsl_matrix* gExt){ for (size_t j=0; j<3*nNodes; ++j){ double F = randomForces[j]; F += gsl_matrix_get(gExt,j,0); gsl_matrix_set(gExt,j,0,F); } } void Simulation::updateNodePositionsNR(gsl_matrix* uk){ /** * The nodal positions vector contains each position of each node in a single vector, and indexing is carried out accordingly. */ int dim = 3; for (size_t i = 0; i<nNodes; ++i){ for (int j=0; j<dim; ++j){ Nodes[i]->Position[j]=gsl_matrix_get(uk,dim*i+j,0); } } } void Simulation::updateElementPositionsinNR(gsl_matrix* uk){ int dim = 3; for(const auto& itElement : Elements){ const vector<int>& nodeIds = itElement->getNodeIds(); size_t nNodes= itElement->getNodeNumber(); for (size_t j=0; j<nNodes; ++j){ double x = gsl_matrix_get(uk,dim*nodeIds[j],0); double y = gsl_matrix_get(uk,dim*nodeIds[j]+1,0); double z = gsl_matrix_get(uk,dim*nodeIds[j]+2,0); itElement->Positions[j][0] = x; itElement->Positions[j][1] = y; itElement->Positions[j][2] = z; } } } void Simulation::calculatePackingForcesToEnclosingSurfacesImplicit3D(){ /** * See the documentation for Simulation#calculatePackingForcesImplicit3D. The methodology is the same, * with rigid wall positions in two z coordinates instead of a second node position. */ size_t nPositive=nodesPackingToPositiveSurface.size(); size_t nNegative=nodesPackingToNegativeSurface.size(); double multiplier = packingMultiplier; double sigmoidSaturation = sigmoidSaturationForPacking; for(size_t i = 0 ; i<nNegative; ++i){ int id0 = nodesPackingToNegativeSurface[i]; double dz = Nodes[id0]->Position[2] - zEnclosementBoundaries[0]; if (initialWeightPackingToNegativeSurface[i]>0){ dz *= -1.0; } double mass = Nodes[id0]->mass; double Fz = multiplier * mass / (1 + exp(sigmoidSaturation / packingToEnclosingSurfacesThreshold * (-1.0*dz))); Fz *= initialWeightPackingToNegativeSurface[i]; PackingForces[id0][2] += Fz; } for(size_t i = 0 ; i<nPositive; ++i){ int id0 = nodesPackingToPositiveSurface[i]; double dz = Nodes[id0]->Position[2] - zEnclosementBoundaries[1]; if (initialWeightPackingToPositiveSurface[i]>0){ dz *= -1.0; } double mass = Nodes[id0]->mass; double Fz = multiplier * mass / (1 + exp(sigmoidSaturation / packingToEnclosingSurfacesThreshold * (-1.0*dz))); Fz *= initialWeightPackingToPositiveSurface[i]; PackingForces[id0][2] += Fz; } } void Simulation::calculatePackingToEnclosingSurfacesJacobian3D(gsl_matrix* K){ /** * See the documentation for Simulation#calculatePackingJacobian3D. The methodology is the same, * with rigid wall positions in two z coordinates instead of a second node position. */ size_t nPositive=nodesPackingToPositiveSurface.size(); size_t nNegative=nodesPackingToNegativeSurface.size(); double sigmoidSaturation = sigmoidSaturationForPacking; double multiplier = packingMultiplier; //not using range based loops here to ensure openMP comaptibility #pragma omp parallel for for(size_t i = 0 ; i<nPositive; ++i){ int id0 = nodesPackingToPositiveSurface[i]; //sigmoid test: double dz = Nodes[id0]->Position[2] - zEnclosementBoundaries[1]; double mass = Nodes[id0]->mass; if (initialWeightPackingToPositiveSurface[i]>0){ dz *= -1.0; } double sigmoidz = 1 / (1 + exp(sigmoidSaturation/ packingToEnclosingSurfacesThreshold * (-1.0 * dz) )); double dFzdz0 = sigmoidz * (1 - sigmoidz) * multiplier * mass * initialWeightPackingToPositiveSurface[i] * (sigmoidSaturation/packingToEnclosingSurfacesThreshold); if (initialWeightPackingToPositiveSurface[i]>0){ dFzdz0 *= -1.0; } //z values: addValueToMatrix(K,3*id0+2,3*id0+2,-dFzdz0); } //not using range based loops here to ensure openMP comaptibility #pragma omp parallel for for(size_t i = 0 ; i<nNegative; ++i){ int id0 = nodesPackingToNegativeSurface[i]; //sigmoid test: double dz = Nodes[id0]->Position[2] - zEnclosementBoundaries[0]; double mass = Nodes[id0]->mass; if (initialWeightPackingToNegativeSurface[i]>0){ dz *= -1.0; } double sigmoidz = 1 / (1 + exp(sigmoidSaturation/ packingToEnclosingSurfacesThreshold * (-1.0 * dz) )); double dFzdz0 = sigmoidz * (1 - sigmoidz) * multiplier * mass * initialWeightPackingToNegativeSurface[i] * (sigmoidSaturation/packingToEnclosingSurfacesThreshold); if (initialWeightPackingToNegativeSurface[i]>0){ dFzdz0 *= -1.0; } //z values: addValueToMatrix(K,3*id0+2,3*id0+2,-dFzdz0); } } bool Simulation::areNodesOnNeighbouingElements(int masterNoeId, int slaveNodeId){ bool neigElements = false; size_t nOwnersMaster = Nodes[masterNoeId]->connectedElementIds.size(); size_t nOwnersSlave = Nodes[slaveNodeId]->connectedElementIds.size(); for (size_t i =0; i<nOwnersMaster; ++i){ int idOwnerMaster = Nodes[masterNoeId]->connectedElementIds[i]; const vector<int>& nodeIdsMasterOwner = Elements[idOwnerMaster]->getNodeIds(); for (size_t j =0; j<nOwnersSlave; ++j){ int idOwnerSlave = Nodes[slaveNodeId]->connectedElementIds[j]; int counter = 0; const vector<int> nodeIdsSlaveOwner = Elements[idOwnerSlave]->getNodeIds(); for (auto currMasterNodeId : nodeIdsMasterOwner ){ for (auto currSlaveNodeId : nodeIdsSlaveOwner){ if (currMasterNodeId == currSlaveNodeId){ counter++; } if (counter>2){ neigElements = true; return neigElements; } } } } } return neigElements; } bool Simulation::isAdhesionAllowed(int masterNodeId, int slaveNodeId){ /** * Two nodes are being attempted to adhere. Certain criteria must be met before operation * can proceed. \n * If any of the nodes is already in the process of being moved due to an adhesion collapse * a new adhesion cannot be formed at this step. */ if(Nodes[slaveNodeId]->positionUpdateOngoing || Nodes[masterNodeId]->positionUpdateOngoing){ return false; } /** * The nodes must be of the same tissue type, peripodial elements cannot bind to columner elements. */ if(Nodes[slaveNodeId]->tissueType != Nodes[masterNodeId]->tissueType){ return false; } /** * The nodes at circumference can only adhere with each other, there are biological resoans with the structure of the matrix for this. */ if( (Nodes[slaveNodeId]->atCircumference && !Nodes[masterNodeId]->atCircumference) ||(!Nodes[slaveNodeId]->atCircumference && Nodes[masterNodeId]->atCircumference) ) { return false; } /** * If the nodes are collapsed on adhesion, then the adhesion can only be one to one, and an alrady adhered node * cannot adhere a another node. The default adhesion id is "-1" indicating no adhesion. */ if(collapseNodesOnAdhesion){ if (Nodes[slaveNodeId]->adheredTo > -1 || Nodes[masterNodeId]->adheredTo > -1) { //std::cout<<"one is already adhered"<<std::endl; return false; } } /** * If this couple have already been adhered, no need to continue the operation. This is done by checking the * slave node id in the list of collapsed nodes for master id (Node#collapsedWith) */ if (binary_search(Nodes[masterNodeId]->collapsedWith.begin(), Nodes[masterNodeId]->collapsedWith.end(),slaveNodeId)){ //the couple is already collapsed: return false; } /** * If this node couple belong to neightbouring elements, do not collapse. */ bool nodeIsOnNeigElement = areNodesOnNeighbouingElements(masterNodeId,slaveNodeId); if (nodeIsOnNeigElement){ return false; } bool collapedNodeIsNeig = false; collapedNodeIsNeig = Nodes[masterNodeId]->isNeigWithMyCollapsedNodes(slaveNodeId,Nodes); if (collapedNodeIsNeig){ //std::cout<<"node are collapsed with neighbours (master)"<<std::endl; return false; } collapedNodeIsNeig = Nodes[slaveNodeId]->isNeigWithMyCollapsedNodes(masterNodeId,Nodes); if (collapedNodeIsNeig){ //std::cout<<"node are collapsed with neighbours (slave)"<<std::endl; return false; } return true; } double Simulation::distanceSqBetweenNodes(int id0, int id1){ double dx = Nodes[id0] ->Position[0] - Nodes[id1] ->Position[0]; double dy = Nodes[id0] ->Position[1] - Nodes[id1] ->Position[1]; double dz = Nodes[id0] ->Position[2] - Nodes[id1] ->Position[2]; double dSq = dx*dx + dy*dy + dz*dz; return dSq; } bool Simulation::checkForElementFlippingUponNodeCollapse(std::vector<int> &newCollapseList, std::array<double,3> avrPos){ /** * If the collapse of two nodes will move the nodes (there is collapse) the owner elemetns are first checked to see if * this movement will cause element flipping. The adhesion is avoided if it will. */ int nCollapsedList = newCollapseList.size(); bool elementWillCollapse = false; for (int nodeIterator=0; nodeIterator<nCollapsedList;++nodeIterator){ int currNodeId = newCollapseList[nodeIterator]; int nElements= Nodes[currNodeId]->connectedElementIds.size(); for (int i=0; i<nElements;++i){ //std::cout<<"checking element : "<< Nodes[currNodeId]->connectedElementIds[i]<<" from node : "<< currNodeId<<std::endl; elementWillCollapse = Elements[Nodes[currNodeId]->connectedElementIds[i]]->isElementFlippedInPotentialNewShape(currNodeId, avrPos[0], avrPos[1], avrPos[2]); if (elementWillCollapse){ std::cout<<" element "<<Nodes[currNodeId]->connectedElementIds[i]<<" will flip if adhered"<<std::endl; return false; } } } return true; } void Simulation::updatePositionsOfNodesCollapsingInStages(){ for(const auto& itNode : Nodes){ if (itNode->positionUpdateOngoing){ std::array<double,3> avrPos = {0.0, 0.0, 0.0}; std::array<bool,3> fix = {false, false, false}; int n = itNode->collapsedWith.size(); for (auto collapsedNodeId : itNode->collapsedWith){ for (size_t j=0; j<3; ++j){ avrPos[j] += Nodes[collapsedNodeId]->Position[j]/n; } } for (auto collapsedNodeId : itNode->collapsedWith){ for (size_t j=0; j<3; ++j){ if(Nodes[collapsedNodeId]->FixedPos[j]){ avrPos[j] = Nodes[collapsedNodeId]->Position[j]; fix[j] = true; } } } itNode->updatePositionTowardsPoint(avrPos,fix); } } } bool Simulation::adhereNodes(){ for(const auto& itNode : Nodes){ itNode->clearDuplicatesFromCollapseList(); } size_t n = pacingNodeCouples0.size(); int dim = 3; bool thereIsBinding = false; vector<bool> adhesionAllowedList; /** * The node couples idedntified as potentially packing to each other Simulation#pacingNodeCouples0 and Simulation#pacingNodeCouples1 * are checked for adhesion. First if the adhesion between the pair is feasible is checked via Simulation#isAdhesionAllowed and recorded in a * vector (adhesionAllowedList). */ for(size_t nodeCoupleIterator = 0 ; nodeCoupleIterator<n; ++nodeCoupleIterator){ bool adhesionAllowed = isAdhesionAllowed(pacingNodeCouples0[nodeCoupleIterator], pacingNodeCouples1[nodeCoupleIterator]); adhesionAllowedList.push_back(adhesionAllowed); } for(size_t nodeCoupleIterator = 0 ; nodeCoupleIterator<n; ++nodeCoupleIterator){ if (!adhesionAllowedList[nodeCoupleIterator]){ continue; } int masterNodeId = pacingNodeCouples0[nodeCoupleIterator]; int slaveNodeId = pacingNodeCouples1[nodeCoupleIterator]; if (collapseNodesOnAdhesion){ /** * If the adhesion collapses nodes, then the adhesion is one-to-one, and should be carried out between the closest couples. */ for (size_t nodeCoupleIteratorFromHereOn = nodeCoupleIterator+1; nodeCoupleIteratorFromHereOn<n; ++nodeCoupleIteratorFromHereOn){ if (masterNodeId == pacingNodeCouples0[nodeCoupleIteratorFromHereOn] || masterNodeId == pacingNodeCouples1[nodeCoupleIteratorFromHereOn] || slaveNodeId == pacingNodeCouples0[nodeCoupleIteratorFromHereOn] || slaveNodeId == pacingNodeCouples1[nodeCoupleIteratorFromHereOn] ){ //one of the node couples occurs somewhere else, is this occurance viable? if (adhesionAllowedList[nodeCoupleIteratorFromHereOn]){ /** * If the adhesion is allowed for this pair, then all the coming pairs are checked to see if there is a pair involving these two * nodes that is closer then this one. */ //yes this adhesion is possible, compare distances: double dSqOriginal = distanceSqBetweenNodes(masterNodeId, slaveNodeId); double dSqNext = distanceSqBetweenNodes(pacingNodeCouples0[nodeCoupleIteratorFromHereOn],pacingNodeCouples1[nodeCoupleIteratorFromHereOn]); if (dSqNext < dSqOriginal){ //the next couple I will reach is closer, adhere them (or another one that may be further down the list and even closer) /** * If a consequent pair I will reach is closer, they should be adhered (or they will also be surpassed by yet another * closer pair). Declare this pari cannot adhere, and continue. */ adhesionAllowedList[nodeCoupleIterator] = false; break; } else{ /** * Alternatively, if a consequent pair is further away, then they should be flagged as not feasible to avoid * re-calculation. The current pair will be adhered and there will be no need to check the following one. \n */ adhesionAllowedList[nodeCoupleIteratorFromHereOn] = false; } } } } if (!adhesionAllowedList[nodeCoupleIterator]){ continue; } } /** * If the current pair is still adhering, then the average position in the middle will be calculated and the nodes will be collapsed. */ if (collapseNodesOnAdhesion){ vector<int> newCollapseList; std::array <double,3> avrPos = {0.0, 0.0, 0.0}; std::array <bool,3> fix = {false, false, false}; Nodes[slaveNodeId]->getNewCollapseListAndAveragePos(newCollapseList, avrPos, fix,Nodes, masterNodeId); Nodes[slaveNodeId]->adheredTo = masterNodeId; Nodes[masterNodeId]->adheredTo = slaveNodeId; if (collapseNodesOnAdhesion){ Nodes[slaveNodeId]->collapseOnNodeInStages(newCollapseList, avrPos, fix, Nodes); } } else{ //Adhering the nodes Nodes[slaveNodeId]->adheredTo = masterNodeId; Nodes[masterNodeId]->adheredTo = slaveNodeId; } /** * The pair will be flagged as adhered in Simulation#pacingNodeCouplesHaveAdhered, and packing forces will not be calculated for them. */ pacingNodeCouplesHaveAdhered[nodeCoupleIterator] = true; /** * If any of the pair have fixed dimensions, this will be reflected on the other. */ for (size_t i =0 ; i<3; ++i){ //if the dimension is fixed in space, fix the other and move on. if (Nodes[masterNodeId]->FixedPos[i]){ Nodes[slaveNodeId]->FixedPos[i]=true; } else if (Nodes[slaveNodeId]->FixedPos[i]){ Nodes[masterNodeId]->FixedPos[i]=true; } if (!Nodes[slaveNodeId]->FixedPos[i]){ int dofmaster = masterNodeId*dim+i; int dofslave = slaveNodeId*dim+i; /** * If the slave is alrady slave to another node (Node#slaveTo is not set to -1, the default non-slave indice), then the master of this processed couple is set to * be the slave of the existing master of the slave, and all three degree of freedoms are bound to each other. */ if (Nodes[slaveNodeId]->slaveTo[i] > -1){ /** * One possiblity is that the potential slave is already a slave to the potential master, then nothing is needed to be done. */ if(Nodes[slaveNodeId]->slaveTo[i] == masterNodeId || Nodes[slaveNodeId]->slaveTo[i] == Nodes[masterNodeId]->slaveTo[i] ){ pacingNodeCouplesHaveAdhered[nodeCoupleIterator] = true; continue; } dofslave = Nodes[slaveNodeId]->slaveTo[i]*dim+i; slaveNodeId = Nodes[slaveNodeId]->slaveTo[i]; } /** * If the potential master node is already a slave to another node, then the potential master is moved to * the original master of the potential master DoF in function NewtonRaphsonSolver#checkMasterUpdate. */ NRSolver->checkMasterUpdate(dofmaster,masterNodeId); /** * In this last check point, if the original couple was flipped such that the potential master vas the slave of the potential slave, * then now both master and slave nodes are equal to the initial potential slave id ( as it has been the master prior to this step). * Then again, nothing needs to be implemented, slave master coupling is already in place. */ if (dofmaster != dofslave){ bool continueAddition = NRSolver->checkIfCombinationExists(dofslave,dofmaster); if (continueAddition){ /** * If the couple is not implemented, then the check for the status of the slave is carried out, if the slave is already master of * other nodes, the coupling is checked and corrected in function NewtonRaphsonSolver#checkIfSlaveIsAlreadyMasterOfOthers. If the * function updates the node couple, then the potential slave was a master, and now is a slave to the potential master. * All slaves of the potential master are moved on to the potential master. \n */ bool madeChange = NRSolver->checkIfSlaveIsAlreadyMasterOfOthers(dofslave,dofmaster); if (madeChange){ for (size_t nodeIt = 0 ; nodeIt<nNodes; ++nodeIt){ if(Nodes[nodeIt]->slaveTo[i]==slaveNodeId){ Nodes[nodeIt]->slaveTo[i]=masterNodeId; } } } vector <int> fixDOF; fixDOF.push_back(dofslave); fixDOF.push_back(dofmaster); NRSolver->slaveMasterList.push_back(fixDOF); Nodes[slaveNodeId]->slaveTo[i] = masterNodeId; Nodes[masterNodeId]->isMaster[i] = true; //std::cout<<" adhereing nodes: "<<masterNodeId<<" "<<slaveNodeId<<" in dof "<<i<<std::endl; thereIsBinding = true; pacingNodeCouplesHaveAdhered[nodeCoupleIterator] = true; } } } } } return thereIsBinding; } void Simulation::calculatePackingForcesImplicit3D(){ /** * This function calculates the packing forces between nodes, inside the Newton-Raphson iteration steps. * The list of nodes that can potentially pack are detected in function , and recorded in Simulation#pacingNodeCouples0 and Simulation#pacingNodeCouples1. * The applied packing force is a function of the distance between nodes, and is calculated * with an inverse logic function: * \f[ f\left( d \right) = \frac{L}{1+ e^{-k\left(d-d_{0}\right)}} \f] * * Here, the amplitude \f$ L \f$ is defined such that the force will scale with the average mass of the two nodes. * The steepness of the curve is the force profile will approach to zero as the distance between nodes approaches * to packing threshold. It is defined the sigmoid saturation term and the packing threshold as detected by the * current average side lengths of mesh elements as below. The sigmoid saturation is set to 5, as this is the approximate * saturation distance of the standard logistic function. * * \f[ -k = \frac{2\:sigmoid\:saturation}{packing\:threshold} \f] * * The distance is shifted with distance \f$ d_{0} \f$ to move the mid point of the function to approximately 60 per cent of * the packing threshold distance. * * \image html packingForce.png * * Then the forces on each node i and j become: * \f[ * \mathbf{F_{i}}\left( d \right) = f\left( d \right)\: \mathbf{e_{i}}\:\:,\:\: F_{j}\left( d \right) = f\left( d \right)\: \mathbf{e_{j}}=-f\left( d \right)\: \mathbf{e_{i}}=-\mathbf{F_{i}} * \f] * * where the distance \f$ d \f$ is \f$ ||\mathbf{x_{i}}-\mathbf{x_{j}} || \f$, and the normal is \f$ \mathbf{e_{i}} = \left( \mathbf{x_{i}}-\mathbf{x_{j}} \right) / ||\mathbf{x_{i}}-\mathbf{x_{j}} || \f$. * * Procedure: */ double zeroThreshold = 1E-3; /** * - Go through all the node couples that are selected to be packing in function */ size_t n = pacingNodeCouples0.size(); for(size_t node_counter = 0 ; node_counter<n; ++node_counter){ if (pacingNodeCouplesHaveAdhered[node_counter]){ continue; } int id0 = pacingNodeCouples0[node_counter]; int id1 = pacingNodeCouples1[node_counter]; double multiplier = packingMultiplier; double sigmoidSaturation = sigmoidSaturationForPacking; double distanceShiftScale = 0.6*packingThreshold; /** * - For each node pair id0 and id1, calculate the distance \f$ d \f$ and the unit normal between them */ double dx = Nodes[id0]->Position[0] - Nodes[id1]->Position[0]; double dy = Nodes[id0]->Position[1] - Nodes[id1]->Position[1]; double dz = Nodes[id0]->Position[2] - Nodes[id1]->Position[2]; double d = pow((dx*dx + dy*dy + dz*dz),0.5); double averageMass = 0.5 *( Nodes[id0]->mass + Nodes[id1]->mass ); double normal[3]= {1.0,0.0,0.0}; /** * - If the distance between the node pair is zero, then set the distance to the zero threshold value set in the function, to avoid division by zero. */ if (d > zeroThreshold){ normal[0] = dx/d; normal[1] = dy/d; normal[2] = dz/d; } else{ d = zeroThreshold; } /** * - Shift the distance by \f$ d_{0} \f$, such that the sigmoid is 0.5 at this distance. * Currently \f$ d_{0} \f$ is set to 60 percent of Simulation#packingThreshold. * A shift of minimum of 50 per cent is necessary, as it will saturate the * sigmoid at distance zero. A higher shift will make the saturation earlier, * keeping a distance between nodes. */ double shifted_d = d - distanceShiftScale; //shift the distance by the selected percentage, /** * - calculate the sigmoid value */ double sigmoid = 1 / (1 + exp(sigmoidSaturation/ packingThreshold * 2.0 * shifted_d)); /** * - Scale with average mass to obtain force per node. There is an additional multiplier that can be used to * scale the force under specific conditions if desired. * - Assign the forces in x, y and z directions with the normal */ double Fmagnitude = multiplier * averageMass * sigmoid; double Fx = Fmagnitude*normal[0]; double Fy = Fmagnitude*normal[1]; double Fz = Fmagnitude*normal[2]; bool printForces = false; if (printForces){ std::cout<<" id0-id1: "<<id0<<"-"<<id1<<" F : "<<Fx<<" "<<Fy<<" "<<Fz<<" d: "<<d<<" packingThreshold: "<<packingThreshold<<" sigmoid: "<<sigmoid; std::cout<<" node0pos: "<<Nodes[id0]->Position[0]<<" "<<Nodes[id0]->Position[1]<<" "<<Nodes[id0]->Position[2]; std::cout<<" node1pos: "<<Nodes[id1]->Position[0]<<" "<<Nodes[id1]->Position[1]<<" "<<Nodes[id1]->Position[2]<<std::endl; } /** * - With the direction of the normal calculation, the algorithm will calculate \f$ \mathbf{F_{0}} \f$. * \f$ \mathbf{F_{1}} \f$ is in the opposite direction. The forces are recorded on the Simulation#PackingForces vector. */ PackingForces[id0][0] += Fx; PackingForces[id0][1] += Fy; PackingForces[id0][2] += Fz; PackingForces[id1][0] -= Fx; PackingForces[id1][1] -= Fy; PackingForces[id1][2] -= Fz; if (std::isnan(Fx)){ std::cout<<" packing force Fx is nan for nodes "<<pacingNodeCouples0[node_counter]<<" - "<<pacingNodeCouples1[node_counter]<<std::endl; } if (std::isnan(Fy)){ std::cout<<" packing force Fy is nan for nodes "<<pacingNodeCouples0[node_counter]<<" - "<<pacingNodeCouples1[node_counter]<<std::endl; } if (std::isnan(Fz)){ std::cout<<" packing force Fz is nan for nodes "<<pacingNodeCouples0[node_counter]<<" - "<<pacingNodeCouples1[node_counter]<<std::endl; } } } void Simulation::calculatePackingJacobian3D(gsl_matrix* K){ /** * This function calculates the derivatives of packing forces between nodes with respect to nodal positions, and fills in hte Jacobian * inside the Newton-Raphson iteration steps. The list of nodes that can potentially * pack are detected in function , and recorded in and recorded in Simulation#pacingNodeCouples0 and Simulation#pacingNodeCouples1.. * The applied packing force is calculated in function Simulation#calculatePackingForcesImplicit3D. * * The derivatives are calculated as * \f[ * \frac{d\mathbf{F_{i}}}{d\mathbf{x_{i}}} = * \frac{f\left( d \right)}{d}\left( \mathbf{I} - \mathbf{e_{i}} \mathbf{e_{i}^{T}}\right) * +\frac{df\left( d \right)}{dd} \mathbf{e_{i}} \mathbf{e_{i}^{T}} * \f] * where distance \f$ d \f$ is \f$ ||\mathbf{x_{i}}-\mathbf{x_{j}} || \f$, * the normal is \f$ \mathbf{e_{i}} = \left( \mathbf{x_{i}}-\mathbf{x_{j}} \right) / ||\mathbf{x_{i}}-\mathbf{x_{j}} || \f$, * and \f$ \mathbf{I} \f$ is the identity matrix. The function \f$ f\left( d \right) \f$, linking the distance between the nodes is an inverse sigmoid function, * detailed in Simulation#calculatePackingForcesImplicit3D. Its derivative is then: * \f[ * \frac{df\left( d \right)}{dd} = * mass\:\frac{-2\:sigmoid\:saturation}{packing\:threshold} f\left( d \right) \left( 1 - f\left( d \right) \right) * \f] * Procedure: */ double zeroThreshold = 1E-3; size_t n = pacingNodeCouples0.size(); /** * - Go through all the node couples that are selected to be packing in function */ for(size_t node_counter = 0 ; node_counter<n; ++node_counter){ if (pacingNodeCouplesHaveAdhered[node_counter]){ continue; } /** * - For each node pair id0 and id1, calculate the distance \f$ d \f$ and the unit normal between them */ int id0 = pacingNodeCouples0[node_counter]; int id1 = pacingNodeCouples1[node_counter]; double multiplier = packingMultiplier; double sigmoidSaturation = sigmoidSaturationForPacking; double distanceShiftScale = 0.6*packingThreshold; double dx = Nodes[id0]->Position[0] - Nodes[id1]->Position[0]; double dy = Nodes[id0]->Position[1] - Nodes[id1]->Position[1]; double dz = Nodes[id0]->Position[2] - Nodes[id1]->Position[2]; double d = pow((dx*dx + dy*dy + dz*dz),0.5); double averageMass = 0.5 *( Nodes[id0]->mass + Nodes[id1]->mass ); /** * - If the distance between the node pair is zero, then set the distance to the zero threshold value set in the function, to avoid division by zero. */ double normal[3]= {1.0,0.0,0.0}; if (d > zeroThreshold){ normal[0] = dx/d; normal[1] = dy/d; normal[2] = dz/d; } else{ d = zeroThreshold; } /** * - Shift the distance by \f$ d_{0} \f$, such that the sigmoid is 0.5 at this distance. * Currently \f$ d_{0} \f$ is set to 60 percent of Simulation#packingThreshold. And calculate the sigmoid function value. */ double shifted_d = d - distanceShiftScale; //shift the distance by the selected percentage, double sigmoid = 1 / (1 + exp(sigmoidSaturation/ packingThreshold * 2.0 * shifted_d)); //F0 = sigmoid * mass //F1 = -sigmoid *mass //dFi / dXi = - dFi / dxj //dFj / dXj = - dFj / dxi /** * - Shift the distance by \f$ d_{0} \f$, such that the sigmoid is 0.5 at this distance. * Currently \f$ d_{0} \f$ is set to 60 percent of Simulation#packingThreshold. And calculate the sigmoid function value. * Calculate the derivative, leave the multiplication by the amplitude (mass) to the last stage. */ double dSdXi = (-sigmoidSaturation/ packingThreshold * 2.0) * sigmoid * (1-sigmoid); gsl_matrix* normalMat = gsl_matrix_calloc(3,1); gsl_matrix_set(normalMat, 0,0,normal[0]); gsl_matrix_set(normalMat, 1,0,normal[1]); gsl_matrix_set(normalMat, 2,0,normal[2]); gsl_matrix* norm_normT = gsl_matrix_calloc(3,3); gsl_blas_dgemm (CblasNoTrans, CblasTrans,1.0, normalMat, normalMat, 0.0, norm_normT); gsl_matrix* dFidXi = gsl_matrix_calloc(3,3); gsl_matrix_set_identity(dFidXi); gsl_matrix_sub(dFidXi,norm_normT); //(I - norm*norm^T) gsl_matrix_scale(dFidXi,sigmoid/d); //sigmoid/d * (I - norm*norm^T) gsl_matrix_scale(norm_normT,dSdXi); // norm*norm^T * dSdXi gsl_matrix_add(dFidXi,norm_normT); // sigmoid/d * (I - norm*norm^T) + norm*norm^T * dSdXi gsl_matrix_scale(dFidXi,multiplier * averageMass); //scale by mass and multiplier when needed //dFidxi = -dFidxj //dFj/dxj = dFidxi = -dFj/dxi bool printForces = false; if (printForces){ std::cout<<" id0-id1: "<<id0<<std::endl; Elements[0]->displayMatrix(dFidXi,"dFidXi"); } //bool printForces = true; /** * - Add the resulting 3 by 3 derivative matrices are added into the Jacobian in the form: * \f[ * - \frac{d\mathbf{F_{0}}}{d\mathbf{x_{0}}} \:\: \rightarrow * * K * \begin{bmatrix} * & \vdots & \vdots & \vdots & \\ \dots & x_{3id0,3id0} & \dots & x_{3id0,3id0+2} & \dots \\ \dots & \vdots & \dots & \vdots & \dots \\ \dots & x_{3id0+2,3id0} & \dots & x_{3id0+2,3id0+2} & \dots \\ & \vdots & \vdots & \vdots & \end{bmatrix}, \f] \f[ \frac{d\mathbf{F_{0}}}{d\mathbf{x_{0}}} \:\: \rightarrow \begin{bmatrix} x_{3id0,3id1} & \dots\\ \dots & x_{3id0+2,3id1+2} \end{bmatrix}, -\frac{d\mathbf{F_{0}}}{d\mathbf{x_{0}}} \:\: \rightarrow \begin{bmatrix} x_{3id1,3id1} & \dots\\ \dots & x_{3id1+2,3id1+2} \end{bmatrix}, \frac{d\mathbf{F_{0}}}{d\mathbf{x_{0}}} \:\: \rightarrow \begin{bmatrix} x_{3id1,3id0} & \dots\\ \dots & x_{3id1+2,3id0+2} \end{bmatrix}. \f] */ for (size_t i=0; i<3; ++i){ for (size_t j=0; j<3; ++j){ double derivativeij = gsl_matrix_get(dFidXi,i,j); addValueToMatrix(K,3*id0+i,3*id0+j,-derivativeij); //dFidxi = -dFidxj addValueToMatrix(K,3*id0+i,3*id1+j,derivativeij); //dFj/dxj = dFidxi addValueToMatrix(K,3*id1+i,3*id1+j,-derivativeij); //dFj/dxi = -dFidxi addValueToMatrix(K,3*id1+i,3*id0+j,derivativeij); } } gsl_matrix_free(normalMat); gsl_matrix_free(dFidXi); gsl_matrix_free(norm_normT); } } void Simulation::addValueToMatrix(gsl_matrix* K, int i, int j , double value){ value += gsl_matrix_get(K,i,j); gsl_matrix_set(K,i,j,value); } void Simulation::processDisplayDataAndSave(){ if (saveData && ( (int) (currSimTimeSec/dt) )% dataSaveInterval == 0){ //timestep % dataSaveInterval == 0){ saveStep(); } } void Simulation::updateNodeMasses(){ for(const auto& itNode : Nodes){ itNode->mass = 0; } for( const auto& itElement : Elements){ itElement->assignVolumesToNodes(Nodes); } } void Simulation::updateNodeViscositySurfaces(){ //not using range based loops here to ensure openMP comaptibility #pragma omp parallel for for(std::vector<std::unique_ptr<ShapeBase>>::iterator itElement = Elements.begin(); itElement <Elements.end(); ++itElement){ (*itElement)->calculateViscositySurfaces(); } //calculated the areas, now assigning them for(const auto& itNode : Nodes){ itNode->viscositySurface = 0; } for( const auto& itElement : Elements){ itElement->assignViscositySurfaceAreaToNodes(Nodes); } } void Simulation:: updateElementToConnectedNodes(const std::vector <std::unique_ptr<Node>>& Nodes){ for(auto& itNode : Nodes){ if (itNode->mass > 0){//an ablated node will have this as zero size_t n = itNode->connectedElementIds.size(); for (size_t i=0; i<n; ++i){ itNode->connectedElementWeights[i] = Elements[itNode->connectedElementIds[i]]->VolumePerNode/itNode->mass; } } } } void Simulation::fillInNodeNeighbourhood(){ for (const auto& itEle : Elements){ itEle->fillNodeNeighbourhood(Nodes); } } void Simulation::setBasalNeighboursForApicalElements(){ /** The basal neighbours are set with ShapeBase#setBasalNeigElementId function. */ //not using range based loops here to ensure openMP comaptibility #pragma omp parallel for for(std::vector<std::unique_ptr<ShapeBase>>::iterator itElement = Elements.begin(); itElement <Elements.end(); ++itElement){ (*itElement)->setBasalNeigElementId(Elements); } } void Simulation::fillInElementColumnLists(){ //not using range based loops here to ensure openMP comaptibility #pragma omp parallel for for(std::vector<std::unique_ptr<ShapeBase>>::iterator itElement = Elements.begin(); itElement <Elements.end(); ++itElement){ if ( (*itElement)->tissueType ==0 ){//Check only the columnar layer elements. if ((*itElement)->tissuePlacement == 0){ //start from the basal element and move up //then you can copy the element numbers to the other elements on the list (*itElement)->constructElementStackList(TissueHeightDiscretisationLayers, Elements); } } } } void Simulation::detectPacingToEnclosingSurfacesNodes(){ /** * The current disctance of packing surfaces are stored in Simulation#zEnclosementBoundaries. The z distance of * nodes to these surfaces are checked against the threshold for packing detection Simulation#packingDetectionToEnclosingSurfacesThreshold. * The actual forces of packing are not calculate4d here, this is for detection of potentially packing nodes. */ packingToEnclosingSurfacesThreshold = 3; //pack to the boundary at 3 microns distance packingDetectionToEnclosingSurfacesThreshold = 1.2 * packingToEnclosingSurfacesThreshold; double t2 = packingDetectionToEnclosingSurfacesThreshold*packingDetectionToEnclosingSurfacesThreshold; //threshold square for rapid calculation nodesPackingToPositiveSurface.clear(); nodesPackingToNegativeSurface.clear(); initialWeightPackingToPositiveSurface.clear(); initialWeightPackingToNegativeSurface.clear(); //calculate the current boundaries: if (currSimTimeSec < initialTimeToEncloseTissueBetweenSurfacesSec){ return; } else if (currSimTimeSec>=finalTimeToEncloseTissueBetweenSurfacesSec){ zEnclosementBoundaries[0] = finalZEnclosementBoundaries[0]; zEnclosementBoundaries[1] = finalZEnclosementBoundaries[1]; } else{ double totalTime = finalTimeToEncloseTissueBetweenSurfacesSec - initialTimeToEncloseTissueBetweenSurfacesSec; double currTimeDiff = currSimTimeSec - initialTimeToEncloseTissueBetweenSurfacesSec; double zNegDifference = finalZEnclosementBoundaries[0] - initialZEnclosementBoundaries[0]; double zPosDifference = finalZEnclosementBoundaries[1] - initialZEnclosementBoundaries[1]; zEnclosementBoundaries[0] = initialZEnclosementBoundaries[0] + currTimeDiff*zNegDifference / totalTime; zEnclosementBoundaries[1] = initialZEnclosementBoundaries[1] + currTimeDiff*zPosDifference / totalTime; } std::cout<<"curr time in sec: "<<currSimTimeSec<<" z enclosement boundaries: "<<zEnclosementBoundaries[0]<<" "<<zEnclosementBoundaries[1]<<" initial boundaries: "<<initialZEnclosementBoundaries[0]<<" "<<initialZEnclosementBoundaries[1]<<" final boundaries: "<<finalZEnclosementBoundaries[0]<<" "<<finalZEnclosementBoundaries[1]<<std::endl; //go over nodes to detect packing: for (const auto& itNode : Nodes){ if (itNode->mass >0){ //node is not ablated bool checkAgainstPositiveSurface = false; bool checkAgainstNegativeSurface = false; if (itNode->atCircumference){ //Node is at the ciscumference, with sufficient rotation, it can pack anywhere //chack against both surfaces. checkAgainstPositiveSurface = true; checkAgainstNegativeSurface = true; } else { //basal node of the columnar layer is checked against the negative surface: if ( itNode->tissuePlacement == 0){ //node is basal //if it is columnar layer, check against negative surface: if( itNode->tissueType ==0 ){ checkAgainstNegativeSurface = true; } else if(itNode->tissueType ==1 ){ //if it is peripodial layer, check against positive surface: checkAgainstPositiveSurface = true; } } //if tissue placement is apical, and the tissue tyoe is columnar, //check against the positive surface: if( itNode->tissuePlacement == 1 && itNode->tissueType ==0 ){ //Node is apical, check against positive border checkAgainstPositiveSurface = true; } } if( checkAgainstNegativeSurface ){ std::array<double,3> pos = itNode->getCurrentPosition(); double dz = pos[2] - zEnclosementBoundaries[0]; double d2 = dz*dz; if (d2<t2){ //node is close enough to pack to surface: nodesPackingToNegativeSurface.push_back(itNode->Id); double d = pow (d2,0.5); initialWeightPackingToNegativeSurface.push_back(dz/d); } } if( checkAgainstPositiveSurface){ std::array<double,3> pos = itNode->getCurrentPosition(); double dz = pos[2] - zEnclosementBoundaries[1]; double d2 = dz*dz; if (d2<t2){ //node is close enough to pack to surface: nodesPackingToPositiveSurface.push_back(itNode->Id); double d = pow (d2,0.5); initialWeightPackingToPositiveSurface.push_back(dz/d); } } } } } void Simulation::assignFoldRegionAndReleasePeripodial(Node* NodeMaster, Node* NodeSlave ){ size_t masterXGridIndex = floor( (NodeMaster->Position[0] - boundingBox[0][0])/boundingBoxSize[0] ); size_t masterYGridIndex = floor( (NodeMaster->Position[1] - boundingBox[0][1])/boundingBoxSize[1] ); /** * If two nodes are adhered they are on an indenting surface and therefore on a fold initiation surface. * The Node#onFoldInitiation booleans are set to true. Then all the nodes falling in between these two nodes * are also declared to be on fold initiation. */ NodeMaster->onFoldInitiation = true; NodeSlave->onFoldInitiation = true; //std::cout<<"assigning to fold initiation, nodes "<<(*itNode)->Id <<" and "<<(*itNodeSlave)->Id<<std::endl; //check for other nodes in the vicinity: //if I am on the apical side, I will check the borders from basal sides //If I am on the basal side, I will chack from apical sides: int masterCorrespondingX = NodeMaster->Position[0]; int slaveCorrespoindingX = NodeSlave->Position[0]; int masterCorrespondingY = NodeMaster->Position[1]; int slaveCorrespoindingY = NodeSlave->Position[1]; for (auto itInt : NodeMaster->immediateNeigs){ if(Nodes[itInt]->tissuePlacement != NodeMaster->tissuePlacement){ int commonOwnerId = NodeMaster->getCommonOwnerId(Nodes[itInt].get()); if (commonOwnerId > -1){ //there is common owner bool nodesConnected = Elements[commonOwnerId]->areNodesDirectlyConnected(NodeMaster->Id, Nodes[itInt]->Id); if (nodesConnected){ masterCorrespondingX = Nodes[itInt]->Position[0]; masterCorrespondingY = Nodes[itInt]->Position[1]; break; } } } } for (auto itInt : NodeSlave->immediateNeigs){ if(Nodes[itInt]->tissuePlacement != NodeSlave->tissuePlacement){ int commonOwnerId = NodeSlave->getCommonOwnerId(Nodes[itInt].get()); if (commonOwnerId > -1){ bool nodesConnected = Elements[commonOwnerId]->areNodesDirectlyConnected(NodeSlave->Id, Nodes[itInt]->Id); if (nodesConnected){ slaveCorrespoindingX = Nodes[itInt]->Position[0]; slaveCorrespoindingY = Nodes[itInt]->Position[1]; break; } } } } double xmin = min(masterCorrespondingX, slaveCorrespoindingX); double xmax = max(masterCorrespondingX, slaveCorrespoindingX); double ymin = min(masterCorrespondingY, slaveCorrespoindingY); double ymax = max(masterCorrespondingY, slaveCorrespoindingY); double zmax = max(NodeMaster->Position[2], NodeSlave->Position[2]); double zmin = min(NodeMaster->Position[2], NodeSlave->Position[2]); ymin -= 4.0*packingDetectionThresholdGrid[masterXGridIndex][masterYGridIndex]; ymax += 4.0*packingDetectionThresholdGrid[masterXGridIndex][masterYGridIndex]; for (auto& itNodeInBetween : Nodes){ if(itNodeInBetween->tissuePlacement == NodeMaster->tissuePlacement ){ if(!itNodeInBetween->onFoldInitiation ){ //for apical curves, chack for zmax, for basal , check for z min if( (itNodeInBetween->tissuePlacement == 1 && itNodeInBetween->Position[2] <= zmax ) ||(itNodeInBetween->tissuePlacement == 0 && itNodeInBetween->Position[2] >= zmin ) ){ if(itNodeInBetween->Position[0] >= xmin && itNodeInBetween->Position[0] <= xmax){ if(itNodeInBetween->Position[1] >= ymin && itNodeInBetween->Position[1] <= ymax){ itNodeInBetween->onFoldInitiation = true; } } } }} } } void Simulation::detectPacingNodes(){ /** * The current distance of node-node packing is dependent on the local average side length and * is sored in a 10x5 grid Simulation#packingDetectionThresholdGrid. */ double periAverageSideLength = 0,colAverageSideLength = 0; getAverageSideLength(periAverageSideLength, colAverageSideLength); if (thereIsPeripodialMembrane){ colAverageSideLength = (periAverageSideLength+colAverageSideLength)/2.0; } double packingDetectionThresholdGridSq[10][5]; for (size_t i=0;i<10;++i){ for(size_t j=0;j<5;++j){ packingDetectionThresholdGrid[i][j] = 0.4 * packingDetectionThresholdGrid[i][j]; packingDetectionThresholdGridSq[i][j] = packingDetectionThresholdGrid[i][j]*packingDetectionThresholdGrid[i][j]; } } packingThreshold = 0.4*colAverageSideLength; //0.6 was old value packingDetectionThreshold = 1.2 * packingThreshold; //0.9 * packingThreshold; packingMultiplier = 5000; //1000 in original, increasing 5 fold to test run54 on 16 april 2018 sigmoidSaturationForPacking = 5; double t2 = packingDetectionThreshold*packingDetectionThreshold; //threshold square for rapid calculation pacingNodeCouples0.clear(); pacingNodeCouples1.clear(); pacingNodeCouplesHaveAdhered.clear(); //not using range based loops here to ensure openMP comaptibility #pragma omp parallel for for(std::vector<std::unique_ptr<ShapeBase>>::iterator itElement = Elements.begin(); itElement <Elements.end(); ++itElement){ if ((*itElement)->tissueType == 0 && ((*itElement)->tissuePlacement == 1 || (*itElement)->spansWholeTissue)){ //columnar element at the apical surface or spans whole tissue (*itElement)->calculateApicalNormalCurrentShape(); } } for (auto itNode=Nodes.begin(); itNode<Nodes.end(); ++itNode){ bool NodeHasPacking = (*itNode)->checkIfNodeHasPacking(); if (NodeHasPacking){ std::array<double,3> pos = (*itNode)->getCurrentPosition(); int masterXGridIndex = floor( (pos[0] - boundingBox[0][0])/boundingBoxSize[0] ); int masterYGridIndex = floor( (pos[1] - boundingBox[0][1])/boundingBoxSize[1] ); t2 = packingDetectionThresholdGridSq[masterXGridIndex][masterYGridIndex]; for (auto itNodeSlave=itNode+1; itNodeSlave<Nodes.end(); ++itNodeSlave){ bool SlaveNodeHasPacking = (*itNodeSlave)->checkIfNodeHasPacking(); if (SlaveNodeHasPacking){ if ((*itNode)->tissuePlacement == (*itNodeSlave)->tissuePlacement){ //nodes can pack, are they connected? bool neigbours = (*itNode)->isMyNeig((*itNodeSlave)->Id); if (neigbours){ continue; } //check if the master node is in the collapsed list? //the vector is sorted, as I sort it to remove duplicates if (binary_search((*itNode)->collapsedWith.begin(), (*itNode)->collapsedWith.end(),(*itNodeSlave)->Id)){ //the couple is already collapsed: continue; } //check if the collapsed nodes of master are neigs of slave neigbours = (*itNode)->isNeigWithMyCollapsedNodes((*itNodeSlave)->Id,Nodes); if (neigbours){ continue; } neigbours = (*itNodeSlave)->isNeigWithMyCollapsedNodes((*itNode)->Id,Nodes); if (neigbours){ continue; } //the nodes can potentially pack, are they close enough? std::array<double,3> posSlave = (*itNodeSlave)->getCurrentPosition(); double dx = pos[0] - posSlave[0]; double dy = pos[1] - posSlave[1]; double dz = pos[2] - posSlave[2]; double d2 = dx*dx + dy*dy + dz*dz; if (d2<t2){ //close enough for packing , add to list: pacingNodeCouples0.push_back((*itNode)->Id); pacingNodeCouples1.push_back((*itNodeSlave)->Id); pacingNodeCouplesHaveAdhered.push_back(false); } bool checkForCurvedRegions = false; double curveIdentificationThresholdSq = packingDetectionThresholdGrid[masterXGridIndex][masterYGridIndex]; curveIdentificationThresholdSq *= curveIdentificationThresholdSq; curveIdentificationThresholdSq *=9;//0.625; if (d2<curveIdentificationThresholdSq){ if (thereIsEmergentEllipseMarking && (!(*itNode)->onFoldInitiation || !(*itNodeSlave)->onFoldInitiation) ){ //only check if the nodes are not covered by emergent ellipse bands checkForCurvedRegions=true; } } if (checkForCurvedRegions){ //std::cout<<" check for curved regions active"<<std::endl; int elementIdMaster = (*itNode)->connectedElementIds[0]; int elementIdSlave = (*itNodeSlave)->connectedElementIds[0]; double dotP = Elements[elementIdSlave]->dotProduct3D(Elements[elementIdMaster]->apicalNormalCurrentShape,Elements[elementIdSlave]->apicalNormalCurrentShape); //std::cout<<"dotp: "<<dotP<<std::endl; if (dotP <0){ //normals point opposite directions //do they face each other? bool releaseNodes = false; std::array<double,3> connectingVec = {0.0}; for (int dimIter=0; dimIter<3; ++dimIter){ connectingVec[dimIter] = (*itNode)->Position[dimIter] - (*itNodeSlave)->Position[dimIter]; } double dotPmaster = Elements[elementIdMaster]->dotProduct3D(connectingVec,Elements[elementIdMaster]->apicalNormalCurrentShape); if (dotPmaster >0 ){ releaseNodes = true; } else{ double dotPslave = Elements[elementIdSlave]->dotProduct3D(connectingVec,Elements[elementIdSlave]->apicalNormalCurrentShape); if (dotPslave>0){ releaseNodes = true; } } if (!releaseNodes){ continue; } assignFoldRegionAndReleasePeripodial((*itNode).get(),(*itNodeSlave).get()); } } } } } } } } void Simulation::addPackingForces(gsl_matrix* gExt){ /** * The packing forces calculated in Simulation#calculatePackingForcesImplicit3D are added to the * system force vector. The vector containd all dimensions of all nodes in one column, therefore indexing is carried out * accordingly. */ for (size_t j=0; j<nNodes; ++j){ double Fx = PackingForces[j][0]; double Fy = PackingForces[j][1]; double Fz = PackingForces[j][2]; int indice = j*3; Fx += gsl_matrix_get(gExt,indice,0); gsl_matrix_set(gExt,indice,0,Fx); Fy += gsl_matrix_get(gExt,indice+1,0); gsl_matrix_set(gExt,indice+1,0,Fy); Fz += gsl_matrix_get(gExt,indice+2,0); gsl_matrix_set(gExt,indice+2,0,Fz); } } void Simulation::updateElementPositions(){ for(const auto& itElement : Elements){ itElement->updatePositions(Nodes); } } void Simulation::updateElementPositionsSingle(size_t i ){ Elements[i]->updatePositions(Nodes); } void Simulation::assignTips(){ double xTips[2] ={ 10000, -10000}; double yTips[2] ={ 10000, -10000}; for (size_t i =0; i<nNodes; ++i){ if (Nodes[i]->tissuePlacement == 0 && Nodes[i]->tissueType == 0 ) { //taking the basal nodes of the columnar layer only if (Nodes[i]->Position[0] < xTips[0] ){ dorsalTipIndex = i; xTips[0] = Nodes[i]->Position[0]; } if (Nodes[i]->Position[1] < yTips[0] ){ anteriorTipIndex = i; yTips[0] = Nodes[i]->Position[1]; } if (Nodes[i]->Position[0] > xTips[1] ){ ventralTipIndex = i; xTips[1] = Nodes[i]->Position[0]; } if (Nodes[i]->Position[1] > yTips[1] ){ posteriorTipIndex = i; yTips[1] = Nodes[i]->Position[1]; } } } //I have identified the tips assuming the tissue is represented in full. //If there is symmetry in the input, then I will need to correct this. //In the case of x symmetry, the minimum x will be correct in DV, but not the maximum x. //In the case of y symmetry, the maximum y will be correct in AP. but not the minimum. if (symmetricX){ double delta = 0.02; //the ventralTipIndex is correct, it is at the minimum of x axis. The dorsalTipIndex is at x=0. but there are a series of nodes at x=0, //and the selected one should be at y=0 too. for (size_t i =0; i<nNodes; ++i){ if (Nodes[i]->tissuePlacement == 0 && Nodes[i]->tissueType == 0 ) { //taking the basal nodes of the columnar layer only if (Nodes[i]->Position[0]< delta && Nodes[i]->Position[0]> -delta){ //this node is at x = 0, is it at y = 0 too? if (Nodes[i]->Position[1]< delta && Nodes[i]->Position[1]> -delta){ dorsalTipIndex = i; break; } } } } } if (symmetricY){ double delta = 0.02; //the posteriorTipIndex is correct, it is at the maximum of y axis. The anteriorTipIndex is at y=0. but there are a series of nodes at y=0, //and the selected one should be at x=0 too. for (size_t i =0; i<nNodes; ++i){ if (Nodes[i]->tissuePlacement == 0 && Nodes[i]->tissueType == 0 ) { //taking the basal nodes of the columnar layer only if (Nodes[i]->Position[1]< delta && Nodes[i]->Position[1]> -delta){ //this node is at x = 0, is it at y = 0 too? if (Nodes[i]->Position[0]< delta && Nodes[i]->Position[0]> -delta){ anteriorTipIndex = i; break; } } } } } std::cout<<"Tip node indexes - dorsalTipIndex: "<<dorsalTipIndex<<" ventralTipIndex: "<<ventralTipIndex<<std::endl; std::cout<<"Tip node indexes - anteriorTipIndex: "<<anteriorTipIndex<<" posteriorTipIndex: "<<posteriorTipIndex<<std::endl; } void Simulation::alignTissueDVToXPositive(){ /** * The bounding box calculateion is relies on the fact that the tissue is lying parallel to the x axis in its initial long axis. * Bring the long axis defined by Simulation#ventralTipIndex and Simulation#dorsalTipIndex Node#Ids parallel to the x axis with a rigid * body rotation. */ if (!symmetricX){ std::array<double,3> u = {0.0, 0.0, 0.0}; //For simulations with no external viscosity, the position of Dorsal tip is fixed, Ventral tip is fixed in y and z, another node is fixed in z for (size_t i=0;i<3;++i){ u[i] = Nodes[ventralTipIndex]->Position[i] - Nodes[dorsalTipIndex]->Position[i]; } (void) Elements[0]->normaliseVector3D(u); std::array<double,3> v = {1.0, 0.0, 0.0}; double c, s; Elements[0]->calculateRotationAngleSinCos(u,v,c,s); std::array<double,3> rotAx = {0.0, 0.0, 1.0}; std::array<double,9> rotMat = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; Elements[0]->calculateRotationAxis(u,v,rotAx,c); //calculating the rotation axis that is perpendicular to both u and v Elements[0]->constructRotationMatrix(c,s,rotAx,rotMat); for(size_t i=1;i<nNodes;++i){ for(size_t j = 0; j< Nodes[i]->nDim; ++j){ u[j] = Nodes[i]->Position[j] - Nodes[0]->Position[j]; } Elements[0]->rotateVectorByRotationMatrix(u,rotMat); for(size_t j = 0; j< Nodes[i]->nDim; ++j){ Nodes[i]->Position[j] = u[j] + Nodes[0]->Position[j]; } } for(auto &currElement : Elements){ currElement->updatePositions(Nodes); } } } void Simulation::calculateDVDistance(){ double d[3]; if (symmetricX){ for (int i=0;i<3;++i){ d[i] = Nodes[ventralTipIndex]->Position[i]; d[i] *=d[i]; } } else{ for (int i=0;i<3;++i){ d[i] = Nodes[dorsalTipIndex]->Position[i] - Nodes[ventralTipIndex]->Position[i]; d[i] *=d[i]; } } double dmag = d[0]+d[1]+d[2]; dmag = pow(dmag,0.5); outputFile<<"time: "<<currSimTimeSec<<" DV distance is: "<<dmag<<" "; std::cout<<"time: "<<currSimTimeSec<<" DV distance is: "<<dmag<<" "; if (symmetricY){ for (int i=0;i<3;++i){ d[i] = Nodes[posteriorTipIndex]->Position[i]; d[i] *=d[i]; } } else{ for (int i=0;i<3;++i){ d[i] = Nodes[anteriorTipIndex]->Position[i] - Nodes[posteriorTipIndex]->Position[i]; d[i] *=d[i]; } } dmag = d[0]+d[1]+d[2]; dmag = pow(dmag,0.5); outputFile<<" AP distance is: "<<dmag<<std::endl; std::cout<<" AP distance is: "<<dmag<<std::endl; } void Simulation::resetForces(bool resetPacking){ for (auto& currNodeForces : SystemForces){ //3 dimensions currNodeForces.fill(0.0); } if (resetPacking){ for (auto& currNodePackingForces : PackingForces){ currNodePackingForces.fill(0.0); } } } void Simulation::calculateApicalSize(){ double sizeLim[2][2] = {{0.0,0.0},{0.0,0.0}}; bool found[2][2] = {{false,false},{false,false}}; for (const auto& itNode : Nodes){ if (itNode->tissueType == 0 && itNode->tissuePlacement == 1){ //checking only columnar apical layer nodes for (int i=0; i<2; ++i){ if ( itNode->Position[i] < sizeLim[0][i] ){ sizeLim[0][i] = itNode->Position[i]; found[0][i] = true; } else if(itNode->Position[i]>sizeLim[1][i]){ sizeLim[1][i] = itNode->Position[i]; found[1][i] = true; } } } } if (!found[0][0] && !found[0][1] && !found[1][0] && !found[1][1]){ std::cerr<<" error in apical bounding box calculation! Found? :"<<found[0][0]<<" "<<found[0][1]<<" "<<found[1][0]<<" "<<found[1][1]<<std::endl; } double DV = sizeLim[1][0] - sizeLim[0][0]; double AP = sizeLim[1][1] - sizeLim[0][1]; outputFile<<"At time: "<<currSimTimeSec<<" apical bounding box size: "<<DV<<" "<<AP<<std::endl; } void Simulation::calculateBoundingBox(){ boundingBox[0][0] = 100000.0; //lower left x boundingBox[0][1] = 100000.0; //lower left y boundingBox[0][2] = 100000.0; //lower z boundingBox[1][0] = -100000.0; //upper right x boundingBox[1][1] = -100000.0; //upper right y boundingBox[1][2] = -100000.0; //upper z bool found[2][3] = {{false,false,false},{false,false,false}}; for (const auto& itNode : Nodes){ //Do not count node if it is part of an explicit ECM: if(!itNode->allOwnersECMMimicing){ for (size_t i=0; i<itNode->nDim; ++i){ if ( itNode->Position[i] < boundingBox[0][i] ){ boundingBox[0][i] = itNode->Position[i]; found[0][i] = true; } else if(itNode->Position[i]>boundingBox[1][i]){ boundingBox[1][i] = itNode->Position[i]; found[1][i] = true; } } } } if (symmetricY){ boundingBox[0][1] = (-1.0)*boundingBox[1][1]; //if there is Y symmetricity, then the bounding box is extended to double the size in y } for (int i=0; i<3; ++i){ boundingBoxSize[i] = boundingBox[1][i] - boundingBox[0][i]; } if (!found[0][0] && !found[0][1] && !found[0][2] && !found[1][0] && !found[1][1] && !found[1][2]){ std::cerr<<" error in bounding box calculation! Found? :"<<found[0][0]<<" "<<found[0][1]<<" "<<found[0][2]<<" "<<found[1][0]<<" "<<found[1][1]<<" "<<found[1][2]<<std::endl; } } void Simulation::saveStep(){ outputFile<<"Saving step: "<< timestep<<" this is :"<<currSimTimeSec<<" sec ("<<currSimTimeSec/3600<<" hr )"<<std::endl; writeSaveFileStepHeader(); writeNodes(); writeElements(); writeSaveFileStepFooter(); writeTensionCompression(); writeGrowth(); writePhysicalProp(); writeGrowthRedistribution(); writeNodeBinding(); } void Simulation::writeSaveFileStepHeader(){ saveFileMesh<<"=============== TIME: "; saveFileMesh.precision(6); saveFileMesh.width(10); saveFileMesh<<currSimTimeSec; saveFileMesh<<"==================================================="<<std::endl; } void Simulation::writeSaveFileStepFooter(){ saveFileMesh<<"=============== END OF TIME: "; saveFileMesh.precision(6); saveFileMesh.width(10); saveFileMesh<<currSimTimeSec; saveFileMesh<<"============================================"<<std::endl; } void Simulation::writeNodes(){ saveFileMesh<<nNodes<<std::endl; for (size_t i = 0; i<nNodes; ++i){ if(Nodes[i]->nDim==2){ saveFileMesh.precision(10);saveFileMesh.width(20); saveFileMesh<<Nodes[i]->Position[0]; saveFileMesh.precision(10);saveFileMesh.width(20); saveFileMesh<<Nodes[i]->Position[1]; saveFileMesh.precision(10);saveFileMesh.width(20); saveFileMesh<<0.0; } else{ int ndim = Nodes[i]->nDim; for (int j=0;j<ndim;++j){ saveFileMesh.precision(10);saveFileMesh.width(20); saveFileMesh<<Nodes[i]->Position[j]; } } saveFileMesh.width(4); saveFileMesh<<Nodes[i]->tissuePlacement; saveFileMesh.width(4); saveFileMesh<<Nodes[i]->tissueType; saveFileMesh.width(4); saveFileMesh<<Nodes[i]->atCircumference; saveFileMesh<<std::endl; } } void Simulation::writeElements(){ saveFileMesh<<nElements<<std::endl; for (size_t i = 0; i<nElements; ++i){ int shapetype = Elements[i]->getShapeType(); saveFileMesh.width(4); saveFileMesh<<shapetype; if(shapetype == 4 ){ double height = Elements[i]->getElementHeight(); saveFileMesh.precision(5);saveFileMesh.width(12); saveFileMesh<<height; } saveFileMesh.width(4); saveFileMesh<<Elements[i]->IsAblated; size_t nodeNumber = Elements[i]->getNodeNumber(); const vector<int>& NodeIds = Elements[i]->getNodeIds(); for (auto currNodeId : NodeIds ){ saveFileMesh.width(9);saveFileMesh<<currNodeId; } size_t dim = Elements[i]->getDim(); const vector<std::array<double,3>> refPos = Elements[i]->getReferencePos(); for (size_t j = 0; j<nodeNumber; ++j ){ for (size_t k = 0; k<dim; ++k ){ saveFileMesh.precision(4);saveFileMesh.width(15); saveFileMesh<<refPos[j][k]; } } saveFileMesh<<std::endl; } } void Simulation::writeTensionCompression(){ for(const auto& itElement : Elements){ for (size_t j=0; j<6; ++j){ double S = gsl_matrix_get(itElement->Strain,j,0); saveFileTensionCompression.write((char*) &S, sizeof S); } } saveFileTensionCompression.flush(); } void Simulation::writeGrowthRedistribution(){ for(const auto& itElement : Elements){ bool thereIsDistribution = itElement->thereIsGrowthRedistribution; bool shrinksElement = itElement->growthRedistributionShrinksElement; saveFileGrowthRedistribution.write((char*) &thereIsDistribution, sizeof thereIsDistribution); saveFileGrowthRedistribution.write((char*) &shrinksElement, sizeof shrinksElement); } saveFileGrowthRedistribution.flush(); } void Simulation::writeNodeBinding(){ vector<int> slaveDOFs, masterDOFs; int counter = 0; for (const auto& itNode : Nodes){ for (size_t i=0; i<3; ++i){ if (itNode->slaveTo[i]>0){ int slavedof = 3*itNode->Id + i; int masterdof = 3*itNode->slaveTo[i] + i; slaveDOFs.push_back(slavedof); masterDOFs.push_back(masterdof); counter++; } } } saveFileNodeBinding<<counter<<" "<<std::endl; for(int i=0;i<counter;++i){ int slave =slaveDOFs[i]; int master = masterDOFs[i]; saveFileNodeBinding<<slave<<" "; saveFileNodeBinding<<master<<" "<<std::endl; //std::cout<<"slaveDOFs :"<<slaveDOFs[i]<<" masterDOFs "<<masterDOFs[i]<<std::endl; } } void Simulation::writeGrowth(){ for(const auto& itElement : Elements){ gsl_matrix* currFg = itElement->getFg(); const std::array<double,3>& growthRate = itElement->getGrowthRate(); for (int j=0; j<3; ++j){ for (int k=0; k<3; ++k){ double Fgjk = gsl_matrix_get(currFg,j,k); saveFileGrowth.write((char*) &Fgjk, sizeof Fgjk); } saveFileGrowthRate.write((char*) &growthRate[j], sizeof growthRate[j]); } gsl_matrix_free(currFg); } saveFileGrowth.flush(); saveFileGrowthRate.flush(); } void Simulation::writePhysicalProp(){ for(const auto& itElement : Elements){ double E = itElement->getYoungModulus(); double interalVisc = itElement->getInternalViscosity(); double zRemodellingSoFar = itElement->getZRemodellingSoFar(); saveFilePhysicalProp.write((char*) &E, sizeof E); saveFilePhysicalProp.write((char*) &interalVisc, sizeof interalVisc); saveFilePhysicalProp.write((char*) &zRemodellingSoFar, sizeof zRemodellingSoFar); } for (const auto& itNode : Nodes){ saveFilePhysicalProp.write((char*) &itNode->externalViscosity[0], sizeof itNode->externalViscosity[0]); saveFilePhysicalProp.write((char*) &itNode->externalViscosity[1], sizeof itNode->externalViscosity[1]); saveFilePhysicalProp.write((char*) &itNode->externalViscosity[2], sizeof itNode->externalViscosity[2]); } saveFilePhysicalProp.flush(); } void Simulation::calculateGrowth(){ cleanUpGrowthRates(); for (int i=0; i<nGrowthFunctions; ++i){ if (GrowthFunctions[i]->Type == 1){ calculateGrowthUniform(GrowthFunctions[i].get()); } else if(GrowthFunctions[i]->Type == 2){ calculateGrowthRing(GrowthFunctions[i].get()); } else if(GrowthFunctions[i]->Type == 3){ calculateGrowthGridBased(GrowthFunctions[i].get()); } } for(auto& itElement : Elements){ if (itElement->isMutated){ itElement->updateGrowthByMutation(dt); } } } void Simulation::calculateShapeChange(){ cleanUpShapeChangeRates(); for (int i=0; i<nShapeChangeFunctions; ++i){ if (ShapeChangeFunctions[i]->Type == 1){ calculateShapeChangeUniform(ShapeChangeFunctions[i].get()); } if (ShapeChangeFunctions[i]->Type == 2){ calculateShapeChangeMarkerEllipseBased(ShapeChangeFunctions[i].get()); } } } void Simulation::cleanUpGrowthRates(){ for(const auto& currElement : Elements){ currElement->setGrowthRate(dt,0.0,0.0,0.0); currElement->updateGrowthIncrementFromRate(); } } void Simulation::cleanUpShapeChangeRates(){ for(const auto& currElement : Elements){ currElement->setShapeChangeRate(0.0,0.0,0.0,0.0,0.0,0.0); currElement->setShapeChangeInrementToIdentity(); } } void Simulation::calculateShapeChangeMarkerEllipseBased (GrowthFunctionBase* currSCF){ if(currSimTimeSec >= currSCF->initTime && currSimTimeSec < currSCF->endTime ){ gsl_matrix* columnarShapeChangeIncrement = gsl_matrix_calloc(3,3); std::array<double,3> growthRates = currSCF->getShapeChangeRateRate(); for(const auto& itElement : Elements){ bool appliedToElement = itElement->isShapeChangeAppliedToElement(currSCF->appliedEllipseBandIds, currSCF->applyToBasalECM, currSCF->applyToLateralECM, currSCF->applyTissueApical, currSCF->applyTissueBasal, currSCF->applyTissueMidLine ); if (appliedToElement){ gsl_matrix_set_identity(columnarShapeChangeIncrement); itElement->calculateShapeChangeIncrementFromRates(dt, growthRates[0],growthRates[1],growthRates[2],columnarShapeChangeIncrement); itElement->updateShapeChangeIncrement(columnarShapeChangeIncrement); } } gsl_matrix_free(columnarShapeChangeIncrement); } } void Simulation::calculateShapeChangeUniform (GrowthFunctionBase* currSCF){ if(currSimTimeSec >= currSCF->initTime && currSimTimeSec < currSCF->endTime ){ std::array<double,3> maxValues = currSCF->getGrowthRate(); for(const auto& itElement : Elements){ if ( currSCF->applyToColumnarLayer){ if (itElement->tissueType == 0){ //columnar layer, grow directly itElement->updateShapeChangeRate(maxValues[0],maxValues[1],maxValues[2],0,0,0); } else if (itElement->tissueType == 2){ //Linker zone, need to weight the growth double weight = itElement->getColumnarness(); itElement->updateShapeChangeRate(weight*maxValues[0],weight*maxValues[1],weight*maxValues[2],0,0,0); } } if ( currSCF->applyToPeripodialMembrane){ if (itElement->tissueType == 1){ //peripodial membrane, grow directly itElement->updateShapeChangeRate(maxValues[0],maxValues[1],maxValues[2],0,0,0); } else if (itElement->tissueType == 2){ //Linker zone, need to weight the growth double weight = itElement->getPeripodialness(); itElement->updateShapeChangeRate(weight*maxValues[0],weight*maxValues[1],weight*maxValues[2],0,0,0); } } } } } void Simulation::calculateGrowthUniform(GrowthFunctionBase* currGF){ if(currSimTimeSec >= currGF->initTime && currSimTimeSec < currGF->endTime ){ gsl_matrix* columnarFgIncrement = gsl_matrix_calloc(3,3); gsl_matrix* peripodialFgIncrement = gsl_matrix_calloc(3,3); std::array<double,3> growthRates = currGF->getGrowthRate(); for(const auto& itElement : Elements){ gsl_matrix_set_identity(columnarFgIncrement); gsl_matrix_set_identity(peripodialFgIncrement); if (currGF->applyToBasalECM || currGF->applyToLateralECM){ if (currGF->applyToBasalECM){ if (itElement->isECMMimicing && itElement->tissuePlacement == 0){ itElement->calculateFgFromRates(dt, growthRates[0],growthRates[1],growthRates[2], currGF->getShearAngleRotationMatrix(), columnarFgIncrement, 0, currGF->zMin, currGF->zMax); } } if (currGF->applyToLateralECM){ if (itElement->isECMMimimcingAtCircumference && !itElement->tissuePlacement == 0){ //do not grow the basal element twice itElement->calculateFgFromRates(dt, growthRates[0],growthRates[1],growthRates[2], currGF->getShearAngleRotationMatrix(), columnarFgIncrement, 0, currGF->zMin, currGF->zMax); } } } if (!thereIsExplicitECM || !itElement->isECMMimicing ){ //There is either no explicit ECM definition, or the element is not ECM mimicing. //If there is explicit ECM, the basal elements should not grow, all others should proceed as usual //If there is no explicit ecm, then all should proceed as usual. if (currGF->applyToColumnarLayer){ itElement->calculateFgFromRates(dt, growthRates[0],growthRates[1],growthRates[2], currGF->getShearAngleRotationMatrix(), columnarFgIncrement, 0, currGF->zMin, currGF->zMax); } if (currGF->applyToPeripodialMembrane){ itElement->calculateFgFromRates(dt, growthRates[0],growthRates[1],growthRates[2], currGF->getShearAngleRotationMatrix(), peripodialFgIncrement, 1, currGF->zMin, currGF->zMax); } } itElement->updateGrowthIncrement(columnarFgIncrement,peripodialFgIncrement); } gsl_matrix_free(columnarFgIncrement); gsl_matrix_free(peripodialFgIncrement); } } void Simulation::calculateGrowthRing(GrowthFunctionBase* currGF){ if(currSimTimeSec >= currGF->initTime && currSimTimeSec < currGF->endTime ){ float centre[2]; currGF->getCentre(centre[0], centre[1]); float innerRadius = currGF->getInnerRadius(); float outerRadius = currGF->getOuterRadius(); std::array<double,3> maxValues = currGF->getGrowthRate(); float innerRadius2 = innerRadius*innerRadius; float outerRadius2 = outerRadius*outerRadius; gsl_matrix* columnarFgIncrement = gsl_matrix_calloc(3,3); gsl_matrix* peripodialFgIncrement = gsl_matrix_calloc(3,3); for(const auto& itElement : Elements){ std::array<double,3> Elementcentre = itElement->getCentre(); //the distance is calculated in the x-y projection double d[2] = {centre[0] - Elementcentre[0], centre[1] - Elementcentre[1]}; double dmag2 = d[0]*d[0] + d[1]*d[1]; if (dmag2 > innerRadius2 && dmag2 < outerRadius2){ //the element is within the growth zone. float distance = pow(dmag2,0.5); //calculating the growth rate: as a fraction increase within this time point double sf = (1.0 - (distance - innerRadius) / (outerRadius - innerRadius) ); double growthscale[3] = {maxValues[0]*sf,maxValues[1]*sf,maxValues[2]*sf}; gsl_matrix_set_identity(columnarFgIncrement); gsl_matrix_set_identity(peripodialFgIncrement); if (currGF->applyToBasalECM || currGF->applyToLateralECM){ if (currGF->applyToBasalECM){ if (itElement->isECMMimicing && itElement->tissuePlacement == 0){ itElement->calculateFgFromRates(dt, growthscale[0],growthscale[1],growthscale[2], currGF->getShearAngleRotationMatrix(), columnarFgIncrement, 0, currGF->zMin, currGF->zMax); } } if (currGF->applyToLateralECM){ if (itElement->isECMMimimcingAtCircumference && !itElement->tissuePlacement == 0){ //do not grow the basal element twice itElement->calculateFgFromRates(dt, growthscale[0],growthscale[1],growthscale[2], currGF->getShearAngleRotationMatrix(), columnarFgIncrement, 0, currGF->zMin, currGF->zMax); } } } if (!thereIsExplicitECM || !itElement->isECMMimicing ){ //There is either no explicit ECM definition, or the element is not ECM mimicing. //If there is explicit ECM, the basal elements should not grow, all others should proceed as usual //If there is no explicit ecm, then all should proceed as usual. if (currGF->applyToColumnarLayer){ itElement->calculateFgFromRates(dt, growthscale[0],growthscale[1],growthscale[2], currGF->getShearAngleRotationMatrix(), columnarFgIncrement, 0, currGF->zMin, currGF->zMax); } if (currGF->applyToPeripodialMembrane){ itElement->calculateFgFromRates(dt, growthscale[0],growthscale[1],growthscale[2], currGF->getShearAngleRotationMatrix(), peripodialFgIncrement, 1, currGF->zMin, currGF->zMax); } } itElement->updateGrowthIncrement(columnarFgIncrement,peripodialFgIncrement); } } gsl_matrix_free(columnarFgIncrement); gsl_matrix_free(peripodialFgIncrement); } } void Simulation::setUpECMMimicingElements(){ /** * First all nodes are assigned as if they are owne explicitly by ECM mimicking elements (Node#allOwnersECMMimicing = true), then * the flags is cleared through the elemtns. */ for(const auto& itNode : Nodes){ itNode->allOwnersECMMimicing = true; } for(const auto& itElement : Elements){ if ( itElement->tissuePlacement == 0 ){ if(itElement->tissueType == 0){ /** * The basal elements (ShapeBase#tissuePlacement = 0) are ECM, their identity is set accordingly. */ itElement->setECMMimicing(true); } } else if ( itElement->tissuePlacement == 1 ){ if(itElement->tissueType == 1){ /** * On the peripodial tissue, conversly apical elements (ShapeBase#tissuePlacement = 1) are ECM. */ itElement->setECMMimicing(true); } } else if ( itElement->tissuePlacement == 2 && itElement->spansWholeTissue ){ /** * If the elements are spanning the whole tissue, (ShapeBase#tissuePlacement = 2), then they are ECM. This * scenario simulates a layer of ECM only, without any cell material. */ itElement->setECMMimicing(true); } if (!itElement->isECMMimicing){ /** * At the end of element ECM status update, if the element is NOT part of the ECM, then its nodes are not * owned exclusively by ECM elements, therefore their flag Node#allOwnersECMMimicing is set false. */ //the element is not ecm mimicking, its nodes will not be ecm mimicking: const vector<int>& nodeIds = itElement->getNodeIds(); for (auto currentNodeId : nodeIds){ Nodes[currentNodeId]->allOwnersECMMimicing = false; } } } /** * If there is explicit ECM, then all basal elements will be ECM, then I need another marker to identify cell material at he most * basal side, attached to ECM. This is done in Simulation#assigneElementsAtTheBorderOfECM. */ assigneElementsAtTheBorderOfECM(); } void Simulation::assigneElementsAtTheBorderOfECM(){ /** * If there is explicit ECM, then all basal elements will be ECM, then I need another marker to identify cell material at he most * basal side, attached to ECM. If an element is ECM, all its nodes are recorded. Then all the elements owning this node, but are not * ECM themselves become new basal elements, and their status is recorded in ShapeBase#atBasalBorderOfECM. */ vector<int> nodeListToCheck; for(const auto& itElement : Elements){ if ( itElement->isECMMimicing && !itElement->isECMMimimcingAtCircumference){ //I do not want to track the elements at the side borders int n = itElement->getNodeNumber(); for (int i=0; i<n; ++i){ bool alreadyRecorded = false; int nVector = nodeListToCheck.size(); for (int j=0 ;j< nVector; ++j){ if (nodeListToCheck[j] ==itElement->NodeIds[i] ){ alreadyRecorded = true; break; } } if (!alreadyRecorded){ nodeListToCheck.push_back(itElement->NodeIds[i]); } } } } int nVector = nodeListToCheck.size(); for(const auto& itElement : Elements){ if (!itElement->isECMMimicing && !itElement->atBasalBorderOfECM){ for (int j=0 ;j< nVector; ++j){ if (itElement->DoesPointBelogToMe(nodeListToCheck[j])){ itElement->atBasalBorderOfECM = true; break; } } } } } void Simulation::assigneElementsAtTheBorderOfActin(){ /** * If there is explicit actin, then all apical elements will be actin rich, I want another marker to identify non-actin material * at the most apical (top) side of the tissue. * If an element is actin rich, all its nodes are recorded. Then all the elements owning this node, but are not * actin-rich themselves become new basal elements, and their status is recorded in ShapeBase#atApicalBorderOfActin. */ vector<int> nodeListToCheck; for(const auto& itElement : Elements){ if ( itElement->isActinMimicing ){ int n = itElement->getNodeNumber(); for (int i=0; i<n; ++i){ bool alreadyRecorded = false; int nVector = nodeListToCheck.size(); for (int j=0 ;j< nVector; ++j){ if (nodeListToCheck[j] == itElement->NodeIds[i] ){ alreadyRecorded = true; break; } } if (!alreadyRecorded){ nodeListToCheck.push_back(itElement->NodeIds[i]); } } } } int nVector = nodeListToCheck.size(); for(const auto& itElement : Elements){ if (!itElement->isActinMimicing && !itElement->isECMMimicing && !itElement->atBasalBorderOfECM){ for (int j=0 ;j< nVector; ++j){ if (itElement->DoesPointBelogToMe(nodeListToCheck[j])){ itElement->atApicalBorderOfActin = true; break; } } } } } void Simulation::setUpActinMimicingElements(){ /** * All elements on the apical side (ShapeBase#tissuePlacement = 1) are actin-rich elements. */ for(const auto& itElement : Elements){ if ( itElement->tissuePlacement == 1 ){ //apical elements are mimicing actin: if (!itElement->isECMMimimcingAtCircumference){ itElement->setActinMimicing(true); } } if ( itElement->tissuePlacement == 2 && itElement->spansWholeTissue ){ /** * If the elements are spanning the whole tissue, (ShapeBase#tissuePlacement = 2), then they are actin-rich. This * scenario simulates a layer of actin mesh only, without any softer material. */ if (!itElement->isECMMimimcingAtCircumference){ itElement->setActinMimicing(true); } } } /** * If there is explicit actin, then all apical elements will be actin rich, I want another marker to identify non-actin material * at the most apical (top) side of the tissue. This is done via Simulation#assigneElementsAtTheBorderOfActin. */ assigneElementsAtTheBorderOfActin(); } void Simulation::calculateGrowthGridBased(GrowthFunctionBase* currGF){ int nGridX = currGF->getGridX(); int nGridY = currGF->getGridY(); if(currSimTimeSec >= currGF->initTime && currSimTimeSec < currGF->endTime ){ gsl_matrix* columnarFgIncrement = gsl_matrix_calloc(3,3); gsl_matrix* peripodialFgIncrement = gsl_matrix_calloc(3,3); for(const auto& itElement : Elements){ gsl_matrix_set_identity(columnarFgIncrement); gsl_matrix_set_identity(peripodialFgIncrement); int IndexX = 0.0, IndexY = 0.0; double FracX = 1.0, FracY = 1.0; if (GridGrowthsPinnedOnInitialMesh){ itElement->getInitialRelativePositionInTissueInGridIndex(nGridX, nGridY, IndexX, IndexY, FracX, FracY); } else{ itElement->getRelativePositionInTissueInGridIndex(nGridX, nGridY, IndexX, IndexY, FracX, FracY); } if (currGF->applyToBasalECM || currGF->applyToLateralECM){ if (currGF->applyToBasalECM){ if (itElement->isECMMimicing && itElement->tissuePlacement == 0){ itElement->calculateFgFromGridCorners(gridGrowthsInterpolationType, dt, currGF, columnarFgIncrement, 0, IndexX, IndexY, FracX, FracY); //sourceTissue is 0 for columnar Layer } } if (currGF->applyToLateralECM){ if (itElement->isECMMimimcingAtCircumference && !itElement->tissuePlacement == 0){ //do not grow the basal element twice itElement->calculateFgFromGridCorners(gridGrowthsInterpolationType, dt, currGF, columnarFgIncrement, 0, IndexX, IndexY, FracX, FracY); //sourceTissue is 0 for columnar Layer } } } if (!thereIsExplicitECM || !itElement->isECMMimicing ){ //There is either no explicit ECM definition, or the element is not ECM mimicing. //If there is explicit ECM, the basal elements should not grow, all others should proceed as usual //If there is no explicit ecm, then all should proceed as usual. if (currGF->applyToColumnarLayer){ itElement->calculateFgFromGridCorners(gridGrowthsInterpolationType, dt, currGF, columnarFgIncrement, 0, IndexX, IndexY, FracX, FracY); //sourceTissue is 0 for columnar Layer } if (currGF->applyToPeripodialMembrane){ itElement->calculateFgFromGridCorners(gridGrowthsInterpolationType, dt, currGF, peripodialFgIncrement, 1, IndexX, IndexY, FracX, FracY); //sourceTissue is 1 for peripodial membrane } } itElement->updateGrowthIncrement(columnarFgIncrement,peripodialFgIncrement); } gsl_matrix_free(columnarFgIncrement); gsl_matrix_free(peripodialFgIncrement); } } void Simulation::setStretch(){ /** * The clap orientation is set in Simulation#DVClamp boolean, where if true, the tissue is stretched in x axis, and stretched in * y axis otherwise. */ for (int i=0;i<3;i++){ leftClampForces[i] = 0.0; rightClampForces[i] = 0.0; } vector <int> clampedNodeIds; double distance = 0; /** * The initial distance is calculated to set the stretched distance at maximum stretch Simulation#StretchStrain. */ if (DVClamp){ distance = fabs(Nodes[ventralTipIndex]->Position[0] - Nodes[dorsalTipIndex]->Position[0]); distanceIndex = 0; //if the clamp is on DV axis, then the direction of interest is x, index is 0; } else{ distance = fabs(Nodes[anteriorTipIndex]->Position[1] - Nodes[posteriorTipIndex]->Position[1]); distanceIndex = 1; //if the clamp is on AP axis, then the direction of interest is y, index is 1. } /** * For each node falling under a clamp, their Ids are recorded to move with clamp, their movement is fixed otherwise. */ for (const auto& currNode : Nodes){ if (currNode->Position[distanceIndex]> StretchMax || currNode->Position[distanceIndex] < StretchMin){ currNode->FixedPos[0]=1; currNode->FixedPos[1]=1; currNode->FixedPos[2]=1; clampedNodeIds.push_back(currNode->Id); } } setUpClampBorders(clampedNodeIds); //the distance that is to be moved: distance *= StretchStrain; /** * Then with the time steps of stretch identified by the user input, the stretch distance at each time step to move the clamped nodes is * obtained. */ double StretchTimeSteps = (StretchEndTime - StretchInitialTime)/dt; StretchDistanceStep = 0.5* (distance / StretchTimeSteps); } void Simulation::setUpClampBorders(std::vector<int>& clampedNodeIds){ int n = clampedNodeIds.size(); for(const auto& itElement : Elements){ const vector<int> nodeIds = itElement->getNodeIds(); bool hasClampedNode = false; bool hasNonClampedNode = false; bool leftHandSide = false; vector <int> clampedBorderNodes; for (auto currNodeId : nodeIds){ bool lastNodeWasClamped = false; for (int k=0; k<n; k++){ if (currNodeId == clampedNodeIds[k]){ hasClampedNode = true; lastNodeWasClamped = true; //check if node is recorded: bool alreadyRecorded = false; int nLeftClamp = leftClampBorder.size(); for (int m=0; m<nLeftClamp; m++){ if (leftClampBorder[m] == currNodeId){ alreadyRecorded = true; break; } } if (!alreadyRecorded){ int nRightClamp = rightClampBorder.size(); for (int m=0; m<nRightClamp; m++){ if (rightClampBorder[m] == currNodeId){ alreadyRecorded = true; break; } } } if (!alreadyRecorded){ clampedBorderNodes.push_back(currNodeId); } if (Nodes[currNodeId]->Position[distanceIndex] < StretchMin){ leftHandSide = true; } break; } } if (lastNodeWasClamped == false){ hasNonClampedNode = true; } } if (hasClampedNode && hasNonClampedNode){ std::cout<<" Element "<<itElement->Id<<" is at the border"<<std::endl; int nClamp = clampedBorderNodes.size(); if(leftHandSide){ std::cout<<"Element is on left hand side"<<std::endl; for (int k=0; k<nClamp; k++){ leftClampBorder.push_back(clampedBorderNodes[k]); } } else { std::cout<<"Element is on right hand side"<<std::endl; for (int k=0; k<nClamp; k++){ rightClampBorder.push_back(clampedBorderNodes[k]); } } } }int nLeftClamp = leftClampBorder.size(); for (int k=0; k<nLeftClamp; k++){ std::cout<<"left clamp border nodes: "<<leftClampBorder[k]<<std::endl; } int nRightClamp = rightClampBorder.size(); for (int k=0; k<nRightClamp; k++){ std::cout<<"right clamp border nodes: "<<rightClampBorder[k]<<std::endl; } } void Simulation::setupPipetteExperiment(){ pipetteInnerRadiusSq = pipetteInnerRadius*pipetteInnerRadius; effectLimitsInZ[0] = pipetteCentre[2] - pipetteDepth; effectLimitsInZ[1] = pipetteCentre[2] + pipetteDepth; /** * When setting the effectiveness boundaries of the suction pipette, the boundary inside the tube needs to be extended, * such that the nodes will not stop being suced in after they go inside a certain length into the tube. * This means increasing the upper boundary for apical suction, and reducing the lower boundary for basal suction. */ if(ApicalSuction){ effectLimitsInZ[1] += 1000; } else{ effectLimitsInZ[0] -= 1000; } //Now I am sticking the other side of the tissue to a surface /** * If the other side of the tissue is attached to a surface, the nodesa re fixed accordingly. */ if (TissueStuckOnGlassDuringPipetteAspiration){ if (ApicalSuction){ for (const auto& currNode : Nodes){ //fix basal nodes of columnar layer: if(currNode->tissuePlacement == 0 && currNode->tissueType == 0) { fixAllD(currNode.get(), false); //this is fixing with adhesives, should be a hard fix at all times } } } else{ for (const auto& currNode : Nodes){ //fix apical nodes and all peripodial membrane nodes: if(currNode->tissuePlacement == 1 || currNode->tissueType == 1) { fixAllD(currNode.get(), false); //this is fixing with adhesives, should be a hard fix at all times } } } } } void Simulation::addPipetteForces(gsl_matrix* gExt){ for (int i=0; i<nPipetteSuctionSteps; ++i){ if (currSimTimeSec >= pipetteSuctionTimes[i]){ SuctionPressure[2] = pipetteSuctionPressures[i]; } else{ break; } } int dim = 3; for (size_t i=0; i<nNodes; ++i){ /** * Each node is checked agains the pipette boundaries. If the node is apical and the suction * is apical OR the suction is basal and the node is basal, the position is checked. */ if( ( ApicalSuction && Nodes[i]->tissuePlacement == 1) || ( !ApicalSuction && Nodes[i]->tissuePlacement == 0)){ if (Nodes[i]->Position[2]> effectLimitsInZ[0] && Nodes[i]->Position[2]< effectLimitsInZ[1]){ double dx = pipetteCentre[0] - Nodes[i]->Position[0]; double dy = pipetteCentre[1] - Nodes[i]->Position[1]; double d2 = dx*dx+dy*dy ; if (d2 < pipetteInnerRadiusSq){ /** * The suction pressure of the pipette is applied to the Node#zProjectedArea and added as an * external force to the nodal force vector. */ double multiplier = 1.0; bool scalePressure = false; if(scalePressure){ multiplier = (1 - d2/pipetteInnerRadiusSq);} double LocalPressure[3] = { multiplier*SuctionPressure[0], multiplier*SuctionPressure[1],multiplier*SuctionPressure[2]}; //node is within suciton range if(!Nodes[i]->FixedPos[0]){ double value = gsl_matrix_get(gExt,i*dim,0); value +=LocalPressure[0]*Nodes[i]->zProjectedArea; gsl_matrix_set(gExt,i*dim,0,value); } if(!Nodes[i]->FixedPos[1]){ double value = gsl_matrix_get(gExt,i*dim+1,0); value +=LocalPressure[1]*Nodes[i]->zProjectedArea; gsl_matrix_set(gExt,i*dim+1,0,value); } if(!Nodes[i]->FixedPos[2]){ double value = gsl_matrix_get(gExt,i*dim+2,0); value +=LocalPressure[2]*Nodes[i]->zProjectedArea; gsl_matrix_set(gExt,i*dim+2,0,value); } } } } } } void Simulation::detectPackingToPipette(){ /** * The current tip of the pipette is defined as the range starting Simulation#pipetteInnerRadius going for Simulation#pipetteThickness, and * the centre of the pipette tip is recorded in Simulation#pipetteCentre. Any node falling within this threshold on the corect surface * can potentially pack to the pipette. * */ TransientZFixListForPipette.clear(); std::array<double,2> pipLim {0.95*pipetteInnerRadius, 1.2*(pipetteInnerRadius+pipetteThickness)}; std::array<double,2> pipLimSq {pipLim[0] *pipLim[0], pipLim[1]* pipLim[1]}; double zPackThreshold = 2.0; std::array<double,2> zLimits{-1.0*zPackThreshold,zPackThreshold}; for (size_t currId=0; currId<nNodes;currId++){ if( ( ApicalSuction && Nodes[currId]->tissuePlacement == 1) || ( !ApicalSuction && Nodes[currId]->tissuePlacement == 0)){ std::array<double,3> distanceToPipetCentre{Nodes[currId]->Position[0]-pipetteCentre[0], Nodes[currId]->Position[1]-pipetteCentre[1], Nodes[currId]->Position[2]-pipetteCentre[2]}; if (distanceToPipetCentre[2] < zLimits[1] && distanceToPipetCentre[2]> zLimits[0]){ double xydist2 = distanceToPipetCentre[0]*distanceToPipetCentre[0]+distanceToPipetCentre[1]*distanceToPipetCentre[1]; if (xydist2>pipLimSq[0] && xydist2<pipLimSq[1]){ TransientZFixListForPipette.push_back(currId); } } } } } void Simulation::calculatePackingToPipetteForcesImplicit3D(){ double zeroThreshold = 1E-3; double zPackThreshold = 2.0; /** * See the documentation for Simulation#calculatePackingForcesImplicit3D. The methodology is the same, * with pipeete tip centre used instead of the second node. */ size_t n = TransientZFixListForPipette.size(); for(size_t node_counter = 0 ; node_counter<n; ++node_counter){ int id0 = TransientZFixListForPipette[node_counter]; double multiplier = packingMultiplier; double sigmoidSaturation = sigmoidSaturationForPacking; double distanceShiftScale = 0.6*zPackThreshold; double d = fabs(Nodes[id0]->Position[2] - pipetteCentre[2]); double averageMass = Nodes[id0]->mass; double normalZ= -1.0;//normal from pipette to node //if node is apical, normal points to -1 if (Nodes[node_counter]->tissuePlacement == 1){ normalZ = 1.0; } if (d < zeroThreshold){ d = zeroThreshold; } double shifted_d = d - distanceShiftScale; //shift the distance by the selected percentage, double sigmoid = 1 / (1 + exp(sigmoidSaturation/ zPackThreshold * 2.0 * shifted_d)); double Fmagnitude = multiplier * averageMass * sigmoid; double Fz = Fmagnitude*normalZ; PackingForces[id0][2] += Fz; if (std::isnan(Fz)){ std::cerr<<" packing force from pipette is nan for node "<<TransientZFixListForPipette[node_counter]<<std::endl; } } } void Simulation::calculatePackingToPipetteJacobian3D(gsl_matrix* K){ double zeroThreshold = 1E-3; double zPackThreshold = 2.0; /** * See the documentation for Simulation#calculatePackingJacobian3D. The methodology is the same, * with pipette tip centre used instead of the second node. */ size_t n = TransientZFixListForPipette.size(); for(size_t node_counter = 0 ; node_counter<n; ++node_counter){ int id0 = TransientZFixListForPipette[node_counter]; double multiplier = packingMultiplier; double sigmoidSaturation = sigmoidSaturationForPacking; double distanceShiftScale = 0.6*zPackThreshold; double d = fabs(Nodes[id0]->Position[2] - pipetteCentre[2]); double averageMass = Nodes[id0]->mass; double normalZ= -1.0;//normal from pipette to node //if node is apical, normal points to -1 if (Nodes[node_counter]->tissuePlacement == 1){ normalZ = 1.0; } if (d < zeroThreshold){ d = zeroThreshold; } double shifted_d = d - distanceShiftScale; //shift the distance by the selected percentage, double sigmoid = 1 / (1 + exp(sigmoidSaturation/ zPackThreshold * 2.0 * shifted_d)); double dSdXi = (-sigmoidSaturation/ zPackThreshold * 2.0) * sigmoid * (1-sigmoid); gsl_matrix* normalMat = gsl_matrix_calloc(3,1); gsl_matrix_set(normalMat, 0,0,0.0); gsl_matrix_set(normalMat, 1,0,0.0); gsl_matrix_set(normalMat, 2,0,normalZ); gsl_matrix* norm_normT = gsl_matrix_calloc(3,3); gsl_blas_dgemm (CblasNoTrans, CblasTrans,1.0, normalMat, normalMat, 0.0, norm_normT); gsl_matrix* dFidXi = gsl_matrix_calloc(3,3); gsl_matrix_set_identity(dFidXi); gsl_matrix_sub(dFidXi,norm_normT); //(I - norm*norm^T) gsl_matrix_scale(dFidXi,sigmoid/d); //sigmoid/d * (I - norm*norm^T) gsl_matrix_scale(norm_normT,dSdXi); // norm*norm^T * dSdXi gsl_matrix_add(dFidXi,norm_normT); // sigmoid/d * (I - norm*norm^T) + norm*norm^T * dSdXi gsl_matrix_scale(dFidXi,multiplier * averageMass); //scale by mass and multiplier when needed for (size_t i=0; i<3; ++i){ for (size_t j=0; j<3; ++j){ double derivativeij = gsl_matrix_get(dFidXi,i,j); addValueToMatrix(K,3*id0+i,3*id0+j,-derivativeij); } } gsl_matrix_free(normalMat); gsl_matrix_free(dFidXi); gsl_matrix_free(norm_normT); } } void Simulation::updateElementVolumesAndTissuePlacements(){ for (auto &itElement : Elements){ std::cout<<"updating element: "<<itElement->Id<<std::endl; itElement->updateElementVolumesAndTissuePlacementsForSave(Nodes); } } void Simulation::updateElasticPropertiesForAllNodes(){ /** * Elastic property update function ShapeBase#updateElasticProperties is called on all elements. */ for (auto &itElement : Elements){ itElement->updateElasticProperties(); } } void Simulation::clearNodeMassLists(){ for (const auto& currNode : Nodes){ currNode->connectedElementIds.size(); currNode->connectedElementIds.clear(); currNode->connectedElementWeights.clear(); currNode->mass=0.0; } } void Simulation::setupYsymmetricity(){ /** * If a node is at the symmetriciy zone, its degree of freedom is fixed on the symmetricity axis. There will be elements of exactly equal strengt * actin on the node and cancelling the forces in the symmetric axis. */ double yLimPos = 0.1; double yLimNeg = (-1.0)*yLimPos; for (size_t i=0; i<nNodes; ++i){ if (Nodes[i]->Position[1]< yLimPos){ if (Nodes[i]->Position[1] > yLimNeg){ Nodes[i]->atSymmetricityBorder = true; fixY(Nodes[i].get(),false); //this is for symmetricity, the fixing has to be hard fixing, not with external viscosity under any condition } } } } void Simulation::setupXsymmetricity(){ /** * If a node is at the symmetriciy zone, its degree of freedom is fixed on the symmetricity axis. There will be elements of exactly equal strengt * actin on the node and cancelling the forces in the symmetric axis. */ double xLimPos = 0.1; double xLimNeg = (-1.0)*xLimPos; for (size_t i=0; i<nNodes; ++i){ if (Nodes[i]->Position[0]< xLimPos){ if (Nodes[i]->Position[0] > xLimNeg){ Nodes[i]->atSymmetricityBorder = true; fixX(Nodes[i].get(),false); //this is for symmetricity, the fixing has to be hard fixing, not with external viscosity under any condition } } } } void Simulation::clearScaleingDueToApikobasalRedistribution(){ //not using range based loops here to ensure openMP comaptibility #pragma omp parallel for for(std::vector<std::unique_ptr<ShapeBase>>::iterator itElement = Elements.begin(); itElement <Elements.end(); ++itElement){ (*itElement)->thereIsGrowthRedistribution = false; (*itElement)->growthRedistributionScale = 0.0; } }
43.145717
627
0.668429
meldatozluoglu
a2b5b67bd7d9e6442f5f033f9952d0f0bfcc98d5
20,096
cpp
C++
src/cinder/audio/ContextPortAudio.cpp
PetrosKataras/Cinder-PortAudio
681b77fa301e49f2e67d0d5a6b855b5d33766ff0
[ "BSD-2-Clause" ]
null
null
null
src/cinder/audio/ContextPortAudio.cpp
PetrosKataras/Cinder-PortAudio
681b77fa301e49f2e67d0d5a6b855b5d33766ff0
[ "BSD-2-Clause" ]
null
null
null
src/cinder/audio/ContextPortAudio.cpp
PetrosKataras/Cinder-PortAudio
681b77fa301e49f2e67d0d5a6b855b5d33766ff0
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) 2018, The Cinder Project This code is intended to be used with the Cinder C++ library, http://libcinder.org 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 "cinder/audio/ContextPortAudio.h" #include "cinder/audio/DeviceManagerPortAudio.h" #include "cinder/audio/dsp/Converter.h" #include "cinder/audio/dsp/RingBuffer.h" #include "cinder/Log.h" #include "portaudio.h" #define LOG_XRUN( stream ) CI_LOG_W( stream ) //#define LOG_XRUN( stream ) ( (void)( 0 ) ) #define LOG_CI_PORTAUDIO( stream ) CI_LOG_I( stream ) //#define LOG_CI_PORTAUDIO( stream ) ( (void)( 0 ) ) //#define LOG_CAPTURE( stream ) CI_LOG_I( stream ) #define LOG_CAPTURE( stream ) ( (void)( 0 ) ) using namespace std; using namespace ci; namespace cinder { namespace audio { // ---------------------------------------------------------------------------------------------------- // OutputDeviceNodePortAudio::Impl // ---------------------------------------------------------------------------------------------------- struct OutputDeviceNodePortAudio::Impl { Impl( OutputDeviceNodePortAudio *parent ) : mParent( parent ) {} static int streamCallback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void *userData ) { auto parent = (OutputDeviceNodePortAudio *)userData; float *out = (float*)outputBuffer; const float *in = (const float *)inputBuffer; // needed in the case of full duplex I/O LOG_CAPTURE( "framesPerBuffer: " << framesPerBuffer << ", statusFlags: " << statusFlags << hex << ", input buffer: " << inputBuffer << ", outputBuffer: " << outputBuffer << dec ); parent->renderAudio( in, out, (size_t)framesPerBuffer ); return paContinue; } PaStream *mStream = nullptr; OutputDeviceNodePortAudio* mParent; }; // ---------------------------------------------------------------------------------------------------- // OutputDeviceNodePortAudio // ---------------------------------------------------------------------------------------------------- OutputDeviceNodePortAudio::OutputDeviceNodePortAudio( const DeviceRef &device, const Format &format ) : OutputDeviceNode( device, format ), mImpl( new Impl( this ) ), mFullDuplexIO( false ), mFullDuplexInputDeviceNode( false ) { LOG_CI_PORTAUDIO( "device key: " << device->getKey() ); LOG_CI_PORTAUDIO( "device channels: " << device->getNumOutputChannels() << ", samplerate: " << device->getSampleRate() << ", framesPerBlock: " << device->getFramesPerBlock() ); } OutputDeviceNodePortAudio::~OutputDeviceNodePortAudio() { } void OutputDeviceNodePortAudio::initialize() { LOG_CI_PORTAUDIO( "bang" ); auto manager = dynamic_cast<DeviceManagePortAudio *>( Context::deviceManager() ); PaDeviceIndex devIndex = (PaDeviceIndex) manager->getPaDeviceIndex( getDevice() ); const PaDeviceInfo *devInfo = Pa_GetDeviceInfo( devIndex ); // Open an audio I/O stream. PaStreamParameters outputParams; outputParams.device = devIndex; outputParams.channelCount = getNumChannels(); //outputParams.sampleFormat = paFloat32 | paNonInterleaved; // TODO: try non-interleaved outputParams.sampleFormat = paFloat32; outputParams.hostApiSpecificStreamInfo = NULL; size_t framesPerBlock = getOutputFramesPerBlock(); double sampleRate = getOutputSampleRate(); outputParams.suggestedLatency = getDevice()->getFramesPerBlock() / sampleRate; // check if any current device nodes are an input device node and have this same device auto ctx = dynamic_pointer_cast<ContextPortAudio>( getContext() ); for( const auto &weakNode : ctx->mDeviceNodes ) { auto node = weakNode.lock(); auto inputDeviceNode = dynamic_pointer_cast<InputDeviceNodePortAudio>( node ); if( inputDeviceNode ) { LOG_CI_PORTAUDIO( "\t- found input device node" ); if( getDevice() == inputDeviceNode->getDevice() ) { mFullDuplexIO = true; mFullDuplexInputDeviceNode = inputDeviceNode.get(); break; } } } // if full duplex I/O, this output node's stream will be used instead of the input node PaStreamFlags streamFlags = 0; if( mFullDuplexIO ) { LOG_CI_PORTAUDIO( "\t- opening full duplex stream" ); mFullDuplexIO = true; PaStreamParameters inputParams; inputParams.device = devIndex; inputParams.channelCount = getNumChannels(); inputParams.sampleFormat = paFloat32; inputParams.hostApiSpecificStreamInfo = NULL; inputParams.suggestedLatency = getDevice()->getFramesPerBlock() / sampleRate; PaError err = Pa_OpenStream( &mImpl->mStream, &inputParams, &outputParams, sampleRate, framesPerBlock, streamFlags, &Impl::streamCallback, this ); if( err != paNoError ) { throw ContextPortAudioExc( "Failed to open stream for output device named '" + getDevice()->getName() + " (full duplex)", err ); } } else { LOG_CI_PORTAUDIO( "\t- opening half duplex stream" ); PaError err = Pa_OpenStream( &mImpl->mStream, nullptr, &outputParams, sampleRate, framesPerBlock, streamFlags, &Impl::streamCallback, this ); if( err != paNoError ) { throw ContextPortAudioExc( "Failed to open stream for output device named '" + getDevice()->getName() + " (half duplex)", err ); } } } void OutputDeviceNodePortAudio::uninitialize() { PaError err = Pa_CloseStream( mImpl->mStream ); CI_ASSERT( err == paNoError ); mImpl->mStream = nullptr; } void OutputDeviceNodePortAudio::enableProcessing() { PaError err = Pa_StartStream( mImpl->mStream ); CI_ASSERT( err == paNoError ); } void OutputDeviceNodePortAudio::disableProcessing() { PaError err = Pa_StopStream( mImpl->mStream ); CI_ASSERT( err == paNoError ); } void OutputDeviceNodePortAudio::renderAudio( const float *inputBuffer, float *outputBuffer, size_t framesPerBuffer ) { auto ctx = getContext(); if( ! ctx ) return; lock_guard<mutex> lock( ctx->getMutex() ); // verify context still exists, since its destructor may have been holding the lock ctx = getContext(); if( ! ctx ) return; CI_ASSERT( framesPerBuffer == getOutputFramesPerBlock() ); // currently expecting these to always match ctx->preProcess(); if( mFullDuplexInputDeviceNode ) { mFullDuplexInputDeviceNode->mFullDuplexInputBuffer = inputBuffer; } auto internalBuffer = getInternalBuffer(); internalBuffer->zero(); pullInputs( internalBuffer ); if( checkNotClipping() ) internalBuffer->zero(); const size_t numFrames = internalBuffer->getNumFrames(); const size_t numChannels = internalBuffer->getNumChannels(); dsp::interleave( internalBuffer->getData(), outputBuffer, numFrames, numChannels, numFrames ); ctx->postProcess(); } // ---------------------------------------------------------------------------------------------------- // InputDeviceNodePortAudio::Impl // ---------------------------------------------------------------------------------------------------- struct InputDeviceNodePortAudio::Impl { const size_t RINGBUFFER_PADDING_FACTOR = 4; Impl( InputDeviceNodePortAudio *parent ) : mParent( parent ) {} void init() { mNumFramesBuffered = 0; mTotalFramesCaptured = 0; if( mParent->mFullDuplexIO ) { // OutputDeviceNodePortAudio will provide the input buffer each frame, we don't need extra buffers or a stream. mReadBuffer = {}; mRingBuffers.clear(); return; } auto manager = dynamic_cast<DeviceManagePortAudio *>( Context::deviceManager() ); auto device = mParent->getDevice(); PaDeviceIndex devIndex = (PaDeviceIndex) manager->getPaDeviceIndex( device ); size_t numChannels = mParent->getNumChannels(); size_t framesPerBlock = mParent->getFramesPerBlock(); // frames per block for the audio graph / context size_t deviceFramesPerBlock = device->getFramesPerBlock(); // frames per block for the input device (might be different, if the samplerate is different) size_t deviceSampleRate = device->getSampleRate(); if( deviceSampleRate != mParent->getSampleRate() ) { // samplerate doesn't match the context, install Converter mConverter = audio::dsp::Converter::create( deviceSampleRate, mParent->getSampleRate(), numChannels, numChannels, deviceFramesPerBlock ); mConverterDestBuffer.setSize( mConverter->getDestMaxFramesPerBlock(), numChannels ); mMaxReadFrames = deviceFramesPerBlock; LOG_CI_PORTAUDIO( "created converter, max source frames: " << mConverter->getSourceMaxFramesPerBlock() << ", max dest frames: " << mConverter->getDestMaxFramesPerBlock() ); } else { mMaxReadFrames = framesPerBlock; } for( size_t ch = 0; ch < numChannels; ch++ ) { mRingBuffers.emplace_back( framesPerBlock * RINGBUFFER_PADDING_FACTOR ); } mReadBuffer.setSize( deviceFramesPerBlock, numChannels ); // Open an audio I/O stream. No callbacks, we'll get pulled from the audio graph and read non-blocking PaStreamParameters inputParams; inputParams.device = devIndex; inputParams.channelCount = numChannels; inputParams.sampleFormat = paFloat32; inputParams.hostApiSpecificStreamInfo = NULL; inputParams.suggestedLatency = (PaTime)framesPerBlock / (PaTime)deviceSampleRate; PaStreamFlags flags = 0; PaError err = Pa_OpenStream( &mStream, &inputParams, nullptr, deviceSampleRate, framesPerBlock, flags, nullptr, nullptr ); if( err != paNoError ) { throw ContextPortAudioExc( "Failed to open stream for input device named '" + device->getName(), err ); } } void captureAudio( float *audioBuffer, size_t framesPerBuffer, size_t numChannels ) { // Using Read/Write I/O Methods signed long readAvailable = Pa_GetStreamReadAvailable( mStream ); CI_ASSERT( readAvailable >= 0 ); LOG_CAPTURE( "[" << mParent->getContext()->getNumProcessedFrames() << "] read available: " << readAvailable << ", ring buffer write available: " << mRingBuffers[0].getAvailableWrite() ); while( readAvailable > 0 ) { unsigned long framesToRead = min( (unsigned long)readAvailable, (unsigned long)mMaxReadFrames ); mReadBuffer.setNumFrames( framesToRead ); if( numChannels == 1 ) { // capture directly into mReadBuffer PaError err = Pa_ReadStream( mStream, mReadBuffer.getData(), framesToRead ); CI_VERIFY( err == paNoError ); } else { // read into audioBuffer, then de-interleave into mReadBuffer // TODO: does it make sense to pass in the audioBuffer here? // - might also be too small when downsampling (ex. input: 48k, output: 44.1k) PaError err = Pa_ReadStream( mStream, audioBuffer, framesToRead ); CI_VERIFY( err == paNoError ); dsp::deinterleave( (float *)audioBuffer, mReadBuffer.getData(), framesPerBuffer, numChannels, framesPerBuffer ); } // write to ring buffer, use Converter if one was installed if( mConverter ) { pair<size_t, size_t> count = mConverter->convert( &mReadBuffer, &mConverterDestBuffer ); LOG_CAPTURE( "\t- frames read: " << framesToRead << ", converted: " << count.second ); for( size_t ch = 0; ch < numChannels; ch++ ) { if( ! mRingBuffers[ch].write( mConverterDestBuffer.getChannel( ch ), count.second ) ) { LOG_XRUN( "[" << mParent->getContext()->getNumProcessedFrames() << "] buffer overrun (with converter). failed to read from ringbuffer, num samples to write: " << count.second << ", channel: " << ch ); mParent->markOverrun(); } } mNumFramesBuffered += count.second; mTotalFramesCaptured += count.second; } else { LOG_CAPTURE( "\t- frames read: " << framesToRead ); for( size_t ch = 0; ch < numChannels; ch++ ) { if( ! mRingBuffers[ch].write( mReadBuffer.getChannel( ch ), framesToRead ) ) { LOG_XRUN( "[" << mParent->getContext()->getNumProcessedFrames() << "] buffer overrun. failed to read from ringbuffer, num samples to write: " << framesToRead << ", channel: " << ch ); mParent->markOverrun(); return; } } mNumFramesBuffered += framesToRead; mTotalFramesCaptured += framesToRead; } readAvailable = Pa_GetStreamReadAvailable( mStream ); LOG_CAPTURE( "[" << mParent->getContext()->getNumProcessedFrames() << "] frames buffered: " << mNumFramesBuffered << ", read available: " << readAvailable << ", ring buffer write available: " << mRingBuffers[0].getAvailableWrite() ); int flarg = 2; } } PaStream *mStream = nullptr; InputDeviceNodePortAudio* mParent; std::unique_ptr<dsp::Converter> mConverter; vector<dsp::RingBufferT<float>> mRingBuffers; // storage for samples ready for consumption in the audio graph BufferDynamic mReadBuffer, mConverterDestBuffer; size_t mNumFramesBuffered; size_t mMaxReadFrames; uint64_t mTotalFramesCaptured = 0; }; // ---------------------------------------------------------------------------------------------------- // InputDeviceNodePortAudio // ---------------------------------------------------------------------------------------------------- InputDeviceNodePortAudio::InputDeviceNodePortAudio( const DeviceRef &device, const Format &format ) : InputDeviceNode( device, format ), mImpl( new Impl( this ) ), mFullDuplexIO( false ), mFullDuplexInputBuffer( nullptr ) { LOG_CI_PORTAUDIO( "device key: " << device->getKey() ); LOG_CI_PORTAUDIO( "device channels: " << device->getNumInputChannels() << ", samplerate: " << device->getSampleRate() << ", framesPerBlock: " << device->getFramesPerBlock() ); } InputDeviceNodePortAudio::~InputDeviceNodePortAudio() { LOG_CI_PORTAUDIO( "bang" ); } void InputDeviceNodePortAudio::initialize() { LOG_CI_PORTAUDIO( "bang" ); // compare device to context output device, if they are the same key then we know we need to setup duplex audio auto outputDeviceNode = dynamic_pointer_cast<OutputDeviceNodePortAudio>( getContext()->getOutput() ); if( getDevice() == outputDeviceNode->getDevice() ) { LOG_CI_PORTAUDIO( "\t- setting up duplex audio.." ); mFullDuplexIO = true; if( ! outputDeviceNode->mFullDuplexIO ) { LOG_CI_PORTAUDIO( "\t- OutputDeviceNode needs re-initializing." ); outputDeviceNode->mFullDuplexIO = true; bool outputWasInitialized = outputDeviceNode->isInitialized(); bool outputWasEnabled = outputDeviceNode->isEnabled(); if( outputWasInitialized ) { outputDeviceNode->disable(); outputDeviceNode->uninitialize(); } if( outputWasInitialized ) outputDeviceNode->initialize(); if( outputWasEnabled ) outputDeviceNode->enable(); } } else { mFullDuplexIO = false; mFullDuplexInputBuffer = nullptr; } mImpl->init(); } void InputDeviceNodePortAudio::uninitialize() { LOG_CI_PORTAUDIO( "bang" ); if( mImpl->mStream ) { PaError err = Pa_CloseStream( mImpl->mStream ); CI_VERIFY( err == paNoError ); } mImpl->mStream = nullptr; mImpl->mConverter = nullptr; } void InputDeviceNodePortAudio::enableProcessing() { LOG_CI_PORTAUDIO( "bang" ); if( mImpl->mStream ) { PaError err = Pa_StartStream( mImpl->mStream ); CI_VERIFY( err == paNoError ); } } void InputDeviceNodePortAudio::disableProcessing() { LOG_CI_PORTAUDIO( "bang" ); if( mImpl->mStream ) { PaError err = Pa_StopStream( mImpl->mStream ); CI_VERIFY( err == paNoError ); } } void InputDeviceNodePortAudio::process( Buffer *buffer ) { if( mFullDuplexIO ) { // read from the buffer provided by OutputDeviceNodePortAudio LOG_CAPTURE( "copying duplex buffer " ); CI_ASSERT( mFullDuplexInputBuffer ); dsp::deinterleave( mFullDuplexInputBuffer, buffer->getData(), buffer->getNumFrames(), buffer->getNumChannels(), buffer->getNumFrames() ); } else { // read from ring buffer const size_t framesNeeded = buffer->getNumFrames(); LOG_CAPTURE( "[" << getContext()->getNumProcessedFrames() << "] audio thread: " << getContext()->isAudioThread() << ", frames buffered: " << mImpl->mNumFramesBuffered << ", frames needed: " << framesNeeded ); mImpl->captureAudio( buffer->getData(), framesNeeded, buffer->getNumChannels() ); if( mImpl->mNumFramesBuffered < framesNeeded ) { // only mark underrun once audio capture has begun if( mImpl->mTotalFramesCaptured >= framesNeeded ) { LOG_XRUN( "[" << getContext()->getNumProcessedFrames() << "] buffer underrun. total frames buffered: " << mImpl->mNumFramesBuffered << ", less than frames needed: " << framesNeeded << ", total captured: " << mImpl->mTotalFramesCaptured ); markUnderrun(); } return; } for( size_t ch = 0; ch < getNumChannels(); ch++ ) { bool readSuccess = mImpl->mRingBuffers[ch].read( buffer->getChannel( ch ), framesNeeded ); //CI_VERIFY( readSuccess ); if( ! readSuccess ) { LOG_XRUN( "[" << getContext()->getNumProcessedFrames() << "] buffer underrun. failed to read from ringbuffer, framesNeeded: " << framesNeeded << ", frames buffered: " << mImpl->mNumFramesBuffered << ", total captured: " << mImpl->mTotalFramesCaptured ); markUnderrun(); } } mImpl->mNumFramesBuffered -= framesNeeded; } } // ---------------------------------------------------------------------------------------------------- // ContextPortAudio // ---------------------------------------------------------------------------------------------------- // static void ContextPortAudio::setAsMaster() { Context::setMaster( new ContextPortAudio, new DeviceManagePortAudio ); } ContextPortAudio::ContextPortAudio() { PaError err = Pa_Initialize(); CI_ASSERT( err == paNoError ); } ContextPortAudio::~ContextPortAudio() { // uninit any device nodes before the portaudio context is destroyed for( auto& deviceNode : mDeviceNodes ) { auto node = deviceNode.lock(); if( node ) { node->disable(); uninitializeNode( node ); } } PaError err = Pa_Terminate(); CI_ASSERT( err == paNoError ); } OutputDeviceNodeRef ContextPortAudio::createOutputDeviceNode( const DeviceRef &device, const Node::Format &format ) { auto result = makeNode( new OutputDeviceNodePortAudio( device, format ) ); mDeviceNodes.push_back( result ); LOG_CI_PORTAUDIO( "created OutputDeviceNodePortAudio for device named '" << device->getName() << "'" ); return result; } InputDeviceNodeRef ContextPortAudio::createInputDeviceNode( const DeviceRef &device, const Node::Format &format ) { auto result = makeNode( new InputDeviceNodePortAudio( device, format ) ); mDeviceNodes.push_back( result ); LOG_CI_PORTAUDIO( "created InputDeviceNodePortAudio for device named '" << device->getName() << "'" ); return result; } // ---------------------------------------------------------------------------------------------------- // MARK: - ContextPortAudioExc // ---------------------------------------------------------------------------------------------------- ContextPortAudioExc::ContextPortAudioExc( const std::string &description ) : AudioExc( description ) { } ContextPortAudioExc::ContextPortAudioExc( const std::string &description, int err ) : AudioExc( "", err ) { stringstream ss; ss << description << " (PaError: " << err << ", '" << Pa_GetErrorText( err ) << "')"; setDescription( ss.str() ); } } } // namespace cinder::audio
38.132827
257
0.680384
PetrosKataras
a2b6603ee91237a08cc7279ac73d8222e709d86e
6,388
hpp
C++
ProjectMajestic/InGameUI.Impl.hpp
Edgaru089/ProjectMajestic
16cda6f86fd5ad02baedc9481609d6140cdda62a
[ "MIT" ]
1
2018-08-29T06:36:23.000Z
2018-08-29T06:36:23.000Z
ProjectMajestic/InGameUI.Impl.hpp
Edgaru089/ProjectMajestic
16cda6f86fd5ad02baedc9481609d6140cdda62a
[ "MIT" ]
null
null
null
ProjectMajestic/InGameUI.Impl.hpp
Edgaru089/ProjectMajestic
16cda6f86fd5ad02baedc9481609d6140cdda62a
[ "MIT" ]
null
null
null
#pragma once #include "InGameUI.hpp" #include "PlayerInventory.hpp" #include "ItemAllocator.hpp" #include "TextSystem.hpp" //////////////////////////////////////// InGameUIManager::~InGameUIManager() { } //////////////////////////////////////// void InGameUIManager::updateLogic() { AUTOLOCKABLE(*this); if (wantChange) { if (curUI != nullptr) curUI->_onClose(); curUI = wantChangeUI; if (curUI != nullptr) curUI->_onOpen(); wantChange = false; } if (curUI == nullptr) return; if (logicIO.keyboardState[Keyboard::Escape] == LogicIO::JustPressed || logicIO.keyboardState[Keyboard::E] == LogicIO::JustPressed) { curUI = nullptr; } } //////////////////////////////////////// void InGameUIManager::runImGui() { AUTOLOCKABLE(*this); if (curUI == nullptr) return; imgui::PushStyleColor(ImGuiCol_ModalWindowDarkening, Color(0, 0, 0, 128)); imgui::PushStyleColor(ImGuiCol_Button, Color::Transparent); imgui::PushStyleColor(ImGuiCol_ButtonHovered, Color(255, 255, 255, 64)); imgui::PushStyleColor(ImGuiCol_ButtonActive, Color(255, 255, 255, 48)); imgui::PushStyleColor(ImGuiCol_FrameBg, Color(0, 0, 0, 128)); imgui::PushStyleColor(ImGuiCol_PopupBg, Color(0, 0, 0, 128)); imgui::PushStyleColor(ImGuiCol_TitleBgActive, imgui::GetStyleColorVec4(ImGuiCol_PopupBg)); imgui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 2.0f); imgui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); GImGui->ModalWindowDarkeningRatio = 1.0f; ImGui::OpenPopup(curUI->windowTitle().c_str()); curUI->runImGui(); imgui::SetNextWindowPos( ImVec2(imgui::GetIO().DisplaySize.x / 2.0f, imgui::GetIO().DisplaySize.y / 2.0f), ImGuiCond_Always, ImVec2(0.5f, 0.5f)); if (curUI->showInventory()) { if (imgui::BeginPopupModal(curUI->windowTitle().c_str(), nullptr, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoMove)) { _runInventoryUI(); // Cursor item TextureInfo info = textureManager.getTextureInfo(playerInventory.slotCursor["item_name"].getDataString()); if (info.vaild) { ImVec2 pos = imgui::GetIO().MousePos; imgui::GetOverlayDrawList()->AddImage((ImTextureID)info.texture->getNativeHandle(), ImVec2(pos.x - 16, pos.y - 16), ImVec2(pos.x + 16, pos.y + 16), ImVec2(info.textureRect.left / (float)info.texture->getSize().x, info.textureRect.top / (float)info.texture->getSize().y), ImVec2((info.textureRect.left + info.textureRect.width) / (float)info.texture->getSize().x, ( info.textureRect.top + info.textureRect.height) / (float)info.texture->getSize().y)); pos.x -= 16 + 3 - 2; pos.y -= 16 + 3; if (playerInventory.slotCursor["count"].getDataInt() != 1) imgui::GetOverlayDrawList()->AddText(pos, ImU32(0xFFFFFFFF), StringParser::toString(playerInventory.slotCursor["count"].getDataInt()).c_str()); } imgui::EndPopup(); } } imgui::PopStyleColor(7); imgui::PopStyleVar(2); } //////////////////////////////////////// void InGameUIManager::_runInventoryUI() { imgui::PopStyleVar(); imgui::TextUnformatted("Inventory"); imgui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); // Player inventory slots for (int i = 1; i <= 3; i++) { for (int j = 0; j < 9; j++) { if (j != 0) imgui::SameLine(); PlayerInventoryUI::ImGuiInventorySlot(playerInventory.slots[i][j], 1677216 + i * 9 + j); } } imgui::Dummy(ImVec2(.0f, 6.0f)); for (int j = 0; j < 9; j++) { if (j != 0) imgui::SameLine(); PlayerInventoryUI::ImGuiInventorySlot(playerInventory.slots[0][j], 1677216 + j); } } //////////////////////////////////////// void PlayerInventoryUI::ImGuiInventorySlot(Dataset& slotData, int pushId) { Dataset& cursor = playerInventory.slotCursor; string& slotName = slotData["item_name"].getDataString(), &cursorName = cursor["item_name"].getDataString(); int& slotCount = slotData["count"].getDataInt(), &cursorCount = cursor["count"].getDataInt(); TextureInfo info = textureManager.getTextureInfo(slotData["item_name"].getDataString()); if (!info.vaild) info = textureManager.getTextureInfo("none"); shared_ptr<Item> item = nullptr; if (slotName.size() > 5) item = itemAllocator.allocate(slotName.substr(5), slotData); int maxItemsThisSlot = maxItemsPerSlot; if (item != nullptr) maxItemsThisSlot = item->getMaxItemsPerSlotCount(); if (pushId != -1) imgui::PushID(pushId); if (imgui::ImageButton(info.getSprite(), Vector2f(32, 32), 3)) { if (cursorName != slotName) swap(slotData, cursor); else { // Stack items int sum = slotCount + cursorCount; int slotCnt = sum; if (slotCnt > maxItemsThisSlot) slotCnt = maxItemsThisSlot; int curCnt = sum - slotCnt; slotCount = slotCnt; cursorCount = curCnt; if (curCnt == 0) cursorName = ""s; } } if (info.id != "none") { if (FloatRect(imgui::GetItemRectMin(), imgui::GetItemRectSize()).contains(Vector2f(logicIO.mousePos))) { if (logicIO.mouseState[Mouse::Right] == LogicIO::JustPressed) { if (cursorName == "") { // Spilt half int curCnt = slotCount / 2 + slotCount % 2; cursorName = slotName; cursorCount = curCnt; if (slotCount - curCnt == 0) slotName = ""s; slotCount = slotCount - curCnt; } else { // TODO Intentory gestures // Place one if (slotName == "" || slotName == cursorName) { slotName = cursorName; if (slotCount + 1 <= maxItemsThisSlot) { slotCount++; cursorCount--; if (cursorCount == 0) cursorName = ""; } } } } imgui::BeginTooltip(); imgui::TextUnformatted(text.get(slotName + ".name")); const string& desc = text.getstr(slotName + ".desc"); if (desc != "") { imgui::PushStyleColor(ImGuiCol_Text, Color(220, 220, 220)); imgui::TextUnformatted(desc.c_str()); imgui::PopStyleColor(); } imgui::PushStyleColor(ImGuiCol_Text, imgui::GetStyleColorVec4(ImGuiCol_TextDisabled)); imgui::Text(text.get("inventory.maxcount"), maxItemsThisSlot); imgui::PopStyleColor(); imgui::EndTooltip(); } if (slotCount != 1) { ImVec2 pos = imgui::GetItemRectMin(); pos.x += 2.0; imgui::GetCurrentWindow()->DrawList->AddText(pos, ImU32(0xFFFFFFFF), StringParser::toString(slotCount).c_str()); } } if (pushId != -1) imgui::PopID(); } //////////////////////////////////////// void PlayerInventoryUI::runImGui() { }
31.160976
148
0.650908
Edgaru089
a2b7d1fd2731c7f96b66c148874be87fcbfd9c02
1,683
hpp
C++
ql/experimental/basismodels/spreadyieldtermstructure.hpp
sschlenkrich/quantlib
ff39ad2cd03d06d185044976b2e26ce34dca470c
[ "BSD-3-Clause" ]
null
null
null
ql/experimental/basismodels/spreadyieldtermstructure.hpp
sschlenkrich/quantlib
ff39ad2cd03d06d185044976b2e26ce34dca470c
[ "BSD-3-Clause" ]
null
null
null
ql/experimental/basismodels/spreadyieldtermstructure.hpp
sschlenkrich/quantlib
ff39ad2cd03d06d185044976b2e26ce34dca470c
[ "BSD-3-Clause" ]
null
null
null
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2010 Sebastian Schlenkrich */ /*! \file spreadyieldtermstructure.hpp \brief compounded yield term structure evaluating exp{ - ( z1 + alpha z2 ) t } */ #ifndef quantlib_spreadyieldtermstructure_hpp #define quantlib_spreadyieldtermstructure_hpp #include <ql/handle.hpp> #include <ql/termstructures/yieldtermstructure.hpp> namespace QuantLib { class SpreadYTS : public YieldTermStructure { private: Handle<YieldTermStructure> baseCurve_; Handle<YieldTermStructure> sprdCurve_; Real alpha_; public : SpreadYTS( const Handle<YieldTermStructure>& baseCurve = Handle<YieldTermStructure>(), const Handle<YieldTermStructure>& sprdCurve = Handle<YieldTermStructure>(), const Real alpha = 1.0 ) : baseCurve_(baseCurve), sprdCurve_(sprdCurve), alpha_(alpha), YieldTermStructure(baseCurve->referenceDate(),baseCurve->calendar(),baseCurve->dayCounter()) { registerWith(baseCurve_); registerWith(sprdCurve_); } Date maxDate() const { return baseCurve_->maxDate(); }; protected : inline DiscountFactor discountImpl(Time t) const { if (alpha_ == 1.0) return baseCurve_->discount(t) * sprdCurve_->discount(t); if (alpha_ ==-1.0) return baseCurve_->discount(t) / sprdCurve_->discount(t); if (alpha_ == 0.0) return baseCurve_->discount(t); return baseCurve_->discount(t) * pow(sprdCurve_->discount(t),alpha_); } }; } #endif
35.0625
116
0.634581
sschlenkrich
a2b97fe5322a6bd5fc2616aa1ac2b0209abb9df5
2,621
cpp
C++
Pinjector/Adapters.cpp
vnagireddy-virsec/pinjectra
679339082a539c395b696b64587146139d6e3b7d
[ "BSD-3-Clause" ]
652
2019-08-08T18:39:26.000Z
2022-03-26T20:37:05.000Z
Pinjector/Adapters.cpp
TheWover/pinjectra
9167b78c46240f6ad331a08db3f5a51c62aadc3b
[ "BSD-3-Clause" ]
1
2020-01-19T07:39:40.000Z
2021-04-04T04:21:31.000Z
Pinjector/Adapters.cpp
TheWover/pinjectra
9167b78c46240f6ad331a08db3f5a51c62aadc3b
[ "BSD-3-Clause" ]
142
2019-08-08T18:39:32.000Z
2022-03-24T08:14:00.000Z
// Copyright (c) 2019, SafeBreach // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. // AUTHORS: Amit Klein, Itzik Kotler // SEE: https://github.com/SafeBreach-Labs/Pinjectra #include "WritingTechniques.h" ////////////////////////////////////////// // ComplexToAdvanceMemoryWriter Adapter // ////////////////////////////////////////// ComplexToMutableAdvanceMemoryWriter::~ComplexToMutableAdvanceMemoryWriter() { } PINJECTRA_PACKET* ComplexToMutableAdvanceMemoryWriter::eval_and_write(TARGET_PROCESS* target, TStrDWORD64Map& params) { PINJECTRA_PACKET* payload_output; RUNTIME_MEM_ENTRY* writer_output; // Evaulate Payload payload_output = this->m_payload->eval(params); // Update Writer this->m_writer->SetBuffer(payload_output->buffer); this->m_writer->SetBufferSize(payload_output->buffer_size); // Write! writer_output = this->m_writer->writeto(target->process, 0); // Hijack Payload Output free(payload_output->buffer); payload_output->buffer = writer_output->addr; payload_output->buffer_size = writer_output->tot_write; return payload_output; }
42.274194
120
0.733308
vnagireddy-virsec
a2ba1759ac856529404c1cd316530628141326bd
3,747
hpp
C++
types/YearMonthIntervalType.hpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
82
2016-04-18T03:59:06.000Z
2019-02-04T11:46:08.000Z
types/YearMonthIntervalType.hpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
265
2016-04-19T17:52:43.000Z
2018-10-11T17:55:08.000Z
types/YearMonthIntervalType.hpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
68
2016-04-18T05:00:34.000Z
2018-10-30T12:41:02.000Z
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 QUICKSTEP_TYPES_YEAR_MONTH_INTERVAL_TYPE_HPP_ #define QUICKSTEP_TYPES_YEAR_MONTH_INTERVAL_TYPE_HPP_ #include <cstddef> #include <cstdio> #include <string> #include "types/IntervalLit.hpp" #include "types/Type.hpp" #include "types/TypeID.hpp" #include "types/TypedValue.hpp" #include "utility/Macros.hpp" namespace quickstep { /** \addtogroup Types * @{ */ /** * @brief A type representing the year-month interval. **/ class YearMonthIntervalType : public Type { public: typedef YearMonthIntervalLit cpptype; static const TypeID kStaticTypeID = kYearMonthInterval; /** * @brief Get a reference to the non-nullable singleton instance of this * Type. * * @return A reference to the non-nullable singleton instance of this Type. **/ static const YearMonthIntervalType& InstanceNonNullable() { static YearMonthIntervalType instance(false); return instance; } /** * @brief Get a reference to the nullable singleton instance of this Type. * * @return A reference to the nullable singleton instance of this Type. **/ static const YearMonthIntervalType& InstanceNullable() { static YearMonthIntervalType instance(true); return instance; } /** * @brief Get a reference to a singleton instance of this Type. * * @param nullable Whether to get the nullable version of this Type. * @return A reference to the desired singleton instance of this Type. **/ static const YearMonthIntervalType& Instance(const bool nullable) { if (nullable) { return InstanceNullable(); } else { return InstanceNonNullable(); } } const Type& getNullableVersion() const override { return InstanceNullable(); } const Type& getNonNullableVersion() const override { return InstanceNonNullable(); } std::size_t estimateAverageByteLength() const override { return sizeof(YearMonthIntervalLit); } bool isCoercibleFrom(const Type &original_type) const override; bool isSafelyCoercibleFrom(const Type &original_type) const override; int getPrintWidth() const override { return YearMonthIntervalLit::kPrintingChars; } std::string printValueToString(const TypedValue &value) const override; void printValueToFile(const TypedValue &value, FILE *file, const int padding = 0) const override; TypedValue makeZeroValue() const override { return TypedValue(YearMonthIntervalLit{0}); } bool parseValueFromString(const std::string &value_string, TypedValue *value) const override; private: explicit YearMonthIntervalType(const bool nullable) : Type(Type::kOther, kYearMonthInterval, nullable, sizeof(YearMonthIntervalLit), sizeof(YearMonthIntervalLit)) { } DISALLOW_COPY_AND_ASSIGN(YearMonthIntervalType); }; /** @} */ } // namespace quickstep #endif // QUICKSTEP_TYPES_YEAR_MONTH_INTERVAL_TYPE_HPP_
29.046512
118
0.724313
Hacker0912
a2c2301445178d9404d920a40de47f590e9e203c
789
cpp
C++
LimeEngine/Engine/Graphics/Systems/DX11/MaterialDX11.cpp
RubyCircle/LimeEngine
06e3628f2aeb3ce023c1251a6379a26b2df2de4b
[ "MIT" ]
1
2022-01-04T19:25:46.000Z
2022-01-04T19:25:46.000Z
LimeEngine/Engine/Graphics/Systems/DX11/MaterialDX11.cpp
RubyCircle/LimeEngine
06e3628f2aeb3ce023c1251a6379a26b2df2de4b
[ "MIT" ]
null
null
null
LimeEngine/Engine/Graphics/Systems/DX11/MaterialDX11.cpp
RubyCircle/LimeEngine
06e3628f2aeb3ce023c1251a6379a26b2df2de4b
[ "MIT" ]
null
null
null
#include "MaterialDX11.hpp" #include "../../Base/Material.hpp" namespace LimeEngine { MaterialDX11::MaterialDX11(const RenderingSystemDX11& renderer, Material* material, VertexShader* vertexShader, PixelShader* pixelShader) noexcept : material(material), renderer(renderer), vertexShader(vertexShader), pixelShader(pixelShader) {} void MaterialDX11::ApplyMaterial() const noexcept { auto deviceContext = renderer.deviceContext.Get(); deviceContext->IASetInputLayout(vertexShader->GatInputLoyout()); deviceContext->VSSetShader(vertexShader->GetShader(), NULL, 0); deviceContext->PSSetShader(pixelShader->GetShader(), NULL, 0); for (auto& texture : material->GetTextures()) { deviceContext->PSSetShaderResources(0, 1, texture->renderTexture.GetViewAddress()); } } }
37.571429
149
0.768061
RubyCircle
a2c6a2e7fd4220d7abbb9ca496593ccf50e2ab2f
70
cpp
C++
test.cpp
farabimahmud/smart
d968ed5123363e9c05512b355c5d67360902d90f
[ "BSD-3-Clause" ]
null
null
null
test.cpp
farabimahmud/smart
d968ed5123363e9c05512b355c5d67360902d90f
[ "BSD-3-Clause" ]
null
null
null
test.cpp
farabimahmud/smart
d968ed5123363e9c05512b355c5d67360902d90f
[ "BSD-3-Clause" ]
null
null
null
#include <cstdio> int main(){ printf("nothing"); return 0; }
10
22
0.571429
farabimahmud
a2ca6a4e81b3c3e6a9603b9a6f7878478505a3df
1,908
cpp
C++
OnlineJudge/LeetCode/Easy/198.house-robber.cpp
yangfly/Interview-Notes
db9214456db8833c0a618b44bbb1c4f8d5b3209e
[ "MIT" ]
3
2019-02-19T07:23:30.000Z
2020-05-11T03:16:57.000Z
OnlineJudge/LeetCode/Easy/198.house-robber.cpp
yangfly/Interview-Notes
db9214456db8833c0a618b44bbb1c4f8d5b3209e
[ "MIT" ]
null
null
null
OnlineJudge/LeetCode/Easy/198.house-robber.cpp
yangfly/Interview-Notes
db9214456db8833c0a618b44bbb1c4f8d5b3209e
[ "MIT" ]
2
2019-02-19T07:23:33.000Z
2020-04-20T16:44:04.000Z
/* * [198] House Robber * * https://leetcode.com/problems/house-robber/description/ * * algorithms * Easy (39.88%) * Total Accepted: 188.4K * Total Submissions: 472.4K * Testcase Example: '[]' * * You are a professional robber planning to rob houses along a street. Each * house has a certain amount of money stashed, the only constraint stopping * you from robbing each of them is that adjacent houses have security system * connected and it will automatically contact the police if two adjacent * houses were broken into on the same night. * * Given a list of non-negative integers representing the amount of money of * each house, determine the maximum amount of money you can rob tonight * without alerting the police. * * Credits:Special thanks to @ifanchu for adding this problem and creating all * test cases. Also thanks to @ts for adding additional test cases. */ #include "common.h" // My Solution 4ms // 注意边界条件 static auto _________ = []() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); return nullptr; }(); class Solution { public: int rob(vector<int>& nums) { std::size_t size = nums.size(); if (size == 0) return 0; else if (size == 1) return nums[0]; vector<int> maxs(size); maxs[0] = nums[0]; maxs[1] = max(nums[0], nums[1]); for (std::size_t i = 2; i < size; i++) { maxs[i] = max(maxs[i-1], maxs[i-2] + nums[i]); } return maxs[size - 1]; } }; // A Simpler Solution class Solution { public: int rob(vector<int>& nums) { int a = 0, b = 0; for (std::size_t i = 0; i < nums.size(); i++) { // a, b 交替记录最大抢劫金额。(状态:抢/没抢) if (i % 2 == 0) a = max(a + nums[i], b); else b = max(b + nums[i], a); } return max(a, b); } };
28.058824
78
0.584906
yangfly
a2cab107c79d0b006e05fc346efd3493bbdfec31
946
cpp
C++
src/protocols/wl/shell.cpp
Link1J/Awning
4e35e092725d1688ac94f8473fb6bffd99a5cfa0
[ "MIT" ]
null
null
null
src/protocols/wl/shell.cpp
Link1J/Awning
4e35e092725d1688ac94f8473fb6bffd99a5cfa0
[ "MIT" ]
null
null
null
src/protocols/wl/shell.cpp
Link1J/Awning
4e35e092725d1688ac94f8473fb6bffd99a5cfa0
[ "MIT" ]
null
null
null
#include "shell.hpp" #include "shell_surface.hpp" #include <spdlog/spdlog.h> namespace Awning::Protocols::WL::Shell { const struct wl_shell_interface interface = { .get_shell_surface = Interface::Get_Shell_Surface }; namespace Interface { void Get_Shell_Surface(struct wl_client *client, struct wl_resource *resource, uint32_t id, struct wl_resource *surface) { Shell_Surface::Create(client, wl_resource_get_version(resource), id, surface); } } void Bind(struct wl_client* wl_client, void* data, uint32_t version, uint32_t id) { struct wl_resource* resource = wl_resource_create(wl_client, &wl_shell_interface, version, id); if (resource == nullptr) { wl_client_post_no_memory(wl_client); return; } wl_resource_set_implementation(resource, &interface, data, nullptr); } wl_global* Add(struct wl_display* display, void* data) { return wl_global_create(display, &wl_shell_interface, 1, data, Bind); } }
27.823529
122
0.751586
Link1J
a2cb03b5413944bdd6b0bc8553707a27a2565843
12,332
cpp
C++
FlipperPlugins/ApplicationSelector.cpp
nbclark/flipper
438e261c09f6e290eb043eb8bf9a64080e043cc9
[ "Apache-2.0" ]
null
null
null
FlipperPlugins/ApplicationSelector.cpp
nbclark/flipper
438e261c09f6e290eb043eb8bf9a64080e043cc9
[ "Apache-2.0" ]
null
null
null
FlipperPlugins/ApplicationSelector.cpp
nbclark/flipper
438e261c09f6e290eb043eb8bf9a64080e043cc9
[ "Apache-2.0" ]
null
null
null
#include "stdafx.h" #include <regext.h> #include <aygshell.h> #include <shellapi.h> #include <windows.h> #include <windowsx.h> #include <commctrl.h> #include <soundfile.h> #include <time.h> #include <notify.h> #include <atltime.h> #include <regext.h> #include <tlhelp32.h> #include "resource.h" #include "ApplicationSelector.h" #include "..\flipper\utils.h" #include "..\FlipperConfig\Anchor.h" HMODULE CApplicationSelector::g_hInstance = NULL; list<LVITEM*> CApplicationSelector::g_lvApplications; HIMAGELIST CApplicationSelector::g_hSmall = NULL; CApplicationSelector::CApplicationSelector(void) { Sleep(0); } CApplicationSelector::~CApplicationSelector(void) { Sleep(0); } bool CApplicationSelector::ShowDialog(HINSTANCE hInstance, HWND hwndParent, WCHAR* wzLnkLocation, bool bChooseProcess) { g_hInstance = hInstance; g_wzLnkLocation = wzLnkLocation; g_bChooseProcess = bChooseProcess; return IDOK == DialogBoxParamW(hInstance, MAKEINTRESOURCE(IDD_SELECTLINK_DIALOG), hwndParent, CApplicationSelector::SelectLaunchProc, (LPARAM)this); } void CApplicationSelector::GetLnkFiles(WCHAR* szPath, HIMAGELIST hSmall, list<LVITEM*>* plvItems, bool bReadOnly) { if (!plvItems && !bReadOnly) { return; } WCHAR szFilteredPath[MAX_PATH]; wcscpy(szFilteredPath, szPath); wcscat(szFilteredPath, L"*"); WIN32_FIND_DATAW data; HANDLE hFile = FindFirstFile(szFilteredPath, &data); do { if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { // recurse WCHAR szNewPath[MAX_PATH]; wcscpy(szNewPath, szPath); wcscat(szNewPath, data.cFileName); wcscat(szNewPath, L"\\"); GetLnkFiles(szNewPath, hSmall, plvItems, bReadOnly); } else { WCHAR* wzExt = wcsrchr(data.cFileName, L'.'); if (wzExt && 0 == wcsicmp(wzExt, L".lnk") && 0 != wcsicmp(data.cFileName, L"icon.lnk")) { if (!bReadOnly) { wcscpy(szFilteredPath, szPath); wcscat(szFilteredPath, data.cFileName); LVITEM* plvItem = new LVITEM(); memset(plvItem, 0, sizeof(LVITEM)); plvItem->mask = LVIF_TEXT | LVIF_IMAGE | LVIF_STATE | LVIF_PARAM; plvItem->state = 0; plvItem->stateMask = 0; plvItems->push_back(plvItem); HICON hIcon = GetApplicationIcon(szFilteredPath, true, NULL, NULL, NULL); if (hIcon) { int iIndex = ImageList_ReplaceIcon(hSmall, -1, hIcon); plvItem->iImage = iIndex; DestroyIcon(hIcon); } else { plvItem->iImage = 0; } int iLen = wcslen(data.cFileName)+1; plvItem->pszText = new WCHAR[iLen]; wcscpy(plvItem->pszText, data.cFileName); plvItem->cchTextMax = iLen; WCHAR* wzExt = wcschr(plvItem->pszText, L'.'); if (wzExt) { wzExt[0] = 0; } iLen = wcslen(szFilteredPath)+1; plvItem->lParam = (LPARAM)new WCHAR[iLen]; wcscpy((WCHAR*)plvItem->lParam, szFilteredPath); } } } } while (FindNextFile(hFile, &data)); } int CALLBACK CApplicationSelector::ListViewCompareProc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort) { WCHAR* wzItem1 = (WCHAR*)lParam1; WCHAR* wzItem2 = (WCHAR*)lParam2; WCHAR* wzName1 = wcsrchr(wzItem1, L'\\'); WCHAR* wzName2 = wcsrchr(wzItem2, L'\\'); return (wcsicmp(wzName1, wzName2)); } BOOL CALLBACK CApplicationSelector::SelectLaunchProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam) { HWND hwndList; static HWND hWndMenu = NULL; static WCHAR* wzLnkLocation = NULL; static CApplicationSelector* p_this = NULL; static CDlgAnchor g_dlgAnchor; switch (message) { case WM_SIZE : { g_dlgAnchor.OnSize(); } break; case WM_INITDIALOG: { hwndList = GetDlgItem(hwndDlg, IDC_LIST_LINK); p_this = (CApplicationSelector*)lParam; wzLnkLocation = p_this->g_wzLnkLocation; RECT rect, rectText; GetClientRect(hwndDlg, &rect); GetWindowRect(GetDlgItem(hwndDlg, IDC_EDIT_LINK), &rectText); if (p_this->g_bChooseProcess) { MoveWindow(GetDlgItem(hwndDlg, IDC_EDIT_LINK), rect.left + 5, rect.top + 5, (rect.right - rect.left) - 10, (rectText.bottom - rectText.top), TRUE); MoveWindow(hwndList, rect.left + 5, rect.top + 10 + (rectText.bottom - rectText.top), (rect.right - rect.left) - 10, (rect.bottom - rect.top) - 15 - (rectText.bottom - rectText.top), TRUE); } else { ShowWindow(GetDlgItem(hwndDlg, IDC_EDIT_LINK), SW_HIDE); MoveWindow(hwndList, rect.left + 5, rect.top + 5, (rect.right - rect.left) - 10, (rect.bottom - rect.top) - 10, TRUE); } g_dlgAnchor.Init(hwndDlg); g_dlgAnchor.Add(IDC_LIST_LINK, ANCHOR_ALL); g_dlgAnchor.Add(IDC_EDIT_LINK, ANCHOR_ALL & ~ANCHOR_BOTTOM); SHMENUBARINFO mbi; memset(&mbi, 0, sizeof(SHMENUBARINFO)); mbi.cbSize = sizeof(SHMENUBARINFO); mbi.hwndParent = hwndDlg; mbi.nToolBarId = IDR_Flipper_SET_MENUBAR; mbi.hInstRes = CApplicationSelector::g_hInstance; mbi.nBmpId = 0; mbi.cBmpImages = 0; if (FALSE == SHCreateMenuBar(&mbi)) { MessageBox(hwndDlg, L"SHCreateMenuBar Failed", L"Error", MB_OK); } hWndMenu = mbi.hwndMB; SHINITDLGINFO shidi; // Create a Done button and size it. shidi.dwMask = SHIDIM_FLAGS; shidi.dwFlags = SHIDIF_DONEBUTTON | SHIDIF_SIPDOWN | SHIDIF_SIZEDLGFULLSCREEN; shidi.hDlg = hwndDlg; SHInitDialog(&shidi); LV_COLUMN lvC; lvC.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM; lvC.fmt = LVCFMT_LEFT; // left-align column lvC.cx = 400; // width of column in pixels lvC.pszText = L"File"; //0x00A00000 | SetWindowLong(hwndList, GWL_STYLE, WS_BORDER | WS_VSCROLL | LVS_NOCOLUMNHEADER | LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_SHAREIMAGELISTS); SetWindowLong(hwndList, GWL_EXSTYLE, LVS_EX_NOHSCROLL | LVS_EX_FULLROWSELECT | LVS_EX_CHECKBOXES | LVS_EX_GRIDLINES); if (NULL == CApplicationSelector::g_hSmall) { int iconSize = GetSystemMetrics(SM_CXSMICON); CApplicationSelector::g_hSmall = ImageList_Create(iconSize, iconSize, ILC_COLOR, 0, 32); ImageList_SetBkColor(CApplicationSelector::g_hSmall, RGB(0xFF, 0xFF, 0xFF)); HICON hIcon = LoadIconW(CApplicationSelector::g_hInstance, MAKEINTRESOURCE(IDI_ICON1)); DRA::ImageList_AddIcon(CApplicationSelector::g_hSmall, hIcon); DestroyIcon(hIcon); int dwApplications = 0; TCHAR szStartMenu[MAX_PATH]; if (SHGetSpecialFolderPath(NULL, szStartMenu, CSIDL_STARTMENU, FALSE)) { wcscat(szStartMenu, L"\\"); } else { wcscpy(szStartMenu, L"\\windows\\start menu\\"); } GetLnkFiles(szStartMenu, CApplicationSelector::g_hSmall, &(CApplicationSelector::g_lvApplications), false); } ListView_InsertColumn(hwndList, 0, &lvC); ListView_SetImageList(hwndList, CApplicationSelector::g_hSmall, LVSIL_SMALL); int iIndex = 0; for (list<LVITEM*>::iterator iter = CApplicationSelector::g_lvApplications.begin(); iter != CApplicationSelector::g_lvApplications.end(); ++iter) { LVITEM* pItem = (*iter); // Always append to the end pItem->iItem = iIndex++; iIndex = ListView_InsertItem(hwndList, pItem); if (wzLnkLocation && 0 == wcsicmp((WCHAR*)pItem->lParam, wzLnkLocation)) { ListView_SetItemState(hwndList, iIndex, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED) ListView_SetSelectionMark(hwndList, iIndex); } } ListView_SortItems(hwndList, ListViewCompareProc, 0); int iSelIndex = ListView_GetSelectionMark(hwndList); ListView_EnsureVisible(hwndList, iSelIndex, FALSE); SetCursor(NULL); return 0; } break; case WM_NOTIFY : { hwndList = GetDlgItem(hwndDlg, IDC_LIST_LINK); NMHDR * pnmh = (NMHDR *)lParam; switch (pnmh->code) { case NM_SETFOCUS : { int iItem = ListView_GetSelectionMark(hwndList); SetFocus(hwndList); SetActiveWindow(hwndList); } break; case LVN_ITEMCHANGED : { LPNMLISTVIEW pnmv = (LPNMLISTVIEW) lParam; if (pnmv->uNewState & LVIS_SELECTED) { WCHAR* wzSlash = NULL; if (p_this->g_bChooseProcess) { WCHAR wzExe[MAX_PATH]; SHGetShortcutTarget((WCHAR*)pnmv->lParam, wzExe, ARRAYSIZE(wzExe)); WCHAR* wzReturn = wcschr(wzExe, L'\r'); if (wzReturn) { wzReturn[0] = '\0'; } while (wzExe[0] == L':') { WCHAR* wzSpace = wcschr(wzExe, L' '); if (wzSpace) { wzSpace[0] = L'\0'; } HKEY hKey = NULL; if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Shell\\Rai", 0, KEY_READ, &hKey)) { bool bSuccess = false; if (ERROR_SUCCESS == RegistryGetString(hKey, wzExe, L"1", wzExe, ARRAYSIZE(wzExe))) { bSuccess = true; } RegCloseKey(hKey); if (!bSuccess) { break; } } } wzSlash = wcsrchr(wzExe, L'\\'); if (!wzSlash) { wzSlash = wzExe; } WCHAR* wzDelim = wcschr(wzSlash, L' '); if (wzDelim) { wzDelim[0] = L'\0'; } wzDelim = wcschr(wzSlash, L','); if (wzDelim) { wzDelim[0] = L'\0'; } } else { WCHAR wzExe[MAX_PATH]; StringCchCopy(wzExe, ARRAYSIZE(wzExe), (WCHAR*)pnmv->lParam); wzSlash = wzExe; } SetDlgItemTextW(hwndDlg, IDC_EDIT_LINK, wzSlash); } } break; } Sleep(0); } break; case WM_COMMAND: switch (LOWORD(wParam)) { case IDOK: { EndDialog(hwndDlg, IDOK); } break; case IDM_Flipper_SET_ACCEPT: { EndDialog(hwndDlg, IDOK); } break; case IDM_Flipper_SET_CANCEL: { EndDialog(hwndDlg, IDCANCEL); } break; } break; case WM_DESTROY: { //g_dlgAnchor.RemoveAll(); GetDlgItemText(hwndDlg, IDC_EDIT_LINK, wzLnkLocation, MAX_PATH); if (hWndMenu) { DestroyWindow(hWndMenu); hWndMenu = NULL; } } break; } return DefWindowProcW(hwndDlg, message, wParam, lParam); }
32.282723
194
0.533977
nbclark
a2d3c6f65d83066c256798101c9b513b054d5f65
1,857
cpp
C++
sources/enduro2d/high/systems/touch_system.cpp
NechukhrinN/enduro2d
774f120395885a6f0f21418c4de024e7668ee436
[ "MIT" ]
null
null
null
sources/enduro2d/high/systems/touch_system.cpp
NechukhrinN/enduro2d
774f120395885a6f0f21418c4de024e7668ee436
[ "MIT" ]
null
null
null
sources/enduro2d/high/systems/touch_system.cpp
NechukhrinN/enduro2d
774f120395885a6f0f21418c4de024e7668ee436
[ "MIT" ]
null
null
null
/******************************************************************************* * This file is part of the "Enduro2D" * For conditions of distribution and use, see copyright notice in LICENSE.md * Copyright (C) 2018-2020, by Matvey Cherevko (blackmatov@gmail.com) ******************************************************************************/ #include <enduro2d/high/systems/touch_system.hpp> #include "touch_system_impl/touch_system_base.hpp" #include "touch_system_impl/touch_system_colliders.hpp" #include "touch_system_impl/touch_system_dispatcher.hpp" namespace { using namespace e2d; using namespace e2d::touch_system_impl; } namespace e2d { // // touch_system::internal_state // class touch_system::internal_state final : private noncopyable { public: internal_state(input& i, window& w) : input_(i) , window_(w) , dispatcher_(window_.register_event_listener<dispatcher>()) {} ~internal_state() noexcept { window_.unregister_event_listener(dispatcher_); } void process_update(ecs::registry& owner) { update_world_space_colliders(owner); update_world_space_colliders_under_mouse(input_, window_, owner); dispatcher_.dispatch_all_events(owner); } private: input& input_; window& window_; dispatcher& dispatcher_; }; // // touch_system // touch_system::touch_system() : state_(new internal_state(the<input>(), the<window>())) {} touch_system::~touch_system() noexcept = default; void touch_system::process( ecs::registry& owner, const ecs::before<systems::update_event>& trigger) { E2D_UNUSED(trigger); E2D_PROFILER_SCOPE("touch_system.process_update"); state_->process_update(owner); } }
29.015625
80
0.610124
NechukhrinN
a2e1bddd2b65aa72a0a4ef172c8297a2f36e6dc4
730
cpp
C++
topic_wise/binarysearch/firstBadVersion.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
1
2021-01-27T16:37:36.000Z
2021-01-27T16:37:36.000Z
topic_wise/binarysearch/firstBadVersion.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
null
null
null
topic_wise/binarysearch/firstBadVersion.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
null
null
null
/** * @author : archit * @GitHub : archit-1997 * @Email : architsingh456@gmail.com * @file : firstBadVersion.cpp * @created : Saturday Aug 28, 2021 22:33:57 IST */ #include <bits/stdc++.h> using namespace std; // The API isBadVersion is defined for you. // bool isBadVersion(int version); class Solution { public: int find(int l,int r){ int ans=INT_MAX; while(l<=r){ int mid=l+(r-l)/2; if(isBadVersion(mid)){ ans=min(ans,mid); r=mid-1; } else l=mid+1; } return ans; } int firstBadVersion(int n) { return find(1,n); } };
20.277778
52
0.482192
archit-1997
a2e1f1a9b078f89c9e9f5b156101bb41d9bd4b6c
300
cpp
C++
node_modules/lzz-gyp/lzz-source/smtc_CreateFuncDeclEntity.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
3
2019-09-18T16:44:33.000Z
2021-03-29T13:45:27.000Z
node_modules/lzz-gyp/lzz-source/smtc_CreateFuncDeclEntity.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
null
null
null
node_modules/lzz-gyp/lzz-source/smtc_CreateFuncDeclEntity.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
2
2019-03-29T01:06:38.000Z
2019-09-18T16:44:34.000Z
// smtc_CreateFuncDeclEntity.cpp // #include "smtc_CreateFuncDeclEntity.h" // semantic #include "smtc_FuncDeclEntity.h" #define LZZ_INLINE inline namespace smtc { EntityPtr createFuncDeclEntity (FuncDeclPtr const & func_decl) { return new FuncDeclEntity (func_decl); } } #undef LZZ_INLINE
18.75
64
0.773333
SuperDizor
a2e22934ab085311704419745e7ef118821fb5e5
2,132
cpp
C++
test/test_Configuration.cpp
tidewise/drivers-imu_aceinna_openimu
5808bec84c7d6d65f760be8de3bd9735426f0cd2
[ "Unlicense" ]
null
null
null
test/test_Configuration.cpp
tidewise/drivers-imu_aceinna_openimu
5808bec84c7d6d65f760be8de3bd9735426f0cd2
[ "Unlicense" ]
1
2019-08-09T02:59:48.000Z
2019-08-09T17:31:23.000Z
test/test_Configuration.cpp
tidewise/drivers-imu_aceinna_openimu
5808bec84c7d6d65f760be8de3bd9735426f0cd2
[ "Unlicense" ]
null
null
null
#include <gtest/gtest.h> #include <imu_aceinna_openimu/Configuration.hpp> using namespace imu_aceinna_openimu; struct ConfigurationOrientationTest : public ::testing::Test { }; TEST_F(ConfigurationOrientationTest, it_is_equal_if_all_three_fields_are) { Configuration::Orientation conf0( ORIENTATION_AXIS_PLUS_X, ORIENTATION_AXIS_PLUS_Y, ORIENTATION_AXIS_PLUS_Z); Configuration::Orientation conf1( ORIENTATION_AXIS_PLUS_X, ORIENTATION_AXIS_PLUS_Y, ORIENTATION_AXIS_PLUS_Z); ASSERT_EQ(conf0, conf1); ASSERT_TRUE(!(conf0 != conf1)); } TEST_F(ConfigurationOrientationTest, it_is_not_equal_if_forward_differs) { Configuration::Orientation conf0( ORIENTATION_AXIS_PLUS_X, ORIENTATION_AXIS_PLUS_Y, ORIENTATION_AXIS_PLUS_Z); Configuration::Orientation conf1( ORIENTATION_AXIS_PLUS_Y, ORIENTATION_AXIS_PLUS_Y, ORIENTATION_AXIS_PLUS_Z); ASSERT_NE(conf0, conf1); ASSERT_TRUE(conf0 != conf1); } TEST_F(ConfigurationOrientationTest, it_is_not_equal_if_right_differs) { Configuration::Orientation conf0( ORIENTATION_AXIS_PLUS_X, ORIENTATION_AXIS_PLUS_Y, ORIENTATION_AXIS_PLUS_Z); Configuration::Orientation conf1( ORIENTATION_AXIS_PLUS_X, ORIENTATION_AXIS_PLUS_X, ORIENTATION_AXIS_PLUS_Z); ASSERT_NE(conf0, conf1); ASSERT_TRUE(conf0 != conf1); } TEST_F(ConfigurationOrientationTest, it_is_not_equal_if_down_differs) { Configuration::Orientation conf0( ORIENTATION_AXIS_PLUS_X, ORIENTATION_AXIS_PLUS_Y, ORIENTATION_AXIS_PLUS_Z); Configuration::Orientation conf1( ORIENTATION_AXIS_PLUS_X, ORIENTATION_AXIS_PLUS_Y, ORIENTATION_AXIS_PLUS_Y); ASSERT_NE(conf0, conf1); ASSERT_TRUE(conf0 != conf1); } TEST_F(ConfigurationOrientationTest, it_formats_itself_to_string) { Configuration::Orientation confplus( ORIENTATION_AXIS_PLUS_X, ORIENTATION_AXIS_PLUS_Y, ORIENTATION_AXIS_PLUS_Z); ASSERT_EQ("+X+Y+Z", to_string(confplus)); Configuration::Orientation confminus( ORIENTATION_AXIS_MINUS_X, ORIENTATION_AXIS_MINUS_Y, ORIENTATION_AXIS_MINUS_Z); ASSERT_EQ("-X-Y-Z", to_string(confminus)); }
40.226415
86
0.788931
tidewise
a2e23fc92af129b91af7b2db1b12e6edd890221f
1,202
hpp
C++
include/opengl/buffer.hpp
bjadamson/BoomHS
60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4
[ "MIT" ]
2
2016-07-22T10:09:21.000Z
2017-09-16T06:50:01.000Z
include/opengl/buffer.hpp
bjadamson/BoomHS
60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4
[ "MIT" ]
14
2016-08-13T22:45:56.000Z
2018-12-16T03:56:36.000Z
include/opengl/buffer.hpp
bjadamson/BoomHS
60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4
[ "MIT" ]
null
null
null
#pragma once #include <boomhs/color.hpp> #include <boomhs/obj.hpp> #include <string> namespace opengl { class VertexAttribute; struct BufferFlags { bool const vertices, normals, colors, uvs; explicit constexpr BufferFlags(bool const v, bool const n, bool const c, bool const u) : vertices(v) , normals(n) , colors(c) , uvs(u) { } std::string to_string() const; static BufferFlags from_va(VertexAttribute const&); }; bool operator==(BufferFlags const&, BufferFlags const&); bool operator!=(BufferFlags const&, BufferFlags const&); std::ostream& operator<<(std::ostream&, BufferFlags const&); struct VertexBuffer { boomhs::ObjVertices vertices; boomhs::ObjIndices indices; BufferFlags const flags; private: VertexBuffer(BufferFlags const&); COPY_CONSTRUCTIBLE(VertexBuffer); NO_COPY_ASSIGN(VertexBuffer); public: MOVE_CONSTRUCTIBLE(VertexBuffer); NO_MOVE_ASSIGN(VertexBuffer); std::string to_string() const; // Public copy method VertexBuffer copy() const; void set_colors(boomhs::Color const&); static VertexBuffer create_interleaved(common::Logger&, boomhs::ObjData const&, BufferFlags const&); }; } // namespace opengl
19.387097
88
0.723794
bjadamson
a2e5838ac27e04590e5709269453e58debfd02ea
8,706
hpp
C++
include/codegen/include/RootMotion/FinalIK/IKSolverVR_Leg.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/RootMotion/FinalIK/IKSolverVR_Leg.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/RootMotion/FinalIK/IKSolverVR_Leg.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:09:17 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: RootMotion.FinalIK.IKSolverVR/BodyPart #include "RootMotion/FinalIK/IKSolverVR_BodyPart.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: Transform class Transform; // Forward declaring type: AnimationCurve class AnimationCurve; } // Completed forward declares // Type namespace: RootMotion.FinalIK namespace RootMotion::FinalIK { // Autogenerated type: RootMotion.FinalIK.IKSolverVR/Leg class IKSolverVR::Leg : public RootMotion::FinalIK::IKSolverVR::BodyPart { public: // public UnityEngine.Transform target // Offset: 0x48 UnityEngine::Transform* target; // public UnityEngine.Transform bendGoal // Offset: 0x50 UnityEngine::Transform* bendGoal; // public System.Single positionWeight // Offset: 0x58 float positionWeight; // public System.Single rotationWeight // Offset: 0x5C float rotationWeight; // public System.Single bendGoalWeight // Offset: 0x60 float bendGoalWeight; // public System.Single swivelOffset // Offset: 0x64 float swivelOffset; // public System.Single bendToTargetWeight // Offset: 0x68 float bendToTargetWeight; // public System.Single legLengthMlp // Offset: 0x6C float legLengthMlp; // public UnityEngine.AnimationCurve stretchCurve // Offset: 0x70 UnityEngine::AnimationCurve* stretchCurve; // public UnityEngine.Vector3 IKPosition // Offset: 0x78 UnityEngine::Vector3 IKPosition; // public UnityEngine.Quaternion IKRotation // Offset: 0x84 UnityEngine::Quaternion IKRotation; // public UnityEngine.Vector3 footPositionOffset // Offset: 0x94 UnityEngine::Vector3 footPositionOffset; // public UnityEngine.Vector3 heelPositionOffset // Offset: 0xA0 UnityEngine::Vector3 heelPositionOffset; // public UnityEngine.Quaternion footRotationOffset // Offset: 0xAC UnityEngine::Quaternion footRotationOffset; // public System.Single currentMag // Offset: 0xBC float currentMag; // public System.Boolean useAnimatedBendNormal // Offset: 0xC0 bool useAnimatedBendNormal; // private UnityEngine.Vector3 <position>k__BackingField // Offset: 0xC4 UnityEngine::Vector3 position; // private UnityEngine.Quaternion <rotation>k__BackingField // Offset: 0xD0 UnityEngine::Quaternion rotation; // private System.Boolean <hasToes>k__BackingField // Offset: 0xE0 bool hasToes; // private UnityEngine.Vector3 <thighRelativeToPelvis>k__BackingField // Offset: 0xE4 UnityEngine::Vector3 thighRelativeToPelvis; // private UnityEngine.Vector3 footPosition // Offset: 0xF0 UnityEngine::Vector3 footPosition; // private UnityEngine.Quaternion footRotation // Offset: 0xFC UnityEngine::Quaternion footRotation; // private UnityEngine.Vector3 bendNormal // Offset: 0x10C UnityEngine::Vector3 bendNormal; // private UnityEngine.Quaternion calfRelToThigh // Offset: 0x118 UnityEngine::Quaternion calfRelToThigh; // private UnityEngine.Quaternion thighRelToFoot // Offset: 0x128 UnityEngine::Quaternion thighRelToFoot; // private UnityEngine.Vector3 bendNormalRelToPelvis // Offset: 0x138 UnityEngine::Vector3 bendNormalRelToPelvis; // private UnityEngine.Vector3 bendNormalRelToTarget // Offset: 0x144 UnityEngine::Vector3 bendNormalRelToTarget; // public UnityEngine.Vector3 get_position() // Offset: 0x1428834 UnityEngine::Vector3 get_position(); // private System.Void set_position(UnityEngine.Vector3 value) // Offset: 0x1428840 void set_position(UnityEngine::Vector3 value); // public UnityEngine.Quaternion get_rotation() // Offset: 0x142884C UnityEngine::Quaternion get_rotation(); // private System.Void set_rotation(UnityEngine.Quaternion value) // Offset: 0x1428858 void set_rotation(UnityEngine::Quaternion value); // public System.Boolean get_hasToes() // Offset: 0x1428864 bool get_hasToes(); // private System.Void set_hasToes(System.Boolean value) // Offset: 0x142886C void set_hasToes(bool value); // public RootMotion.FinalIK.IKSolverVR/VirtualBone get_thigh() // Offset: 0x1428878 RootMotion::FinalIK::IKSolverVR::VirtualBone* get_thigh(); // private RootMotion.FinalIK.IKSolverVR/VirtualBone get_calf() // Offset: 0x14288AC RootMotion::FinalIK::IKSolverVR::VirtualBone* get_calf(); // private RootMotion.FinalIK.IKSolverVR/VirtualBone get_foot() // Offset: 0x14288E4 RootMotion::FinalIK::IKSolverVR::VirtualBone* get_foot(); // private RootMotion.FinalIK.IKSolverVR/VirtualBone get_toes() // Offset: 0x142891C RootMotion::FinalIK::IKSolverVR::VirtualBone* get_toes(); // public RootMotion.FinalIK.IKSolverVR/VirtualBone get_lastBone() // Offset: 0x1428954 RootMotion::FinalIK::IKSolverVR::VirtualBone* get_lastBone(); // public UnityEngine.Vector3 get_thighRelativeToPelvis() // Offset: 0x1428994 UnityEngine::Vector3 get_thighRelativeToPelvis(); // private System.Void set_thighRelativeToPelvis(UnityEngine.Vector3 value) // Offset: 0x14289A0 void set_thighRelativeToPelvis(UnityEngine::Vector3 value); // private System.Void ApplyPositionOffset(UnityEngine.Vector3 offset, System.Single weight) // Offset: 0x1429798 void ApplyPositionOffset(UnityEngine::Vector3 offset, float weight); // private System.Void ApplyRotationOffset(UnityEngine.Quaternion offset, System.Single weight) // Offset: 0x1429560 void ApplyRotationOffset(UnityEngine::Quaternion offset, float weight); // public System.Void Solve(System.Boolean stretch) // Offset: 0x1429E54 void Solve(bool stretch); // private System.Void FixTwistRotations() // Offset: 0x142A5A0 void FixTwistRotations(); // private System.Void Stretching() // Offset: 0x142A074 void Stretching(); // protected override System.Void OnRead(UnityEngine.Vector3[] positions, UnityEngine.Quaternion[] rotations, System.Boolean hasChest, System.Boolean hasNeck, System.Boolean hasShoulders, System.Boolean hasToes, System.Boolean hasLegs, System.Int32 rootIndex, System.Int32 index) // Offset: 0x14289AC // Implemented from: RootMotion.FinalIK.IKSolverVR/BodyPart // Base method: System.Void BodyPart::OnRead(UnityEngine.Vector3[] positions, UnityEngine.Quaternion[] rotations, System.Boolean hasChest, System.Boolean hasNeck, System.Boolean hasShoulders, System.Boolean hasToes, System.Boolean hasLegs, System.Int32 rootIndex, System.Int32 index) void OnRead(::Array<UnityEngine::Vector3>* positions, ::Array<UnityEngine::Quaternion>* rotations, bool hasChest, bool hasNeck, bool hasShoulders, bool hasToes, bool hasLegs, int rootIndex, int index); // public override System.Void PreSolve() // Offset: 0x1428FB4 // Implemented from: RootMotion.FinalIK.IKSolverVR/BodyPart // Base method: System.Void BodyPart::PreSolve() void PreSolve(); // public override System.Void ApplyOffsets() // Offset: 0x142989C // Implemented from: RootMotion.FinalIK.IKSolverVR/BodyPart // Base method: System.Void BodyPart::ApplyOffsets() void ApplyOffsets(); // public override System.Void Write(UnityEngine.Vector3[] solvedPositions, UnityEngine.Quaternion[] solvedRotations) // Offset: 0x142AA08 // Implemented from: RootMotion.FinalIK.IKSolverVR/BodyPart // Base method: System.Void BodyPart::Write(UnityEngine.Vector3[] solvedPositions, UnityEngine.Quaternion[] solvedRotations) void Write(::Array<UnityEngine::Vector3>*& solvedPositions, ::Array<UnityEngine::Quaternion>*& solvedRotations); // public override System.Void ResetOffsets() // Offset: 0x142AC24 // Implemented from: RootMotion.FinalIK.IKSolverVR/BodyPart // Base method: System.Void BodyPart::ResetOffsets() void ResetOffsets(); // public System.Void .ctor() // Offset: 0x142ACD4 // Implemented from: RootMotion.FinalIK.IKSolverVR/BodyPart // Base method: System.Void BodyPart::.ctor() // Base method: System.Void Object::.ctor() static IKSolverVR::Leg* New_ctor(); }; // RootMotion.FinalIK.IKSolverVR/Leg } DEFINE_IL2CPP_ARG_TYPE(RootMotion::FinalIK::IKSolverVR::Leg*, "RootMotion.FinalIK", "IKSolverVR/Leg"); #pragma pack(pop)
44.418367
287
0.732024
Futuremappermydud
a2eb7a599d345bfcd08c48068c0292fc897ea87f
2,523
hpp
C++
impl/jamtemplate/common/tilemap.hpp
runvs/Gemga
91cd5d6d60ae8369a5a5674efebc6eb84c510a10
[ "CC0-1.0" ]
null
null
null
impl/jamtemplate/common/tilemap.hpp
runvs/Gemga
91cd5d6d60ae8369a5a5674efebc6eb84c510a10
[ "CC0-1.0" ]
null
null
null
impl/jamtemplate/common/tilemap.hpp
runvs/Gemga
91cd5d6d60ae8369a5a5674efebc6eb84c510a10
[ "CC0-1.0" ]
null
null
null
#ifndef GUARD_JAMTEMPLATE_TILEMAP_HPP_GUARD #define GUARD_JAMTEMPLATE_TILEMAP_HPP_GUARD #include "drawable_impl.hpp" #include "info_rect.hpp" #include "render_target.hpp" #include "sprite.hpp" #include "tileson.h" #include <memory> #include <vector> namespace jt { // forward declaration class GameInterface; class Tilemap : public DrawableImpl { public: using Sptr = std::shared_ptr<Tilemap>; /// Constructor /// \param path path to the tilemap file explicit Tilemap(std::string const& path); /// Get map size in Tiles /// \return map size in tiles jt::Vector2u getMapSizeInTiles(); void doDraw(std::shared_ptr<jt::renderTarget> sptr) const override; void doDrawFlash(std::shared_ptr<jt::renderTarget> sptr) const override; void doDrawShadow(std::shared_ptr<jt::renderTarget> sptr) const override; void doUpdate(float elapsed) override; void setColor(jt::Color const& col) override; jt::Color getColor() const override; void setPosition(jt::Vector2 const& pos) override; jt::Vector2 getPosition() const override; jt::Rect getGlobalBounds() const override; jt::Rect getLocalBounds() const override; void setFlashColor(jt::Color const& col) override; jt::Color getFlashColor() const override; void setScale(jt::Vector2 const& scale) override; jt::Vector2 getScale() const override; void setOrigin(jt::Vector2 const& origin) override; jt::Vector2 getOrigin() const override; void doRotate(float /*rot*/) override; void setScreenSizeHint(jt::Vector2 const& hint); /// get Object Groups from map /// \return the object group std::map<std::string, std::vector<InfoRect>> getObjectGroups() { return m_objectGroups; }; private: std::unique_ptr<tson::Map> m_map { nullptr }; // Map from object layer name to vector of objects, all rectangular. std::map<std::string, std::vector<InfoRect>> m_objectGroups {}; mutable std::vector<jt::Sprite> m_tileSprites {}; Vector2 m_position { 0.0f, 0.0f }; Vector2 m_origin { 0.0f, 0.0f }; Vector2 m_screenSizeHint { 0.0f, 0.0f }; Vector2 m_scale { 1.0f, 1.0f }; Color m_color { jt::colors::White }; Color m_flashColor { jt::colors::White }; void checkIdBounds(tson::TileObject& tile) const; void drawSingleTileLayer(std::shared_ptr<jt::renderTarget> const& rt, Vector2 const& posOffset, tson::Layer& layer) const; void parseObjects(); }; } // namespace jt #endif // !JAMTEMPLATE_TILEMAP_HPP_GUARD
29.682353
99
0.702338
runvs
a2eba887673c001351e50a16c9bdbb0489ca26c0
1,027
cpp
C++
C++/Clase 6/Clase6.2.cpp
Rofernweh/UDPpl
da448091396b3f567f83e2964e8db97f6b8382bc
[ "MIT" ]
null
null
null
C++/Clase 6/Clase6.2.cpp
Rofernweh/UDPpl
da448091396b3f567f83e2964e8db97f6b8382bc
[ "MIT" ]
1
2021-06-29T05:16:19.000Z
2021-06-29T05:16:19.000Z
C++/Clase 6/Clase6.2.cpp
Rofernweh/UDPpl
da448091396b3f567f83e2964e8db97f6b8382bc
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; /*Una empresa quiere dar un bono a cada trabajador basado en la antigüedad en la empresa. Si lleva más de 10 años, será un bono de 25%. Si lleva entre 2 y 10 años, será un bono de 10%. Si lleva menos que 2 años, el bono será del 5%. Todos los bonos son sobre el sueldo. Crear un programa que en base al sueldo y los años de servicio, entregue el sueldo total (con bono). */ int main() { int sueldo, years, sueldo_total, bono; cout << "Ingrese su sueldo: \n"; cin >> sueldo; cout << "Ingrese sus años de servicio: \n"; cin >> years; if (years>=10) { bono = sueldo*.25; sueldo_total = sueldo + bono; cout << "Su sueldo total es $" << sueldo_total; } else if (years<10 && years>=2) { bono = sueldo*.10; sueldo_total = sueldo + bono; cout << "Su sueldo total es $" << sueldo_total; } else if (years<2) { bono = sueldo*.05; sueldo_total = sueldo + bono; cout << "Su sueldo total es $" << sueldo_total; } return 0; }
28.527778
104
0.63778
Rofernweh
a2f8e31e600597270e5d79007f14ff274588ee92
2,462
cc
C++
src/field_info.cc
AnthonyCalandra/bytecode-scanner
e2638a7063447bc947f0bc11d841d536735407ec
[ "MIT" ]
8
2019-07-21T20:15:46.000Z
2021-06-15T12:28:12.000Z
src/field_info.cc
AnthonyCalandra/bytecode-scanner
e2638a7063447bc947f0bc11d841d536735407ec
[ "MIT" ]
null
null
null
src/field_info.cc
AnthonyCalandra/bytecode-scanner
e2638a7063447bc947f0bc11d841d536735407ec
[ "MIT" ]
1
2020-09-24T08:28:04.000Z
2020-09-24T08:28:04.000Z
/** * Copyright 2019 Anthony Calandra * * 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 <fstream> #include <vector> #include "attribute_info.hh" #include "field_info.hh" #include "util.hh" std::vector<field_info> parse_fields(std::ifstream& file, const constant_pool& cp) { std::vector<field_info> fields; READ_U2_FIELD(fields_count, "Failed to parse fields count of class file."); for (uint16_t curr_field_idx = 0; curr_field_idx < fields_count; curr_field_idx++) { fields.emplace_back(field_info::parse_field(file, cp)); } return fields; } field_info field_info::parse_field(std::ifstream& file, const constant_pool& cp) { READ_U2_FIELD(access_flag_bytes, "Failed to parse access flags of field."); auto access_flags = field_access_flags{access_flag_bytes}; READ_U2_FIELD(name_index, "Failed to parse name index of field."); READ_U2_FIELD(descriptor_index, "Failed to parse descriptor index of field."); return field_info{cp, access_flags, name_index, descriptor_index, parse_attributes(file, cp)}; } field_info::field_info(const constant_pool& cp, field_access_flags access_flags, constant_pool_entry_id name_index, constant_pool_entry_id descriptor_index, entry_attributes field_attributes) : cp{cp}, access_flags{access_flags}, name_index{name_index}, descriptor_index{descriptor_index}, field_attributes{std::move(field_attributes)} {}
42.448276
98
0.760764
AnthonyCalandra
a2fb8ea0d8b93538725a060cb4e62186ceaba506
924
cpp
C++
testsuite/multiChannelIteration.cpp
RaftLib/ipc
608dcb10e1acb84e0f3be89639a91abe5395566b
[ "Apache-2.0" ]
6
2021-08-04T20:03:16.000Z
2021-08-17T16:16:10.000Z
testsuite/multiChannelIteration.cpp
RaftLib/ipc
608dcb10e1acb84e0f3be89639a91abe5395566b
[ "Apache-2.0" ]
9
2021-08-05T01:14:13.000Z
2021-08-31T21:39:28.000Z
testsuite/multiChannelIteration.cpp
RaftLib/ipc
608dcb10e1acb84e0f3be89639a91abe5395566b
[ "Apache-2.0" ]
null
null
null
#include <cstdlib> #include <iostream> #include <unistd.h> #include <cstdint> #include <sys/types.h> #include <unistd.h> #include <buffer> int main() { ipc::buffer::register_signal_handlers(); auto *buffer = ipc::buffer::initialize( "thehandle" ); auto channel_id = 1; auto thread_id = getpid(); auto *fake_tls = ipc::buffer::get_tls_structure( buffer, thread_id ); ipc::buffer::add_spsc_lf_record_channel( fake_tls, channel_id, ipc::producer ); ipc::buffer::add_spsc_lf_record_channel( fake_tls, channel_id + 1, ipc::producer ); auto channel_list = ipc::buffer::get_channel_list( fake_tls ); for( auto &pair : (*channel_list) ) { std::cout << pair.first << " - " << ipc::channel_type_names[ pair.second ] << "\n"; } ipc::buffer::close_tls_structure( fake_tls ); ipc::buffer::destruct( buffer, "thehandle" ); return( EXIT_SUCCESS ); }
26.4
87
0.649351
RaftLib
a2fc9e91df96d32f57dd484442047687eecd64c3
1,737
cpp
C++
Part.cpp
JulesStringer/GerberParser
2133908a0984e5a5b46e200e254a1bb0b53601b6
[ "MIT" ]
29
2017-09-14T09:47:58.000Z
2022-03-21T03:16:51.000Z
Part.cpp
thaidao/GerberParser
2133908a0984e5a5b46e200e254a1bb0b53601b6
[ "MIT" ]
3
2017-08-23T13:59:12.000Z
2022-01-18T09:49:28.000Z
Part.cpp
thaidao/GerberParser
2133908a0984e5a5b46e200e254a1bb0b53601b6
[ "MIT" ]
24
2017-03-14T02:48:34.000Z
2022-03-21T03:16:52.000Z
#include "Part.h" #include "Rectangle.h" #include "WKBGeometry.h" #include "GerberRender.h" #include "GerberAperature.h" #include "GerberState.h" CPart::CPart() : m_xmin(0) , m_ymin(0) , m_xmax(0) , m_ymax(0) , m_bFirst(true) , m_pState(NULL) , m_bInflated(false) , m_dInflateW(0.0) , m_dInflateH(0.0) { } CPart::CPart(const char* pszName, CGerberState* pState) : m_xmin(0) , m_ymin(0) , m_xmax(0) , m_ymax(0) , m_bFirst(true) , m_pState(pState) , m_strName(pszName) , m_bInflated(false) , m_dInflateW(0.0) , m_dInflateH(0.0) { } CPart::~CPart() { } void CPart::Inflate(double X, double Y) { if (m_bFirst) { m_xmin = m_xmax = X; m_ymin = m_ymax = Y; m_bFirst = false; } else { m_xmin = X < m_xmin ? X : m_xmin; m_ymin = Y < m_ymin ? Y : m_ymin; m_xmax = X > m_xmax ? X : m_xmax; m_ymax = Y > m_ymax ? Y : m_ymax; } } #if 0 void CPart::Inflate(CGerberCommand* pCommand) { double X = pCommand->xmin(); double Y = pCommand->ymin(); Inflate(X, Y); X = p->xmax(); Y = p->ymax(); Inflate(X, Y); } #endif const char* CPart::Name() { return m_strName.c_str(); } void CPart::Render(CGerberRender* pRender, CLayer* pLayer, double dInflate) { if (!m_bFirst) { double dInflateW = dInflate; double dInflateH = dInflate; if (m_bInflated) { dInflateW = m_dInflateW; dInflateH = m_dInflateH; } // Add in inflation parameter m_pState->SetLayer(pLayer); CRectangle rc(m_xmin - dInflateW, m_ymin - dInflateH, m_xmax + dInflateW, m_ymax + dInflateH); pRender->Rectangle(&rc, m_pState); } } void CPart::SetInflate(double W, double H) { m_dInflateW = W; m_dInflateH = H; m_bInflated = true; }
19.3
97
0.621762
JulesStringer
a2fd3b675ea4f538421829dd0ed99704e631eb5b
1,515
cpp
C++
JTS/CF-A/CF287-D2-B/test.cpp
rahulsrma26/ol_codes
dc599f5b70c14229a001c5239c366ba1b990f68b
[ "MIT" ]
2
2019-03-18T16:06:10.000Z
2019-04-07T23:17:06.000Z
JTS/CF-A/CF287-D2-B/test.cpp
rahulsrma26/ol_codes
dc599f5b70c14229a001c5239c366ba1b990f68b
[ "MIT" ]
null
null
null
JTS/CF-A/CF287-D2-B/test.cpp
rahulsrma26/ol_codes
dc599f5b70c14229a001c5239c366ba1b990f68b
[ "MIT" ]
1
2019-03-18T16:06:52.000Z
2019-03-18T16:06:52.000Z
// Date : 2019-03-18 // Author : Rahul Sharma // Problem : http://codeforces.com/contest/287/problem/B #include <algorithm> #include <iostream> #include <random> #include <string> #include <vector> using num = long long; template <class T, class Calc> T bs(T n, T l, T r, Calc calc) { T cl = calc(l); if (n <= cl) return l; T cr = calc(r); if (n > cr) return -1; while (l < r) { T m = (l + r) / 2; T cm = calc(m); if (n < cm) r = m - 1; else if (n > cm) l = m + 1; } return l; } template <class T, class Calc> T ss(T n, T l, T r, Calc calc) { for (; l <= r; l++) if (n <= calc(l)) return l; return -1; } void test(int t, int kl) { using namespace std; std::default_random_engine rnd; std::uniform_int_distribution<int> ks(2, kl); int f = 0; for (int i = 0; i < t; i++) { int k = ks(rnd); std::uniform_int_distribution<int> ns(1, k * k); int n = ns(rnd); auto calc = [=](int i) { return i * k - (i + 2) * (i - 1) / 2; }; auto r1 = ss(n, 1, k, calc); auto r2 = bs(n, 1, k, calc); if (r1 != r2) { std::cout << r1 << " != " << r2 << '\n'; std::cout << n << ", " << k << '\n'; f++; } } cout << f << " out of " << t << " failed.\n"; } int main() { using namespace std; ios_base::sync_with_stdio(false); cin.tie(0); test(1'000'000, 20); }
22.279412
73
0.456106
rahulsrma26
0c00900b9dcf7e84a07a98750b56bbf1abccfe1d
1,592
hh
C++
vm/vm/main/cached/FailedSpace-implem.hh
Ahzed11/mozart2
4806504b103e11be723e7813be8f69e4d85875cf
[ "BSD-2-Clause" ]
379
2015-01-02T20:27:33.000Z
2022-03-26T23:18:17.000Z
vm/vm/main/cached/FailedSpace-implem.hh
Ahzed11/mozart2
4806504b103e11be723e7813be8f69e4d85875cf
[ "BSD-2-Clause" ]
81
2015-01-08T13:18:52.000Z
2021-12-21T14:02:21.000Z
vm/vm/main/cached/FailedSpace-implem.hh
Ahzed11/mozart2
4806504b103e11be723e7813be8f69e4d85875cf
[ "BSD-2-Clause" ]
75
2015-01-06T09:08:20.000Z
2021-12-17T09:40:18.000Z
void TypeInfoOf<FailedSpace>::gCollect(GC gc, RichNode from, StableNode& to) const { assert(from.type() == type()); to.make<FailedSpace>(gc->vm, gc, from.access<FailedSpace>()); } void TypeInfoOf<FailedSpace>::gCollect(GC gc, RichNode from, UnstableNode& to) const { assert(from.type() == type()); to.make<FailedSpace>(gc->vm, gc, from.access<FailedSpace>()); } void TypeInfoOf<FailedSpace>::sClone(SC sc, RichNode from, StableNode& to) const { assert(from.type() == type()); to.init(sc->vm, from); } void TypeInfoOf<FailedSpace>::sClone(SC sc, RichNode from, UnstableNode& to) const { assert(from.type() == type()); to.init(sc->vm, from); } inline bool TypedRichNode<FailedSpace>::isSpace(VM vm) { return _self.access<FailedSpace>().isSpace(vm); } inline class mozart::UnstableNode TypedRichNode<FailedSpace>::askSpace(VM vm) { return _self.access<FailedSpace>().askSpace(vm); } inline class mozart::UnstableNode TypedRichNode<FailedSpace>::askVerboseSpace(VM vm) { return _self.access<FailedSpace>().askVerboseSpace(vm); } inline class mozart::UnstableNode TypedRichNode<FailedSpace>::mergeSpace(VM vm) { return _self.access<FailedSpace>().mergeSpace(vm); } inline void TypedRichNode<FailedSpace>::commitSpace(VM vm, class mozart::RichNode value) { _self.access<FailedSpace>().commitSpace(vm, value); } inline class mozart::UnstableNode TypedRichNode<FailedSpace>::cloneSpace(VM vm) { return _self.access<FailedSpace>().cloneSpace(vm); } inline void TypedRichNode<FailedSpace>::killSpace(VM vm) { _self.access<FailedSpace>().killSpace(vm); }
28.428571
86
0.729271
Ahzed11
0c0b8ac386eb6cee0ac5e8645819d9a7a4b3ed2a
1,845
cpp
C++
Blackbox/gui/listeners/ListenerFactory.cpp
Alias-m/Blackbox
1fb5af88cb9688e224e096b40987876f9d544f99
[ "MIT" ]
null
null
null
Blackbox/gui/listeners/ListenerFactory.cpp
Alias-m/Blackbox
1fb5af88cb9688e224e096b40987876f9d544f99
[ "MIT" ]
1
2017-02-19T20:22:21.000Z
2017-02-19T20:25:23.000Z
Blackbox/gui/listeners/ListenerFactory.cpp
Alias-m/Blackbox
1fb5af88cb9688e224e096b40987876f9d544f99
[ "MIT" ]
null
null
null
#include "ListenerFactory.h" ListenerFactory ListenerFactory::instance; ListenerFactory::ListenerFactory() { default_listener = CommonEventListener::create; listenerList[SDL_WINDOWEVENT] = WindowListener::create; listenerList[SDL_MOUSEBUTTONDOWN] = MouseButtonListener::create; listenerList[SDL_MOUSEBUTTONUP] = MouseButtonListener::create; listenerList[SDL_MOUSEMOTION] = MouseMotionListener::create; listenerList[SDL_MOUSEWHEEL] = MouseWheelListener::create; listenerList[SDL_QUIT] = QuitListener::create; listenerList[SDL_AUDIODEVICEADDED] = AudioDeviceListener::create; listenerList[SDL_AUDIODEVICEREMOVED] = AudioDeviceListener::create; //TODO : Simple � r�aliser //listenerList[SDL_CONTROLLERAXISMOTION] = ControllerAxisListener::create; //TODO : long � �crire //listenerList[SDL_KEYDOWN] = KeyDownListener::create; //listenerList[SDL_KEYUP] = KeyUpListener::create; /* listenerList[SDL_JOYAXISMOTION] = JoyAxisMotionListener(); listenerList[SDL_JOYBALLMOTION] = JoyBallMotionListener(); listenerList[SDL_JOYHATMOTION] = JoyHatListener(); listenerList[SDL_JOYBUTTONDOWN] = JoyButtonDownListener(); listenerList[SDL_JOYBUTTONUP] = JoyButtonUpListener(); listenerList[SDL_SYSWMEVENT] = SysWEventListener(); listenerList[SDL_VIDEORESIZE] = VideoResizeListener(); listenerList[SDL_VIDEOEXPOSE] = VideoExposeListener(); listenerList[SDL_USEREVENT] = UserEventListener();*/ } ListenerFactory::~ListenerFactory() { //TODO : delete all from tab } Listener* ListenerFactory::getListener(SDL_Event* event) { std::map<int, generator>::iterator it; it = listenerList.find(event->type); return it != listenerList.end() ? listenerList[event->type](event) : default_listener(event); }
37.653061
98
0.737669
Alias-m
0c0c9fa3f4c823f4e6f2d62f67ef474342b30930
1,021
cpp
C++
18.cpp
zfang399/LeetCode-Problems
4cb25718a3d1361569f5ee6fde7b4a9a4fde2186
[ "MIT" ]
8
2018-10-31T11:00:19.000Z
2020-07-31T05:25:06.000Z
18.cpp
zfang399/LeetCode-Problems
4cb25718a3d1361569f5ee6fde7b4a9a4fde2186
[ "MIT" ]
null
null
null
18.cpp
zfang399/LeetCode-Problems
4cb25718a3d1361569f5ee6fde7b4a9a4fde2186
[ "MIT" ]
2
2018-05-31T11:29:22.000Z
2019-09-11T06:34:40.000Z
class Solution { public: vector<vector<int>> fourSum(vector<int>& nums, int target) { vector<vector<int>> ans; map<vector<int>,bool> e; int n=nums.size(); if(n<4) return ans; sort(nums.begin(),nums.end()); for(int i=0;i<n-3;i++){ for(int j=i+1;j<n-2;j++){ int f=j+1,r=n-1; int sum=nums[i]+nums[j]+nums[f]+nums[r]; while(f<r){ sum=nums[i]+nums[j]+nums[f]+nums[r]; if(sum==target){ if(!e[{nums[i],nums[j],nums[f],nums[r]}]) ans.push_back({nums[i],nums[j],nums[f],nums[r]}); e[{nums[i],nums[j],nums[f],nums[r]}]=true; f++; r--; }else if(sum>target){ r--; }else{ f++; } } } } return ans; } };
31.90625
77
0.348678
zfang399
0c152ee74a4b1c33fa98b7cd366a187afcb89451
939
hpp
C++
include/mlib/convert.hpp
AoD314/mlib
3a6a5b9a30ccbe87528ef573ebd9be7f496256f4
[ "BSD-2-Clause" ]
null
null
null
include/mlib/convert.hpp
AoD314/mlib
3a6a5b9a30ccbe87528ef573ebd9be7f496256f4
[ "BSD-2-Clause" ]
null
null
null
include/mlib/convert.hpp
AoD314/mlib
3a6a5b9a30ccbe87528ef573ebd9be7f496256f4
[ "BSD-2-Clause" ]
null
null
null
#ifndef __CONVERT_HPP__ #define __CONVERT_HPP__ #include <string> #include <sstream> #include <iomanip> namespace mlib { //! Convert bool value to "true" or "false" std::string to_str(bool t); //! Convert Type to std::string template <typename T> std::string to_str(const T& t, int align = 0, int precision = 0, char c = ' ') { std::stringstream ss; ss << std::setiosflags(std::ios::fixed) << std::setprecision(precision) << std::setw(align) << std::setfill(c) << t; return ss.str(); } //! Parse Type from std::string template <typename T> T from_str(const std::string& val, T defval = T()) { std::istringstream iss(val); T t = T(); bool result = iss >> t; if (!result) return defval; return t; } template<> std::string from_str<std::string>(const std::string& val, std::string defval); } #endif
21.340909
124
0.58147
AoD314
0c1a1e3c62649f40e89bb1305e80fcda60a4a758
2,413
cc
C++
bench/rmr/assoc.cc
ronmrdechai/moat
8586e95c3666923fe74bf603d448c43263e842e5
[ "BSL-1.0" ]
2
2018-09-09T05:08:09.000Z
2018-09-11T08:55:50.000Z
bench/rmr/assoc.cc
ronmrdechai/moat
8586e95c3666923fe74bf603d448c43263e842e5
[ "BSL-1.0" ]
null
null
null
bench/rmr/assoc.cc
ronmrdechai/moat
8586e95c3666923fe74bf603d448c43263e842e5
[ "BSL-1.0" ]
null
null
null
// Armor // // Copyright Ron Mordechai, 2018 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.txt or copy at http://boost.org/LICENSE_1_0.txt) #include <algorithm> #include <fstream> #include <string> #include <vector> #include <random> #include <iostream> #include <benchmark/benchmark.h> #include <rmr/trie_set.h> #include <rmr/tst_set.h> struct alpha { std::size_t operator()(std::size_t c) const { return ('a' <= c && c <= 'z') ? c - 'a' : c - 'A'; } }; struct trie_set : rmr::trie_set<26, alpha> { using rmr::trie_set<26, alpha>::trie_set; }; struct tst_set : rmr::tst_set<> { using rmr::tst_set<>::tst_set; }; namespace bench { std::vector<std::size_t> random_indices(std::size_t n, std::size_t max) { std::default_random_engine engine(std::random_device{}()); std::uniform_int_distribution dist(0ul, max); std::vector<std::size_t> indices; for (std::size_t i = 0; i < n; i++) indices.push_back(dist(engine)); std::sort(indices.begin(), indices.end()); return indices; } std::vector<std::string> random_words(std::size_t n) { std::ifstream words_file(WORDS_FILE); std::size_t word_count = std::count( std::istreambuf_iterator<char>(words_file), std::istreambuf_iterator<char>(), '\n' ); auto indices = random_indices(n, word_count); words_file.clear(); words_file.seekg(0, std::ios::beg); std::vector<std::string> words; std::size_t target_line = 0; for (std::size_t current_line = 0; current_line < word_count; current_line++) { std::string line; std::getline(words_file, line); if (current_line == indices[target_line]) { words.push_back(line); target_line++; } } return words; } } // namespace bench #define ARMOR_TEMPLATE_BENCHMARK(func, param)\ void func##_##param(benchmark::State& s) { func<param>(s); }\ BENCHMARK(func##_##param) template <typename T> void insertion(benchmark::State& state) { auto words = bench::random_words(state.range(0)); for (auto _ : state) { state.PauseTiming(); T t; state.ResumeTiming(); t.insert(words.begin(), words.end()); } } ARMOR_TEMPLATE_BENCHMARK(insertion, trie_set)->RangeMultiplier(10)->Range(10, 100000); ARMOR_TEMPLATE_BENCHMARK(insertion, tst_set)->RangeMultiplier(10)->Range(10, 100000);
28.05814
102
0.6523
ronmrdechai
0c236118a2fd4b2ec4abebce7fb3a08eb58acbff
18,229
cpp
C++
Examples/ThemeAero/Sources/theme_views.cpp
xctan/ClanLib
1a8d6eb6cab3e93fd5c6be618fb6f7bd1146fc2d
[ "Linux-OpenIB" ]
248
2015-01-08T05:21:40.000Z
2022-03-20T02:59:16.000Z
Examples/ThemeAero/Sources/theme_views.cpp
xctan/ClanLib
1a8d6eb6cab3e93fd5c6be618fb6f7bd1146fc2d
[ "Linux-OpenIB" ]
39
2015-01-14T17:37:07.000Z
2022-03-17T12:59:26.000Z
Examples/ThemeAero/Sources/theme_views.cpp
xctan/ClanLib
1a8d6eb6cab3e93fd5c6be618fb6f7bd1146fc2d
[ "Linux-OpenIB" ]
82
2015-01-11T13:23:49.000Z
2022-02-19T03:17:24.000Z
/* ** ClanLib SDK ** Copyright (c) 1997-2016 The ClanLib Team ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any damages ** arising from the use of this software. ** ** Permission is granted to anyone to use this software for any purpose, ** including commercial applications, and to alter it and redistribute it ** freely, subject to the following restrictions: ** ** 1. The origin of this software must not be misrepresented; you must not ** claim that you wrote the original software. If you use this software ** in a product, an acknowledgment in the product documentation would be ** appreciated but is not required. ** 2. Altered source versions must be plainly marked as such, and must not be ** misrepresented as being the original software. ** 3. This notice may not be removed or altered from any source distribution. ** ** Note: Some of the libraries ClanLib may link to may have additional ** requirements or restrictions. ** ** File Author(s): ** ** Magnus Norddahl ** Mark Page */ #include "precomp.h" #include "theme_views.h" namespace clan { ThemeButtonView::ThemeButtonView() { style()->set("border-image-slice: 6 6 5 5 fill;"); style()->set("border-image-width:6px 6px 5px 5px;"); style()->set("border-image-repeat:stretch;"); style()->set("border-image-source:url('Resources/button_normal.png');"); style("hot")->set("border-image-source:url('Resources/button_hot.png');"); style("pressed")->set("border-image-source:url('Resources/button_pressed.png');"); style("disabled")->set("border-image-source:url('Resources/button_disabled.png');"); label()->style()->set("margin: 5px auto; font: 13px/18px 'Segoe UI'; padding: 0 10px; color: rgb(0,0,0);"); label()->style("disabled")->set("color: rgb(128,128,128);"); label()->set_text_alignment(TextAlignment::center); } ThemeCheckBoxView::ThemeCheckBoxView() { style()->set("background-position:center center;"); style()->set("background-repeat:no-repeat;"); style()->set("background-attachment:scroll;"); style()->set("width:13px; height:13px"); style()->set("background-image:url('Resources/checkbox_unchecked_normal.png');"); style("unchecked_hot")->set("background-image:url('Resources/checkbox_unchecked_hot.png');"); style("unchecked_pressed")->set("background-image:url('Resources/checkbox_unchecked_pressed.png');"); style("unchecked_disabled")->set("background-image:url('Resources/checkbox_unchecked_disabled.png');"); style("checked")->set("background-image:url('Resources/checkbox_checked_normal.png');"); style("checked_hot")->set("background-image:url('Resources/checkbox_checked_hot.png');"); style("checked_pressed")->set("background-image:url('Resources/checkbox_checked_pressed.png');"); style("checked_disabled")->set("background-image:url('Resources/checkbox_checked_disabled.png');"); } ThemeImageView::ThemeImageView() { } ThemeLabelView::ThemeLabelView() { style()->set("font: 16px 'Segoe UI'; color: black"); } ThemeListBoxView::ThemeListBoxView() { style()->set("margin: 7px 0; border: 1px solid black; padding: 5px; background: #f0f0f0"); } ThemeListBoxLabelView::ThemeListBoxLabelView(const std::string &text) { style()->set("font: 13px/17px 'Segoe UI'; color: black; margin: 1px 0; padding: 0 2px"); style("selected")->set("background: #7777f0; color: white;"); style("hot")->set("background: #ccccf0; color: black"); set_text(text); } ThemeRadioButtonView::ThemeRadioButtonView() { style()->set("background-position:center center;"); style()->set("background-repeat:no-repeat;"); style()->set("background-attachment:scroll;"); style()->set("width:13px; height:13px"); style()->set("background-image:url('Resources/radio_unchecked_normal.png');"); style("unchecked_hot")->set("background-image:url('Resources/radio_unchecked_hot.png');"); style("unchecked_pressed")->set("background-image:url('Resources/radio_unchecked_pressed.png');"); style("unchecked_disabled")->set("background-image:url('Resources/radio_unchecked_disabled.png');"); style("checked")->set("background-image:url('Resources/radio_checked_normal.png');"); style("checked_hot")->set("background-image:url('Resources/radio_checked_hot.png');"); style("checked_pressed")->set("background-image:url('Resources/radio_checked_pressed.png');"); style("checked_disabled")->set("background-image:url('Resources/radio_checked_disabled.png');"); } ThemeScrollView::ThemeScrollView() { scrollbar_x_view()->style()->set("flex: 0 0 main-size"); scrollbar_x_view()->style()->set("background: rgb(232, 232, 236)"); scrollbar_x_view()->track()->style()->set("border-image-slice: 4 0 3 0 fill;"); scrollbar_x_view()->track()->style()->set("border-image-width:4px 0px 3px 0px;"); scrollbar_x_view()->track()->style()->set("border-image-repeat:stretch;"); scrollbar_x_view()->track()->style()->set("border-image-source:url('Resources/scrollbar_hori_track_normal.png');"); scrollbar_x_view()->track()->style("hot")->set("border-image-source:url('Resources/scrollbar_hori_track_hot.png');"); scrollbar_x_view()->track()->style("pressed")->set("border-image-source:url('Resources/scrollbar_hori_track_pressed.png');"); scrollbar_x_view()->track()->style("disabled")->set("border-image-source:url('Resources/scrollbar_hori_track_disabled.png');"); scrollbar_x_view()->thumb()->style()->set("border-image-slice: 5 5 5 5 fill;"); scrollbar_x_view()->thumb()->style()->set("border-image-width:5px 5px 5px 5px;"); scrollbar_x_view()->thumb()->style()->set("border-image-repeat:stretch;"); scrollbar_x_view()->thumb()->style()->set("border-image-source:url('Resources/scrollbar_hori_thumb_normal.png');"); scrollbar_x_view()->thumb()->style("hot")->set("border-image-source:url('Resources/scrollbar_hori_thumb_hot.png');"); scrollbar_x_view()->thumb()->style("pressed")->set("border-image-source:url('Resources/scrollbar_hori_thumb_pressed.png');"); scrollbar_x_view()->thumb()->style("disabled")->set("border-image-source:url('Resources/scrollbar_hori_thumb_disabled.png');"); scrollbar_x_view()->thumb_grip()->style()->set("background-position:center center;"); scrollbar_x_view()->thumb_grip()->style()->set("background-repeat:no-repeat;"); scrollbar_x_view()->thumb_grip()->style()->set("background-attachment:scroll; "); scrollbar_x_view()->thumb_grip()->style()->set("background-image:url('Resources/scrollbar_hori_thumb_gripper_normal.png');"); scrollbar_x_view()->thumb_grip()->style("hot")->set("background-image:url('Resources/scrollbar_hori_thumb_gripper_hot.png');"); scrollbar_x_view()->thumb_grip()->style("pressed")->set("background-image:url('Resources/scrollbar_hori_thumb_gripper_pressed.png');"); scrollbar_x_view()->thumb_grip()->style("disabled")->set("background-image:url('Resources/scrollbar_hori_thumb_gripper_disabled.png');"); scrollbar_x_view()->button_decrement()->style()->set("width:17px; height:17px"); scrollbar_x_view()->button_decrement()->style()->set("border-image-slice: 3 3 3 3 fill;"); scrollbar_x_view()->button_decrement()->style()->set("border-image-width:3px 3px 3px 3px;"); scrollbar_x_view()->button_decrement()->style()->set("border-image-repeat:stretch;"); scrollbar_x_view()->button_decrement()->style()->set("border-image-source:url('Resources/scrollbar_hori_button_left_normal_withglyph.png');"); scrollbar_x_view()->button_decrement()->style("hot")->set("border-image-source:url('Resources/scrollbar_hori_button_left_hot_withglyph.png');"); scrollbar_x_view()->button_decrement()->style("pressed")->set("border-image-source:url('Resources/scrollbar_hori_button_left_pressed_withglyph.png');"); scrollbar_x_view()->button_decrement()->style("disabled")->set("border-image-source:url('Resources/scrollbar_hori_button_left_disabled_withglyph.png');"); scrollbar_x_view()->button_increment()->style()->set("width:17px; height:17px"); scrollbar_x_view()->button_increment()->style()->set("border-image-slice: 3 3 3 3 fill;"); scrollbar_x_view()->button_increment()->style()->set("border-image-width:3px 3px 3px 3px;"); scrollbar_x_view()->button_increment()->style()->set("border-image-repeat:stretch;"); scrollbar_x_view()->button_increment()->style()->set("border-image-source:url('Resources/scrollbar_hori_button_right_normal_withglyph.png');"); scrollbar_x_view()->button_increment()->style("hot")->set("border-image-source:url('Resources/scrollbar_hori_button_right_hot_withglyph.png');"); scrollbar_x_view()->button_increment()->style("pressed")->set("border-image-source:url('Resources/scrollbar_hori_button_right_pressed_withglyph.png');"); scrollbar_x_view()->button_increment()->style("disabled")->set("border-image-source:url('Resources/scrollbar_hori_button_right_disabled_withglyph.png');"); scrollbar_y_view()->style()->set("flex: 0 0 main-size"); scrollbar_y_view()->style()->set("background: rgb(232, 232, 236)"); scrollbar_y_view()->track()->style()->set("border-image-slice: 4 0 3 0 fill;"); scrollbar_y_view()->track()->style()->set("border-image-width:4px 0px 3px 0px;"); scrollbar_y_view()->track()->style()->set("border-image-repeat:stretch;"); scrollbar_y_view()->track()->style()->set("border-image-source:url('Resources/scrollbar_vert_track_normal.png');"); scrollbar_y_view()->track()->style("hot")->set("border-image-source:url('Resources/scrollbar_vert_track_hot.png');"); scrollbar_y_view()->track()->style("pressed")->set("border-image-source:url('Resources/scrollbar_vert_track_pressed.png');"); scrollbar_y_view()->track()->style("disabled")->set("border-image-source:url('Resources/scrollbar_vert_track_disabled.png');"); scrollbar_y_view()->thumb()->style()->set("border-image-slice: 5 5 5 5 fill;"); scrollbar_y_view()->thumb()->style()->set("border-image-width:5px 5px 5px 5px;"); scrollbar_y_view()->thumb()->style()->set("border-image-repeat:stretch;"); scrollbar_y_view()->thumb()->style()->set("border-image-source:url('Resources/scrollbar_vert_thumb_normal.png');"); scrollbar_y_view()->thumb()->style("hot")->set("border-image-source:url('Resources/scrollbar_vert_thumb_hot.png');"); scrollbar_y_view()->thumb()->style("pressed")->set("border-image-source:url('Resources/scrollbar_vert_thumb_pressed.png');"); scrollbar_y_view()->thumb()->style("disabled")->set("border-image-source:url('Resources/scrollbar_vert_thumb_disabled.png');"); scrollbar_y_view()->thumb_grip()->style()->set("background-position:center center;"); scrollbar_y_view()->thumb_grip()->style()->set("background-repeat:no-repeat;"); scrollbar_y_view()->thumb_grip()->style()->set("background-attachment:scroll; "); scrollbar_y_view()->thumb_grip()->style()->set("background-image:url('Resources/scrollbar_vert_thumb_gripper_normal.png');"); scrollbar_y_view()->thumb_grip()->style("hot")->set("background-image:url('Resources/scrollbar_vert_thumb_gripper_hot.png');"); scrollbar_y_view()->thumb_grip()->style("pressed")->set("background-image:url('Resources/scrollbar_vert_thumb_gripper_pressed.png');"); scrollbar_y_view()->thumb_grip()->style("disabled")->set("background-image:url('Resources/scrollbar_vert_thumb_gripper_disabled.png');"); scrollbar_y_view()->button_decrement()->style()->set("width:17px; height:17px"); scrollbar_y_view()->button_decrement()->style()->set("border-image-slice: 3 3 3 3 fill;"); scrollbar_y_view()->button_decrement()->style()->set("border-image-width:3px 3px 3px 3px;"); scrollbar_y_view()->button_decrement()->style()->set("border-image-repeat:stretch;"); scrollbar_y_view()->button_decrement()->style()->set("border-image-source:url('Resources/scrollbar_vert_button_left_normal_withglyph.png');"); scrollbar_y_view()->button_decrement()->style("hot")->set("border-image-source:url('Resources/scrollbar_vert_button_left_hot_withglyph.png');"); scrollbar_y_view()->button_decrement()->style("pressed")->set("border-image-source:url('Resources/scrollbar_vert_button_left_pressed_withglyph.png');"); scrollbar_y_view()->button_decrement()->style("disabled")->set("border-image-source:url('Resources/scrollbar_vert_button_left_disabled_withglyph.png');"); scrollbar_y_view()->button_increment()->style()->set("width:17px; height:17px"); scrollbar_y_view()->button_increment()->style()->set("border-image-slice: 3 3 3 3 fill;"); scrollbar_y_view()->button_increment()->style()->set("border-image-width:3px 3px 3px 3px;"); scrollbar_y_view()->button_increment()->style()->set("border-image-repeat:stretch;"); scrollbar_y_view()->button_increment()->style()->set("border-image-source:url('Resources/scrollbar_vert_button_right_normal_withglyph.png');"); scrollbar_y_view()->button_increment()->style("hot")->set("border-image-source:url('Resources/scrollbar_vert_button_right_hot_withglyph.png');"); scrollbar_y_view()->button_increment()->style("pressed")->set("border-image-source:url('Resources/scrollbar_vert_button_right_pressed_withglyph.png');"); scrollbar_y_view()->button_increment()->style("disabled")->set("border-image-source:url('Resources/scrollbar_vert_button_right_disabled_withglyph.png');"); } ThemeScrollBarView::ThemeScrollBarView() { set_horizontal(); style()->set("flex: 0 0 main-size"); style()->set("background: rgb(232, 232, 236)"); track()->style()->set("border-image-slice: 4 0 3 0 fill;"); track()->style()->set("border-image-width:4px 0px 3px 0px;"); track()->style()->set("border-image-repeat:stretch;"); track()->style()->set("border-image-source:url('Resources/scrollbar_hori_track_normal.png');"); track()->style("hot")->set("border-image-source:url('Resources/scrollbar_hori_track_hot.png');"); track()->style("pressed")->set("border-image-source:url('Resources/scrollbar_hori_track_pressed.png');"); track()->style("disabled")->set("border-image-source:url('Resources/scrollbar_hori_track_disabled.png');"); thumb()->style()->set("border-image-slice: 5 5 5 5 fill;"); thumb()->style()->set("border-image-width:5px 5px 5px 5px;"); thumb()->style()->set("border-image-repeat:stretch;"); thumb()->style()->set("border-image-source:url('Resources/scrollbar_hori_thumb_normal.png');"); thumb()->style("hot")->set("border-image-source:url('Resources/scrollbar_hori_thumb_hot.png');"); thumb()->style("pressed")->set("border-image-source:url('Resources/scrollbar_hori_thumb_pressed.png');"); thumb()->style("disabled")->set("border-image-source:url('Resources/scrollbar_hori_thumb_disabled.png');"); thumb_grip()->style()->set("background-position:center center;"); thumb_grip()->style()->set("background-repeat:no-repeat;"); thumb_grip()->style()->set("background-attachment:scroll; "); thumb_grip()->style()->set("background-image:url('Resources/scrollbar_hori_thumb_gripper_normal.png');"); thumb_grip()->style("hot")->set("background-image:url('Resources/scrollbar_hori_thumb_gripper_hot.png');"); thumb_grip()->style("pressed")->set("background-image:url('Resources/scrollbar_hori_thumb_gripper_pressed.png');"); thumb_grip()->style("disabled")->set("background-image:url('Resources/scrollbar_hori_thumb_gripper_disabled.png');"); button_decrement()->style()->set("width:17px; height:17px"); button_decrement()->style()->set("border-image-slice: 3 3 3 3 fill;"); button_decrement()->style()->set("border-image-width:3px 3px 3px 3px;"); button_decrement()->style()->set("border-image-repeat:stretch;"); button_decrement()->style()->set("border-image-source:url('Resources/scrollbar_hori_button_left_normal_withglyph.png');"); button_decrement()->style("hot")->set("border-image-source:url('Resources/scrollbar_hori_button_left_hot_withglyph.png');"); button_decrement()->style("pressed")->set("border-image-source:url('Resources/scrollbar_hori_button_left_pressed_withglyph.png');"); button_decrement()->style("disabled")->set("border-image-source:url('Resources/scrollbar_hori_button_left_disabled_withglyph.png');"); button_increment()->style()->set("width:17px; height:17px"); button_increment()->style()->set("border-image-slice: 3 3 3 3 fill;"); button_increment()->style()->set("border-image-width:3px 3px 3px 3px;"); button_increment()->style()->set("border-image-repeat:stretch;"); button_increment()->style()->set("border-image-source:url('Resources/scrollbar_hori_button_right_normal_withglyph.png');"); button_increment()->style("hot")->set("border-image-source:url('Resources/scrollbar_hori_button_right_hot_withglyph.png');"); button_increment()->style("pressed")->set("border-image-source:url('Resources/scrollbar_hori_button_right_pressed_withglyph.png');"); button_increment()->style("disabled")->set("border-image-source:url('Resources/scrollbar_hori_button_right_disabled_withglyph.png');"); } ThemeSliderView::ThemeSliderView() { set_horizontal(); style()->set("flex-direction: row;"); track()->style()->set("flex: 1 1 main-size;"); track()->style()->set("height: 4px;"); track()->style()->set("margin: 7px 0px"); track()->style()->set("border-image-slice: 1 2 1 1 fill;"); track()->style()->set("border-image-width:1px 2px 1px 1px;"); track()->style()->set("border-image-repeat:stretch;"); track()->style()->set("border-image-source:url('Resources/slider_track.png');"); thumb()->style()->set("position: absolute;"); thumb()->style()->set("width:11px;"); thumb()->style()->set("height:19px;"); thumb()->style()->set("border-image-slice:9 3 9 2 fill;"); thumb()->style()->set("border-image-width:9px 3px 9px 2px;"); thumb()->style()->set("border-image-repeat:stretch;"); thumb()->style()->set("border-image-source:url('Resources/slider_horizontal_thumb_normal.png');"); thumb()->style("hot")->set("border-image-source:url('Resources/slider_horizontal_thumb_hot.png');"); thumb()->style("pressed")->set("border-image-source:url('Resources/slider_horizontal_thumb_pressed.png');"); thumb()->style("disabled")->set("border-image-source:url('Resources/slider_horizontal_thumb_disabled.png');"); } ThemeSpinView::ThemeSpinView() { } ThemeTextFieldView::ThemeTextFieldView() { } ThemeTextView::ThemeTextView() { } }
65.336918
157
0.727796
xctan
0c25994288eeaaba4e722ddd2b43f40831247d4c
1,999
cpp
C++
source/linux/brfilenamelinux.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
115
2015-01-18T17:29:30.000Z
2022-01-30T04:31:48.000Z
source/linux/brfilenamelinux.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
9
2015-01-22T04:53:38.000Z
2015-01-31T13:52:40.000Z
source/linux/brfilenamelinux.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
9
2015-01-23T20:06:46.000Z
2020-05-20T16:06:00.000Z
/*************************************** Linux version Copyright (c) 2021 by Rebecca Ann Heineman <becky@burgerbecky.com> It is released under an MIT Open Source license. Please see LICENSE for license details. Yes, you can use it in a commercial title without paying anything, just give me a credit. Please? It's not like I'm asking you for money! ***************************************/ #include "brfilename.h" #if defined(BURGER_LINUX) || defined(DOXYGEN) #include "brglobals.h" #include <errno.h> #include <limits.h> #include <sys/utsname.h> #include <unistd.h> /*************************************** \brief Set the filename to the current working directory Query the operating system for the current working directory and set the filename to that directory. The path is converted into UTF8 character encoding and stored in Burgerlib filename format On platforms where a current working directory doesn't make sense, like an ROM based system, the filename is cleared out. ***************************************/ Burger::eError BURGER_API Burger::Filename::SetSystemWorkingDirectory( void) BURGER_NOEXCEPT { Clear(); // Get the current working directory from Linux char* pTemp = getcwd(nullptr, 0); if (pTemp) { SetFromNative(pTemp); free(pTemp); } return kErrorNone; } /*************************************** \brief Set the filename to the application's directory Determine the directory where the application resides and set the filename to that directory. The path is converted into UTF8 character encoding and stored in Burgerlib filename format. On platforms where a current working directory doesn't make sense, like an ROM based system, the filename is cleared out. ***************************************/ Burger::eError BURGER_API Burger::Filename::SetApplicationDirectory(void) BURGER_NOEXCEPT { Clear(); char result[PATH_MAX]; readlink("/proc/self/exe", result, PATH_MAX); SetFromNative(result); return kErrorNone; } #endif
26.653333
89
0.673337
Olde-Skuul
0c28d53c6bc446db757e7ce248032107a075990a
3,567
cpp
C++
example/DomainDecomposition/Euler/src/EulerRK4.cpp
novertonCSU/Chombo_4
b833e49793758a7d6d22f976694c9d2e90d29c00
[ "BSD-3-Clause-LBNL" ]
11
2019-06-08T01:20:51.000Z
2021-12-21T12:18:54.000Z
example/DomainDecomposition/Euler/src/EulerRK4.cpp
novertonCSU/Chombo_4
b833e49793758a7d6d22f976694c9d2e90d29c00
[ "BSD-3-Clause-LBNL" ]
3
2020-03-13T06:25:55.000Z
2021-06-23T18:12:53.000Z
example/DomainDecomposition/Euler/src/EulerRK4.cpp
novertonCSU/Chombo_4
b833e49793758a7d6d22f976694c9d2e90d29c00
[ "BSD-3-Clause-LBNL" ]
4
2019-08-27T14:34:34.000Z
2021-10-04T21:46:59.000Z
#ifdef CH_LANG_CC /* * _______ __ * / ___/ / ___ __ _ / / ___ * / /__/ _ \/ _ \/ V \/ _ \/ _ \ * \___/_//_/\___/_/_/_/_.__/\___/ * Please refer to Copyright.txt, in Chombo's root directory. */ #endif #include "EulerRK4.H" #include "Chombo_DataIterator.H" #include "Chombo_ProtoInterface.H" #include "Chombo_NamespaceHeader.H" //using ::Proto::Point; /****/ EulerState:: EulerState(shared_ptr<LevelBoxData<NUMCOMPS> > a_U) { m_U = a_U; m_grids = m_U->disjointBoxLayout(); } /****/ void EulerState:: increment(const EulerDX & a_DX) { CH_TIME("EulerState::increment"); LevelBoxData<NUMCOMPS> & data = *m_U; LevelBoxData<NUMCOMPS> & delta = *(a_DX.m_DU); DataIterator dit = m_grids.dataIterator(); for(int ibox = 0; ibox < dit.size(); ibox++) { data[dit[ibox]] += delta[dit[ibox]]; } } /****/ void EulerDX:: increment(Real & a_weight, const EulerDX & a_DX) { CH_TIME("EulerDX::increment"); LevelBoxData<NUMCOMPS>& data = *m_DU; LevelBoxData<NUMCOMPS>& delta = *(a_DX.m_DU); DataIterator dit = m_grids.dataIterator(); for(int ibox = 0; ibox < dit.size(); ibox++) { BoxData<Real, NUMCOMPS> incr(delta[dit[ibox]].box()); delta[dit[ibox]].copyTo(incr); incr *= a_weight; data[dit[ibox]] += incr; } } /****/ void EulerDX:: init(const EulerState& a_State) { CH_TIME("EulerDX::init"); m_grids = a_State.m_grids; if(m_DU == NULL) m_DU = shared_ptr<LevelBoxData<NUMCOMPS> >(new LevelBoxData<NUMCOMPS>(m_grids, a_State.m_U->ghostVect())); if(U_ave == NULL) U_ave = shared_ptr<LevelBoxData<NUMCOMPS> >(new LevelBoxData<NUMCOMPS>(m_grids, a_State.m_U->ghostVect())); DataIterator dit = m_grids.dataIterator(); for(int ibox = 0; ibox < dit.size(); ibox++) { (*m_DU)[dit[ibox]].setVal(0.); } } /****/ void EulerDX:: operator*=(const Real& a_weight) { CH_TIME("EulerDX::operator*="); DataIterator dit = m_grids.dataIterator(); //#pragma omp parallel for(int ibox = 0; ibox < dit.size(); ibox++) { (*m_DU)[dit[ibox]] *= a_weight; } } /****/ void EulerRK4Op:: operator()(EulerDX& a_DX, Real a_time, Real a_dt, EulerState& a_State) const { CH_TIMERS("EulerRKOp::operator()"); CH_TIMER("defining leveldatas",tdef); CH_TIMER("copying to temporary",tcop); CH_TIMER("RK arithmetic_no_comm", trk); CH_START(tdef); //int ncomp = a_State.m_U->nComp(); //IntVect gv = a_State.m_U->ghostVect(); DisjointBoxLayout grids = a_State.m_grids; LevelBoxData<NUMCOMPS>& delta = *(a_DX.m_DU); CH_STOP(tdef); CH_START(tcop); //Interval interv(0, ncomp-1); //Copier copier(grids, grids); LevelBoxData<NUMCOMPS>& U_ave= *(a_DX.U_ave); DataIterator it = grids.dataIterator(); int nbox = it.size(); for (int ibox = 0; ibox < nbox; ibox++) { a_State.m_U->operator[](it[ibox]).copyTo(U_ave[it[ibox]]); } CH_STOP(tcop); CH_START(trk); DataIterator dit = grids.dataIterator(); for(int ibox = 0; ibox < dit.size(); ibox++) { U_ave[dit[ibox]] += delta[dit[ibox]]; } EulerOp::step(*a_DX.m_DU, U_ave, a_State.m_Rxn); for(int ibox = 0; ibox < dit.size(); ibox++) { delta[dit[ibox]] *= a_dt; } CH_STOP(trk); } Real EulerRK4Op:: maxWave(EulerState& a_State) { CH_TIME("EulerRKOp::maxwave_init"); EulerDX DX; DX.init(a_State); Reduction<Real,Op::Abs>& rxn = a_State.m_Rxn; EulerOp::step(*(DX.m_DU),*(a_State.m_U), rxn); Real velmax = rxn.fetch(); return velmax; } #include "Chombo_NamespaceFooter.H"
21.75
111
0.625456
novertonCSU
0c29132816936645d83aed041344133201312a28
1,139
hpp
C++
libcaf_io/caf/io/network/scribe_impl.hpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
2,517
2015-01-04T22:19:43.000Z
2022-03-31T12:20:48.000Z
libcaf_io/caf/io/network/scribe_impl.hpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
894
2015-01-07T14:21:21.000Z
2022-03-30T06:37:18.000Z
libcaf_io/caf/io/network/scribe_impl.hpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
570
2015-01-21T18:59:33.000Z
2022-03-31T19:00:02.000Z
// 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. #pragma once #include "caf/detail/io_export.hpp" #include "caf/io/fwd.hpp" #include "caf/io/network/native_socket.hpp" #include "caf/io/network/stream_impl.hpp" #include "caf/io/scribe.hpp" #include "caf/policy/tcp.hpp" namespace caf::io::network { /// Default scribe implementation. class CAF_IO_EXPORT scribe_impl : public scribe { public: scribe_impl(default_multiplexer& mx, native_socket sockfd); void configure_read(receive_policy::config config) override; void ack_writes(bool enable) override; byte_buffer& wr_buf() override; byte_buffer& rd_buf() override; void graceful_shutdown() override; void flush() override; std::string addr() const override; uint16_t port() const override; void launch(); void add_to_loop() override; void remove_from_loop() override; protected: bool launched_; stream_impl<policy::tcp> stream_; }; } // namespace caf::io::network
23.244898
77
0.748025
seewpx
0c29f0a84e16c412426a857352294acff5f280e5
508
cpp
C++
src/tests/bitflag.cpp
LAK132/lak
cb7fbc8925d526bbd4f9318ccf572b395cdd01e3
[ "MIT", "Unlicense" ]
3
2021-07-12T02:32:50.000Z
2022-01-30T03:39:53.000Z
src/tests/bitflag.cpp
LAK132/lak
cb7fbc8925d526bbd4f9318ccf572b395cdd01e3
[ "MIT", "Unlicense" ]
1
2020-11-03T08:57:04.000Z
2020-11-03T09:04:41.000Z
src/tests/bitflag.cpp
LAK132/lak
cb7fbc8925d526bbd4f9318ccf572b395cdd01e3
[ "MIT", "Unlicense" ]
null
null
null
#include "lak/bitflag.hpp" #include "lak/test.hpp" BEGIN_TEST(bitflag) { enum struct my_enum { bit1 = 0, bit2 = 1, bit3 = 2 }; lak::bitflag<my_enum, my_enum::bit1, my_enum::bit3, my_enum::bit2> flags; flags.set<my_enum::bit1>(true); flags.set<my_enum::bit2>(false); flags.set<my_enum::bit3>(true); DEBUG((flags.get<my_enum::bit1>() ? "true" : "false")); DEBUG((flags.get<my_enum::bit2>() ? "true" : "false")); DEBUG((flags.get<my_enum::bit3>() ? "true" : "false")); return 0; } END_TEST()
22.086957
74
0.639764
LAK132
0c2b42d2be1f1d196adcd7e4355c34bcab26b1bd
1,330
hh
C++
elements/standard/settimestamp.hh
BorisPis/asplos22-nicmem-fastclick
ab4df08ee056ed48a4c534ec5f8536a958f756b5
[ "BSD-3-Clause-Clear" ]
129
2015-10-08T14:38:35.000Z
2022-03-06T14:54:44.000Z
elements/standard/settimestamp.hh
BorisPis/asplos22-nicmem-fastclick
ab4df08ee056ed48a4c534ec5f8536a958f756b5
[ "BSD-3-Clause-Clear" ]
241
2016-02-17T16:17:58.000Z
2022-03-15T09:08:33.000Z
elements/standard/settimestamp.hh
BorisPis/asplos22-nicmem-fastclick
ab4df08ee056ed48a4c534ec5f8536a958f756b5
[ "BSD-3-Clause-Clear" ]
61
2015-12-17T01:46:58.000Z
2022-02-07T22:25:19.000Z
// -*- c-basic-offset: 4 -*- #ifndef CLICK_SETTIMESTAMP_HH #define CLICK_SETTIMESTAMP_HH #include <click/batchelement.hh> CLICK_DECLS /* =c SetTimestamp([TIMESTAMP, I<keyword> FIRST]) =s timestamps store the time in the packet's timestamp annotation =d Store the specified TIMESTAMP in the packet's timestamp annotation. If TIMESTAMP is not specified, then sets the annotation to the system time when the packet arrived at the SetTimestamp element. Keyword arguments are: =over 8 =item FIRST Boolean. If true, then set the packet's "first timestamp" annotation, not its timestamp annotation. Default is false. =back =a StoreTimestamp, AdjustTimestamp, SetTimestampDelta, PrintOld */ class SetTimestamp : public BatchElement { public: SetTimestamp() CLICK_COLD; const char *class_name() const override { return "SetTimestamp"; } const char *port_count() const override { return PORTS_1_1; } int configure(Vector<String> &, ErrorHandler *) CLICK_COLD; Packet *simple_action(Packet *) override; #if HAVE_BATCH PacketBatch *simple_action_batch(PacketBatch *) override; #endif private: enum { ACT_NOW, ACT_TIME, ACT_FIRST_NOW, ACT_FIRST_TIME }; // order matters int _action; bool _per_batch; Timestamp _tv; inline void rmaction(Packet *); }; CLICK_ENDDECLS #endif
21.803279
79
0.744361
BorisPis
0c2c2534d07aaefd542105674a6adc32da79e19a
1,054
cpp
C++
cpp/0100-0199/100. Same Tree/solution.cpp
RapDoodle/LeetCode-Solutions
6f14b7621bc6db12303be7f85508f3a5b2c2c30a
[ "MIT" ]
null
null
null
cpp/0100-0199/100. Same Tree/solution.cpp
RapDoodle/LeetCode-Solutions
6f14b7621bc6db12303be7f85508f3a5b2c2c30a
[ "MIT" ]
null
null
null
cpp/0100-0199/100. Same Tree/solution.cpp
RapDoodle/LeetCode-Solutions
6f14b7621bc6db12303be7f85508f3a5b2c2c30a
[ "MIT" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { // Reached the leaf nodes if (p == nullptr && q == nullptr) return true; // When the two nodes are not empty and // have the same value, search using DFS in // the left and right path recursively. if (p != nullptr && q != nullptr && p->val == q->val) return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); // When the two nodes' values are different, // or at least one node is a null pointer, // which indicates the two paths are different. return false; } };
34
93
0.550285
RapDoodle
0c2fc3209dbb38bf1501247f9b9a7812dcf9ebdf
566
cpp
C++
lib/sai_redis_fdb.cpp
vmittal-msft/sonic-sairedis
6baff35880005aee2854fdcde105c4322c28d04f
[ "Apache-2.0" ]
50
2016-03-23T08:04:44.000Z
2022-03-25T05:06:16.000Z
lib/sai_redis_fdb.cpp
vmittal-msft/sonic-sairedis
6baff35880005aee2854fdcde105c4322c28d04f
[ "Apache-2.0" ]
589
2016-04-01T04:09:09.000Z
2022-03-31T00:38:10.000Z
lib/sai_redis_fdb.cpp
vmittal-msft/sonic-sairedis
6baff35880005aee2854fdcde105c4322c28d04f
[ "Apache-2.0" ]
234
2016-03-28T20:59:21.000Z
2022-03-23T09:26:22.000Z
#include "sai_redis.h" static sai_status_t redis_flush_fdb_entries( _In_ sai_object_id_t switch_id, _In_ uint32_t attr_count, _In_ const sai_attribute_t *attr_list) { SWSS_LOG_ENTER(); return redis_sai->flushFdbEntries( switch_id, attr_count, attr_list); } REDIS_GENERIC_QUAD_ENTRY(FDB_ENTRY,fdb_entry); REDIS_BULK_QUAD_ENTRY(FDB_ENTRY,fdb_entry); const sai_fdb_api_t redis_fdb_api = { REDIS_GENERIC_QUAD_API(fdb_entry) redis_flush_fdb_entries, REDIS_BULK_QUAD_API(fdb_entry) };
20.962963
46
0.719081
vmittal-msft
0c3147ee0c397ff419ad0f65555d25cb4762e72f
2,889
cpp
C++
src/utilities.cpp
DavidR86/mxd
bf0a72305701dd5c76c2b3daa4bdba14d638b29d
[ "MIT" ]
2
2018-11-06T18:57:29.000Z
2018-11-06T19:06:36.000Z
src/utilities.cpp
DavidR86/mxd
bf0a72305701dd5c76c2b3daa4bdba14d638b29d
[ "MIT" ]
27
2018-11-12T23:45:43.000Z
2019-01-21T15:39:18.000Z
src/utilities.cpp
DavidR86/mxd
bf0a72305701dd5c76c2b3daa4bdba14d638b29d
[ "MIT" ]
3
2018-11-08T00:38:49.000Z
2020-06-18T04:40:11.000Z
// -*- coding:utf-8; mode:c++; mode:auto-fill; fill-column:80; -*- /// @file utilities.cpp /// @brief Implementation of utilities.hpp. /// @author J. Arrieta <Juan.Arrieta@nablazerolabs.com> /// @date November 13, 2018 /// @copyright (C) 2018 Nabla Zero Labs // Related mxd header #include "utilities.hpp" // C++ Standard Library #include <cerrno> #include <cstdlib> #include <fstream> #include <sstream> #include <stdexcept> #include <string> #include <system_error> // Third Party Libraries #include <GL/glew.h> #include <GLFW/glfw3.h> namespace { // anonymous namespace std::string error_string(GLenum error_code) { switch (error_code) { case GL_INVALID_ENUM: return "[GL_INVALID_ENUM] An unacceptable value is specified for an " "enumerated argument."; case GL_INVALID_VALUE: return "[GL_INVALID_VALUE] A numeric argument is out of range."; case GL_INVALID_OPERATION: return "[GL_INVALID_OPERATION] The specified operation is not allowed in " "the current state."; case GL_INVALID_FRAMEBUFFER_OPERATION: return "[GL_INVALID_FRAMEBUFFER_OPERATION] The framebuffer object is not " "complete."; case GL_OUT_OF_MEMORY: return "[GL_OUT_OF_MEMORY] There is not enough memory left to execute " "the command."; case GL_STACK_UNDERFLOW: return "[GL_STACK_UNDERFLOW] An attempt has been made to perform an " "operation that would cause an internal stack to underflow."; case GL_STACK_OVERFLOW: return "[GL_STACK_OVERFLOW] An attempt has been made to perform an " "operation that would cause an internal stack to overflow."; case GL_NO_ERROR: return "[GL_NO_ERROR] No error detected."; default: return "[???] Unwnown error code received in error_string."; } } } // anonymous namespace namespace nzl { std::string slurp(const std::string& path) { std::ifstream fp(path, std::ios::in | std::ios::binary | std::ios::ate); if (fp.good()) { std::string contents; contents.resize(fp.tellg()); fp.seekg(0, fp.beg); fp.read(contents.data(), contents.size()); fp.close(); return contents; } std::ostringstream oss; oss << "Cannot slurp file \"" << path << "\": "; throw std::system_error(errno, std::system_category(), oss.str()); } std::string get_env_var(const std::string& key) { char* val; val = std::getenv(key.c_str()); std::string ret_val = ""; if (val != nullptr) { ret_val = val; } return ret_val; } void check_gl_errors() { if (auto error_code = glGetError(); error_code != GL_NO_ERROR) { std::ostringstream oss; oss << "OpenGL errors:\n"; do { oss << " - " << error_string(error_code) << "\n"; } while ((error_code = glGetError()) != GL_NO_ERROR); throw std::runtime_error(oss.str()); } } } // namespace nzl
29.783505
80
0.653859
DavidR86
0c314d77cae5827be9cb0a090a221e26c607c17f
1,295
cpp
C++
Training/Educational Codefources round 77 - D.cpp
nicolasventer/Algorithmic-problems-in-cpp
cdd29d692c0353866a549593a25335fe816840e2
[ "MIT" ]
null
null
null
Training/Educational Codefources round 77 - D.cpp
nicolasventer/Algorithmic-problems-in-cpp
cdd29d692c0353866a549593a25335fe816840e2
[ "MIT" ]
null
null
null
Training/Educational Codefources round 77 - D.cpp
nicolasventer/Algorithmic-problems-in-cpp
cdd29d692c0353866a549593a25335fe816840e2
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int m,n,k,t; // m : allies count, n : level length, // k : trap count, t : time to succeed cin >> m >> n >> k >> t; int a[m]; for (int i = 0; i < m; ++i) { cin >> a[i]; } int l[k], r[k], d[k]; // l : trap location, r : trap disable location, d : trap difficulty int sl[k]; for (int i = 0; i < k; ++i) { cin >> l[i] >> r[i] >> d[i]; sl[i] = i; } sort(a, a+m); sort(sl, sl+k, [&](int a, int b) { return l[a] < l[b]; }); auto check = [&](int N) { vector<int> v; for (int i = 0; i < k; ++i) { if (d[sl[i]] > N) v.push_back(sl[i]); } int time_spent = 0; int unlocked_to = 0; for (auto u : v) { if (r[u] <= unlocked_to) { continue; } if (unlocked_to < l[u]) { unlocked_to = l[u] - 1; } time_spent += r[u] - unlocked_to; unlocked_to = r[u]; } return (n + 1) + (time_spent << 1) <= t; // mult by 2 }; int low = 0; int high = m-1; if (!check(a[m-1])) { cout << 0 << endl; return 0; } while(low < high) { int mid = (low + high) >> 1; // div by 2 if (check(a[mid])) high = mid; else low = mid + 1; } cout << m - low << endl; return 0; }
15.987654
69
0.493436
nicolasventer
0c35e6491d9db1cae4480fc128fcdcca93466123
1,710
hpp
C++
libvast/vast/system/query_supervisor_actor.hpp
a4z/vast
2ce9ddbac61cc7f195434b06fe3605f0bdeec520
[ "BSD-3-Clause" ]
null
null
null
libvast/vast/system/query_supervisor_actor.hpp
a4z/vast
2ce9ddbac61cc7f195434b06fe3605f0bdeec520
[ "BSD-3-Clause" ]
null
null
null
libvast/vast/system/query_supervisor_actor.hpp
a4z/vast
2ce9ddbac61cc7f195434b06fe3605f0bdeec520
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #pragma once #include "vast/fwd.hpp" #include "vast/system/index_client_actor.hpp" #include "vast/system/partition_actor.hpp" #include "vast/uuid.hpp" #include <caf/detail/unordered_flat_map.hpp> #include <caf/typed_actor.hpp> #include <vector> namespace vast::system { /// A set of relevant partition actors, and their uuids. using query_map = std::vector<std::pair<uuid, partition_actor>>; /// The QUERY SUPERVISOR actor interface. using query_supervisor_actor = caf::typed_actor< /// Reacts to an expression and a set of relevant partitions by /// sending several `vast::ids` to the index_client_actor, followed /// by a final `atom::done`. caf::reacts_to<expression, query_map, index_client_actor>>; } // namespace vast::system
42.75
80
0.511111
a4z
0c36ef700c32429eaec2a659aff73149f1ef6539
907
hpp
C++
src/Parse/Lex/SourceFile.hpp
wexaris/Scarlett
051e4468ae8520545a267d4b22671580eb3841a7
[ "Apache-2.0" ]
1
2019-06-25T14:23:02.000Z
2019-06-25T14:23:02.000Z
src/Parse/Lex/SourceFile.hpp
wexaris/Scarlett
051e4468ae8520545a267d4b22671580eb3841a7
[ "Apache-2.0" ]
null
null
null
src/Parse/Lex/SourceFile.hpp
wexaris/Scarlett
051e4468ae8520545a267d4b22671580eb3841a7
[ "Apache-2.0" ]
null
null
null
#pragma once #include <fstream> namespace scar { class SourceFile { public: explicit SourceFile(const std::string& path); std::string_view GetString(size_t start, size_t count, bool stopAtNewline = false) const; char GetChar(size_t pos) const { return m_Text[pos]; } std::string GetFileName() const; const std::string& GetFilePath() const { return m_FilePath; } size_t GetLength() const { return m_Text.length(); } bool IsEOF() const { return m_File.eof(); } private: std::ifstream m_File; const std::string m_FilePath; std::string m_Text; }; class SourceMap { public: static SourceFile* Load(const std::string& path); static SourceFile* Find(const std::string& path); private: static std::vector<Scope<SourceFile>> s_Files; }; }
26.676471
98
0.603087
wexaris
0c3dbe6b1ecd6b9ca33866aa4d0bfa7afd523034
162
cpp
C++
examples/intx/main.cpp
Costallat/hunter
dc0d79cb37b30cad6d6472d7143fe27be67e26d5
[ "BSD-2-Clause" ]
2,146
2015-01-10T07:26:58.000Z
2022-03-21T02:28:01.000Z
examples/intx/main.cpp
koinos/hunter
fc17bc391210bf139c55df7f947670c5dff59c57
[ "BSD-2-Clause" ]
1,778
2015-01-03T11:50:30.000Z
2019-12-26T05:31:20.000Z
examples/intx/main.cpp
koinos/hunter
fc17bc391210bf139c55df7f947670c5dff59c57
[ "BSD-2-Clause" ]
734
2015-03-05T19:52:34.000Z
2022-02-22T23:18:54.000Z
// Copyright(c) 2019, Pawel Bylica #include <intx/intx.hpp> int main() { auto r = intx::uint512{1, 0} / intx::uint512{1}; return static_cast<int>(r); }
16.2
52
0.623457
Costallat
0c40ed132ca8d7a36cd34a4a99857eb8a82539b6
2,348
cpp
C++
cplusplus/ListNode.cpp
cherishman2005/nginx-consul
fc6a1a36244237f9c664749a06af09b0c4636f64
[ "MIT" ]
2
2020-10-28T13:15:39.000Z
2022-01-06T08:42:49.000Z
cplusplus/ListNode.cpp
cherishman2005/nginx-consul
fc6a1a36244237f9c664749a06af09b0c4636f64
[ "MIT" ]
10
2021-11-03T07:54:41.000Z
2022-03-17T08:57:37.000Z
cplus/ListNode.cpp
cherishman2005/nginx-modules
ccec0b4719c7fa6622684fd2e849adf2d3a421a6
[ "MIT" ]
null
null
null
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <vector> #include <set> #include <map> #include <unordered_map> #include <algorithm> #include <cmath> #include <sstream> #include <iterator> #include <math.h> #include <string> using namespace std; // alloc-dealloc-mismatch /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; class Solution { public: ListNode* removeElements(ListNode* head, int val) { vector<int> vec; for (ListNode *p = head; p; p = p->next) { ListNode *q = p; if (p->val != val) { vec.push_back(p->val); } //free(q); } copy(vec.begin(), vec.end(), ostream_iterator<int>(cout, ",")); cout << endl; ListNode *h = nullptr; ListNode *p = nullptr; for (auto e : vec) { ListNode *q = new ListNode(e); //q->val = e; //q->next = nullptr; if (!p) { p = q; h = p; } else { p->next = q; p = q; } } return h; } //private: ListNode* createList(const vector<int> &vec) { ListNode *h = nullptr; ListNode *p = nullptr; for (auto e : vec) { ListNode *q = new ListNode(e); //q->val = e; //q->next = nullptr; if (!p) { p = q; h = p; } else { p->next = q; p = q; } } return h; } }; int main() { int s = 7; vector<int> nums = {2,3,1,2,4,3}; Solution solution; ListNode* head = solution.createList(nums); auto o = solution.removeElements(head, 1); cout << o << endl; //std::copy(o.begin(), o.end(), ostream_iterator<int>(std::cout, ",")); return 0; }
21.541284
75
0.470187
cherishman2005
0c4a7abdd33058ef06a4834193430eb20bcd426f
3,069
hpp
C++
cppcache/include/geode/internal/functional.hpp
vaijira/geode-native
5a46b659b86ecc4890df59c1b7abe727192e5d06
[ "Apache-2.0" ]
null
null
null
cppcache/include/geode/internal/functional.hpp
vaijira/geode-native
5a46b659b86ecc4890df59c1b7abe727192e5d06
[ "Apache-2.0" ]
null
null
null
cppcache/include/geode/internal/functional.hpp
vaijira/geode-native
5a46b659b86ecc4890df59c1b7abe727192e5d06
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 GEODE_UTIL_FUNCTIONAL_H_ #define GEODE_UTIL_FUNCTIONAL_H_ #include <functional> #include <memory> #include <type_traits> #include <string> #include <codecvt> #include <locale> namespace apache { namespace geode { namespace client { namespace internal { template <class _T> struct dereference_hash; template <class _T> struct dereference_hash<std::shared_ptr<_T>> : public std::unary_function<std::shared_ptr<_T>, size_t> { size_t operator()(const std::shared_ptr<_T>& val) const { return std::hash<_T>{}(*val); } }; template <class _T> struct dereference_hash<_T*> : public std::unary_function<_T*, size_t> { typedef _T* argument_type; size_t operator()(const argument_type& val) const { return std::hash<_T>{}(*val); } }; template <class _T> struct dereference_equal_to; template <class _T> struct dereference_equal_to<std::shared_ptr<_T>> : public std::binary_function<std::shared_ptr<_T>, std::shared_ptr<_T>, bool> { constexpr bool operator()(const std::shared_ptr<_T>& lhs, const std::shared_ptr<_T>& rhs) const { return std::equal_to<_T>{}(*lhs, *rhs); } }; template <class _T> struct dereference_equal_to<_T*> : std::equal_to<_T*> { typedef _T* first_argument_type; typedef _T* second_argument_type; constexpr bool operator()(const first_argument_type& lhs, const second_argument_type& rhs) const { return std::equal_to<_T>{}(*lhs, *rhs); } }; /** * Hashes based on the same algorithm used in the Geode server. * * @tparam _T class type to hash. */ template <class _T> struct geode_hash { typedef _T argument_type; int32_t operator()(const argument_type& val); }; /** * Hashes like java.lang.String */ template <> struct geode_hash<std::u16string> { inline int32_t operator()(const std::u16string& val) { int32_t hash = 0; for (auto&& c : val) { hash = 31 * hash + c; } return hash; } }; /** * Hashes like java.lang.String */ template <> struct geode_hash<std::string> { int32_t operator()(const std::string& val); }; } // namespace internal } // namespace client } // namespace geode } // namespace apache #endif // GEODE_UTIL_FUNCTIONAL_H_
26.456897
75
0.692408
vaijira
0c4bbe230d1fc0348c2063c7a6302d79209a26d0
4,174
cxx
C++
STEER/STEERBase/AliPIDValues.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
STEER/STEERBase/AliPIDValues.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
STEER/STEERBase/AliPIDValues.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /////////////////////////////////////////////////////////////////////////// // PID Values // // // // // /* Class to store PID information for each particle species */ // // /////////////////////////////////////////////////////////////////////////// #include "AliPIDValues.h" ClassImp(AliPIDValues) AliPIDValues::AliPIDValues() : TObject(), fPIDStatus(AliPIDResponse::kDetPidOk) { // // default constructor // Int_t nspecies=AliPID::kSPECIESCN; for (Int_t i=0; i<nspecies; ++i) fValues[i]=0.; } //_______________________________________________________________________ AliPIDValues::AliPIDValues(const AliPIDValues &val) : TObject(val), fPIDStatus(val.fPIDStatus) { // // copy constructor // Int_t nspecies=AliPID::kSPECIESCN; for (Int_t i=0; i<nspecies; ++i) fValues[i]=val.fValues[i]; } //_______________________________________________________________________ AliPIDValues::AliPIDValues(Double_t val[], Int_t nspecies, AliPIDResponse::EDetPidStatus status) : TObject(), fPIDStatus(AliPIDResponse::kDetPidOk) { // // constructor with array of values // SetValues(val,nspecies,status); } //_______________________________________________________________________ AliPIDValues& AliPIDValues::operator= (const AliPIDValues &val) { // // assignment operator // if (this!=&val){ TObject::operator=(val); Int_t nspecies=AliPID::kSPECIESCN; for (Int_t i=0; i<nspecies; ++i) fValues[i]=val.fValues[i]; fPIDStatus=val.fPIDStatus; } return *this; } //_______________________________________________________________________ void AliPIDValues::Copy(TObject &obj) const { // this overwrites the virtual TObject::Copy() // to allow run time copying without casting // in AliPIDValues if(this==&obj)return; AliPIDValues *robj = dynamic_cast<AliPIDValues*>(&obj); if(!robj)return; // not AliPIDValues *robj = *this; } //_______________________________________________________________________ void AliPIDValues::SetValues(const Double_t val[], Int_t nspecies, AliPIDResponse::EDetPidStatus status) { // // set array of values // if (nspecies>AliPID::kSPECIESCN) nspecies=AliPID::kSPECIESCN; for (Int_t i=0; i<nspecies; ++i) fValues[i]=val[i]; fPIDStatus=status; } //_______________________________________________________________________ AliPIDResponse::EDetPidStatus AliPIDValues::GetValues(Double_t val[], Int_t nspecies) const { // // get array of values // if (nspecies>AliPID::kSPECIESCN) nspecies=AliPID::kSPECIESCN; for (Int_t i=0; i<nspecies; ++i) val[i]=fValues[i]; return fPIDStatus; } //_______________________________________________________________________ Double_t AliPIDValues::GetValue(AliPID::EParticleType type) const { // // get values for a specific particle type // return fValues[(Int_t)type]; }
32.866142
104
0.597748
AllaMaevskaya
0c4d137b5a8fae311a045bfe03b3486cbae24886
9,537
cpp
C++
src/caffe/layers/mkldnn_convolution_layer.cpp
shayanshams66/caffe
3b031d59cd6a419b433e9fe05c9fe4bfc3060f4e
[ "Intel", "BSD-2-Clause" ]
1
2017-01-04T03:35:46.000Z
2017-01-04T03:35:46.000Z
src/caffe/layers/mkldnn_convolution_layer.cpp
shayanshams66/caffe
3b031d59cd6a419b433e9fe05c9fe4bfc3060f4e
[ "Intel", "BSD-2-Clause" ]
null
null
null
src/caffe/layers/mkldnn_convolution_layer.cpp
shayanshams66/caffe
3b031d59cd6a419b433e9fe05c9fe4bfc3060f4e
[ "Intel", "BSD-2-Clause" ]
null
null
null
#ifdef MKLDNN_SUPPORTED #include <algorithm> #include <cstdlib> #include <vector> #include "caffe/filler.hpp" #include "caffe/layer.hpp" #include "caffe/layers/mkldnn_layers.hpp" #include "mkl_service.h" // TODO: Correct process case if there are no bias // TODO: Exception handling - mkl-dnn produces exceptions on errors namespace caffe { template <typename Dtype> MKLDNNConvolutionLayer<Dtype>::MKLDNNConvolutionLayer(const LayerParameter& param) : ConvolutionLayer<Dtype>(param) , fwd_bottom_data(NULL) , fwd_top_data(NULL) , fwd_weights_data(NULL) , fwd_bias_data(NULL) , convFwd_pd(NULL) , convFwd(NULL) { } template <typename Dtype> void MKLDNNConvolutionLayer<Dtype>::compute_output_shape() { ConvolutionLayer<Dtype>::compute_output_shape(); this->height_out_ = (this->height_ + 2 * this->pad_h_ - this->kernel_h_) / this->stride_h_ + 1; this->width_out_ = (this->width_ + 2 * this->pad_w_ - this->kernel_w_) / this->stride_w_ + 1; } template <typename Dtype> void MKLDNNConvolutionLayer<Dtype>::init_properties(const vector<Blob<Dtype>*>& bottom , const vector<Blob<Dtype>*>& top) { this->stride_w_ = this->stride_.cpu_data()[0]; this->stride_h_ = this->stride_.cpu_data()[1]; this->width_ = bottom[0]->width(); this->height_ = bottom[0]->height(); this->pad_w_ = this->pad_.cpu_data()[0]; this->pad_h_ = this->pad_.cpu_data()[1]; this->kernel_w_ = this->kernel_shape_.cpu_data()[0]; this->kernel_h_ = this->kernel_shape_.cpu_data()[1]; } template <typename Dtype> void MKLDNNConvolutionLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom , const vector<Blob<Dtype>*>& top) { VLOG(1) << "<< MKLDNNConvolutionLayer<Dtype>::LayerSetUp: " << this->layer_param_.name(); ConvolutionLayer<Dtype>::LayerSetUp(bottom, top); init_properties(bottom, top); this->bottom_shape_ = &bottom[0]->shape(); } template <typename Dtype> void MKLDNNConvolutionLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom , const vector<Blob<Dtype>*>& top) { VLOG(1) << " MKLDNNConvolutionLayer<Dtype>::Reshape: " << this->layer_param_.name(); BaseConvolutionLayer<Dtype>::Reshape(bottom, top); init_properties(bottom, top); } template <typename Dtype> void MKLDNNConvolutionLayer<Dtype>::InitConvolution(const vector<Blob<Dtype>*>& bottom , const vector<Blob<Dtype>*>& top) { if (std::is_same<Dtype, double>::value) NOT_IMPLEMENTED; uint32_t g = std::max(this->group_, 1); uint32_t n = this->num_; uint32_t iw = this->width_; uint32_t ih = this->height_; uint32_t ic = this->channels_; uint32_t ow = this->width_out_; uint32_t oh = this->height_out_; uint32_t oc = this->num_output_; uint32_t kw = this->kernel_w_; uint32_t kh = this->kernel_h_; tensor::dims convolutionStrides {this->stride_h_, this->stride_w_}; tensor::nd_offset padding {this->pad_h_, this->pad_w_}; // ---- Initialize memory descriptors (fromat = any) to create convolution descriptor ------------- memory::precision mpcsn = memory::precision::f32; memory::format mfmt_any = memory::format::any; engine cpu_engine = CpuEngine::Instance().get_engine(); tensor::dims input_tz = {n, ic, ih, iw}; tensor::dims bias_tz = {oc}; tensor::dims output_tz = {n, oc, oh, ow}; tensor::dims weights_tz = ( g!= 1) ? tensor::dims{g, oc/g, ic/g, kh, kw} : tensor::dims{oc, ic, kh, kw}; // ---- Memory descriptors for initializing of convolution primitive descriptor ------------- memory::desc init_input_md({input_tz}, mpcsn, mfmt_any); memory::desc init_bias_md({bias_tz}, mpcsn, mfmt_any); memory::desc init_output_md({output_tz}, mpcsn, mfmt_any); memory::desc init_weights_md({weights_tz}, mpcsn, mfmt_any); // ---- Initialize convolution primitive descriptor ------------- convolution::desc convFwd_desc(prop_kind::forward, convolution::direct, init_input_md , init_weights_md, init_bias_md , init_output_md, convolutionStrides , padding, padding_kind::zero); convFwd_pd.reset(new convolution::primitive_desc(convFwd_desc, cpu_engine)); // -- Memory descriptors initialization ------------------------------------------ // ---- Get memory descriptors from convolution primitive descriptor ------------- memory::desc prv_input_md(convFwd_pd->data.src_primitive_desc.memory_desc); memory::desc prv_weights_md(convFwd_pd->data.weights_primitive_desc.memory_desc); memory::desc prv_bias_md(convFwd_pd->data.bias_primitive_desc.memory_desc); memory::desc prv_output_md(convFwd_pd->data.dst_primitive_desc.memory_desc); typedef typename memory::primitive_desc MemPD; // short name for memory::primitive_desc // ---- Create priv memory primitive descriptors stored as class members ------------- shared_ptr<MemPD> prv_input_memory_pd(new MemPD(prv_input_md, cpu_engine)); shared_ptr<MemPD> prv_bias_memory_pd(new MemPD(prv_bias_md, cpu_engine)); shared_ptr<MemPD> prv_output_memory_pd(new MemPD(prv_output_md, cpu_engine)); shared_ptr<MemPD> prv_weights_memory_pd(new MemPD(prv_weights_md, cpu_engine)); // ---- Create usr memory primitive descriptors ------------- memory::format mfmt_nchw = memory::format::nchw; memory::format weights_mfmt = ( g!= 1) ? memory::format::goihw : memory::format::oihw; shared_ptr<MemPD> usr_input_memory_pd(new MemPD({{input_tz}, mpcsn, mfmt_nchw}, cpu_engine)); shared_ptr<MemPD> usr_bias_memory_pd(new MemPD({{bias_tz}, mpcsn, memory::format::x}, cpu_engine)); shared_ptr<MemPD> usr_output_memory_pd(new MemPD({{output_tz}, mpcsn, mfmt_nchw}, cpu_engine)); shared_ptr<MemPD> usr_weights_memory_pd(new MemPD({{weights_tz}, mpcsn, weights_mfmt}, cpu_engine)); fwd_bottom_data.reset(new MKLDNNData<Dtype>(usr_input_memory_pd, prv_input_memory_pd)); fwd_top_data.reset(new MKLDNNData<Dtype>(usr_output_memory_pd, prv_output_memory_pd)); fwd_weights_data.reset(new MKLDNNData<Dtype>(usr_weights_memory_pd, prv_weights_memory_pd)); if (this->bias_term_) { fwd_bias_data.reset(new MKLDNNData<Dtype>(usr_bias_memory_pd, prv_bias_memory_pd)); } // Names are for debugging purposes only. fwd_bottom_data ->name = "fwd_bottom_data @ " + this->layer_param_.name(); fwd_top_data ->name = "fwd_top_data @ " + this->layer_param_.name(); fwd_weights_data->name = "fwd_weights_data @ " + this->layer_param_.name(); fwd_bias_data ->name = "fwd_bias_data @ " + this->layer_param_.name(); // ---- Create memory --------------------- input_memory.reset(new memory(*fwd_bottom_data->prv_memory_pd() ,fwd_bottom_data->get_blob_data_ptr(bottom[0], false))); weights_memory.reset(new memory(*fwd_weights_data->prv_memory_pd() ,fwd_weights_data->get_blob_data_ptr(this->blobs_[0].get(), true))); bias_memory.reset(new memory(*fwd_bias_data->prv_memory_pd() ,fwd_bias_data->get_blob_data_ptr(this->blobs_[1].get(), true))); if (fwd_top_data->conversion_needed()) top[0]->set_prv_data_descriptor(fwd_top_data); output_memory = fwd_top_data->create_output_memory(top[0]); // ---- Create convolution -------------------- convFwd.reset(new convolution(*convFwd_pd , *input_memory, *weights_memory , *bias_memory, *output_memory)); } template <typename Dtype> void MKLDNNConvolutionLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom , const vector<Blob<Dtype>*>& top) { VLOG(1) << "MKLDNNConvolutionLayer<Dtype>::Forward_cpu: " << this->layer_param_.name(); if( convFwd_pd == NULL) { InitConvolution(bottom, top); } else { fwd_bottom_data->sync_blob_prv_data(bottom[0]); fwd_weights_data->sync_blob_prv_data(this->blobs_[0].get()); fwd_bias_data->sync_blob_prv_data(this->blobs_[1].get()); if (fwd_top_data->conversion_needed()) top[0]->set_prv_data_descriptor(fwd_top_data); } stream().submit({*convFwd}).wait(); } template <typename Dtype> void MKLDNNConvolutionLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top , const vector<bool>& propagate_down , const vector<Blob<Dtype>*>& bottom) { NOT_IMPLEMENTED; } #ifdef CPU_ONLY STUB_GPU(MKLDNNConvolutionLayer); #else template <typename Dtype> void MKLDNNConvolutionLayer<Dtype>::Forward_gpu(const vector<Blob<Dtype>*>& bottom , const vector<Blob<Dtype>*>& top) { NOT_IMPLEMENTED; } template <typename Dtype> void MKLDNNConvolutionLayer<Dtype>::Backward_gpu(const vector<Blob<Dtype>*>& top , const vector<bool>& propagate_down , const vector<Blob<Dtype>*>& bottom) { NOT_IMPLEMENTED; } #endif INSTANTIATE_CLASS(MKLDNNConvolutionLayer); } // namespace caffe #endif // #ifdef MKLDNN_SUPPORTED
43.153846
108
0.646849
shayanshams66
0c5155114a8aae5d9994e8f39346187058754bcf
833
cpp
C++
muduo/EventLoopThread.cpp
13015517713/MyMuduo
eb864450e8827a1ed46c642b16e808b7a9d4f50f
[ "MIT" ]
null
null
null
muduo/EventLoopThread.cpp
13015517713/MyMuduo
eb864450e8827a1ed46c642b16e808b7a9d4f50f
[ "MIT" ]
1
2020-12-26T15:05:30.000Z
2020-12-26T15:05:30.000Z
muduo/EventLoopThread.cpp
13015517713/MyMuduo
eb864450e8827a1ed46c642b16e808b7a9d4f50f
[ "MIT" ]
null
null
null
#include "EventLoopThread.h" #include "EventLoop.h" EventLoopThread::EventLoopThread(const ThreadInitCallback &cb, const std::string &name) :_threadInitCallback(cb), _loop(NULL), _thread(std::bind(&EventLoopThread::threadFunc,this),name), _exiting(false) { sem_init(&_sem, 0, 0); } EventLoopThread::~EventLoopThread(){} // 执行threadFunc 初始化loop EventLoop *EventLoopThread::startLoop(){ _thread.start(); sem_wait(&_sem); return _loop; } // 开启线程执行循环 void EventLoopThread::threadFunc(){ EventLoop loop; if (_threadInitCallback){ _threadInitCallback(&loop); } _loop = &loop; sem_post(&_sem); loop.loop(); // 整个线程的核心就是让Loop跑起来 { std::lock_guard<std::mutex> tmutex(_mutex); _loop = NULL; } }
23.138889
71
0.619448
13015517713
0c51933a6ee355b008b811dbd930b8ad2af64514
4,739
cpp
C++
libs/neuro/test/tests.cpp
rufus-stone/genetic-algo-cpp
5e31f080d30ffc204fa7891883703183302b2954
[ "MIT" ]
null
null
null
libs/neuro/test/tests.cpp
rufus-stone/genetic-algo-cpp
5e31f080d30ffc204fa7891883703183302b2954
[ "MIT" ]
null
null
null
libs/neuro/test/tests.cpp
rufus-stone/genetic-algo-cpp
5e31f080d30ffc204fa7891883703183302b2954
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN // This tells the Catch2 header to generate a main #include "catch.hpp" #include <random> #include <vector> #include <neuro/nn.hpp> TEST_CASE("Neural Network", "[nn][network]") { // Seed an mt19937 for a predictable "random" number to use for testing auto prng = std::mt19937{0}; // Define our layer topologies auto layer_topologies = std::vector<nn::LayerTopology>{{3}, {5}, {1}}; REQUIRE(layer_topologies.size() == 3); // Roll a new Network with randomly chosen Neuron values in each layer auto nn = nn::Network::random(prng, layer_topologies); // Check the weights of the entire network REQUIRE_THAT(nn.weights(), Catch::Matchers::Approx(std::vector<double>{0.185689233, 0.6885314885, 0.71589124, 0.6945034748, 0.247127393, -0.2312365833, -0.4049307893, -0.8865740481, -0.4546874105, -0.0446697765, 0.6243374533, -0.0400456569, -0.2144304134, 0.6721575381, -0.3252076767, 0.2963437532, -0.2635169253, 0.914310309, -0.7192984448, 0.7401745025, -0.0527839195, 0.6018215054, 0.0409549612, 0.3577590677, 0.4412653032, 0.1640395828})); // Check the bias of the first neuron in the first layer REQUIRE(nn.layers().front().neurons().front().bias() == Approx(0.185689233)); // Check the weights of the second neuron in the first layer REQUIRE_THAT(nn.layers().front().neurons()[1].weights(), Catch::Matchers::Approx(std::vector<double>{-0.2312365833, -0.4049307893, -0.8865740481})); // Propogate with the specified inputs std::vector<double> outputs = nn.propagate({1.0, -2.0, 3.5}); // Check that we only get one output REQUIRE(outputs.size() == 1); // Check the value of the output REQUIRE(outputs[0] == Approx(2.7889203667)); } TEST_CASE("Neuron Random", "[nn][neuron][random]") { // Seed an mt19937 for a predictable "random" number to use for testing auto prng = std::mt19937{0}; // Roll a new random Neuron with 4 outputs auto neuron = nn::Neuron::random(prng, 4); // Check the bias of the neuron REQUIRE(neuron.bias() == Approx(0.185689233)); // Check the number of weights for the neuron REQUIRE(neuron.weights().size() == 4); // Check the weights of the neuron REQUIRE_THAT(neuron.weights(), Catch::Matchers::Approx(std::vector<double>{0.6885314885, 0.71589124, 0.6945034748, 0.247127393})); } TEST_CASE("Neuron Propogation", "[nn][neuron][propagation]") { // Create a new Neuron with the specified bias and weights auto neuron = nn::Neuron{0.1, {-0.3, 0.6, 0.9}}; // Make up some fake input data and calculate the propogated value double output = neuron.propagate({0.5, -0.6, 0.7}); // This is effectively the calculation the .propogate() function should be performing double expected = std::max(((0.1 + (0.5 * -0.3) + (-0.6 * 0.6) + (0.7 * 0.9))), 0.0); // Check the results of the propogation match what we expected REQUIRE(output == Approx(expected)); } TEST_CASE("Neuron Output Restriction", "[nn][neuron][restriction]") { // Create a new Neuron with the specified bias and weights auto neuron = nn::Neuron{0.0, {0.5}}; // Calculate the propogated value given various different input values double v0 = neuron.propagate({-1.0}); // 0.0 + (-1.0 * 0.5) == -0.5 so this should produce 0.0 double v1 = neuron.propagate({-0.5}); // 0.0 + (-0.5 * 0.5) == -0.25 so this should produce 0.0 double v2 = neuron.propagate({0.0}); // 0.0 + (0.0 * 0.5) == 0.0 so this should produce 0.0 double v3 = neuron.propagate({0.5}); // 0.0 + (0.5 * 0.5) == 0.25 so this should produce 0.25 double v4 = neuron.propagate({1.0}); // 0.0 + (1.0 * 0.5) == 0.5 so this should produce 0.5 // Check the results of the propogation match what we expected REQUIRE(v0 == Approx(0.0)); REQUIRE(v1 == Approx(0.0)); REQUIRE(v2 == Approx(0.0)); REQUIRE(v3 == Approx(0.25)); REQUIRE(v4 == Approx(0.5)); // Create another new Neuron with a different bias and weights auto neuron2 = nn::Neuron{2.0, {0.15}}; // Calculate the propogated value given various different input values double v5 = neuron2.propagate({-1.0}); // 2.0 + (-1.0 * 0.15) == 1.85 so this should produce 1.85 double v6 = neuron2.propagate({-0.5}); // 2.0 + (-0.5 * 0.15) == 1.925 so this should produce 1.925 double v7 = neuron2.propagate({0.0}); // 2.0 + (0.0 * 0.15) == 2.0 so this should produce 2.0 double v8 = neuron2.propagate({0.5}); // 2.0 + (0.5 * 0.15) == 2.075 so this should produce 2.075 double v9 = neuron2.propagate({-7.0}); // 2.0 + (-7.0 * 0.15) == 0.95 so this should produce 0.95 // Check the results of the propogation match what we expected REQUIRE(v5 == Approx(1.85)); REQUIRE(v6 == Approx(1.925)); REQUIRE(v7 == Approx(2.0)); REQUIRE(v8 == Approx(2.075)); REQUIRE(v9 == Approx(0.95)); }
41.570175
445
0.667018
rufus-stone
31af7f864ad0ee757749b3840a5d63b536ce69ee
1,739
cpp
C++
dali/devel-api/adaptor-framework/canvas-renderer-drawable-group.cpp
dalihub/dali-adaptor
b7943ae5aeb7ddd069be7496a1c1cee186b740c5
[ "Apache-2.0", "BSD-3-Clause" ]
6
2016-11-18T10:26:46.000Z
2021-11-01T12:29:05.000Z
dali/devel-api/adaptor-framework/canvas-renderer-drawable-group.cpp
dalihub/dali-adaptor
b7943ae5aeb7ddd069be7496a1c1cee186b740c5
[ "Apache-2.0", "BSD-3-Clause" ]
5
2020-07-15T11:30:49.000Z
2020-12-11T19:13:46.000Z
dali/devel-api/adaptor-framework/canvas-renderer-drawable-group.cpp
dalihub/dali-adaptor
b7943ae5aeb7ddd069be7496a1c1cee186b740c5
[ "Apache-2.0", "BSD-3-Clause" ]
7
2019-05-17T07:14:40.000Z
2021-05-24T07:25:26.000Z
/* * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * 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. * */ // CLASS HEADER #include <dali/devel-api/adaptor-framework/canvas-renderer-drawable-group.h> // INTERNAL INCLUDES #include <dali/internal/canvas-renderer/common/canvas-renderer-impl.h> #include <dali/internal/canvas-renderer/common/drawable-group-factory.h> #include <dali/internal/canvas-renderer/common/drawable-group-impl.h> namespace Dali { CanvasRenderer::DrawableGroup CanvasRenderer::DrawableGroup::New() { return DrawableGroup(Internal::Adaptor::DrawableGroupFactory::New()); } CanvasRenderer::DrawableGroup::DrawableGroup() { } CanvasRenderer::DrawableGroup::~DrawableGroup() { } CanvasRenderer::DrawableGroup::DrawableGroup(Internal::Adaptor::DrawableGroup* impl) : CanvasRenderer::Drawable(impl) { } bool CanvasRenderer::DrawableGroup::AddDrawable(Drawable& drawable) { return GetImplementation(*this).AddDrawable(drawable); } bool CanvasRenderer::DrawableGroup::RemoveDrawable(Drawable drawable) { return GetImplementation(*this).RemoveDrawable(drawable); } bool CanvasRenderer::DrawableGroup::RemoveAllDrawables() { return GetImplementation(*this).RemoveAllDrawables(); } } // namespace Dali
28.048387
84
0.772858
dalihub
31afcba4982663f8b32319a168a9d3b19b68aad3
3,381
cpp
C++
cpp_proj/cv/cam_fps/cam_fps.cpp
1487quantum/cv4_cpp
e8074a3aca72ed4bc0d9f9839f229b18fbf69222
[ "MIT" ]
7
2020-07-08T02:56:01.000Z
2021-11-10T06:09:08.000Z
cpp_proj/cv/cam_fps/cam_fps.cpp
1487quantum/cv4_cpp
e8074a3aca72ed4bc0d9f9839f229b18fbf69222
[ "MIT" ]
null
null
null
cpp_proj/cv/cam_fps/cam_fps.cpp
1487quantum/cv4_cpp
e8074a3aca72ed4bc0d9f9839f229b18fbf69222
[ "MIT" ]
1
2020-10-15T05:36:05.000Z
2020-10-15T05:36:05.000Z
#include "cam_fps.h" std::string gstreamer_pipeline(int8_t cam_id, int8_t s_mode, int display_width, int display_height, int8_t framerate, int8_t flip_method, std::string outputFormat) { return "nvarguscamerasrc sensor_id=" + std::to_string(cam_id) + " sensor_mode=" + std::to_string(s_mode) + " ! video/x-raw(memory:NVMM), format=(string)NV12, " "framerate=(fraction)" + std::to_string(framerate) + "/1 ! nvvidconv flip-method=" + std::to_string(flip_method) + " ! video/x-raw, width=(int)" + std::to_string(display_width) + ", height=(int)" + std::to_string(display_height) + ", format=(string)BGRx ! videoconvert ! video/x-raw, format=(string)" + outputFormat + " ! appsink"; } std::string addCam(int8_t id) { std::string outputFormat{"BGR"}; // BGR,GRAY8 return gstreamer_pipeline(id, s_mode, display_width, display_height, framerate, flip_method, outputFormat); } Mat drawRect(Mat img, int x, int y, int w, int h) { cv::Rect rect(x, y, w, h); cv::rectangle(img, rect, cv::Scalar(0, 255, 0)); return img; } // x, y: starting xy position for text Mat drawText(Mat img, int x, int y, std::string msg) { Point pt_loc(x, y); putText(img, msg, pt_loc, FONT_HERSHEY_COMPLEX_SMALL, 0.8, cv::Scalar(0, 200, 250), 1, LINE_AA); return img; } Mat addCross(Mat img, int x, int y, int m_size) { Point pt_loc(x, y); drawMarker(img, pt_loc, cv::Scalar(255, 255, 255), MARKER_CROSS, m_size, 1, 8); return img; } int main() { std::string camL = addCam(0); std::cout << "Running with OpenCV Version: " << CV_VERSION << "\n"; // std::cout << "Using pipeline: \n\t" << camL << "\n"; VideoCapture capL(camL, CAP_GSTREAMER); if (!capL.isOpened()) { std::cout << "Failed to open camera." << std::endl; return (-1); } namedWindow("IMG", WINDOW_AUTOSIZE); std::cout << "Hit ESC to exit" << "\n"; Mat imgL; // Camera Feed Rect wa; // Get display window size // Track time long frameCounter = 0; long fps = 0; std::time_t timeBegin = std::time(0); int tick = 0; while (true) { auto start = Time::now(); // Start timer int capr = capL.read(imgL); if (!capr) { std::cout << "Capture read error" << std::endl; break; } // std::cout << wa.x << "," << wa.y << "," << wa.width << "," << wa.height // << std::endl; // Draw a smaller rectangle overlay wa = getWindowImageRect("IMG"); // Get display width and height imgL = drawRect(imgL, wa.width * 0.25, wa.height * 0.25, wa.width * 0.5, wa.height * 0.5); // Add marker at center imgL = addCross(imgL, wa.width / 2, wa.height / 2, 20); // Display fps std::string t_fps = "FPS: " + std::to_string(fps); imgL = drawText(imgL, 30, 30, t_fps); imshow("IMG", imgL); // FPS frameCounter++; std::time_t timeNow = std::time(0) - timeBegin; if (timeNow - tick >= 1) { tick++; fps = frameCounter; // std::cout << "Frames per second: " << frameCounter << std::endl; frameCounter = 0; } // ESC to escape int keycode = waitKey(30) & 0xff; if (keycode == 27) break; } capL.release(); destroyAllWindows(); return 0; }
28.652542
80
0.575865
1487quantum
31b3b17b60bd6a072feb93c1f5955e5ebb480be9
280
cpp
C++
c3dEngine2/c3dEngine/c3dEngine/core/c3dObject.cpp
wantnon2/c3dEngine2
0c12d077d8f2bac8c12b8f720eccc5a2f3f3a7c1
[ "MIT" ]
27
2015-01-11T15:42:21.000Z
2021-10-10T06:24:37.000Z
c3dEngine2/c3dEngine/c3dEngine/core/c3dObject.cpp
wantnon2/c3dEngine2
0c12d077d8f2bac8c12b8f720eccc5a2f3f3a7c1
[ "MIT" ]
null
null
null
c3dEngine2/c3dEngine/c3dEngine/core/c3dObject.cpp
wantnon2/c3dEngine2
0c12d077d8f2bac8c12b8f720eccc5a2f3f3a7c1
[ "MIT" ]
18
2015-01-11T15:42:28.000Z
2021-10-10T06:24:38.000Z
// // c3dObject.cpp // HelloOpenGL // // Created by wantnon (yang chao) on 14-1-13. // // #include "c3dObject.h" #include "c3dAutoreleasePool.h" void Cc3dObject::autorelease(){ //add to autorelease pool Cc3dAutoreleasePool::sharedAutoreleasePool()->addObject(this); }
18.666667
66
0.696429
wantnon2
31b3c8e8770e5d38cb3cc7d938fa3d9948b26111
669
hpp
C++
include/milppp/strong_types.hpp
fhamonic/milp_builder
0e1370cded14cffd0eea9ab26860b345b48a1556
[ "BSL-1.0" ]
1
2021-09-23T11:56:33.000Z
2021-09-23T11:56:33.000Z
include/milppp/strong_types.hpp
fhamonic/milppp
0e1370cded14cffd0eea9ab26860b345b48a1556
[ "BSL-1.0" ]
null
null
null
include/milppp/strong_types.hpp
fhamonic/milppp
0e1370cded14cffd0eea9ab26860b345b48a1556
[ "BSL-1.0" ]
null
null
null
#ifndef MILPPP_STRONG_TYPES #define MILPPP_STRONG_TYPES namespace fhamonic { namespace milppp { class Var { private: int _id; public: constexpr Var(const Var & v) noexcept : _id(v.id()) {} explicit constexpr Var(const int & i) noexcept : _id(i) {} [[nodiscard]] constexpr int id() const noexcept { return _id; } }; class Constr { private: int _id; public: constexpr Constr(const Constr & c) noexcept : _id(c.id()) {} explicit constexpr Constr(const int & i) noexcept : _id(i) {} [[nodiscard]] constexpr int id() const noexcept { return _id; } }; } // namespace milppp } // namespace fhamonic #endif // MILP_BUILDER_STRONG_TYPES
22.3
67
0.675635
fhamonic
31b6de98478a4ecb9da3084ff0bbb636496de133
1,291
hpp
C++
5_Processes_Signals_Files_Pipes/4_Pipes/1_Simple-shell-pipe/src/Command/Command.hpp
PP189B/Multithreaded-programming-practice
f80378343824e51a164241289399ec92150852e8
[ "MIT" ]
null
null
null
5_Processes_Signals_Files_Pipes/4_Pipes/1_Simple-shell-pipe/src/Command/Command.hpp
PP189B/Multithreaded-programming-practice
f80378343824e51a164241289399ec92150852e8
[ "MIT" ]
null
null
null
5_Processes_Signals_Files_Pipes/4_Pipes/1_Simple-shell-pipe/src/Command/Command.hpp
PP189B/Multithreaded-programming-practice
f80378343824e51a164241289399ec92150852e8
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <string> namespace PipeApp { class Command final { // Fields private: char* command_; char** argv_; // Constructor and destructor public: Command(const std::string::const_iterator& begin, const std::string::const_iterator& end); Command(const std::string& command); Command(Command&& old); Command& operator=(Command&& old); Command(const Command& other) = delete; Command& operator=(const Command& other) = delete; ~Command(); // Logic const char* getCommand() const; char* const* getArgv(); }; //!class Command final class CommandList final { // Fields public: using container = std::vector<Command>; using iterator = typename container::iterator; private: std::vector<Command> container_; // Constructor and destructor public: CommandList(const std::string& commandline); CommandList(CommandList&& old); CommandList& operator=(CommandList&& old); CommandList(const CommandList& other) = delete; CommandList& operator=(const CommandList& other) = delete; ~CommandList() = default; // Logic iterator begin(); iterator end(); }; //!class CommandList final } //!namespace PipeApp
19.560606
63
0.648335
PP189B
31c9bef98b58e631a6af7813805cd5659a8ceb22
6,338
cpp
C++
DatabaseList/LinkedList.cpp
coreyFuller/LINKED-LIST-DATABASE
b8af8fe907d580e9c675ae20d26e940ae18e382e
[ "MIT" ]
1
2019-08-05T00:36:16.000Z
2019-08-05T00:36:16.000Z
DatabaseList/LinkedList.cpp
coreyFuller/LINKED-LIST-DATABASE
b8af8fe907d580e9c675ae20d26e940ae18e382e
[ "MIT" ]
null
null
null
DatabaseList/LinkedList.cpp
coreyFuller/LINKED-LIST-DATABASE
b8af8fe907d580e9c675ae20d26e940ae18e382e
[ "MIT" ]
null
null
null
#include "LinkedList.hpp" LinkedList::LinkedList(string cmd) { head = nullptr; nodeCount = 1; average = 0; maxSale = 0; minSale = 0; sum = 0; workerCount = 0; output.open(cmd); } LinkedList::~LinkedList() { Node * temp; cout << "Deleting Database" << endl; if(head == NULL) { cout << "Database already empty!" << endl; } else { while(head){ temp = head; head = head->next; free(temp); } cout << "Database empty!" << endl; } } void LinkedList::makeReport() { Node * temp = head; output << "\t\t\t" "***ANNUAL REPORT***" << endl << endl << endl; output << "\t" << "Owners this Year: " << endl; while(temp) { if(temp->code == 'O') { output << "-" << temp->name << endl; } temp = temp->next; } output << endl << endl << endl; temp = head; output <<"\t" <<"Managers this year: " << endl;; while(temp) { if(temp->code == 'M') { output << "-" << temp->name << endl; } temp = temp->next; } output << endl << endl << endl; temp = head; output << "\t" <<"Workers this year: " << endl; while(temp) { if(temp->code == 'W') { output << "-" << temp->name << endl; } temp = temp->next; } output << endl; temp = head; while(temp) { if(temp->sales == minSale) { output << "Lowest Earning Emloyee: "<< temp->name << endl << endl; output << temp->name << " to be terminated at next meeting." << endl; } temp = temp->next; } output << endl << endl << endl; output << "Totals Annual Sales: $" << sum << endl<< "Average Annual Sales: $"<< average << endl << endl; output << "All employees earnings greater than the average are to recieve a five percent bonus on next pay period " << endl; temp = head; while( temp) { if (temp->code == 'M') { if(temp->sales >= average) { output << "\tManager(Bonus): " << temp->name << endl; } } else if(temp->code == 'W') { if(temp->sales >= average) { output << "\tWorker(Bonus): " << temp->name << endl; } } temp = temp->next; } } void LinkedList::sumAll() { Node * temp = head; while(temp != nullptr) { sum += temp->sales; temp = temp->next; } } void LinkedList::avg() { average = sum / (double)workerCount; } void LinkedList::max() { Node * temp = head; while(temp!= nullptr) { if (maxSale < temp->sales) { maxSale = temp->sales; } temp = temp->next; } } void LinkedList::min() { Node * temp = head; while(temp!= nullptr) { if(temp->code == 'M' || temp->code =='W') { if(minSale == 0) { minSale = temp->sales; } if(temp->sales < minSale) { minSale = temp->sales; } } temp = temp->next; } } void LinkedList::pop_front() { Node * temp = head; if(isEmpty()) { cout << "List is empty!" << endl; return; } else { head = temp->next; free(temp); } } void LinkedList::pop_back() { Node * current = head; Node * temp; if(isEmpty()) { cout << "List is empty!" << endl; return; } else { while (current->next != nullptr) { temp = current; current = current->next; } free(current); temp->next = nullptr; } } void LinkedList::at(int num) { Node * temp = head; if(isEmpty()) { cout << "List is empty" << endl; } else { while (temp!= nullptr) { if (temp->key == num) { cout << "Name: " << temp->name << endl << "Code: " <<temp->code << endl; if(temp->code == 'O') { cout << "Total Sales: N/A" << endl; return; } else { cout << "\tTotal Sales: $"<<temp->sales << endl; return; } } else { temp = temp->next; } } cout << "Employee not found" << endl; } } void LinkedList::printList() { Node * temp = head; if(isEmpty()) { cout << "List is empty!" << endl; return; } else { while(temp!= nullptr) { cout << "Employee " << temp->key <<": " << temp->name << endl; cout << "Paycode: " << temp->code << endl; if(temp->code == 'O') { cout << "Total Sales: N/A " << endl; } else { cout << "Total Sales: " << temp->sales << endl; } cout << endl; temp = temp->next; } } } void LinkedList::push_back(){ Node * temp = head; Node * newNode = new Node; newNode->next = nullptr; newNode->key = nodeCount; nodeCount++; cout << "Enter name: "; cin.ignore(); getline(cin, newNode->name); cout << "Enter paycode(O/Owner, M/Manager, W/Worker): "; cin >> newNode->code; if(newNode->code == 'M' || newNode->code == 'W') { cout << "Enter sales for employee: "; cin >> newNode->sales; workerCount++; } cout << endl; if(isEmpty()) { head = newNode; minSale = newNode->sales; } else { while (temp->next != nullptr) { temp = temp->next; } temp->next = newNode; } } void LinkedList::peek_front() { if(isEmpty()) { cout << "List is empty!" << endl; return; } else { cout << "Employee " << head->key <<": " << head->name << endl; cout << "Paycode: " << head->code << endl; if(head->code == 'O') { cout << "Total Sales: N/A" << endl; } else { cout << "Total Sales: " << head->sales << endl; cout << endl; } } } void LinkedList::peek_back() { Node * temp = head; if(isEmpty()) { cout << "List is empty!" << endl; return; } else { while(temp->next != nullptr) { temp = temp->next; } cout << "Employee " << temp->key <<": " << temp->name << endl; cout << "Paycode: " << temp->code << endl; if(temp->code == 'O') { cout << "Total Sales: N/A" << endl; } else { cout << "Total Sales: " << temp->sales << endl; cout << endl; } } } bool LinkedList::isEmpty(){ if(head == nullptr) { return true; } else { return false; } } void LinkedList::push_front(){ Node * newNode = new Node; newNode->key = nodeCount; nodeCount++; cout << "Enter name: "; cin.ignore(); getline(cin, newNode->name); cout << "Enter paycode: "; cin >> newNode->code; cin.ignore(); if(newNode->code == 'M' || newNode->code == 'W') { cout << "Enter sales for employee: "; cin >> newNode->sales; workerCount++; } cout << endl; newNode->next = head; head = newNode; }
19.323171
126
0.515778
coreyFuller
31d0db86b5933eee2600384569c99c80305f2b20
1,544
cpp
C++
leetcode/num_count_tests.cpp
codetalks-new/learn-cpp
ec91c2cfba70c4c5aad52898f97e5bd2d35d9d8b
[ "MIT" ]
1
2019-12-29T15:12:14.000Z
2019-12-29T15:12:14.000Z
leetcode/num_count_tests.cpp
codetalks-new/learn-cpp
ec91c2cfba70c4c5aad52898f97e5bd2d35d9d8b
[ "MIT" ]
null
null
null
leetcode/num_count_tests.cpp
codetalks-new/learn-cpp
ec91c2cfba70c4c5aad52898f97e5bd2d35d9d8b
[ "MIT" ]
null
null
null
#include <gmock/gmock.h> #include <gtest/gtest.h> #include <iostream> #include <set> #include <string> #include <vector> using std::cout; using std::endl; using std::set; using std::string; using std::vector; int singleNumber(vector<int> nums) { int ans = 0; for (int num : nums) { ans ^= num; } return ans; } vector<int> singleNumber2(vector<int> nums) { int ab = 0; // value of a^b for (int num : nums) { ab ^= num; } int group1_flag = ab & (~(ab & (ab - 1))); int a = 0; for (int num : nums) { if (num & group1_flag) { a ^= num; } } int b = ab ^ a; if (a > b) { return {b, a}; } else { return {a, b}; } } TEST(NumCountTestSuite, SingleNumberTestCase) { EXPECT_EQ(singleNumber({2, 2, 1}), 1); EXPECT_EQ(singleNumber({4, 1, 2, 1, 2}), 4); } TEST(NumCountTestSuite, SingleNumber2TestCase) { vector<int> s1{1, 3}; EXPECT_EQ(singleNumber2({2, 2, 1, 3}), s1); vector<int> s2{3, 5}; EXPECT_EQ(singleNumber2({1, 2, 1, 3, 2, 5}), s2); } int singleNumber3(vector<int> nums) { int ones = 0, twos = 0; for (int num : nums) { ones = (ones ^ num) & ~twos; twos = (twos ^ num) & ~ones; } return ones; } TEST(NumCountTestSuite, SingleNumber3TestCase) { EXPECT_EQ(singleNumber3({2, 2, 2, 1}), 1); EXPECT_EQ(singleNumber3({2, 2, 2, 3}), 3); EXPECT_EQ(singleNumber3({4, 1, 1, 2, 2, 1, 2}), 4); } GTEST_API_ int main(int argc, char* argv[]) { printf("Running main() from %s\n", __FILE__); testing::InitGoogleMock(&argc, argv); return RUN_ALL_TESTS(); }
21.150685
53
0.59715
codetalks-new
31d73f59c3568e84418570e315430337dd11fa8a
808
cpp
C++
Lab13_Q1.cpp
xz-cs/CS2310_Lab
31d117dc1c8d31d41e0b192ad5b7a539f185800c
[ "FSFAP" ]
null
null
null
Lab13_Q1.cpp
xz-cs/CS2310_Lab
31d117dc1c8d31d41e0b192ad5b7a539f185800c
[ "FSFAP" ]
null
null
null
Lab13_Q1.cpp
xz-cs/CS2310_Lab
31d117dc1c8d31d41e0b192ad5b7a539f185800c
[ "FSFAP" ]
null
null
null
#include <fstream> using namespace std; int main() { ifstream fin; ofstream fout; fin.open("lab13.txt"); fout.open("lab13_output.txt"); if (fin.fail()) exit(1); int num; fin >> num; fin.ignore(100, 'L'); for (int i = 0; i < num; ++i) { char content[100]; fin.getline(content, 100); fout << "Student " << i + 1 << ":\nName: "; int j; for (j = 0; content[j] != ','; ++j) { fout << content[j]; } fout << "\nStudent ID: "; for (j += 2; content[j] != ' '; ++j) { fout << content[j]; } fout << "\nTel: "; for (j++; content[j] != '\0'; ++j) { fout << content[j]; } fout << "\n\n"; } fin.close(); fout.close(); return 0; }
23.085714
51
0.417079
xz-cs
31d82cc7a92c21936a8bc8c850cf746c76038eb4
55
cpp
C++
AppStandard/displayvex.cpp
100Ohm/Data-structure-Graph-Qt-Navigation-System
2b771e5913fbb73fc33e465a5e7526328c914fe9
[ "Apache-2.0" ]
6
2018-11-20T03:46:26.000Z
2020-07-04T15:33:24.000Z
AppStandard/displayvex.cpp
liziwenzzzz/Data-structure-Graph-Qt-Navigation-System
2b771e5913fbb73fc33e465a5e7526328c914fe9
[ "Apache-2.0" ]
null
null
null
AppStandard/displayvex.cpp
liziwenzzzz/Data-structure-Graph-Qt-Navigation-System
2b771e5913fbb73fc33e465a5e7526328c914fe9
[ "Apache-2.0" ]
1
2018-11-20T03:50:28.000Z
2018-11-20T03:50:28.000Z
#include "displayvex.h" DisplayVex::DisplayVex() { }
7.857143
24
0.690909
100Ohm
31d9f73c3c88a681d172157356699a70efbc2a6e
1,161
cpp
C++
tf2_src/utils/vgui_panel_zoo/SampleCheckButtons.cpp
IamIndeedGamingAsHardAsICan03489/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
4
2021-10-03T05:16:55.000Z
2021-12-28T16:49:27.000Z
tf2_src/utils/vgui_panel_zoo/SampleCheckButtons.cpp
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
null
null
null
tf2_src/utils/vgui_panel_zoo/SampleCheckButtons.cpp
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
3
2022-02-02T18:09:58.000Z
2022-03-06T18:54:39.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "DemoPage.h" #include <VGUI/IVGui.h> #include <Keyvalues.h> #include <vgui_controls/Controls.h> using namespace vgui; class SampleCheckButtons: public DemoPage { public: SampleCheckButtons(Panel *parent, const char *name); ~SampleCheckButtons(); private: }; //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- SampleCheckButtons::SampleCheckButtons(Panel *parent, const char *name) : DemoPage(parent, name) { LoadControlSettings("Demo/SampleCheckButtons.res"); } //----------------------------------------------------------------------------- // Purpose: Destructor //----------------------------------------------------------------------------- SampleCheckButtons::~SampleCheckButtons() { } Panel* SampleCheckButtons_Create(Panel *parent) { return new SampleCheckButtons(parent, "Check buttons"); }
22.764706
96
0.469423
IamIndeedGamingAsHardAsICan03489
31dcd479013bd0ed4dbb243f77297ed2c5ebacbc
6,670
hpp
C++
AutoChessServer/Dependencies/common/http_util.hpp
908760230/MyAutoChess
3421534c111d2c69ab3338925b92f093ec7ade12
[ "MIT" ]
null
null
null
AutoChessServer/Dependencies/common/http_util.hpp
908760230/MyAutoChess
3421534c111d2c69ab3338925b92f093ec7ade12
[ "MIT" ]
null
null
null
AutoChessServer/Dependencies/common/http_util.hpp
908760230/MyAutoChess
3421534c111d2c69ab3338925b92f093ec7ade12
[ "MIT" ]
null
null
null
#pragma once #include <unordered_map> namespace http { namespace util { inline char tolower(unsigned char c) { return static_cast<char>(std::tolower(c)); } template<typename String> inline bool iequal_string(const String&str1, const String& str2) { if (str1.size() != str2.size()) return false; auto iter1begin = str1.begin(); auto iter2begin = str2.begin(); auto iter1end = str1.end(); auto iter2end = str2.end(); for (; iter1begin != iter1end && iter2begin != iter2end; ++iter1begin, ++iter2begin) { if (!(toupper(*iter1begin) == toupper(*iter2begin))) { return false; } } return true; } template<typename String> struct ihash_string_functor { size_t operator()(const String &str) const noexcept { size_t h = 0; std::hash<int> hash; for (auto c : str) h ^= hash(tolower(c)) + 0x9e3779b9 + (h << 6) + (h >> 2); return h; } }; template<typename String> struct iequal_string_functor { bool operator()(const String &str1, const String &str2) const noexcept { return iequal_string(str1, str2); } }; using iequal_string_functor_t = iequal_string_functor<std::string>; using iequal_string_view_functor_t = iequal_string_functor<string_view_t>; using ihash_string_view_functor_t = ihash_string_functor<string_view_t>; using case_insensitive_multimap_view = std::unordered_multimap<string_view_t, string_view_t, ihash_string_view_functor_t, iequal_string_view_functor_t>; string_view_t readline(const char* data, size_t size, size_t& readpos) { string_view_t strref(data + readpos, size); size_t pos = strref.find("\r\n"); if (pos != string_view_t::npos) { readpos += (pos + 2); return string_view_t(strref.data(), pos); } pos = size; readpos += pos; return string_view_t(strref.data(), pos); } class http_header { public: /// Parse header fields static case_insensitive_multimap_view parse(string_view_t sv) noexcept { case_insensitive_multimap_view result; auto data = sv.data(); auto size = sv.size(); size_t rpos = 0; string_view_t line = readline(data, size, rpos); size_t param_end = 0; while ((param_end = line.find(':')) != string_view_t::npos) { size_t value_start = param_end + 1; if (value_start < line.size()) { if (line[value_start] == ' ') value_start++; if (value_start < line.size()) result.emplace(line.substr(0, param_end), line.substr(value_start, line.size() - value_start)); } line = readline(data, size, rpos); } return result; } }; class request_parser { public: /// Parse request line and header fields static bool parse(string_view_t sv, string_view_t& method, string_view_t& path, string_view_t& query_string, string_view_t& http_version, case_insensitive_multimap_view& header) noexcept { auto data = sv.data(); auto size = sv.size(); size_t rpos = 0; string_view_t line = readline(data, size, rpos); size_t method_end; if ((method_end = line.find(' ')) != string_view_t::npos) { method = line.substr(0, method_end); size_t query_start = string_view_t::npos; size_t path_and_query_string_end = string_view_t::npos; for (size_t i = method_end + 1; i < line.size(); ++i) { if (line[i] == '?' && (i + 1) < line.size()) { query_start = i + 1; } else if (line[i] == ' ') { path_and_query_string_end = i; break; } } if (path_and_query_string_end != string_view_t::npos) { if (query_start != string_view_t::npos) { path = line.substr(method_end + 1, query_start - method_end - 2); query_string = line.substr(query_start, path_and_query_string_end - query_start); } else path = line.substr(method_end + 1, path_and_query_string_end - method_end - 1); size_t protocol_end; if ((protocol_end = line.find('/', path_and_query_string_end + 1)) != string_view_t::npos) { if (line.compare(path_and_query_string_end + 1, protocol_end - path_and_query_string_end - 1, "HTTP") != 0) return false; http_version = line.substr(protocol_end + 1, line.size() - protocol_end - 1); } else return false; header = http_header::parse(string_view_t{ data + rpos,size - rpos }); } else return false; } else return false; return true; } }; template<typename TMap, typename TKey, typename TValue> inline bool try_get_header(const TMap& map, const TKey& key, TValue& value) { auto iter = map.find(key); if (iter != map.end()) { value = iter->second; return true; } return false; } } }
38.554913
199
0.458621
908760230
31de40c1e4a2c98c403ea8b53f4fba1cf8319d0b
93
cpp
C++
Windows/VS2017/vtkCommonExecutionModel/vtkCommonExecutionModel.cpp
WinBuilds/VTK
508ab2644432973724259184f2cb83aced602484
[ "BSD-3-Clause" ]
null
null
null
Windows/VS2017/vtkCommonExecutionModel/vtkCommonExecutionModel.cpp
WinBuilds/VTK
508ab2644432973724259184f2cb83aced602484
[ "BSD-3-Clause" ]
null
null
null
Windows/VS2017/vtkCommonExecutionModel/vtkCommonExecutionModel.cpp
WinBuilds/VTK
508ab2644432973724259184f2cb83aced602484
[ "BSD-3-Clause" ]
null
null
null
#include "vtkCommonExecutionModel.h" vtkCommonExecutionModel::vtkCommonExecutionModel() { }
15.5
50
0.827957
WinBuilds
31e0ad5ce83577814a44c6b123e57167d84f7247
2,122
cc
C++
cinnrt/host_context/mlir_exec.cc
Aurelius84/CINN
2de029387f7526f0a46d5bed9060d7e8f7a70767
[ "Apache-2.0" ]
null
null
null
cinnrt/host_context/mlir_exec.cc
Aurelius84/CINN
2de029387f7526f0a46d5bed9060d7e8f7a70767
[ "Apache-2.0" ]
null
null
null
cinnrt/host_context/mlir_exec.cc
Aurelius84/CINN
2de029387f7526f0a46d5bed9060d7e8f7a70767
[ "Apache-2.0" ]
null
null
null
#include <llvm/Support/CommandLine.h> #include <iostream> #include <string> #include "cinnrt/common/global.h" #include "cinnrt/dialect/mlir_loader.h" #include "cinnrt/host_context/core_runtime.h" #include "cinnrt/host_context/kernel_registry.h" #include "cinnrt/host_context/mlir_to_runtime_translate.h" #include "cinnrt/kernel/basic_kernels.h" #include "cinnrt/kernel/control_flow_kernels.h" #include "cinnrt/kernel/tensor_kernels.h" #include "cinnrt/kernel/tensor_shape_kernels.h" #include "llvm/Support/DynamicLibrary.h" static llvm::cl::list<std::string> cl_shared_libs( // NOLINT "shared_libs", llvm::cl::desc("Specify shared library with kernels."), llvm::cl::ZeroOrMore, llvm::cl::MiscFlags::CommaSeparated); int main(int argc, char** argv) { using namespace llvm; // NOLINT using namespace cinnrt; // NOLINT cl::opt<std::string> input_file("i", cl::desc("Specify input filename"), cl::value_desc("input file name")); cl::ParseCommandLineOptions(argc, argv); mlir::MLIRContext* context = cinnrt::Global::getMLIRContext(); auto module = dialect::LoadMlirFile(input_file.c_str(), context); host_context::KernelRegistry registry; kernel::RegisterBasicKernels(&registry); kernel::RegisterTensorShapeKernels(&registry); kernel::RegisterTensorKernels(&registry); kernel::RegisterControlFlowKernels(&registry); // load extra shared library for (const auto& lib_path : cl_shared_libs) { std::string err; llvm::sys::DynamicLibrary dynLib = llvm::sys::DynamicLibrary::getPermanentLibrary(lib_path.c_str(), &err); if (!dynLib.isValid()) { llvm::errs() << "Load shared library failed. Error: " << err << "\n"; return 1; } if (auto reg_sym = dynLib.SearchForAddressOfSymbol("RegisterKernels")) { auto reg_func = reinterpret_cast<void (*)(host_context::KernelRegistry*)>(reg_sym); reg_func(&registry); } else { llvm::outs() << "Symbol \"RegisterKernels\" not found in \"" << lib_path << "\". Skip.\n"; } } host_context::TestMlir(module.get(), &registry); std::cout << std::endl; return 0; }
35.366667
110
0.705467
Aurelius84
31e14cdb9d51da2f200ed4b9256a1d746519ec69
359
cpp
C++
HelloWorldTest/chapter_9_07/9_7.cpp
choi2649/C-Study
790f0fd8b8c13f392183d2194348b50ad66aba7c
[ "MIT" ]
null
null
null
HelloWorldTest/chapter_9_07/9_7.cpp
choi2649/C-Study
790f0fd8b8c13f392183d2194348b50ad66aba7c
[ "MIT" ]
null
null
null
HelloWorldTest/chapter_9_07/9_7.cpp
choi2649/C-Study
790f0fd8b8c13f392183d2194348b50ad66aba7c
[ "MIT" ]
null
null
null
#include <iostream> #include <cassert> using namespace std; class Acc { private: int m_conut = 0; public: Acc operator () (int i) { m_conut += i; cout << m_conut << endl; return *this; } Acc &print() { cout << "m_count" << endl; return *this; } }; int main() { Acc acc; acc.print().print().print().print(); acc(10).print(); return 0; }
12.821429
37
0.590529
choi2649
31e74039fa98e52a5d9096164d9446482528c3b6
6,183
cpp
C++
src/StorageManager.cpp
JoaquimBreno/modhealthsupplies
4cc9108bdb54a8339e99cddf85740e8da72aac2b
[ "MIT" ]
1
2021-09-10T15:27:12.000Z
2021-09-10T15:27:12.000Z
src/StorageManager.cpp
mattheusmendonca/modhealthsupplies
4cc9108bdb54a8339e99cddf85740e8da72aac2b
[ "MIT" ]
null
null
null
src/StorageManager.cpp
mattheusmendonca/modhealthsupplies
4cc9108bdb54a8339e99cddf85740e8da72aac2b
[ "MIT" ]
3
2021-06-17T03:05:12.000Z
2021-06-19T03:39:28.000Z
#include "StorageManager.h" using namespace std; StorageManager::StorageManager() { } void StorageManager::lerInsumos(Controler &ct) { ifstream file; file.open("Estoque.csv", fstream::in); //abrir arquivo csv para leitura if(file.is_open()){ bool existeInsumo = false; while(!file.eof()){ //estrutura de repetição para ser verdade enquanto o arquivo nao chegar ao fim string aux; vector<string> atributos; string palavra; int x = 9; int local = 0; try{ getline(file, aux);//Lê linha por linha, colocando em aux if(aux.size()){ // Verifica se há conteúdo na linha istringstream linhaInsumo(aux); //Transforma em uma stream //Lê a linha do insumo e vai colocando cada palavra em um vector para ser usada como atributo //o número x corresponde ao número de atributos de cada insumo for(int i=0; i<x; i++){ getline(linhaInsumo, palavra, ','); try{ if(i==0){ // Transforma a primeira palavra no index do local local = stoi(palavra); } if(i!=0){ if(!existeInsumo){ //condição para deletar todos os insumos de todos os locais for( int i = 0; i < 28; i ++){ ct.getLocal(i).deletaTodosInsumos(); } existeInsumo = true; } //Esse switch muda o numero de iterações de acordo com a quantidade de atributos //referentes ao tipo de insumo daquela linha if(i==1){ switch(stoi(palavra)){ case VACINA: x = 10; break; case MEDICAMENTO: x = 10; break; case EPI: x = 9; break; } } //forma um vector contendo o conteudo da linha atributos.push_back(palavra); } } catch(std::invalid_argument){ //Pega o erro derivado da função stoi() cout << "Invalid argument" << endl; } } try{ Insumo *generico; //Esse switch inicializa o ponteiro "generico" com o tipo de insumo dependendo linha switch(std::stoi(atributos[0])){ // Verifica a coluna do tipo case VACINA: { generico = new Vacina(atributos); break; } case MEDICAMENTO: { generico = new Medicamento(atributos); break; } case EPI: { generico = new Epi(atributos); break; } } //Cadastra o insumo da linha no local da linha ct.getLocal(local).setInsumo(generico); } catch(std::exception){ cout << " Ocorreu um erro " << endl; } } } catch(std::exception){ cout << " Ocorreu um erro " << endl; } } file.close(); } else{ cout<< "Não foi possivel abrir o arquivo!" << endl; } } void StorageManager::salvarInsumos(Controler &ct) { for(int i = 0 ; i < 28; i++){ ct.delecaoDeInsumo(ct.getLocal(i)); } ofstream file; file.open("Estoque.csv", fstream::out); //abre o arquirvo para a escrita if(file.is_open()){ for(int x = 0; x < 28 ; x++){ //percorre os locais um por um if(ct.getLocal(x).getInsumos().size() > 0){ //Se o vector de insumos do local tiver algum insumo faça: //Percorre o vector de insumos escrevendo cada insumo no arquivo for(int i = 0; i < ct.getLocal(x).getInsumos().size(); i++){ file << ct.getLocal(x).getIndex() << ","; file << ct.getLocal(x).getInsumos()[i]->getTipoInsumo() << ","; file << ct.getLocal(x).getInsumos()[i]->getNome() << ","; file << ct.getLocal(x).getInsumos()[i]->getQuantidade() << ","; file << ct.getLocal(x).getInsumos()[i]->getValorUnit() << ","; file << ct.getLocal(x).getInsumos()[i]->getDtVencimento() << ","; file << ct.getLocal(x).getInsumos()[i]->getNomeFabricante() << ","; //Parte personalizada dos atributos de acordo com o tipo de insumo ct.getLocal(x).getInsumos()[i]->salvaAtributos(file); } } } file.close(); }else{ cout << "Nao foi possivel abrir o arquivo!" << endl; } }
40.677632
114
0.377001
JoaquimBreno
31ec367139282e388b636b5ef3f6913751c8b628
94,708
cpp
C++
corelib/src/util3d.cpp
redater/PAM-BATR
3fc8f95972ec13963a53c5448921b59df80a8c8b
[ "BSD-3-Clause" ]
1
2017-05-25T20:41:33.000Z
2017-05-25T20:41:33.000Z
corelib/src/util3d.cpp
redater/PAM-BATR
3fc8f95972ec13963a53c5448921b59df80a8c8b
[ "BSD-3-Clause" ]
null
null
null
corelib/src/util3d.cpp
redater/PAM-BATR
3fc8f95972ec13963a53c5448921b59df80a8c8b
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2010-2014, Mathieu Labbe - IntRoLab - Universite de Sherbrooke 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 Universite de Sherbrooke nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <rtabmap/core/EpipolarGeometry.h> #include <rtabmap/utilite/UMath.h> #include <rtabmap/utilite/UStl.h> #include <rtabmap/utilite/ULogger.h> #include <pcl/registration/transformation_estimation_svd.h> #include <pcl/registration/transformation_estimation_2D.h> #include <pcl/registration/correspondence_rejection_sample_consensus.h> #include <pcl/registration/icp_nl.h> #include <pcl/io/pcd_io.h> #include <pcl/common/distances.h> #include <pcl/surface/gp3.h> #include <pcl/features/normal_3d_omp.h> #include <pcl/surface/mls.h> #include <pcl/ModelCoefficients.h> #include <pcl/segmentation/sac_segmentation.h> #include <opencv2/calib3d/calib3d.hpp> #include <opencv2/video/tracking.hpp> #include <rtabmap/core/VWDictionary.h> #include <cmath> #include <stdio.h> #include "rtabmap/utilite/UConversion.h" #include "rtabmap/utilite/UTimer.h" #include "rtabmap/core/util3d.h" #include "rtabmap/core/Signature.h" #include <pcl/filters/random_sample.h> namespace rtabmap { namespace util3d { cv::Mat bgrFromCloud(const pcl::PointCloud<pcl::PointXYZRGBA> & cloud, bool bgrOrder) { cv::Mat frameBGR = cv::Mat(cloud.height,cloud.width,CV_8UC3); for(unsigned int h = 0; h < cloud.height; h++) { for(unsigned int w = 0; w < cloud.width; w++) { if(bgrOrder) { frameBGR.at<cv::Vec3b>(h,w)[0] = cloud.at(h*cloud.width + w).b; frameBGR.at<cv::Vec3b>(h,w)[1] = cloud.at(h*cloud.width + w).g; frameBGR.at<cv::Vec3b>(h,w)[2] = cloud.at(h*cloud.width + w).r; } else { frameBGR.at<cv::Vec3b>(h,w)[0] = cloud.at(h*cloud.width + w).r; frameBGR.at<cv::Vec3b>(h,w)[1] = cloud.at(h*cloud.width + w).g; frameBGR.at<cv::Vec3b>(h,w)[2] = cloud.at(h*cloud.width + w).b; } } } return frameBGR; } // return float image in meter cv::Mat depthFromCloud( const pcl::PointCloud<pcl::PointXYZRGBA> & cloud, float & fx, float & fy, bool depth16U) { cv::Mat frameDepth = cv::Mat(cloud.height,cloud.width,depth16U?CV_16UC1:CV_32FC1); fx = 0.0f; // needed to reconstruct the cloud fy = 0.0f; // needed to reconstruct the cloud for(unsigned int h = 0; h < cloud.height; h++) { for(unsigned int w = 0; w < cloud.width; w++) { float depth = cloud.at(h*cloud.width + w).z; if(depth16U) { depth *= 1000.0f; unsigned short depthMM = 0; if(depth <= (float)USHRT_MAX) { depthMM = (unsigned short)depth; } frameDepth.at<unsigned short>(h,w) = depthMM; } else { frameDepth.at<float>(h,w) = depth; } // update constants if(fx == 0.0f && uIsFinite(cloud.at(h*cloud.width + w).x) && uIsFinite(depth) && w != cloud.width/2 && depth > 0) { fx = cloud.at(h*cloud.width + w).x / ((float(w) - float(cloud.width)/2.0f) * depth); if(depth16U) { fx*=1000.0f; } } if(fy == 0.0f && uIsFinite(cloud.at(h*cloud.width + w).y) && uIsFinite(depth) && h != cloud.height/2 && depth > 0) { fy = cloud.at(h*cloud.width + w).y / ((float(h) - float(cloud.height)/2.0f) * depth); if(depth16U) { fy*=1000.0f; } } } } return frameDepth; } // return (unsigned short 16bits image in mm) (float 32bits image in m) void rgbdFromCloud(const pcl::PointCloud<pcl::PointXYZRGBA> & cloud, cv::Mat & frameBGR, cv::Mat & frameDepth, float & fx, float & fy, bool bgrOrder, bool depth16U) { frameDepth = cv::Mat(cloud.height,cloud.width,depth16U?CV_16UC1:CV_32FC1); frameBGR = cv::Mat(cloud.height,cloud.width,CV_8UC3); fx = 0.0f; // needed to reconstruct the cloud fy = 0.0f; // needed to reconstruct the cloud for(unsigned int h = 0; h < cloud.height; h++) { for(unsigned int w = 0; w < cloud.width; w++) { //rgb if(bgrOrder) { frameBGR.at<cv::Vec3b>(h,w)[0] = cloud.at(h*cloud.width + w).b; frameBGR.at<cv::Vec3b>(h,w)[1] = cloud.at(h*cloud.width + w).g; frameBGR.at<cv::Vec3b>(h,w)[2] = cloud.at(h*cloud.width + w).r; } else { frameBGR.at<cv::Vec3b>(h,w)[0] = cloud.at(h*cloud.width + w).r; frameBGR.at<cv::Vec3b>(h,w)[1] = cloud.at(h*cloud.width + w).g; frameBGR.at<cv::Vec3b>(h,w)[2] = cloud.at(h*cloud.width + w).b; } //depth float depth = cloud.at(h*cloud.width + w).z; if(depth16U) { depth *= 1000.0f; unsigned short depthMM = 0; if(depth <= (float)USHRT_MAX) { depthMM = (unsigned short)depth; } frameDepth.at<unsigned short>(h,w) = depthMM; } else { frameDepth.at<float>(h,w) = depth; } // update constants if(fx == 0.0f && uIsFinite(cloud.at(h*cloud.width + w).x) && uIsFinite(depth) && w != cloud.width/2 && depth > 0) { fx = 1.0f/(cloud.at(h*cloud.width + w).x / ((float(w) - float(cloud.width)/2.0f) * depth)); if(depth16U) { fx/=1000.0f; } } if(fy == 0.0f && uIsFinite(cloud.at(h*cloud.width + w).y) && uIsFinite(depth) && h != cloud.height/2 && depth > 0) { fy = 1.0f/(cloud.at(h*cloud.width + w).y / ((float(h) - float(cloud.height)/2.0f) * depth)); if(depth16U) { fy/=1000.0f; } } } } } cv::Mat cvtDepthFromFloat(const cv::Mat & depth32F) { UASSERT(depth32F.empty() || depth32F.type() == CV_32FC1); cv::Mat depth16U; if(!depth32F.empty()) { depth16U = cv::Mat(depth32F.rows, depth32F.cols, CV_16UC1); for(int i=0; i<depth32F.rows; ++i) { for(int j=0; j<depth32F.cols; ++j) { float depth = (depth32F.at<float>(i,j)*1000.0f); unsigned short depthMM = 0; if(depth <= (float)USHRT_MAX) { depthMM = (unsigned short)depth; } depth16U.at<unsigned short>(i, j) = depthMM; } } } return depth16U; } cv::Mat cvtDepthToFloat(const cv::Mat & depth16U) { UASSERT(depth16U.empty() || depth16U.type() == CV_16UC1); cv::Mat depth32F; if(!depth16U.empty()) { depth32F = cv::Mat(depth16U.rows, depth16U.cols, CV_32FC1); for(int i=0; i<depth16U.rows; ++i) { for(int j=0; j<depth16U.cols; ++j) { float depth = float(depth16U.at<unsigned short>(i,j))/1000.0f; depth32F.at<float>(i, j) = depth; } } } return depth32F; } pcl::PointCloud<pcl::PointXYZ>::Ptr generateKeypoints3DDepth( const std::vector<cv::KeyPoint> & keypoints, const cv::Mat & depth, float fx, float fy, float cx, float cy, const Transform & transform) { UASSERT(!depth.empty() && (depth.type() == CV_32FC1 || depth.type() == CV_16UC1)); pcl::PointCloud<pcl::PointXYZ>::Ptr keypoints3d(new pcl::PointCloud<pcl::PointXYZ>); if(!depth.empty()) { keypoints3d->resize(keypoints.size()); for(unsigned int i=0; i!=keypoints.size(); ++i) { pcl::PointXYZ pt = util3d::projectDepthTo3D( depth, keypoints[i].pt.x, keypoints[i].pt.y, cx, cy, fx, fy, true); if(!transform.isNull() && !transform.isIdentity()) { pt = pcl::transformPoint(pt, transform.toEigen3f()); } keypoints3d->at(i) = pt; } } return keypoints3d; } pcl::PointCloud<pcl::PointXYZ>::Ptr generateKeypoints3DDisparity( const std::vector<cv::KeyPoint> & keypoints, const cv::Mat & disparity, float fx, float baseline, float cx, float cy, const Transform & transform) { UASSERT(!disparity.empty() && (disparity.type() == CV_16SC1 || disparity.type() == CV_32F)); pcl::PointCloud<pcl::PointXYZ>::Ptr keypoints3d(new pcl::PointCloud<pcl::PointXYZ>); keypoints3d->resize(keypoints.size()); for(unsigned int i=0; i!=keypoints.size(); ++i) { pcl::PointXYZ pt = util3d::projectDisparityTo3D( keypoints[i].pt, disparity, cx, cy, fx, baseline); if(pcl::isFinite(pt) && !transform.isNull() && !transform.isIdentity()) { pt = pcl::transformPoint(pt, transform.toEigen3f()); } keypoints3d->at(i) = pt; } return keypoints3d; } pcl::PointCloud<pcl::PointXYZ>::Ptr generateKeypoints3DStereo( const std::vector<cv::KeyPoint> & keypoints, const cv::Mat & leftImage, const cv::Mat & rightImage, float fx, float baseline, float cx, float cy, const Transform & transform, int flowWinSize, int flowMaxLevel, int flowIterations, double flowEps) { UASSERT(!leftImage.empty() && !rightImage.empty() && leftImage.type() == CV_8UC1 && rightImage.type() == CV_8UC1 && leftImage.rows == rightImage.rows && leftImage.cols == rightImage.cols); std::vector<cv::Point2f> leftCorners; cv::KeyPoint::convert(keypoints, leftCorners); // Find features in the new left image std::vector<unsigned char> status; std::vector<float> err; std::vector<cv::Point2f> rightCorners; UDEBUG("cv::calcOpticalFlowPyrLK() begin"); cv::calcOpticalFlowPyrLK( leftImage, rightImage, leftCorners, rightCorners, status, err, cv::Size(flowWinSize, flowWinSize), flowMaxLevel, cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, flowIterations, flowEps), cv::OPTFLOW_LK_GET_MIN_EIGENVALS, 1e-4); UDEBUG("cv::calcOpticalFlowPyrLK() end"); pcl::PointCloud<pcl::PointXYZ>::Ptr keypoints3d(new pcl::PointCloud<pcl::PointXYZ>); keypoints3d->resize(keypoints.size()); float bad_point = std::numeric_limits<float>::quiet_NaN (); UASSERT(status.size() == keypoints.size()); for(unsigned int i=0; i<status.size(); ++i) { pcl::PointXYZ pt(bad_point, bad_point, bad_point); if(status[i]) { float disparity = leftCorners[i].x - rightCorners[i].x; if(disparity > 0.0f) { pcl::PointXYZ tmpPt = util3d::projectDisparityTo3D( leftCorners[i], disparity, cx, cy, fx, baseline); if(pcl::isFinite(tmpPt)) { pt = tmpPt; if(!transform.isNull() && !transform.isIdentity()) { pt = pcl::transformPoint(pt, transform.toEigen3f()); } } } } keypoints3d->at(i) = pt; } return keypoints3d; } // cameraTransform, from ref to next // return 3D points in ref referential // If cameraTransform is not null, it will be used for triangulation instead of the camera transform computed by epipolar geometry // when refGuess3D is passed and cameraTransform is null, scale will be estimated, returning scaled cloud and camera transform std::multimap<int, pcl::PointXYZ> generateWords3DMono( const std::multimap<int, cv::KeyPoint> & refWords, const std::multimap<int, cv::KeyPoint> & nextWords, float fx, float fy, float cx, float cy, const Transform & localTransform, Transform & cameraTransform, int pnpIterations, float pnpReprojError, int pnpFlags, float ransacParam1, float ransacParam2, const std::multimap<int, pcl::PointXYZ> & refGuess3D, double * varianceOut) { std::multimap<int, pcl::PointXYZ> words3D; std::list<std::pair<int, std::pair<cv::KeyPoint, cv::KeyPoint> > > pairs; if(EpipolarGeometry::findPairsUnique(refWords, nextWords, pairs) > 8) { std::vector<unsigned char> status; cv::Mat F = EpipolarGeometry::findFFromWords(pairs, status, ransacParam1, ransacParam2); if(!F.empty()) { //get inliers //normalize coordinates int oi = 0; UASSERT(status.size() == pairs.size()); std::list<std::pair<int, std::pair<cv::KeyPoint, cv::KeyPoint> > >::iterator iter=pairs.begin(); std::vector<cv::Point2f> refCorners(status.size()); std::vector<cv::Point2f> newCorners(status.size()); std::vector<int> indexes(status.size()); for(unsigned int i=0; i<status.size(); ++i) { if(status[i]) { refCorners[oi] = iter->second.first.pt; newCorners[oi] = iter->second.second.pt; indexes[oi] = iter->first; ++oi; } ++iter; } refCorners.resize(oi); newCorners.resize(oi); indexes.resize(oi); UDEBUG("inliers=%d/%d", oi, pairs.size()); if(oi > 3) { std::vector<cv::Point2f> refCornersRefined; std::vector<cv::Point2f> newCornersRefined; cv::correctMatches(F, refCorners, newCorners, refCornersRefined, newCornersRefined); refCorners = refCornersRefined; newCorners = newCornersRefined; cv::Mat x(3, (int)refCorners.size(), CV_64FC1); cv::Mat xp(3, (int)refCorners.size(), CV_64FC1); for(unsigned int i=0; i<refCorners.size(); ++i) { x.at<double>(0, i) = refCorners[i].x; x.at<double>(1, i) = refCorners[i].y; x.at<double>(2, i) = 1; xp.at<double>(0, i) = newCorners[i].x; xp.at<double>(1, i) = newCorners[i].y; xp.at<double>(2, i) = 1; } cv::Mat K = (cv::Mat_<double>(3,3) << fx, 0, cx, 0, fy, cy, 0, 0, 1); cv::Mat Kinv = K.inv(); cv::Mat E = K.t()*F*K; cv::Mat x_norm = Kinv * x; cv::Mat xp_norm = Kinv * xp; x_norm = x_norm.rowRange(0,2); xp_norm = xp_norm.rowRange(0,2); cv::Mat P = EpipolarGeometry::findPFromE(E, x_norm, xp_norm); if(!P.empty()) { cv::Mat P0 = cv::Mat::zeros(3, 4, CV_64FC1); P0.at<double>(0,0) = 1; P0.at<double>(1,1) = 1; P0.at<double>(2,2) = 1; bool useCameraTransformGuess = !cameraTransform.isNull(); //if camera transform is set, use it instead of the computed one from epipolar geometry if(useCameraTransformGuess) { Transform t = (localTransform.inverse()*cameraTransform*localTransform).inverse(); P = (cv::Mat_<double>(3,4) << (double)t.r11(), (double)t.r12(), (double)t.r13(), (double)t.x(), (double)t.r21(), (double)t.r22(), (double)t.r23(), (double)t.y(), (double)t.r31(), (double)t.r32(), (double)t.r33(), (double)t.z()); } // triangulate the points //std::vector<double> reprojErrors; //pcl::PointCloud<pcl::PointXYZ>::Ptr cloud; //EpipolarGeometry::triangulatePoints(x_norm, xp_norm, P0, P, cloud, reprojErrors); cv::Mat pts4D; cv::triangulatePoints(P0, P, x_norm, xp_norm, pts4D); for(unsigned int i=0; i<indexes.size(); ++i) { //if(cloud->at(i).z > 0) //{ // words3D.insert(std::make_pair(indexes[i], util3d::transformPoint(cloud->at(i), localTransform))); //} pts4D.col(i) /= pts4D.at<double>(3,i); if(pts4D.at<double>(2,i) > 0) { words3D.insert(std::make_pair(indexes[i], util3d::transformPoint(pcl::PointXYZ(pts4D.at<double>(0,i), pts4D.at<double>(1,i), pts4D.at<double>(2,i)), localTransform))); } } if(!useCameraTransformGuess) { cv::Mat R, T; EpipolarGeometry::findRTFromP(P, R, T); Transform t(R.at<double>(0,0), R.at<double>(0,1), R.at<double>(0,2), T.at<double>(0), R.at<double>(1,0), R.at<double>(1,1), R.at<double>(1,2), T.at<double>(1), R.at<double>(2,0), R.at<double>(2,1), R.at<double>(2,2), T.at<double>(2)); cameraTransform = (localTransform * t).inverse() * localTransform; } if(refGuess3D.size()) { // scale estimation pcl::PointCloud<pcl::PointXYZ>::Ptr inliersRef(new pcl::PointCloud<pcl::PointXYZ>); pcl::PointCloud<pcl::PointXYZ>::Ptr inliersRefGuess(new pcl::PointCloud<pcl::PointXYZ>); util3d::findCorrespondences( words3D, refGuess3D, *inliersRef, *inliersRefGuess, 0); if(inliersRef->size()) { // estimate the scale float scale = 1.0f; float variance = 1.0f; if(!useCameraTransformGuess) { std::multimap<float, float> scales; // <variance, scale> for(unsigned int i=0; i<inliersRef->size(); ++i) { // using x as depth, assuming we are in global referential float s = inliersRefGuess->at(i).x/inliersRef->at(i).x; std::vector<float> errorSqrdDists(inliersRef->size()); for(unsigned int j=0; j<inliersRef->size(); ++j) { pcl::PointXYZ refPt = inliersRef->at(j); refPt.x *= s; refPt.y *= s; refPt.z *= s; const pcl::PointXYZ & newPt = inliersRefGuess->at(j); errorSqrdDists[j] = uNormSquared(refPt.x-newPt.x, refPt.y-newPt.y, refPt.z-newPt.z); } std::sort(errorSqrdDists.begin(), errorSqrdDists.end()); double median_error_sqr = (double)errorSqrdDists[errorSqrdDists.size () >> 1]; float var = 2.1981 * median_error_sqr; //UDEBUG("scale %d = %f variance = %f", (int)i, s, variance); scales.insert(std::make_pair(var, s)); } scale = scales.begin()->second; variance = scales.begin()->first;; } else { //compute variance at scale=1 std::vector<float> errorSqrdDists(inliersRef->size()); for(unsigned int j=0; j<inliersRef->size(); ++j) { const pcl::PointXYZ & refPt = inliersRef->at(j); const pcl::PointXYZ & newPt = inliersRefGuess->at(j); errorSqrdDists[j] = uNormSquared(refPt.x-newPt.x, refPt.y-newPt.y, refPt.z-newPt.z); } std::sort(errorSqrdDists.begin(), errorSqrdDists.end()); double median_error_sqr = (double)errorSqrdDists[errorSqrdDists.size () >> 1]; variance = 2.1981 * median_error_sqr; } UDEBUG("scale used = %f (variance=%f)", scale, variance); if(varianceOut) { *varianceOut = variance; } if(!useCameraTransformGuess) { std::vector<cv::Point3f> objectPoints(indexes.size()); std::vector<cv::Point2f> imagePoints(indexes.size()); int oi=0; for(unsigned int i=0; i<indexes.size(); ++i) { std::multimap<int, pcl::PointXYZ>::iterator iter = words3D.find(indexes[i]); if(pcl::isFinite(iter->second)) { iter->second.x *= scale; iter->second.y *= scale; iter->second.z *= scale; objectPoints[oi].x = iter->second.x; objectPoints[oi].y = iter->second.y; objectPoints[oi].z = iter->second.z; imagePoints[oi] = newCorners[i]; ++oi; } } objectPoints.resize(oi); imagePoints.resize(oi); //PnPRansac Transform guess = localTransform.inverse(); cv::Mat R = (cv::Mat_<double>(3,3) << (double)guess.r11(), (double)guess.r12(), (double)guess.r13(), (double)guess.r21(), (double)guess.r22(), (double)guess.r23(), (double)guess.r31(), (double)guess.r32(), (double)guess.r33()); cv::Mat rvec(1,3, CV_64FC1); cv::Rodrigues(R, rvec); cv::Mat tvec = (cv::Mat_<double>(1,3) << (double)guess.x(), (double)guess.y(), (double)guess.z()); std::vector<int> inliersV; cv::solvePnPRansac( objectPoints, imagePoints, K, cv::Mat(), rvec, tvec, true, pnpIterations, pnpReprojError, 0, inliersV, pnpFlags); UDEBUG("PnP inliers = %d / %d", (int)inliersV.size(), (int)objectPoints.size()); if(inliersV.size()) { cv::Rodrigues(rvec, R); Transform pnp(R.at<double>(0,0), R.at<double>(0,1), R.at<double>(0,2), tvec.at<double>(0), R.at<double>(1,0), R.at<double>(1,1), R.at<double>(1,2), tvec.at<double>(1), R.at<double>(2,0), R.at<double>(2,1), R.at<double>(2,2), tvec.at<double>(2)); cameraTransform = (localTransform * pnp).inverse(); } else { UWARN("No inliers after PnP!"); cameraTransform = Transform(); } } } else { UWARN("Cannot compute the scale, no points corresponding between the generated ref words and words guess"); } } } } } } UDEBUG("wordsSet=%d / %d", (int)words3D.size(), (int)refWords.size()); return words3D; } std::multimap<int, cv::KeyPoint> aggregate( const std::list<int> & wordIds, const std::vector<cv::KeyPoint> & keypoints) { std::multimap<int, cv::KeyPoint> words; std::vector<cv::KeyPoint>::const_iterator kpIter = keypoints.begin(); for(std::list<int>::const_iterator iter=wordIds.begin(); iter!=wordIds.end(); ++iter) { words.insert(std::pair<int, cv::KeyPoint >(*iter, *kpIter)); ++kpIter; } return words; } std::list<std::pair<cv::Point2f, cv::Point2f> > findCorrespondences( const std::multimap<int, cv::KeyPoint> & words1, const std::multimap<int, cv::KeyPoint> & words2) { std::list<std::pair<cv::Point2f, cv::Point2f> > correspondences; // Find pairs std::list<std::pair<int, std::pair<cv::KeyPoint, cv::KeyPoint> > > pairs; rtabmap::EpipolarGeometry::findPairsUnique(words1, words2, pairs); if(pairs.size() > 7) // 8 min? { // Find fundamental matrix std::vector<uchar> status; cv::Mat fundamentalMatrix = rtabmap::EpipolarGeometry::findFFromWords(pairs, status); //ROS_INFO("inliers = %d/%d", uSum(status), pairs.size()); if(!fundamentalMatrix.empty()) { int i = 0; //int goodCount = 0; for(std::list<std::pair<int, std::pair<cv::KeyPoint, cv::KeyPoint> > >::iterator iter=pairs.begin(); iter!=pairs.end(); ++iter) { if(status[i]) { correspondences.push_back(std::pair<cv::Point2f, cv::Point2f>(iter->second.first.pt, iter->second.second.pt)); //ROS_INFO("inliers kpts %f %f vs %f %f", iter->second.first.pt.x, iter->second.first.pt.y, iter->second.second.pt.x, iter->second.second.pt.y); } ++i; } } } return correspondences; } void findCorrespondences( const std::multimap<int, pcl::PointXYZ> & words1, const std::multimap<int, pcl::PointXYZ> & words2, pcl::PointCloud<pcl::PointXYZ> & inliers1, pcl::PointCloud<pcl::PointXYZ> & inliers2, float maxDepth, std::set<int> * uniqueCorrespondences) { std::list<int> ids = uUniqueKeys(words1); // Find pairs inliers1.resize(ids.size()); inliers2.resize(ids.size()); int oi=0; for(std::list<int>::iterator iter=ids.begin(); iter!=ids.end(); ++iter) { if(words1.count(*iter) == 1 && words2.count(*iter) == 1) { inliers1[oi] = words1.find(*iter)->second; inliers2[oi] = words2.find(*iter)->second; if(pcl::isFinite(inliers1[oi]) && pcl::isFinite(inliers2[oi]) && (inliers1[oi].x != 0 || inliers1[oi].y != 0 || inliers1[oi].z != 0) && (inliers2[oi].x != 0 || inliers2[oi].y != 0 || inliers2[oi].z != 0) && (maxDepth <= 0 || (inliers1[oi].x > 0 && inliers1[oi].x <= maxDepth && inliers2[oi].x>0 &&inliers2[oi].x<=maxDepth))) { ++oi; if(uniqueCorrespondences) { uniqueCorrespondences->insert(*iter); } } } } inliers1.resize(oi); inliers2.resize(oi); } pcl::PointXYZ projectDepthTo3D( const cv::Mat & depthImage, float x, float y, float cx, float cy, float fx, float fy, bool smoothing, float maxZError) { UASSERT(depthImage.type() == CV_16UC1 || depthImage.type() == CV_32FC1); pcl::PointXYZ pt; float bad_point = std::numeric_limits<float>::quiet_NaN (); int u = int(x+0.5f); int v = int(y+0.5f); if(!(u >=0 && u<depthImage.cols && v >=0 && v<depthImage.rows)) { UERROR("!(x >=0 && x<depthImage.cols && y >=0 && y<depthImage.rows) cond failed! returning bad point. (x=%f (u=%d), y=%f (v=%d), cols=%d, rows=%d)", x,u,y,v,depthImage.cols, depthImage.rows); pt.x = pt.y = pt.z = bad_point; return pt; } bool isInMM = depthImage.type() == CV_16UC1; // is in mm? // Inspired from RGBDFrame::getGaussianMixtureDistribution() method from // https://github.com/ccny-ros-pkg/rgbdtools/blob/master/src/rgbd_frame.cpp // Window weights: // | 1 | 2 | 1 | // | 2 | 4 | 2 | // | 1 | 2 | 1 | int u_start = std::max(u-1, 0); int v_start = std::max(v-1, 0); int u_end = std::min(u+1, depthImage.cols-1); int v_end = std::min(v+1, depthImage.rows-1); float depth = isInMM?(float)depthImage.at<uint16_t>(v,u)*0.001f:depthImage.at<float>(v,u); if(depth!=0.0f && uIsFinite(depth)) { if(smoothing) { float sumWeights = 0.0f; float sumDepths = 0.0f; for(int uu = u_start; uu <= u_end; ++uu) { for(int vv = v_start; vv <= v_end; ++vv) { if(!(uu == u && vv == v)) { float d = isInMM?(float)depthImage.at<uint16_t>(vv,uu)*0.001f:depthImage.at<float>(vv,uu); // ignore if not valid or depth difference is too high if(d != 0.0f && uIsFinite(d) && fabs(d - depth) < maxZError) { if(uu == u || vv == v) { sumWeights+=2.0f; d*=2.0f; } else { sumWeights+=1.0f; } sumDepths += d; } } } } // set window weight to center point depth *= 4.0f; sumWeights += 4.0f; // mean depth = (depth+sumDepths)/sumWeights; } // Use correct principal point from calibration cx = cx > 0.0f ? cx : float(depthImage.cols/2) - 0.5f; //cameraInfo.K.at(2) cy = cy > 0.0f ? cy : float(depthImage.rows/2) - 0.5f; //cameraInfo.K.at(5) // Fill in XYZ pt.x = (x - cx) * depth / fx; pt.y = (y - cy) * depth / fy; pt.z = depth; } else { pt.x = pt.y = pt.z = bad_point; } return pt; } pcl::PointCloud<pcl::PointXYZ>::Ptr cloudFromDepth( const cv::Mat & imageDepth, float cx, float cy, float fx, float fy, int decimation) { UASSERT(!imageDepth.empty() && (imageDepth.type() == CV_16UC1 || imageDepth.type() == CV_32FC1)); UASSERT(imageDepth.rows % decimation == 0); UASSERT(imageDepth.cols % decimation == 0); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>); if(decimation < 1) { return cloud; } //cloud.header = cameraInfo.header; cloud->height = imageDepth.rows/decimation; cloud->width = imageDepth.cols/decimation; cloud->is_dense = false; cloud->resize(cloud->height * cloud->width); int count = 0 ; for(int h = 0; h < imageDepth.rows; h+=decimation) { for(int w = 0; w < imageDepth.cols; w+=decimation) { pcl::PointXYZ & pt = cloud->at((h/decimation)*cloud->width + (w/decimation)); pcl::PointXYZ ptXYZ = projectDepthTo3D(imageDepth, w, h, cx, cy, fx, fy, false); pt.x = ptXYZ.x; pt.y = ptXYZ.y; pt.z = ptXYZ.z; ++count; } } return cloud; } pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloudFromDepthRGB( const cv::Mat & imageRgb, const cv::Mat & imageDepth, float cx, float cy, float fx, float fy, int decimation) { UASSERT(imageRgb.rows == imageDepth.rows && imageRgb.cols == imageDepth.cols); UASSERT(!imageDepth.empty() && (imageDepth.type() == CV_16UC1 || imageDepth.type() == CV_32FC1)); UASSERT(imageDepth.rows % decimation == 0); UASSERT(imageDepth.cols % decimation == 0); pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZRGB>); if(decimation < 1) { return cloud; } bool mono; if(imageRgb.channels() == 3) // BGR { mono = false; } else if(imageRgb.channels() == 1) // Mono { mono = true; } else { return cloud; } //cloud.header = cameraInfo.header; cloud->height = imageDepth.rows/decimation; cloud->width = imageDepth.cols/decimation; cloud->is_dense = false; cloud->resize(cloud->height * cloud->width); for(int h = 0; h < imageDepth.rows && h/decimation < (int)cloud->height; h+=decimation) { for(int w = 0; w < imageDepth.cols && w/decimation < (int)cloud->width; w+=decimation) { pcl::PointXYZRGB & pt = cloud->at((h/decimation)*cloud->width + (w/decimation)); if(!mono) { pt.b = imageRgb.at<cv::Vec3b>(h,w)[0]; pt.g = imageRgb.at<cv::Vec3b>(h,w)[1]; pt.r = imageRgb.at<cv::Vec3b>(h,w)[2]; } else { unsigned char v = imageRgb.at<unsigned char>(h,w); pt.b = v; pt.g = v; pt.r = v; } pcl::PointXYZ ptXYZ = projectDepthTo3D(imageDepth, w, h, cx, cy, fx, fy, false); pt.x = ptXYZ.x; pt.y = ptXYZ.y; pt.z = ptXYZ.z; } } return cloud; } pcl::PointCloud<pcl::PointXYZ>::Ptr cloudFromDisparity( const cv::Mat & imageDisparity, float cx, float cy, float fx, float baseline, int decimation) { UASSERT(imageDisparity.type() == CV_32FC1 || imageDisparity.type()==CV_16SC1); UASSERT(imageDisparity.rows % decimation == 0); UASSERT(imageDisparity.cols % decimation == 0); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>); if(decimation < 1) { return cloud; } //cloud.header = cameraInfo.header; cloud->height = imageDisparity.rows/decimation; cloud->width = imageDisparity.cols/decimation; cloud->is_dense = false; cloud->resize(cloud->height * cloud->width); if(imageDisparity.type()==CV_16SC1) { for(int h = 0; h < imageDisparity.rows && h/decimation < (int)cloud->height; h+=decimation) { for(int w = 0; w < imageDisparity.cols && w/decimation < (int)cloud->width; w+=decimation) { float disp = float(imageDisparity.at<short>(h,w))/16.0f; cloud->at((h/decimation)*cloud->width + (w/decimation)) = projectDisparityTo3D(cv::Point2f(w, h), disp, cx, cy, fx, baseline); } } } else { for(int h = 0; h < imageDisparity.rows && h/decimation < (int)cloud->height; h+=decimation) { for(int w = 0; w < imageDisparity.cols && w/decimation < (int)cloud->width; w+=decimation) { float disp = imageDisparity.at<float>(h,w); cloud->at((h/decimation)*cloud->width + (w/decimation)) = projectDisparityTo3D(cv::Point2f(w, h), disp, cx, cy, fx, baseline); } } } return cloud; } pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloudFromDisparityRGB( const cv::Mat & imageRgb, const cv::Mat & imageDisparity, float cx, float cy, float fx, float baseline, int decimation) { UASSERT(imageRgb.rows == imageDisparity.rows && imageRgb.cols == imageDisparity.cols && (imageDisparity.type() == CV_32FC1 || imageDisparity.type()==CV_16SC1)); UASSERT(imageDisparity.rows % decimation == 0); UASSERT(imageDisparity.cols % decimation == 0); pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZRGB>); if(decimation < 1) { return cloud; } bool mono; if(imageRgb.channels() == 3) // BGR { mono = false; } else if(imageRgb.channels() == 1) // Mono { mono = true; } else { return cloud; } //cloud.header = cameraInfo.header; cloud->height = imageRgb.rows/decimation; cloud->width = imageRgb.cols/decimation; cloud->is_dense = false; cloud->resize(cloud->height * cloud->width); for(int h = 0; h < imageRgb.rows && h/decimation < (int)cloud->height; h+=decimation) { for(int w = 0; w < imageRgb.cols && w/decimation < (int)cloud->width; w+=decimation) { pcl::PointXYZRGB & pt = cloud->at((h/decimation)*cloud->width + (w/decimation)); if(!mono) { pt.b = imageRgb.at<cv::Vec3b>(h,w)[0]; pt.g = imageRgb.at<cv::Vec3b>(h,w)[1]; pt.r = imageRgb.at<cv::Vec3b>(h,w)[2]; } else { unsigned char v = imageRgb.at<unsigned char>(h,w); pt.b = v; pt.g = v; pt.r = v; } float disp = imageDisparity.type()==CV_16SC1?float(imageDisparity.at<short>(h,w))/16.0f:imageDisparity.at<float>(h,w); pcl::PointXYZ ptXYZ = projectDisparityTo3D(cv::Point2f(w, h), disp, cx, cy, fx, baseline); pt.x = ptXYZ.x; pt.y = ptXYZ.y; pt.z = ptXYZ.z; } } return cloud; } pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloudFromStereoImages( const cv::Mat & imageLeft, const cv::Mat & imageRight, float cx, float cy, float fx, float baseline, int decimation) { UASSERT(imageRight.type() == CV_8UC1); cv::Mat leftMono; if(imageLeft.channels() == 3) { cv::cvtColor(imageLeft, leftMono, CV_BGR2GRAY); } else { leftMono = imageLeft; } return rtabmap::util3d::cloudFromDisparityRGB( imageLeft, util3d::disparityFromStereoImages(leftMono, imageRight), cx, cy, fx, baseline, decimation); } cv::Mat disparityFromStereoImages( const cv::Mat & leftImage, const cv::Mat & rightImage) { UASSERT(!leftImage.empty() && !rightImage.empty() && (leftImage.type() == CV_8UC1 || leftImage.type() == CV_8UC3) && rightImage.type() == CV_8UC1 && leftImage.cols == rightImage.cols && leftImage.rows == rightImage.rows); cv::Mat leftMono; if(leftImage.channels() == 3) { cv::cvtColor(leftImage, leftMono, CV_BGR2GRAY); } else { leftMono = leftImage; } cv::StereoBM stereo(cv::StereoBM::BASIC_PRESET); stereo.state->SADWindowSize = 15; stereo.state->minDisparity = 0; stereo.state->numberOfDisparities = 64; stereo.state->preFilterSize = 9; stereo.state->preFilterCap = 31; stereo.state->uniquenessRatio = 15; stereo.state->textureThreshold = 10; stereo.state->speckleWindowSize = 100; stereo.state->speckleRange = 4; cv::Mat disparity; stereo(leftMono, rightImage, disparity, CV_16SC1); return disparity; } cv::Mat disparityFromStereoImages( const cv::Mat & leftImage, const cv::Mat & rightImage, const std::vector<cv::Point2f> & leftCorners, int flowWinSize, int flowMaxLevel, int flowIterations, double flowEps, float maxCorrespondencesSlope) { UASSERT(!leftImage.empty() && !rightImage.empty() && leftImage.type() == CV_8UC1 && rightImage.type() == CV_8UC1 && leftImage.cols == rightImage.cols && leftImage.rows == rightImage.rows); // Find features in the new left image std::vector<unsigned char> status; std::vector<float> err; std::vector<cv::Point2f> rightCorners; UDEBUG("cv::calcOpticalFlowPyrLK() begin"); cv::calcOpticalFlowPyrLK( leftImage, rightImage, leftCorners, rightCorners, status, err, cv::Size(flowWinSize, flowWinSize), flowMaxLevel, cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, flowIterations, flowEps), cv::OPTFLOW_LK_GET_MIN_EIGENVALS, 1e-4); UDEBUG("cv::calcOpticalFlowPyrLK() end"); return disparityFromStereoCorrespondences(leftImage, leftCorners, rightCorners, status, maxCorrespondencesSlope); } cv::Mat depthFromStereoImages( const cv::Mat & leftImage, const cv::Mat & rightImage, const std::vector<cv::Point2f> & leftCorners, float fx, float baseline, int flowWinSize, int flowMaxLevel, int flowIterations, double flowEps) { UASSERT(!leftImage.empty() && !rightImage.empty() && leftImage.type() == CV_8UC1 && rightImage.type() == CV_8UC1 && leftImage.cols == rightImage.cols && leftImage.rows == rightImage.rows); UASSERT(fx > 0.0f && baseline > 0.0f); // Find features in the new left image std::vector<unsigned char> status; std::vector<float> err; std::vector<cv::Point2f> rightCorners; UDEBUG("cv::calcOpticalFlowPyrLK() begin"); cv::calcOpticalFlowPyrLK( leftImage, rightImage, leftCorners, rightCorners, status, err, cv::Size(flowWinSize, flowWinSize), flowMaxLevel, cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, flowIterations, flowEps), cv::OPTFLOW_LK_GET_MIN_EIGENVALS, 1e-4); UDEBUG("cv::calcOpticalFlowPyrLK() end"); return depthFromStereoCorrespondences(leftImage, leftCorners, rightCorners, status, fx, baseline); } cv::Mat disparityFromStereoCorrespondences( const cv::Mat & leftImage, const std::vector<cv::Point2f> & leftCorners, const std::vector<cv::Point2f> & rightCorners, const std::vector<unsigned char> & mask, float maxSlope) { UASSERT(!leftImage.empty() && leftCorners.size() == rightCorners.size()); UASSERT(mask.size() == 0 || mask.size() == leftCorners.size()); cv::Mat disparity = cv::Mat::zeros(leftImage.rows, leftImage.cols, CV_32FC1); for(unsigned int i=0; i<leftCorners.size(); ++i) { if(mask.size() == 0 || mask[i]) { float d = leftCorners[i].x - rightCorners[i].x; float slope = fabs((leftCorners[i].y - rightCorners[i].y) / (leftCorners[i].x - rightCorners[i].x)); if(d > 0.0f && slope < maxSlope) { disparity.at<float>(int(leftCorners[i].y+0.5f), int(leftCorners[i].x+0.5f)) = d; } } } return disparity; } cv::Mat depthFromStereoCorrespondences( const cv::Mat & leftImage, const std::vector<cv::Point2f> & leftCorners, const std::vector<cv::Point2f> & rightCorners, const std::vector<unsigned char> & mask, float fx, float baseline) { UASSERT(!leftImage.empty() && leftCorners.size() == rightCorners.size()); UASSERT(mask.size() == 0 || mask.size() == leftCorners.size()); cv::Mat depth = cv::Mat::zeros(leftImage.rows, leftImage.cols, CV_32FC1); for(unsigned int i=0; i<leftCorners.size(); ++i) { if(mask.size() == 0 || mask[i]) { float disparity = leftCorners[i].x - rightCorners[i].x; if(disparity > 0.0f) { float d = baseline * fx / disparity; depth.at<float>(int(leftCorners[i].y+0.5f), int(leftCorners[i].x+0.5f)) = d; } } } return depth; } // inspired from ROS image_geometry/src/stereo_camera_model.cpp pcl::PointXYZ projectDisparityTo3D( const cv::Point2f & pt, float disparity, float cx, float cy, float fx, float baseline) { if(disparity > 0.0f && baseline > 0.0f && fx > 0.0f) { float W = disparity/baseline;// + (right_.cx() - left_.cx()) / Tx; return pcl::PointXYZ((pt.x - cx)/W, (pt.y - cy)/W, fx/W); } float bad_point = std::numeric_limits<float>::quiet_NaN (); return pcl::PointXYZ(bad_point, bad_point, bad_point); } pcl::PointXYZ projectDisparityTo3D( const cv::Point2f & pt, const cv::Mat & disparity, float cx, float cy, float fx, float baseline) { UASSERT(!disparity.empty() && (disparity.type() == CV_32FC1 || disparity.type() == CV_16SC1)); int u = int(pt.x+0.5f); int v = int(pt.y+0.5f); float bad_point = std::numeric_limits<float>::quiet_NaN (); if(uIsInBounds(u, 0, disparity.cols) && uIsInBounds(v, 0, disparity.rows)) { float d = disparity.type() == CV_16SC1?float(disparity.at<short>(v,u))/16.0f:disparity.at<float>(v,u); return projectDisparityTo3D(pt, d, cx, cy, fx, baseline); } return pcl::PointXYZ(bad_point, bad_point, bad_point); } cv::Mat depthFromDisparity(const cv::Mat & disparity, float fx, float baseline, int type) { UASSERT(!disparity.empty() && (disparity.type() == CV_32FC1 || disparity.type() == CV_16SC1)); UASSERT(type == CV_32FC1 || type == CV_16U); cv::Mat depth = cv::Mat::zeros(disparity.rows, disparity.cols, type); for (int i = 0; i < disparity.rows; i++) { for (int j = 0; j < disparity.cols; j++) { float disparity_value = disparity.type() == CV_16SC1?float(disparity.at<short>(i,j))/16.0f:disparity.at<float>(i,j); if (disparity_value > 0.0f) { // baseline * focal / disparity float d = baseline * fx / disparity_value; if(depth.type() == CV_32FC1) { depth.at<float>(i,j) = d; } else { depth.at<unsigned short>(i,j) = (unsigned short)(d*1000.0f); } } } } return depth; } cv::Mat registerDepth( const cv::Mat & depth, const cv::Mat & depthK, const cv::Mat & colorK, const rtabmap::Transform & transform) { UASSERT(!transform.isNull()); UASSERT(!depth.empty()); UASSERT(depth.type() == CV_16UC1); // mm UASSERT(depthK.type() == CV_64FC1 && depthK.cols == 3 && depthK.cols == 3); UASSERT(colorK.type() == CV_64FC1 && colorK.cols == 3 && colorK.cols == 3); float fx = depthK.at<double>(0,0); float fy = depthK.at<double>(1,1); float cx = depthK.at<double>(0,2); float cy = depthK.at<double>(1,2); float rfx = colorK.at<double>(0,0); float rfy = colorK.at<double>(1,1); float rcx = colorK.at<double>(0,2); float rcy = colorK.at<double>(1,2); Eigen::Affine3f proj = transform.toEigen3f(); Eigen::Vector4f P4,P3; P4[3] = 1; cv::Mat registered = cv::Mat::zeros(depth.rows, depth.cols, depth.type()); for(int y=0; y<depth.rows; ++y) { for(int x=0; x<depth.cols; ++x) { //filtering float dz = float(depth.at<unsigned short>(y,x))*0.001f; // put in meter for projection if(dz>=0.0f) { // Project to 3D P4[0] = (x - cx) * dz / fx; // Optimization: we could have (x-cx)/fx in a lookup table P4[1] = (y - cy) * dz / fy; // Optimization: we could have (y-cy)/fy in a lookup table P4[2] = dz; P3 = proj * P4; float z = P3[2]; float invZ = 1.0f/z; int dx = (rfx*P3[0])*invZ + rcx; int dy = (rfy*P3[1])*invZ + rcy; if(uIsInBounds(dx, 0, registered.cols) && uIsInBounds(dy, 0, registered.rows)) { unsigned short z16 = z * 1000; //mm unsigned short &zReg = registered.at<unsigned short>(dy, dx); if(zReg == 0 || z16 < zReg) { zReg = z16; } } } } } return registered; } void fillRegisteredDepthHoles(cv::Mat & registeredDepth, bool vertical, bool horizontal, bool fillDoubleHoles) { UASSERT(registeredDepth.type() == CV_16UC1); int margin = fillDoubleHoles?2:1; for(int x=1; x<registeredDepth.cols-margin; ++x) { for(int y=1; y<registeredDepth.rows-margin; ++y) { unsigned short & b = registeredDepth.at<unsigned short>(y, x); bool set = false; if(vertical) { const unsigned short & a = registeredDepth.at<unsigned short>(y-1, x); unsigned short & c = registeredDepth.at<unsigned short>(y+1, x); if(a && c) { unsigned short error = 0.01*((a+c)/2); if(((b == 0 && a && c) || (b > a+error && b > c+error)) && (a>c?a-c<=error:c-a<=error)) { b = (a+c)/2; set = true; if(!horizontal) { ++y; } } } if(!set && fillDoubleHoles) { const unsigned short & d = registeredDepth.at<unsigned short>(y+2, x); if(a && d && (b==0 || c==0)) { unsigned short error = 0.01*((a+d)/2); if(((b == 0 && a && d) || (b > a+error && b > d+error)) && ((c == 0 && a && d) || (c > a+error && c > d+error)) && (a>d?a-d<=error:d-a<=error)) { if(a>d) { unsigned short tmp = (a-d)/4; b = d + tmp; c = d + 3*tmp; } else { unsigned short tmp = (d-a)/4; b = a + tmp; c = a + 3*tmp; } set = true; if(!horizontal) { y+=2; } } } } } if(!set && horizontal) { const unsigned short & a = registeredDepth.at<unsigned short>(y, x-1); unsigned short & c = registeredDepth.at<unsigned short>(y, x+1); if(a && c) { unsigned short error = 0.01*((a+c)/2); if(((b == 0 && a && c) || (b > a+error && b > c+error)) && (a>c?a-c<=error:c-a<=error)) { b = (a+c)/2; set = true; } } if(!set && fillDoubleHoles) { const unsigned short & d = registeredDepth.at<unsigned short>(y, x+2); if(a && d && (b==0 || c==0)) { unsigned short error = 0.01*((a+d)/2); if(((b == 0 && a && d) || (b > a+error && b > d+error)) && ((c == 0 && a && d) || (c > a+error && c > d+error)) && (a>d?a-d<=error:d-a<=error)) { if(a>d) { unsigned short tmp = (a-d)/4; b = d + tmp; c = d + 3*tmp; } else { unsigned short tmp = (d-a)/4; b = a + tmp; c = a + 3*tmp; } } } } } } } } cv::Mat laserScanFromPointCloud(const pcl::PointCloud<pcl::PointXYZ> & cloud) { cv::Mat laserScan(1, (int)cloud.size(), CV_32FC2); for(unsigned int i=0; i<cloud.size(); ++i) { laserScan.at<cv::Vec2f>(i)[0] = cloud.at(i).x; laserScan.at<cv::Vec2f>(i)[1] = cloud.at(i).y; } return laserScan; } pcl::PointCloud<pcl::PointXYZ>::Ptr laserScanToPointCloud(const cv::Mat & laserScan) { UASSERT(laserScan.empty() || laserScan.type() == CV_32FC2); pcl::PointCloud<pcl::PointXYZ>::Ptr output(new pcl::PointCloud<pcl::PointXYZ>); output->resize(laserScan.cols); for(int i=0; i<laserScan.cols; ++i) { output->at(i).x = laserScan.at<cv::Vec2f>(i)[0]; output->at(i).y = laserScan.at<cv::Vec2f>(i)[1]; } return output; } void extractXYZCorrespondences(const std::multimap<int, pcl::PointXYZ> & words1, const std::multimap<int, pcl::PointXYZ> & words2, pcl::PointCloud<pcl::PointXYZ> & cloud1, pcl::PointCloud<pcl::PointXYZ> & cloud2) { const std::list<int> & ids = uUniqueKeys(words1); for(std::list<int>::const_iterator i=ids.begin(); i!=ids.end(); ++i) { if(words1.count(*i) == 1 && words2.count(*i) == 1) { const pcl::PointXYZ & pt1 = words1.find(*i)->second; const pcl::PointXYZ & pt2 = words2.find(*i)->second; if(pcl::isFinite(pt1) && pcl::isFinite(pt2)) { cloud1.push_back(pt1); cloud2.push_back(pt2); } } } } void extractXYZCorrespondencesRANSAC(const std::multimap<int, pcl::PointXYZ> & words1, const std::multimap<int, pcl::PointXYZ> & words2, pcl::PointCloud<pcl::PointXYZ> & cloud1, pcl::PointCloud<pcl::PointXYZ> & cloud2) { std::list<std::pair<pcl::PointXYZ, pcl::PointXYZ> > pairs; const std::list<int> & ids = uUniqueKeys(words1); for(std::list<int>::const_iterator i=ids.begin(); i!=ids.end(); ++i) { if(words1.count(*i) == 1 && words2.count(*i) == 1) { const pcl::PointXYZ & pt1 = words1.find(*i)->second; const pcl::PointXYZ & pt2 = words2.find(*i)->second; if(pcl::isFinite(pt1) && pcl::isFinite(pt2)) { pairs.push_back(std::pair<pcl::PointXYZ, pcl::PointXYZ>(pt1, pt2)); } } } if(pairs.size() > 7) { // Remove outliers using fundamental matrix RANSAC std::vector<uchar> status(pairs.size(), 0); //Convert Keypoints to a structure that OpenCV understands //3 dimensions (Homogeneous vectors) cv::Mat points1(1, (int)pairs.size(), CV_32FC2); cv::Mat points2(1, (int)pairs.size(), CV_32FC2); float * points1data = points1.ptr<float>(0); float * points2data = points2.ptr<float>(0); // Fill the points here ... int i=0; for(std::list<std::pair<pcl::PointXYZ, pcl::PointXYZ> >::const_iterator iter = pairs.begin(); iter != pairs.end(); ++iter ) { points1data[i*2] = (*iter).first.x; points1data[i*2+1] = (*iter).first.y; points2data[i*2] = (*iter).second.x; points2data[i*2+1] = (*iter).second.y; ++i; } // Find the fundamental matrix cv::Mat fundamentalMatrix = cv::findFundamentalMat( points1, points2, status, cv::FM_RANSAC, 3.0, 0.99); if(!fundamentalMatrix.empty()) { int i = 0; for(std::list<std::pair<pcl::PointXYZ, pcl::PointXYZ> >::iterator iter=pairs.begin(); iter!=pairs.end(); ++iter) { if(status[i]) { cloud1.push_back(iter->first); cloud2.push_back(iter->second); } ++i; } } } } void extractXYZCorrespondences(const std::list<std::pair<cv::Point2f, cv::Point2f> > & correspondences, const cv::Mat & depthImage1, const cv::Mat & depthImage2, float cx, float cy, float fx, float fy, float maxDepth, pcl::PointCloud<pcl::PointXYZ> & cloud1, pcl::PointCloud<pcl::PointXYZ> & cloud2) { cloud1.resize(correspondences.size()); cloud2.resize(correspondences.size()); int oi=0; for(std::list<std::pair<cv::Point2f, cv::Point2f> >::const_iterator iter = correspondences.begin(); iter!=correspondences.end(); ++iter) { pcl::PointXYZ pt1 = projectDepthTo3D(depthImage1, iter->first.x, iter->first.y, cx, cy, fx, fy, true); pcl::PointXYZ pt2 = projectDepthTo3D(depthImage2, iter->second.x, iter->second.y, cx, cy, fx, fy, true); if(pcl::isFinite(pt1) && pcl::isFinite(pt2) && (maxDepth <= 0 || (pt1.z <= maxDepth && pt2.z<=maxDepth))) { cloud1[oi] = pt1; cloud2[oi] = pt2; ++oi; } } cloud1.resize(oi); cloud2.resize(oi); } template<typename PointT> inline void extractXYZCorrespondencesImpl(const std::list<std::pair<cv::Point2f, cv::Point2f> > & correspondences, const pcl::PointCloud<PointT> & cloud1, const pcl::PointCloud<PointT> & cloud2, pcl::PointCloud<pcl::PointXYZ> & inliers1, pcl::PointCloud<pcl::PointXYZ> & inliers2, char depthAxis) { for(std::list<std::pair<cv::Point2f, cv::Point2f> >::const_iterator iter = correspondences.begin(); iter!=correspondences.end(); ++iter) { PointT pt1 = cloud1.at(int(iter->first.y+0.5f) * cloud1.width + int(iter->first.x+0.5f)); PointT pt2 = cloud2.at(int(iter->second.y+0.5f) * cloud2.width + int(iter->second.x+0.5f)); if(pcl::isFinite(pt1) && pcl::isFinite(pt2)) { inliers1.push_back(pcl::PointXYZ(pt1.x, pt1.y, pt1.z)); inliers2.push_back(pcl::PointXYZ(pt2.x, pt2.y, pt2.z)); } } } void extractXYZCorrespondences(const std::list<std::pair<cv::Point2f, cv::Point2f> > & correspondences, const pcl::PointCloud<pcl::PointXYZ> & cloud1, const pcl::PointCloud<pcl::PointXYZ> & cloud2, pcl::PointCloud<pcl::PointXYZ> & inliers1, pcl::PointCloud<pcl::PointXYZ> & inliers2, char depthAxis) { extractXYZCorrespondencesImpl(correspondences, cloud1, cloud2, inliers1, inliers2, depthAxis); } void extractXYZCorrespondences(const std::list<std::pair<cv::Point2f, cv::Point2f> > & correspondences, const pcl::PointCloud<pcl::PointXYZRGB> & cloud1, const pcl::PointCloud<pcl::PointXYZRGB> & cloud2, pcl::PointCloud<pcl::PointXYZ> & inliers1, pcl::PointCloud<pcl::PointXYZ> & inliers2, char depthAxis) { extractXYZCorrespondencesImpl(correspondences, cloud1, cloud2, inliers1, inliers2, depthAxis); } int countUniquePairs(const std::multimap<int, pcl::PointXYZ> & wordsA, const std::multimap<int, pcl::PointXYZ> & wordsB) { const std::list<int> & ids = uUniqueKeys(wordsA); int pairs = 0; for(std::list<int>::const_iterator i=ids.begin(); i!=ids.end(); ++i) { std::list<pcl::PointXYZ> ptsA = uValues(wordsA, *i); std::list<pcl::PointXYZ> ptsB = uValues(wordsB, *i); if(ptsA.size() == 1 && ptsB.size() == 1) { ++pairs; } } return pairs; } void filterMaxDepth(pcl::PointCloud<pcl::PointXYZ> & inliers1, pcl::PointCloud<pcl::PointXYZ> & inliers2, float maxDepth, char depthAxis, bool removeDuplicates) { std::list<pcl::PointXYZ> addedPts; if(maxDepth > 0.0f && inliers1.size() && inliers1.size() == inliers2.size()) { pcl::PointCloud<pcl::PointXYZ> tmpInliers1; pcl::PointCloud<pcl::PointXYZ> tmpInliers2; for(unsigned int i=0; i<inliers1.size(); ++i) { if((depthAxis == 'x' && inliers1.at(i).x < maxDepth && inliers2.at(i).x < maxDepth) || (depthAxis == 'y' && inliers1.at(i).y < maxDepth && inliers2.at(i).y < maxDepth) || (depthAxis == 'z' && inliers1.at(i).z < maxDepth && inliers2.at(i).z < maxDepth)) { bool dup = false; if(removeDuplicates) { for(std::list<pcl::PointXYZ>::iterator iter = addedPts.begin(); iter!=addedPts.end(); ++iter) { if(iter->x == inliers1.at(i).x && iter->y == inliers1.at(i).y && iter->z == inliers1.at(i).z) { dup = true; } } if(!dup) { addedPts.push_back(inliers1.at(i)); } } if(!dup) { tmpInliers1.push_back(inliers1.at(i)); tmpInliers2.push_back(inliers2.at(i)); } } } inliers1 = tmpInliers1; inliers2 = tmpInliers2; } } // Get transform from cloud2 to cloud1 Transform transformFromXYZCorrespondences( const pcl::PointCloud<pcl::PointXYZ>::ConstPtr & cloud1, const pcl::PointCloud<pcl::PointXYZ>::ConstPtr & cloud2, double inlierThreshold, int iterations, bool refineModel, double refineModelSigma, int refineModelIterations, std::vector<int> * inliersOut, double * varianceOut) { //NOTE: this method is a mix of two methods: // - getRemainingCorrespondences() in pcl/registration/impl/correspondence_rejection_sample_consensus.hpp // - refineModel() in pcl/sample_consensus/sac.h if(varianceOut) { *varianceOut = 1.0; } Transform transform; if(cloud1->size() >=3 && cloud1->size() == cloud2->size()) { // RANSAC UDEBUG("iterations=%d inlierThreshold=%f", iterations, inlierThreshold); std::vector<int> source_indices (cloud2->size()); std::vector<int> target_indices (cloud1->size()); // Copy the query-match indices for (int i = 0; i < (int)cloud1->size(); ++i) { source_indices[i] = i; target_indices[i] = i; } // From the set of correspondences found, attempt to remove outliers // Create the registration model pcl::SampleConsensusModelRegistration<pcl::PointXYZ>::Ptr model; model.reset(new pcl::SampleConsensusModelRegistration<pcl::PointXYZ>(cloud2, source_indices)); // Pass the target_indices model->setInputTarget (cloud1, target_indices); // Create a RANSAC model pcl::RandomSampleConsensus<pcl::PointXYZ> sac (model, inlierThreshold); sac.setMaxIterations(iterations); // Compute the set of inliers if(sac.computeModel()) { std::vector<int> inliers; Eigen::VectorXf model_coefficients; sac.getInliers(inliers); sac.getModelCoefficients (model_coefficients); if (refineModel) { double inlier_distance_threshold_sqr = inlierThreshold * inlierThreshold; double error_threshold = inlierThreshold; double sigma_sqr = refineModelSigma * refineModelSigma; int refine_iterations = 0; bool inlier_changed = false, oscillating = false; std::vector<int> new_inliers, prev_inliers = inliers; std::vector<size_t> inliers_sizes; Eigen::VectorXf new_model_coefficients = model_coefficients; do { // Optimize the model coefficients model->optimizeModelCoefficients (prev_inliers, new_model_coefficients, new_model_coefficients); inliers_sizes.push_back (prev_inliers.size ()); // Select the new inliers based on the optimized coefficients and new threshold model->selectWithinDistance (new_model_coefficients, error_threshold, new_inliers); UDEBUG("RANSAC refineModel: Number of inliers found (before/after): %d/%d, with an error threshold of %f.", (int)prev_inliers.size (), (int)new_inliers.size (), error_threshold); if (new_inliers.empty ()) { ++refine_iterations; if (refine_iterations >= refineModelIterations) { break; } continue; } // Estimate the variance and the new threshold double variance = model->computeVariance (); error_threshold = sqrt (std::min (inlier_distance_threshold_sqr, sigma_sqr * variance)); UDEBUG ("RANSAC refineModel: New estimated error threshold: %f (variance=%f) on iteration %d out of %d.", error_threshold, variance, refine_iterations, refineModelIterations); inlier_changed = false; std::swap (prev_inliers, new_inliers); // If the number of inliers changed, then we are still optimizing if (new_inliers.size () != prev_inliers.size ()) { // Check if the number of inliers is oscillating in between two values if (inliers_sizes.size () >= 4) { if (inliers_sizes[inliers_sizes.size () - 1] == inliers_sizes[inliers_sizes.size () - 3] && inliers_sizes[inliers_sizes.size () - 2] == inliers_sizes[inliers_sizes.size () - 4]) { oscillating = true; break; } } inlier_changed = true; continue; } // Check the values of the inlier set for (size_t i = 0; i < prev_inliers.size (); ++i) { // If the value of the inliers changed, then we are still optimizing if (prev_inliers[i] != new_inliers[i]) { inlier_changed = true; break; } } } while (inlier_changed && ++refine_iterations < refineModelIterations); // If the new set of inliers is empty, we didn't do a good job refining if (new_inliers.empty ()) { UWARN ("RANSAC refineModel: Refinement failed: got an empty set of inliers!"); } if (oscillating) { UDEBUG("RANSAC refineModel: Detected oscillations in the model refinement."); } std::swap (inliers, new_inliers); model_coefficients = new_model_coefficients; } if (inliers.size() >= 3) { if(inliersOut) { *inliersOut = inliers; } if(varianceOut) { *varianceOut = model->computeVariance(); } // get best transformation Eigen::Matrix4f bestTransformation; bestTransformation.row (0) = model_coefficients.segment<4>(0); bestTransformation.row (1) = model_coefficients.segment<4>(4); bestTransformation.row (2) = model_coefficients.segment<4>(8); bestTransformation.row (3) = model_coefficients.segment<4>(12); transform = Transform::fromEigen4f(bestTransformation); UDEBUG("RANSAC inliers=%d/%d tf=%s", (int)inliers.size(), (int)cloud1->size(), transform.prettyPrint().c_str()); return transform.inverse(); // inverse to get actual pose transform (not correspondences transform) } else { UDEBUG("RANSAC: Model with inliers < 3"); } } else { UDEBUG("RANSAC: Failed to find model"); } } else { UDEBUG("Not enough points to compute the transform"); } return Transform(); } // return transform from source to target (All points must be finite!!!) Transform icp(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr & cloud_source, const pcl::PointCloud<pcl::PointXYZ>::ConstPtr & cloud_target, double maxCorrespondenceDistance, int maximumIterations, bool * hasConvergedOut, double * variance, int * inliers) { pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp; // Set the input source and target icp.setInputTarget (cloud_target); icp.setInputSource (cloud_source); // Set the max correspondence distance to 5cm (e.g., correspondences with higher distances will be ignored) icp.setMaxCorrespondenceDistance (maxCorrespondenceDistance); // Set the maximum number of iterations (criterion 1) icp.setMaximumIterations (maximumIterations); // Set the transformation epsilon (criterion 2) //icp.setTransformationEpsilon (transformationEpsilon); // Set the euclidean distance difference epsilon (criterion 3) //icp.setEuclideanFitnessEpsilon (1); //icp.setRANSACOutlierRejectionThreshold(maxCorrespondenceDistance); // Perform the alignment pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_source_registered(new pcl::PointCloud<pcl::PointXYZ>); icp.align (*cloud_source_registered); bool hasConverged = icp.hasConverged(); // compute variance if((inliers || variance) && hasConverged) { pcl::registration::CorrespondenceEstimation<pcl::PointXYZ, pcl::PointXYZ>::Ptr est; est.reset(new pcl::registration::CorrespondenceEstimation<pcl::PointXYZ, pcl::PointXYZ>); est->setInputTarget(cloud_target); est->setInputSource(cloud_source_registered); pcl::Correspondences correspondences; est->determineCorrespondences(correspondences, maxCorrespondenceDistance); if(variance) { if(correspondences.size()>=3) { std::vector<double> distances(correspondences.size()); for(unsigned int i=0; i<correspondences.size(); ++i) { distances[i] = correspondences[i].distance; } //variance std::sort(distances.begin (), distances.end ()); double median_error_sqr = distances[distances.size () >> 1]; *variance = (2.1981 * median_error_sqr); } else { hasConverged = false; *variance = -1.0; } } if(inliers) { *inliers = (int)correspondences.size(); } } else { if(inliers) { *inliers = 0; } if(variance) { *variance = -1; } } if(hasConvergedOut) { *hasConvergedOut = hasConverged; } return Transform::fromEigen4f(icp.getFinalTransformation()); } // return transform from source to target (All points/normals must be finite!!!) Transform icpPointToPlane( const pcl::PointCloud<pcl::PointNormal>::ConstPtr & cloud_source, const pcl::PointCloud<pcl::PointNormal>::ConstPtr & cloud_target, double maxCorrespondenceDistance, int maximumIterations, bool * hasConvergedOut, double * variance, int * inliers) { pcl::IterativeClosestPoint<pcl::PointNormal, pcl::PointNormal> icp; // Set the input source and target icp.setInputTarget (cloud_target); icp.setInputSource (cloud_source); pcl::registration::TransformationEstimationPointToPlaneLLS<pcl::PointNormal, pcl::PointNormal>::Ptr est; est.reset(new pcl::registration::TransformationEstimationPointToPlaneLLS<pcl::PointNormal, pcl::PointNormal>); icp.setTransformationEstimation(est); // Set the max correspondence distance to 5cm (e.g., correspondences with higher distances will be ignored) icp.setMaxCorrespondenceDistance (maxCorrespondenceDistance); // Set the maximum number of iterations (criterion 1) icp.setMaximumIterations (maximumIterations); // Set the transformation epsilon (criterion 2) //icp.setTransformationEpsilon (transformationEpsilon); // Set the euclidean distance difference epsilon (criterion 3) //icp.setEuclideanFitnessEpsilon (1); //icp.setRANSACOutlierRejectionThreshold(maxCorrespondenceDistance); // Perform the alignment pcl::PointCloud<pcl::PointNormal>::Ptr cloud_source_registered(new pcl::PointCloud<pcl::PointNormal>); icp.align (*cloud_source_registered); bool hasConverged = icp.hasConverged(); // compute variance if((inliers || variance) && hasConverged) { pcl::registration::CorrespondenceEstimation<pcl::PointNormal, pcl::PointNormal>::Ptr est; est.reset(new pcl::registration::CorrespondenceEstimation<pcl::PointNormal, pcl::PointNormal>); est->setInputTarget(cloud_target); est->setInputSource(cloud_source_registered); pcl::Correspondences correspondences; est->determineCorrespondences(correspondences, maxCorrespondenceDistance); if(variance) { if(correspondences.size()>=3) { std::vector<double> distances(correspondences.size()); for(unsigned int i=0; i<correspondences.size(); ++i) { distances[i] = correspondences[i].distance; } //variance std::sort(distances.begin (), distances.end ()); double median_error_sqr = distances[distances.size () >> 1]; *variance = (2.1981 * median_error_sqr); } else { hasConverged = false; *variance = -1.0; } } if(inliers) { *inliers = (int)correspondences.size(); } } else { if(inliers) { *inliers = 0; } if(variance) { *variance = -1; } } if(hasConvergedOut) { *hasConvergedOut = hasConverged; } return Transform::fromEigen4f(icp.getFinalTransformation()); } // return transform from source to target (All points must be finite!!!) Transform icp2D(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr & cloud_source, const pcl::PointCloud<pcl::PointXYZ>::ConstPtr & cloud_target, double maxCorrespondenceDistance, int maximumIterations, bool * hasConvergedOut, double * variance, int * inliers) { pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp; // Set the input source and target icp.setInputTarget (cloud_target); icp.setInputSource (cloud_source); pcl::registration::TransformationEstimation2D<pcl::PointXYZ, pcl::PointXYZ>::Ptr est; est.reset(new pcl::registration::TransformationEstimation2D<pcl::PointXYZ, pcl::PointXYZ>); icp.setTransformationEstimation(est); // Set the max correspondence distance to 5cm (e.g., correspondences with higher distances will be ignored) icp.setMaxCorrespondenceDistance (maxCorrespondenceDistance); // Set the maximum number of iterations (criterion 1) icp.setMaximumIterations (maximumIterations); // Set the transformation epsilon (criterion 2) //icp.setTransformationEpsilon (transformationEpsilon); // Set the euclidean distance difference epsilon (criterion 3) //icp.setEuclideanFitnessEpsilon (1); //icp.setRANSACOutlierRejectionThreshold(maxCorrespondenceDistance); // Perform the alignment pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_source_registered(new pcl::PointCloud<pcl::PointXYZ>); icp.align (*cloud_source_registered); bool hasConverged = icp.hasConverged(); // compute variance if((inliers || variance) && hasConverged) { pcl::registration::CorrespondenceEstimation<pcl::PointXYZ, pcl::PointXYZ>::Ptr est; est.reset(new pcl::registration::CorrespondenceEstimation<pcl::PointXYZ, pcl::PointXYZ>); est->setInputTarget(cloud_target); est->setInputSource(cloud_source_registered); pcl::Correspondences correspondences; est->determineCorrespondences(correspondences, maxCorrespondenceDistance); if(variance) { if(correspondences.size()>=3) { std::vector<double> distances(correspondences.size()); for(unsigned int i=0; i<correspondences.size(); ++i) { distances[i] = correspondences[i].distance; } //variance std::sort(distances.begin (), distances.end ()); double median_error_sqr = distances[distances.size () >> 1]; *variance = (2.1981 * median_error_sqr); } else { hasConverged = false; *variance = -1.0; } } if(inliers) { *inliers = (int)correspondences.size(); } } else { if(inliers) { *inliers = 0; } if(variance) { *variance = -1; } } if(hasConvergedOut) { *hasConvergedOut = hasConverged; } return Transform::fromEigen4f(icp.getFinalTransformation()); } pcl::PointCloud<pcl::PointNormal>::Ptr computeNormals( const pcl::PointCloud<pcl::PointXYZ>::Ptr & cloud, int normalKSearch) { pcl::PointCloud<pcl::PointNormal>::Ptr cloud_with_normals(new pcl::PointCloud<pcl::PointNormal>); pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>); tree->setInputCloud (cloud); // Normal estimation* pcl::NormalEstimationOMP<pcl::PointXYZ, pcl::Normal> n; pcl::PointCloud<pcl::Normal>::Ptr normals (new pcl::PointCloud<pcl::Normal>); n.setInputCloud (cloud); n.setSearchMethod (tree); n.setKSearch (normalKSearch); n.compute (*normals); //* normals should not contain the point normals + surface curvatures // Concatenate the XYZ and normal fields* pcl::concatenateFields (*cloud, *normals, *cloud_with_normals); //* cloud_with_normals = cloud + normals*/ return cloud_with_normals; } pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr computeNormals( const pcl::PointCloud<pcl::PointXYZRGB>::Ptr & cloud, int normalKSearch) { pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr cloud_with_normals(new pcl::PointCloud<pcl::PointXYZRGBNormal>); pcl::search::KdTree<pcl::PointXYZRGB>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZRGB>); tree->setInputCloud (cloud); // Normal estimation* pcl::NormalEstimationOMP<pcl::PointXYZRGB, pcl::Normal> n; pcl::PointCloud<pcl::Normal>::Ptr normals (new pcl::PointCloud<pcl::Normal>); n.setInputCloud (cloud); n.setSearchMethod (tree); n.setKSearch (normalKSearch); n.compute (*normals); //* normals should not contain the point normals + surface curvatures // Concatenate the XYZ and normal fields* pcl::concatenateFields (*cloud, *normals, *cloud_with_normals); //* cloud_with_normals = cloud + normals*/ return cloud_with_normals; } pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr computeNormalsSmoothed( const pcl::PointCloud<pcl::PointXYZRGB>::Ptr & cloud, float smoothingSearchRadius, bool smoothingPolynomialFit) { pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr cloud_with_normals(new pcl::PointCloud<pcl::PointXYZRGBNormal>); pcl::search::KdTree<pcl::PointXYZRGB>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZRGB>); tree->setInputCloud (cloud); // Init object (second point type is for the normals, even if unused) pcl::MovingLeastSquares<pcl::PointXYZRGB, pcl::PointXYZRGBNormal> mls; mls.setComputeNormals (true); // Set parameters mls.setInputCloud (cloud); mls.setPolynomialFit (smoothingPolynomialFit); mls.setSearchMethod (tree); mls.setSearchRadius (smoothingSearchRadius); // Reconstruct mls.process (*cloud_with_normals); return cloud_with_normals; } // a kdtree is constructed with cloud_target, then nearest neighbor // is computed for each cloud_source points. int getCorrespondencesCount(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr & cloud_source, const pcl::PointCloud<pcl::PointXYZ>::ConstPtr & cloud_target, float maxDistance) { pcl::search::KdTree<pcl::PointXYZ>::Ptr kdTree(new pcl::search::KdTree<pcl::PointXYZ>); kdTree->setInputCloud(cloud_target); int count = 0; float sqrdMaxDistance = maxDistance * maxDistance; for(unsigned int i=0; i<cloud_source->size(); ++i) { std::vector<int> ind(1); std::vector<float> dist(1); if(kdTree->nearestKSearch(cloud_source->at(i), 1, ind, dist) && dist[0] < sqrdMaxDistance) { ++count; } } return count; } /** * if a=[1 2 3 4 6 6], b=[1 1 2 4 5 6 6], results= [(2,2) (4,4)] * realPairsCount = 5 */ void findCorrespondences( const std::multimap<int, cv::KeyPoint> & wordsA, const std::multimap<int, cv::KeyPoint> & wordsB, std::list<std::pair<cv::Point2f, cv::Point2f> > & pairs) { const std::list<int> & ids = uUniqueKeys(wordsA); pairs.clear(); for(std::list<int>::const_iterator i=ids.begin(); i!=ids.end(); ++i) { std::list<cv::KeyPoint> ptsA = uValues(wordsA, *i); std::list<cv::KeyPoint> ptsB = uValues(wordsB, *i); if(ptsA.size() == 1 && ptsB.size() == 1) { pairs.push_back(std::pair<cv::Point2f, cv::Point2f>(ptsA.front().pt, ptsB.front().pt)); } } } pcl::PointCloud<pcl::PointXYZ>::Ptr cvMat2Cloud( const cv::Mat & matrix, const Transform & tranform) { UASSERT(matrix.type() == CV_32FC2 || matrix.type() == CV_32FC3); UASSERT(matrix.rows == 1); Eigen::Affine3f t = tranform.toEigen3f(); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>); cloud->resize(matrix.cols); if(matrix.channels() == 2) { for(int i=0; i<matrix.cols; ++i) { cloud->at(i).x = matrix.at<cv::Vec2f>(0,i)[0]; cloud->at(i).y = matrix.at<cv::Vec2f>(0,i)[1]; cloud->at(i).z = 0.0f; cloud->at(i) = pcl::transformPoint(cloud->at(i), t); } } else // channels=3 { for(int i=0; i<matrix.cols; ++i) { cloud->at(i).x = matrix.at<cv::Vec3f>(0,i)[0]; cloud->at(i).y = matrix.at<cv::Vec3f>(0,i)[1]; cloud->at(i).z = matrix.at<cv::Vec3f>(0,i)[2]; cloud->at(i) = pcl::transformPoint(cloud->at(i), t); } } return cloud; } // If "voxel" > 0, "samples" is ignored pcl::PointCloud<pcl::PointXYZ>::Ptr getICPReadyCloud( const cv::Mat & depth, float fx, float fy, float cx, float cy, int decimation, double maxDepth, float voxel, int samples, const Transform & transform) { UASSERT(!depth.empty() && (depth.type() == CV_16UC1 || depth.type() == CV_32FC1)); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud; cloud = cloudFromDepth( depth, cx, cy, fx, fy, decimation); if(cloud->size()) { if(maxDepth>0.0) { cloud = passThrough<pcl::PointXYZ>(cloud, "z", 0, maxDepth); } if(cloud->size()) { if(voxel>0) { cloud = voxelize<pcl::PointXYZ>(cloud, voxel); } else if(samples>0 && (int)cloud->size() > samples) { cloud = sampling<pcl::PointXYZ>(cloud, samples); } if(cloud->size()) { if(!transform.isNull() && !transform.isIdentity()) { cloud = transformPointCloud<pcl::PointXYZ>(cloud, transform); } } } } return cloud; } pcl::PointCloud<pcl::PointXYZ>::Ptr concatenateClouds(const std::list<pcl::PointCloud<pcl::PointXYZ>::Ptr> & clouds) { pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>); for(std::list<pcl::PointCloud<pcl::PointXYZ>::Ptr>::const_iterator iter = clouds.begin(); iter!=clouds.end(); ++iter) { *cloud += *(*iter); } return cloud; } pcl::PointCloud<pcl::PointXYZRGB>::Ptr concatenateClouds(const std::list<pcl::PointCloud<pcl::PointXYZRGB>::Ptr> & clouds) { pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZRGB>); for(std::list<pcl::PointCloud<pcl::PointXYZRGB>::Ptr>::const_iterator iter = clouds.begin(); iter!=clouds.end(); ++iter) { *cloud+=*(*iter); } return cloud; } pcl::PointCloud<pcl::PointXYZ>::Ptr get3DFASTKpts( const cv::Mat & image, const cv::Mat & imageDepth, float constant, int fastThreshold, bool fastNonmaxSuppression, float maxDepth) { // Extract words cv::FastFeatureDetector detector(fastThreshold, fastNonmaxSuppression); std::vector<cv::KeyPoint> kpts; detector.detect(image, kpts); pcl::PointCloud<pcl::PointXYZ>::Ptr points(new pcl::PointCloud<pcl::PointXYZ>); for(unsigned int i=0; i<kpts.size(); ++i) { pcl::PointXYZ pt = projectDepthTo3D(imageDepth, kpts[i].pt.x, kpts[i].pt.y, 0, 0, 1.0f/constant, 1.0f/constant, true); if(uIsFinite(pt.z) && (maxDepth <= 0 || pt.z <= maxDepth)) { points->push_back(pt); } } UDEBUG("points %d -> %d", (int)kpts.size(), (int)points->size()); return points; } pcl::PolygonMesh::Ptr createMesh( const pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr & cloudWithNormals, float gp3SearchRadius, float gp3Mu, int gp3MaximumNearestNeighbors, float gp3MaximumSurfaceAngle, float gp3MinimumAngle, float gp3MaximumAngle, bool gp3NormalConsistency) { pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr cloudWithNormalsNoNaN = removeNaNNormalsFromPointCloud<pcl::PointXYZRGBNormal>(cloudWithNormals); // Create search tree* pcl::search::KdTree<pcl::PointXYZRGBNormal>::Ptr tree2 (new pcl::search::KdTree<pcl::PointXYZRGBNormal>); tree2->setInputCloud (cloudWithNormalsNoNaN); // Initialize objects pcl::GreedyProjectionTriangulation<pcl::PointXYZRGBNormal> gp3; pcl::PolygonMesh::Ptr mesh(new pcl::PolygonMesh); // Set the maximum distance between connected points (maximum edge length) gp3.setSearchRadius (gp3SearchRadius); // Set typical values for the parameters gp3.setMu (gp3Mu); gp3.setMaximumNearestNeighbors (gp3MaximumNearestNeighbors); gp3.setMaximumSurfaceAngle(gp3MaximumSurfaceAngle); // 45 degrees gp3.setMinimumAngle(gp3MinimumAngle); // 10 degrees gp3.setMaximumAngle(gp3MaximumAngle); // 120 degrees gp3.setNormalConsistency(gp3NormalConsistency); // Get result gp3.setInputCloud (cloudWithNormalsNoNaN); gp3.setSearchMethod (tree2); gp3.reconstruct (*mesh); return mesh; } void occupancy2DFromLaserScan( const cv::Mat & scan, cv::Mat & ground, cv::Mat & obstacles, float cellSize) { if(scan.empty()) { return; } std::map<int, Transform> poses; poses.insert(std::make_pair(1, Transform::getIdentity())); pcl::PointCloud<pcl::PointXYZ>::Ptr obstaclesCloud = util3d::laserScanToPointCloud(scan); //obstaclesCloud = util3d::voxelize<pcl::PointXYZ>(obstaclesCloud, cellSize); std::map<int, pcl::PointCloud<pcl::PointXYZ>::Ptr> scans; scans.insert(std::make_pair(1, obstaclesCloud)); float xMin, yMin; cv::Mat map8S = create2DMap(poses, scans, cellSize, false, xMin, yMin); // find ground cells std::list<int> groundIndices; for(unsigned int i=0; i< map8S.total(); ++i) { if(map8S.data[i] == 0) { groundIndices.push_back(i); } } // Convert to position matrices, get points to each center of the cells ground = cv::Mat(); if(groundIndices.size()) { ground = cv::Mat((int)groundIndices.size(), 1, CV_32FC2); int i=0; for(std::list<int>::iterator iter=groundIndices.begin();iter!=groundIndices.end(); ++iter) { int x = *iter / map8S.cols; int y = *iter - x*map8S.cols; ground.at<cv::Vec2f>(i)[0] = (float(y)+0.5)*cellSize + xMin; ground.at<cv::Vec2f>(i)[1] = (float(x)+0.5)*cellSize + yMin; ++i; } } // copy directly obstacles precise positions obstacles = cv::Mat(); if(obstaclesCloud->size()) { obstacles = cv::Mat((int)obstaclesCloud->size(), 1, CV_32FC2); for(unsigned int i=0;i<obstaclesCloud->size(); ++i) { obstacles.at<cv::Vec2f>(i)[0] = obstaclesCloud->at(i).x; obstacles.at<cv::Vec2f>(i)[1] = obstaclesCloud->at(i).y; } } } /** * Create 2d Occupancy grid (CV_8S) from 2d occupancy * -1 = unknown * 0 = empty space * 100 = obstacle * @param poses * @param occupancy <empty, occupied> * @param cellSize m * @param xMin * @param yMin * @param minMapSize minimum width (m) * @param erode */ cv::Mat create2DMapFromOccupancyLocalMaps( const std::map<int, Transform> & poses, const std::map<int, std::pair<cv::Mat, cv::Mat> > & occupancy, float cellSize, float & xMin, float & yMin, float minMapSize, bool erode) { UASSERT(minMapSize >= 0.0f); UDEBUG("cellSize=%f m, minMapSize=%f m, erode=%d", cellSize, minMapSize, erode?1:0); UTimer timer; std::map<int, cv::Mat> emptyLocalMaps; std::map<int, cv::Mat> occupiedLocalMaps; float minX=-minMapSize/2.0, minY=-minMapSize/2.0, maxX=minMapSize/2.0, maxY=minMapSize/2.0; bool undefinedSize = minMapSize == 0.0f; float x=0.0f,y=0.0f,z=0.0f,roll=0.0f,pitch=0.0f,yaw=0.0f,cosT=0.0f,sinT=0.0f; cv::Mat affineTransform(2,3,CV_32FC1); for(std::map<int, Transform>::const_iterator iter = poses.begin(); iter!=poses.end(); ++iter) { if(uContains(occupancy, iter->first)) { UASSERT(!iter->second.isNull()); const std::pair<cv::Mat, cv::Mat> & pair = occupancy.at(iter->first); iter->second.getTranslationAndEulerAngles(x,y,z,roll,pitch,yaw); cosT = cos(yaw); sinT = sin(yaw); affineTransform.at<float>(0,0) = cosT; affineTransform.at<float>(0,1) = -sinT; affineTransform.at<float>(1,0) = sinT; affineTransform.at<float>(1,1) = cosT; affineTransform.at<float>(0,2) = x; affineTransform.at<float>(1,2) = y; if(undefinedSize) { minX = maxX = x; minY = maxY = y; undefinedSize = false; } else { if(minX > x) minX = x; else if(maxX < x) maxX = x; if(minY > y) minY = y; else if(maxY < y) maxY = y; } //ground if(pair.first.rows) { UASSERT(pair.first.type() == CV_32FC2); cv::Mat ground(pair.first.rows, pair.first.cols, pair.first.type()); cv::transform(pair.first, ground, affineTransform); for(int i=0; i<ground.rows; ++i) { if(minX > ground.at<float>(i,0)) minX = ground.at<float>(i,0); else if(maxX < ground.at<float>(i,0)) maxX = ground.at<float>(i,0); if(minY > ground.at<float>(i,1)) minY = ground.at<float>(i,1); else if(maxY < ground.at<float>(i,1)) maxY = ground.at<float>(i,1); } emptyLocalMaps.insert(std::make_pair(iter->first, ground)); } //obstacles if(pair.second.rows) { UASSERT(pair.second.type() == CV_32FC2); cv::Mat obstacles(pair.second.rows, pair.second.cols, pair.second.type()); cv::transform(pair.second, obstacles, affineTransform); for(int i=0; i<obstacles.rows; ++i) { if(minX > obstacles.at<float>(i,0)) minX = obstacles.at<float>(i,0); else if(maxX < obstacles.at<float>(i,0)) maxX = obstacles.at<float>(i,0); if(minY > obstacles.at<float>(i,1)) minY = obstacles.at<float>(i,1); else if(maxY < obstacles.at<float>(i,1)) maxY = obstacles.at<float>(i,1); } occupiedLocalMaps.insert(std::make_pair(iter->first, obstacles)); } } } UDEBUG("timer=%fs", timer.ticks()); cv::Mat map; if(minX != maxX && minY != maxY) { //Get map size float margin = cellSize*10.0f; xMin = minX-margin; yMin = minY-margin; float xMax = maxX+margin; float yMax = maxY+margin; if(fabs((yMax - yMin) / cellSize) > 99999 || fabs((xMax - xMin) / cellSize) > 99999) { UERROR("Large map size!! map min=(%f, %f) max=(%f,%f). " "There's maybe an error with the poses provided! The map will not be created!", xMin, yMin, xMax, yMax); } else { UDEBUG("map min=(%f, %f) max=(%f,%f)", xMin, yMin, xMax, yMax); map = cv::Mat::ones((yMax - yMin) / cellSize + 0.5f, (xMax - xMin) / cellSize + 0.5f, CV_8S)*-1; for(std::map<int, Transform>::const_iterator kter = poses.begin(); kter!=poses.end(); ++kter) { std::map<int, cv::Mat >::iterator iter = emptyLocalMaps.find(kter->first); std::map<int, cv::Mat >::iterator jter = occupiedLocalMaps.find(kter->first); if(iter!=emptyLocalMaps.end()) { for(int i=0; i<iter->second.rows; ++i) { cv::Point2i pt((iter->second.at<float>(i,0)-xMin)/cellSize + 0.5f, (iter->second.at<float>(i,1)-yMin)/cellSize + 0.5f); map.at<char>(pt.y, pt.x) = 0; // free space } } if(jter!=occupiedLocalMaps.end()) { for(int i=0; i<jter->second.rows; ++i) { cv::Point2i pt((jter->second.at<float>(i,0)-xMin)/cellSize + 0.5f, (jter->second.at<float>(i,1)-yMin)/cellSize + 0.5f); map.at<char>(pt.y, pt.x) = 100; // obstacles } } //UDEBUG("empty=%d occupied=%d", empty, occupied); } // fill holes and remove empty from obstacle borders cv::Mat updatedMap = map.clone(); std::list<std::pair<int, int> > obstacleIndices; for(int i=2; i<map.rows-2; ++i) { for(int j=2; j<map.cols-2; ++j) { if(map.at<char>(i, j) == -1 && map.at<char>(i+1, j) != -1 && map.at<char>(i-1, j) != -1 && map.at<char>(i, j+1) != -1 && map.at<char>(i, j-1) != -1) { updatedMap.at<char>(i, j) = 0; } else if(map.at<char>(i, j) == 100) { // obstacle/empty/unknown -> remove empty // unknown/empty/obstacle -> remove empty if(map.at<char>(i-1, j) == 0 && map.at<char>(i-2, j) == -1) { updatedMap.at<char>(i-1, j) = -1; } else if(map.at<char>(i+1, j) == 0 && map.at<char>(i+2, j) == -1) { updatedMap.at<char>(i+1, j) = -1; } if(map.at<char>(i, j-1) == 0 && map.at<char>(i, j-2) == -1) { updatedMap.at<char>(i, j-1) = -1; } else if(map.at<char>(i, j+1) == 0 && map.at<char>(i, j+2) == -1) { updatedMap.at<char>(i, j+1) = -1; } if(erode) { obstacleIndices.push_back(std::make_pair(i, j)); } } else if(map.at<char>(i, j) == 0) { // obstacle/empty/obstacle -> remove empty if(map.at<char>(i-1, j) == 100 && map.at<char>(i+1, j) == 100) { updatedMap.at<char>(i, j) = -1; } else if(map.at<char>(i, j-1) == 100 && map.at<char>(i, j+1) == 100) { updatedMap.at<char>(i, j) = -1; } } } } map = updatedMap; if(erode) { // remove obstacles which touch to empty cells but not unknown cells cv::Mat erodedMap = map.clone(); for(std::list<std::pair<int,int> >::iterator iter = obstacleIndices.begin(); iter!= obstacleIndices.end(); ++iter) { int i = iter->first; int j = iter->second; bool touchEmpty = map.at<char>(i+1, j) == 0 || map.at<char>(i-1, j) == 0 || map.at<char>(i, j+1) == 0 || map.at<char>(i, j-1) == 0; if(touchEmpty && map.at<char>(i+1, j) != -1 && map.at<char>(i-1, j) != -1 && map.at<char>(i, j+1) != -1 && map.at<char>(i, j-1) != -1) { erodedMap.at<char>(i, j) = 0; // empty } } map = erodedMap; } } } UDEBUG("timer=%fs", timer.ticks()); return map; } /** * Create 2d Occupancy grid (CV_8S) * -1 = unknown * 0 = empty space * 100 = obstacle * @param poses * @param scans * @param cellSize m * @param unknownSpaceFilled if false no fill, otherwise a virtual laser sweeps the unknown space from each pose (stopping on detected obstacle) * @param xMin * @param yMin */ cv::Mat create2DMap(const std::map<int, Transform> & poses, const std::map<int, pcl::PointCloud<pcl::PointXYZ>::Ptr > & scans, float cellSize, bool unknownSpaceFilled, float & xMin, float & yMin, float minMapSize) { UDEBUG("poses=%d, scans = %d", poses.size(), scans.size()); std::map<int, pcl::PointCloud<pcl::PointXYZ>::Ptr > localScans; pcl::PointCloud<pcl::PointXYZ> minMax; if(minMapSize > 0.0f) { minMax.push_back(pcl::PointXYZ(-minMapSize/2.0, -minMapSize/2.0, 0)); minMax.push_back(pcl::PointXYZ(minMapSize/2.0, minMapSize/2.0, 0)); } for(std::map<int, Transform>::const_iterator iter = poses.begin(); iter!=poses.end(); ++iter) { if(uContains(scans, iter->first) && scans.at(iter->first)->size()) { UASSERT(!iter->second.isNull()); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud = transformPointCloud<pcl::PointXYZ>(scans.at(iter->first), iter->second); pcl::PointXYZ min, max; pcl::getMinMax3D(*cloud, min, max); minMax.push_back(min); minMax.push_back(max); minMax.push_back(pcl::PointXYZ(iter->second.x(), iter->second.y(), iter->second.z())); localScans.insert(std::make_pair(iter->first, cloud)); } } cv::Mat map; if(minMax.size()) { //Get map size pcl::PointXYZ min, max; pcl::getMinMax3D(minMax, min, max); // Added X2 to make sure that all points are inside the map (when rounded to integer) float marging = cellSize*10.0f; xMin = min.x-marging; yMin = min.y-marging; float xMax = max.x+marging; float yMax = max.y+marging; UDEBUG("map min=(%f, %f) max=(%f,%f)", xMin, yMin, xMax, yMax); UTimer timer; map = cv::Mat::ones((yMax - yMin) / cellSize + 0.5f, (xMax - xMin) / cellSize + 0.5f, CV_8S)*-1; std::vector<float> maxSquaredLength(localScans.size(), 0.0f); int j=0; for(std::map<int, pcl::PointCloud<pcl::PointXYZ>::Ptr >::iterator iter = localScans.begin(); iter!=localScans.end(); ++iter) { const Transform & pose = poses.at(iter->first); cv::Point2i start((pose.x()-xMin)/cellSize + 0.5f, (pose.y()-yMin)/cellSize + 0.5f); for(unsigned int i=0; i<iter->second->size(); ++i) { cv::Point2i end((iter->second->points[i].x-xMin)/cellSize + 0.5f, (iter->second->points[i].y-yMin)/cellSize + 0.5f); map.at<char>(end.y, end.x) = 100; // obstacle rayTrace(start, end, map, true); // trace free space if(unknownSpaceFilled) { float dx = iter->second->points[i].x - pose.x(); float dy = iter->second->points[i].y - pose.y(); float l = dx*dx + dy*dy; if(l > maxSquaredLength[j]) { maxSquaredLength[j] = l; } } } ++j; } UDEBUG("Ray trace known space=%fs", timer.ticks()); // now fill unknown spaces if(unknownSpaceFilled) { j=0; for(std::map<int, pcl::PointCloud<pcl::PointXYZ>::Ptr >::iterator iter = localScans.begin(); iter!=localScans.end(); ++iter) { if(iter->second->size() > 1 && maxSquaredLength[j] > 0.0f) { float maxLength = sqrt(maxSquaredLength[j]); if(maxLength > cellSize) { // compute angle float a = (CV_PI/2.0f) / (maxLength / cellSize); //UWARN("a=%f PI/256=%f", a, CV_PI/256.0f); UASSERT_MSG(a >= 0 && a < 5.0f*CV_PI/8.0f, uFormat("a=%f length=%f cell=%f", a, maxLength, cellSize).c_str()); const Transform & pose = poses.at(iter->first); cv::Point2i start((pose.x()-xMin)/cellSize + 0.5f, (pose.y()-yMin)/cellSize + 0.5f); //UWARN("maxLength = %f", maxLength); //rotate counterclockwise from the first point until we pass the last point cv::Mat rotation = (cv::Mat_<float>(2,2) << cos(a), -sin(a), sin(a), cos(a)); cv::Mat origin(2,1,CV_32F), endFirst(2,1,CV_32F), endLast(2,1,CV_32F); origin.at<float>(0) = pose.x(); origin.at<float>(1) = pose.y(); endFirst.at<float>(0) = iter->second->points[0].x; endFirst.at<float>(1) = iter->second->points[0].y; endLast.at<float>(0) = iter->second->points[iter->second->points.size()-1].x; endLast.at<float>(1) = iter->second->points[iter->second->points.size()-1].y; //UWARN("origin = %f %f", origin.at<float>(0), origin.at<float>(1)); //UWARN("endFirst = %f %f", endFirst.at<float>(0), endFirst.at<float>(1)); //UWARN("endLast = %f %f", endLast.at<float>(0), endLast.at<float>(1)); cv::Mat tmp = (endFirst - origin); cv::Mat endRotated = rotation*((tmp/cv::norm(tmp))*maxLength) + origin; cv::Mat endLastVector(3,1,CV_32F), endRotatedVector(3,1,CV_32F); endLastVector.at<float>(0) = endLast.at<float>(0) - origin.at<float>(0); endLastVector.at<float>(1) = endLast.at<float>(1) - origin.at<float>(1); endLastVector.at<float>(2) = 0.0f; endRotatedVector.at<float>(0) = endRotated.at<float>(0) - origin.at<float>(0); endRotatedVector.at<float>(1) = endRotated.at<float>(1) - origin.at<float>(1); endRotatedVector.at<float>(2) = 0.0f; //UWARN("endRotated = %f %f", endRotated.at<float>(0), endRotated.at<float>(1)); while(endRotatedVector.cross(endLastVector).at<float>(2) > 0.0f) { cv::Point2i end((endRotated.at<float>(0)-xMin)/cellSize + 0.5f, (endRotated.at<float>(1)-yMin)/cellSize + 0.5f); //end must be inside the grid end.x = end.x < 0?0:end.x; end.x = end.x >= map.cols?map.cols-1:end.x; end.y = end.y < 0?0:end.y; end.y = end.y >= map.rows?map.rows-1:end.y; rayTrace(start, end, map, true); // trace free space // next point endRotated = rotation*(endRotated - origin) + origin; endRotatedVector.at<float>(0) = endRotated.at<float>(0) - origin.at<float>(0); endRotatedVector.at<float>(1) = endRotated.at<float>(1) - origin.at<float>(1); //UWARN("endRotated = %f %f", endRotated.at<float>(0), endRotated.at<float>(1)); } } } ++j; } UDEBUG("Fill empty space=%fs", timer.ticks()); } } return map; } void rayTrace(const cv::Point2i & start, const cv::Point2i & end, cv::Mat & grid, bool stopOnObstacle) { UASSERT_MSG(start.x >= 0 && start.x < grid.cols, uFormat("start.x=%d grid.cols=%d", start.x, grid.cols).c_str()); UASSERT_MSG(start.y >= 0 && start.y < grid.rows, uFormat("start.y=%d grid.rows=%d", start.y, grid.rows).c_str()); UASSERT_MSG(end.x >= 0 && end.x < grid.cols, uFormat("end.x=%d grid.cols=%d", end.x, grid.cols).c_str()); UASSERT_MSG(end.y >= 0 && end.y < grid.rows, uFormat("end.x=%d grid.cols=%d", end.y, grid.rows).c_str()); cv::Point2i ptA, ptB; ptA = start; ptB = end; float slope = float(ptB.y - ptA.y)/float(ptB.x - ptA.x); bool swapped = false; if(slope<-1.0f || slope>1.0f) { // swap x and y slope = 1.0f/slope; int tmp = ptA.x; ptA.x = ptA.y; ptA.y = tmp; tmp = ptB.x; ptB.x = ptB.y; ptB.y = tmp; swapped = true; } float b = ptA.y - slope*ptA.x; for(int x=ptA.x; ptA.x<ptB.x?x<ptB.x:x>ptB.x; ptA.x<ptB.x?++x:--x) { int upperbound = float(x)*slope + b; int lowerbound = upperbound; if(x != ptA.x) { lowerbound = (ptA.x<ptB.x?x+1:x-1)*slope + b; } if(lowerbound > upperbound) { int tmp = upperbound; upperbound = lowerbound; lowerbound = tmp; } if(!swapped) { UASSERT_MSG(lowerbound >= 0 && lowerbound < grid.rows, uFormat("lowerbound=%f grid.rows=%d x=%d slope=%f b=%f x=%f", lowerbound, grid.rows, x, slope, b, x).c_str()); UASSERT_MSG(upperbound >= 0 && upperbound < grid.rows, uFormat("upperbound=%f grid.rows=%d x+1=%d slope=%f b=%f x=%f", upperbound, grid.rows, x+1, slope, b, x).c_str()); } else { UASSERT_MSG(lowerbound >= 0 && lowerbound < grid.cols, uFormat("lowerbound=%f grid.cols=%d x=%d slope=%f b=%f x=%f", lowerbound, grid.cols, x, slope, b, x).c_str()); UASSERT_MSG(upperbound >= 0 && upperbound < grid.cols, uFormat("upperbound=%f grid.cols=%d x+1=%d slope=%f b=%f x=%f", upperbound, grid.cols, x+1, slope, b, x).c_str()); } for(int y = lowerbound; y<=(int)upperbound; ++y) { char * v; if(swapped) { v = &grid.at<char>(x, y); } else { v = &grid.at<char>(y, x); } if(*v == 100 && stopOnObstacle) { return; } else { *v = 0; // free space } } } } //convert to gray scaled map cv::Mat convertMap2Image8U(const cv::Mat & map8S) { UASSERT(map8S.channels() == 1 && map8S.type() == CV_8S); cv::Mat map8U = cv::Mat(map8S.rows, map8S.cols, CV_8U); for (int i = 0; i < map8S.rows; ++i) { for (int j = 0; j < map8S.cols; ++j) { char v = map8S.at<char>(i, j); unsigned char gray; if(v == 0) { gray = 178; } else if(v == 100) { gray = 0; } else // -1 { gray = 89; } map8U.at<unsigned char>(i, j) = gray; } } return map8U; } pcl::IndicesPtr concatenate(const std::vector<pcl::IndicesPtr> & indices) { //compute total size unsigned int totalSize = 0; for(unsigned int i=0; i<indices.size(); ++i) { totalSize += (unsigned int)indices[i]->size(); } pcl::IndicesPtr ind(new std::vector<int>(totalSize)); unsigned int io = 0; for(unsigned int i=0; i<indices.size(); ++i) { for(unsigned int j=0; j<indices[i]->size(); ++j) { ind->at(io++) = indices[i]->at(j); } } return ind; } pcl::IndicesPtr concatenate(const pcl::IndicesPtr & indicesA, const pcl::IndicesPtr & indicesB) { pcl::IndicesPtr ind(new std::vector<int>(*indicesA)); ind->resize(ind->size()+indicesB->size()); unsigned int oi = (unsigned int)indicesA->size(); for(unsigned int i=0; i<indicesB->size(); ++i) { ind->at(oi++) = indicesB->at(i); } return ind; } cv::Mat decimate(const cv::Mat & image, int decimation) { UASSERT(decimation >= 1); cv::Mat out; if(!image.empty()) { if(decimation > 1) { if((image.type() == CV_32FC1 || image.type()==CV_16UC1)) { UASSERT_MSG(image.rows % decimation == 0 && image.cols % decimation == 0, "Decimation of depth images should be exact!"); out = cv::Mat(image.rows/decimation, image.cols/decimation, image.type()); if(image.type() == CV_32FC1) { for(int j=0; j<out.rows; ++j) { for(int i=0; i<out.cols; ++i) { out.at<float>(j, i) = image.at<float>(j*decimation, i*decimation); } } } else // CV_16UC1 { for(int j=0; j<out.rows; ++j) { for(int i=0; i<out.cols; ++i) { out.at<unsigned short>(j, i) = image.at<unsigned short>(j*decimation, i*decimation); } } } } else { cv::resize(image, out, cv::Size(), 1.0f/float(decimation), 1.0f/float(decimation), cv::INTER_AREA); } } else { out = image; } } return out; } void savePCDWords( const std::string & fileName, const std::multimap<int, pcl::PointXYZ> & words, const Transform & transform) { if(words.size()) { pcl::PointCloud<pcl::PointXYZ> cloud; cloud.resize(words.size()); int i=0; for(std::multimap<int, pcl::PointXYZ>::const_iterator iter=words.begin(); iter!=words.end(); ++iter) { cloud[i++] = util3d::transformPoint(iter->second, transform); } pcl::io::savePCDFile(fileName, cloud); } } } }
29.895202
174
0.636483
redater
31f2a804ed13fbc35603324f00dc64a50bb0b628
167
cpp
C++
div.cpp
etoki/cpp_learn
d5a84df6682f2013770ea12d6e40328c5a74dff3
[ "MIT" ]
null
null
null
div.cpp
etoki/cpp_learn
d5a84df6682f2013770ea12d6e40328c5a74dff3
[ "MIT" ]
null
null
null
div.cpp
etoki/cpp_learn
d5a84df6682f2013770ea12d6e40328c5a74dff3
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int main(){ int ires; float fres; ires = 1%3; fres = 1%3; cout << ires << endl; cout << fres << endl; return 0; }
9.277778
22
0.586826
etoki
31f73b652736d01fb812738ecd71c7a7d1ab060e
1,474
cpp
C++
coast/modules/Oracle/OracleResultset.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
coast/modules/Oracle/OracleResultset.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
coast/modules/Oracle/OracleResultset.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2009, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ #include "OracleResultset.h" #include "OracleStatement.h" #include "OracleException.h" #include "Tracer.h" OracleStatement::Description &OracleResultset::GetOutputDescription() { StartTrace(OracleResultset.GetOutputDescription); return frStmt.GetOutputDescription(); } bool OracleResultset::DefineOutputArea() { StartTrace(OracleResultset.DefineOutputArea); return frStmt.DefineOutputArea(); } OracleResultset::Status OracleResultset::next() { StartTrace(OracleResultset.next); if (fFetchStatus == NOT_READY) { DefineOutputArea(); fFetchStatus = READY; } switch (fFetchStatus) { case READY: case DATA_AVAILABLE: { sword status = frStmt.Fetch(1); Trace("fetch status: " << (long) status) if (status == OCI_SUCCESS || status == OCI_SUCCESS_WITH_INFO) { fFetchStatus = DATA_AVAILABLE; } else // SQL_NO_DATA and other error/warn conditions { fFetchStatus = END_OF_FETCH; } break; } default: break; } return fFetchStatus; } Anything OracleResultset::getValue(long lColumnIndex) { StartTrace1(OracleResultset.getValue, "col index: " << lColumnIndex); return frStmt.getValue(lColumnIndex); }
27.296296
102
0.744912
zer0infinity
31fe6b3b713b5c59b36d2a4ea1717b464e39996e
164
cpp
C++
EDEN3D/OrthographicCamera.cpp
codeart1st/EDEN3D
b39b0fbf3220320b58843990155ffd8173d8f4ef
[ "MIT" ]
null
null
null
EDEN3D/OrthographicCamera.cpp
codeart1st/EDEN3D
b39b0fbf3220320b58843990155ffd8173d8f4ef
[ "MIT" ]
null
null
null
EDEN3D/OrthographicCamera.cpp
codeart1st/EDEN3D
b39b0fbf3220320b58843990155ffd8173d8f4ef
[ "MIT" ]
null
null
null
#include "OrthographicCamera.hpp" namespace EDEN3D { OrthographicCamera::OrthographicCamera() : Camera() { } OrthographicCamera::~OrthographicCamera() { } }
14.909091
54
0.737805
codeart1st
ee06a4ea3bbf8615c8ce3b70e86b916f1ab735b6
409
cpp
C++
prob03/main.cpp
CSUF-CPSC120-2019F23-24/labex03-manuelito013101
1270e828e1262e13317971afce744058b48d3be3
[ "MIT" ]
null
null
null
prob03/main.cpp
CSUF-CPSC120-2019F23-24/labex03-manuelito013101
1270e828e1262e13317971afce744058b48d3be3
[ "MIT" ]
null
null
null
prob03/main.cpp
CSUF-CPSC120-2019F23-24/labex03-manuelito013101
1270e828e1262e13317971afce744058b48d3be3
[ "MIT" ]
null
null
null
// This program calculates a person's height in feet (') and inches (") #include <iostream> int main() { int inches; std::cout << "what is the person \"inches\" in hieght "; std::cin >> inches; //variables to calculate feet and inches int heightFeet=inches / 12; int heightInches=inches % 12; std::cout << "the height of the person is"<<heightFeet<<"\' "<<heightInches<<"\""; return 0; }
19.47619
84
0.645477
CSUF-CPSC120-2019F23-24
ee06cdcaf3473206e2c435b90248b9b05b3dd6b1
4,910
cpp
C++
SRM607/CombinationLockDiv1.cpp
CanoeFZH/SRM
02e3eeaa6044b14640e450725f68684e392009cb
[ "MIT" ]
null
null
null
SRM607/CombinationLockDiv1.cpp
CanoeFZH/SRM
02e3eeaa6044b14640e450725f68684e392009cb
[ "MIT" ]
null
null
null
SRM607/CombinationLockDiv1.cpp
CanoeFZH/SRM
02e3eeaa6044b14640e450725f68684e392009cb
[ "MIT" ]
null
null
null
// BEGIN CUT HERE // END CUT HERE #line 5 "CombinationLockDiv1.cpp" #include <cstdlib> #include <cctype> #include <cstring> #include <cstdio> #include <cmath> #include <algorithm> #include <vector> #include <string> #include <iostream> #include <sstream> #include <map> #include <set> #include <queue> #include <stack> #include <fstream> #include <numeric> #include <iomanip> #include <bitset> #include <list> #include <stdexcept> #include <functional> #include <utility> #include <ctime> using namespace std; const int N = 2510; const int MAX_OPT = 5510; const int INFINITE = 1 << 30; const int OPT [] = {1, 9}; int dp[N][MAX_OPT][2], d[N]; class CombinationLockDiv1 { public: int n; int gao(int p, int x, int rotate) { if (dp[p][x][rotate] != -1) { return dp[p][x][rotate]; } int & ret = dp[p][x][rotate]; if (p == n) { ret = 0; } else { ret = INFINITE; for (int r = 0; r < 2; r++) { for (int add = 0; add <= 9 && add + x < MAX_OPT; add++) { if ((d[p] + OPT[rotate] * (x + add)) % 10 == 0) { ret = min(ret, add + gao(p + 1, x + add, rotate)); } } for (int remove = 0; remove <= x && remove <= 9; remove++) { if ((d[p] + OPT[rotate] * (x - remove)) % 10 == 0) { ret = min(ret, gao(p + 1, x - remove, rotate)); } } int z = OPT[rotate] * d[p] % 10; ret = min(ret, z + gao(p + 1, z, rotate ^ 1)); } } return ret; } int minimumMoves(vector <string> P, vector <string> Q) { string S = accumulate(P.begin(), P.end(), string("")); string T = accumulate(Q.begin(), Q.end(), string("")); this->n = S.size(); for (int i = 0; i < n; i++) { d[i] = (S[i] - T[i] + 10) % 10; } memset(dp, -1, sizeof(dp)); return gao(0, 0, 0); } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arr0[] = {"123"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"112"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 1; verify_case(0, Arg2, minimumMoves(Arg0, Arg1)); } void test_case_1() { string Arr0[] = {"1"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"7"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 4; verify_case(1, Arg2, minimumMoves(Arg0, Arg1)); } void test_case_2() { string Arr0[] = {"6","07"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"","60","7"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 0; verify_case(2, Arg2, minimumMoves(Arg0, Arg1)); } void test_case_3() { string Arr0[] = {"1234"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"4567"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; verify_case(3, Arg2, minimumMoves(Arg0, Arg1)); } void test_case_4() { string Arr0[] = {"020"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"909"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 2; verify_case(4, Arg2, minimumMoves(Arg0, Arg1)); } void test_case_5() { string Arr0[] = {"4423232218340"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"6290421476245"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 18; verify_case(5, Arg2, minimumMoves(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { CombinationLockDiv1 ___test; ___test.run_test(-1); return 0; }
48.137255
316
0.529124
CanoeFZH
ee092cc2c3b0df5fdd3bad30c5fc281e14b97b4a
5,204
cpp
C++
gamgee/utils/variant_field_type.cpp
audiohacked/gamgee
772a095c5f0725c410e7c23e88f79d8b76e098a8
[ "MIT" ]
24
2015-01-20T16:15:46.000Z
2019-09-16T07:53:54.000Z
gamgee/utils/variant_field_type.cpp
audiohacked/gamgee
772a095c5f0725c410e7c23e88f79d8b76e098a8
[ "MIT" ]
8
2015-01-30T07:27:00.000Z
2017-07-11T21:37:17.000Z
gamgee/utils/variant_field_type.cpp
audiohacked/gamgee
772a095c5f0725c410e7c23e88f79d8b76e098a8
[ "MIT" ]
15
2015-01-11T05:28:26.000Z
2022-01-18T08:47:10.000Z
#include "variant_field_type.h" #include "htslib/vcf.h" #include <string> #include <stdexcept> namespace gamgee { namespace utils { int32_t convert_data_to_integer(const uint8_t* data_ptr, const int index, const uint8_t num_bytes_per_value, const VariantFieldType& type) { auto return_val = -1; const auto p = data_ptr + (index * num_bytes_per_value); auto end_val = -1; switch (type) { case VariantFieldType::INT8: return_val = *(reinterpret_cast<const int8_t*>(p)); end_val = bcf_int8_vector_end; break; case VariantFieldType::INT16: return_val = *(reinterpret_cast<const int16_t*>(p)); end_val = bcf_int16_vector_end; break; case VariantFieldType::INT32: return *(reinterpret_cast<const int32_t*>(p)); case VariantFieldType::FLOAT: return *(reinterpret_cast<const float*>(p)); case VariantFieldType::STRING: throw std::invalid_argument("user requested an integer value but underlying type is actually a string"); default: return 0; // undefined or NULL type -- impossible to happen just so the compiler doesn't warn us } //diff = 0 if return_val == vector_end, 1 if return_val == missing, < 0 if return_val is 'normal' auto diff = end_val - return_val; if(diff >= 0) return bcf_int32_vector_end - diff; else return return_val; } float convert_data_to_float(const uint8_t* data_ptr, const int index, const uint8_t num_bytes_per_value, const VariantFieldType& type) { auto return_val = -1; auto end_val = -1; const auto p = data_ptr + (index * num_bytes_per_value); switch (type) { case VariantFieldType::INT8: return_val = *(reinterpret_cast<const int8_t*>(p)); end_val = bcf_int8_vector_end; break; case VariantFieldType::INT16: return_val = *(reinterpret_cast<const int16_t*>(p)); end_val = bcf_int16_vector_end; break; case VariantFieldType::INT32: return_val = *(reinterpret_cast<const int32_t*>(p)); end_val = bcf_int32_vector_end; break; case VariantFieldType::FLOAT: return *(reinterpret_cast<const float*>(p)); case VariantFieldType::STRING: throw std::invalid_argument("user requested a float value but underlying type is actually a string"); default: return 0.0f; // undefined or NULL type -- impossible to happen just so the compiler doesn't warn us } if(end_val >= return_val) //can't use diff because INT32 types are also checked here and diff will wrap-around { auto tmp = 0.0f; //pack bcf_float_missing or bcf_float_vector_end into tmp and return tmp //diff = 0 if return_val == vector_end, 1 if return_val == missing, auto diff = end_val - return_val; bcf_float_set(&tmp, bcf_float_vector_end - diff); return tmp; } else return return_val; } std::string convert_data_to_string(const uint8_t* data_ptr, const int index, const uint8_t num_bytes_per_value, const VariantFieldType& type) { auto result = std::string{}; const auto p = data_ptr + (index * num_bytes_per_value); switch (type) { case VariantFieldType::INT8: return std::to_string(*(reinterpret_cast<const int8_t*>(p))); // convert from integer to string if necessary case VariantFieldType::INT16: return std::to_string(*(reinterpret_cast<const int16_t*>(p))); // convert from integer to string if necessary case VariantFieldType::INT32: return std::to_string(*(reinterpret_cast<const int32_t*>(p))); // convert from integer to string if necessary case VariantFieldType::FLOAT: return std::to_string(*(reinterpret_cast<const float*>(p))); // convert from float to string if necessary case VariantFieldType::STRING: for (auto i = 0u; i != num_bytes_per_value; ++i) { const auto c = reinterpret_cast<const char *>(p)[i]; if (c == bcf_str_vector_end) break; result += c; } return result; default: return std::string{}; // undefined or NULL type -- impossible to happen just so the compiler doesn't warn us } } uint8_t size_for_type(const VariantFieldType& type, const bcf_fmt_t* const format_ptr) { switch (type) { case VariantFieldType::NIL: case VariantFieldType::INT8: case VariantFieldType::INT16: return static_cast<uint8_t>(type); case VariantFieldType::INT32: case VariantFieldType::FLOAT: return 4; case VariantFieldType::STRING: return format_ptr->n; // htslib keeps the number of bytes in the string in the n member variable. This is weird, but that's how it is. default: return 0; } } uint8_t size_for_type(const VariantFieldType& type, const bcf_info_t* const info_ptr) { switch (type) { case VariantFieldType::NIL: case VariantFieldType::INT8: case VariantFieldType::INT16: return static_cast<uint8_t>(type); case VariantFieldType::INT32: case VariantFieldType::FLOAT: return 4; case VariantFieldType::STRING: return info_ptr->len; // htslib keeps the number of bytes in the string in the n member variable. This is weird, but that's how it is. default: return 0; } } } // end namespace utils } // end namespace gamgee
37.985401
143
0.695427
audiohacked
ee0b02c089db313245a176b584b7529e45077fea
2,096
hpp
C++
Src/Assist/Plane.hpp
bnagybalint/BoloDemoEngine
845fc669e0b37bfbffce7aa3d02364d6e715779e
[ "MIT" ]
null
null
null
Src/Assist/Plane.hpp
bnagybalint/BoloDemoEngine
845fc669e0b37bfbffce7aa3d02364d6e715779e
[ "MIT" ]
null
null
null
Src/Assist/Plane.hpp
bnagybalint/BoloDemoEngine
845fc669e0b37bfbffce7aa3d02364d6e715779e
[ "MIT" ]
null
null
null
/* ------------------------------------------------ * * Written by: Nagy Balint * * Contact: b.nagy.balint@gmail.com * * * * This file can be used/improved/redistributed * * under GNU public license * * * * Nagy Balint (C) 2015 * * ------------------------------------------------ */ #ifndef PLANE_HPP_ #define PLANE_HPP_ #include "Assist/Common.h" #include "Assist/MathCommon.h" #include "Assist/MatrixNxN.hpp" // Represents a plane in 3-dimensional space. // // The plane consists of the (x,y,z) points satisfying the eqaution: // a*x + b*y + c*z + d = 0 // // The side class Vector3; class Matrix4x4; class Plane { public: Plane(); Plane(Coordtype a0, Coordtype b0, Coordtype c0, Coordtype d0); ~Plane(); Vector3 getNormal() const; Coordtype getSignedDistance() const; Plane& operator = (const Plane& other); bool operator == (const Plane& other) const; bool operator != (const Plane& other) const; Coordtype operator [] (int i) const; Coordtype& operator [] (int i); // Create plane description using plane equation. // The plane is defined by the equation: // a0*x + b0*y + c0*z + d0 = 0 static Plane createFromEquation(Coordtype a0, Coordtype b0, Coordtype c0, Coordtype d0); static Plane createFromEquation(const Vector3& eqVec); // Create plane description using a point on the plane and the normal vector of the plane. // The normal should not be null-vector. static Plane createFromPointNormal(const Vector3& point, const Vector3& normal); // Create plane description using three points (a triangle). The points should span a plane, // meaning that they do not all lie on a line. static Plane createFromTriangle(const Vector3& v0, const Vector3& v1, const Vector3& v2); // references to the components of the plane equation Coordtype& a; Coordtype& b; Coordtype& c; Coordtype& d; Coordtype p[4]; }; #endif /* PLANE_HPP_ */
29.942857
94
0.604485
bnagybalint
ee0fa97a276046d14649042b194ddaae73f48855
16,152
cpp
C++
src/texture/texture_manager.cpp
hexoctal/zenith
eeef065ed62f35723da87c8e73a6716e50d34060
[ "MIT" ]
2
2021-03-18T16:25:04.000Z
2021-11-13T00:29:27.000Z
src/texture/texture_manager.cpp
hexoctal/zenith
eeef065ed62f35723da87c8e73a6716e50d34060
[ "MIT" ]
null
null
null
src/texture/texture_manager.cpp
hexoctal/zenith
eeef065ed62f35723da87c8e73a6716e50d34060
[ "MIT" ]
1
2021-11-13T00:29:30.000Z
2021-11-13T00:29:30.000Z
/** * @file * @author __AUTHOR_NAME__ <mail@host.com> * @copyright 2021 __COMPANY_LTD__ * @license <a href="https://opensource.org/licenses/MIT">MIT License</a> */ #include "texture_manager.hpp" #include "parsers/json_array.hpp" #include "parsers/json_hash.hpp" #include "parsers/sprite_sheet.hpp" #include "parsers/sprite_sheet_atlas.hpp" #include <tuple> #include <utility> #include <fstream> #include "../utils/messages.hpp" #include "../utils/map/emplace.hpp" #include "../core/config.hpp" #include "../window/window.hpp" #include "components/source.hpp" #include "components/frame.hpp" #include "systems/texture.hpp" #include "systems/frame.hpp" #include "../geom/rectangle.hpp" #include "../display/color.hpp" #include "../components/transform_matrix.hpp" #include "../systems/transform_matrix.hpp" namespace Zen { extern entt::registry g_registry; extern Window g_window; TextureManager::~TextureManager () { // Free surfaces for (auto surface_ = alphaCache.begin(); surface_ != alphaCache.end(); surface_++) { SDL_FreeSurface(surface_->second); } } void TextureManager::boot (GameConfig *config_) { config = config_; addBase64("__DEFAULT", config->defaultImage); addBase64("__MISSING", config->missingImage); addBase64("__WHITE", config->whiteImage); } bool TextureManager::checkKey (std::string key_) { if (exists(key_)) { MessageError("The texture key is already in use: ", key_); return false; } return true; } TextureManager& TextureManager::remove (std::string key_) { if (!exists(key_)) { MessageWarning("No texture found matching the key: ", key_); return *this; } for (auto it_ = list.begin(); it_ != list.end(); it_++) { if (it_->first == key_) { list.erase(it_); emit("remove", key_); break; } } return *this; } Entity TextureManager::addBase64 ( std::string key_, std::string data_) { return addImage(key_, data_); } Entity TextureManager::addImage (std::string key_, std::string path_) { Entity texture_ = entt::null; if (!checkKey(key_)) return texture_; texture_ = create(key_, path_); if (texture_ != entt::null) { int sourceIndex_ = 0; // Get the source Components::TextureSource *source_ = nullptr; for (auto entity_ : g_registry.view<Components::TextureSource>()) { auto& src_ = g_registry.get<Components::TextureSource>(entity_); if (src_.texture == texture_ && src_.index == sourceIndex_) { source_ = &src_; break; } } AddFrame( texture_, "__BASE", sourceIndex_, 0, 0, source_->width, source_->height); emit("add", key_); } return texture_; } Entity TextureManager::addRenderTexture (std::string key_, Entity renderTexture_) { /* * TODO Texture *texture_ = nullptr; if (checkKey(key_)) { texture_ = create(key_, renderTexture_); int sourceIndex_ = 0; texture_->add("__BASE", sourceIndex_, 0, 0, renderTexture_.width_, renderTexture_.height_); emit("add", key_); } return texture_; */ return entt::null; } Entity TextureManager::addAtlas ( std::string key_, std::vector<std::string> sources_, std::string dataPath_) { // Open file std::ifstream file_ (dataPath_); if (!file_) { MessageError("JSON file couldn't be opened: ", dataPath_); return entt::null; } // Create a JSON object nlohmann::json data_; file_ >> data_; // Close file file_.close(); auto texturesIt_ = data_.find("textures"); auto framesIt_ = data_.find("frames"); if ((texturesIt_ != data_.end() && texturesIt_->is_array()) || (framesIt_ != data_.end() && framesIt_->is_array())) { return addAtlasJSONArray(key_, sources_, data_); } else { return addAtlasJSONHash(key_, sources_, data_); } } Entity TextureManager::addAtlas ( std::string key_, std::string source_, std::string dataPath_) { std::vector<std::string> sources_ { source_ }; return addAtlas(key_, sources_, dataPath_); } Entity TextureManager::addAtlasJSONArray ( std::string key_, std::vector<std::string> sources_, nlohmann::json data_) { if (!checkKey(key_)) return entt::null; Entity texture_ = create(key_, sources_); auto texturesIt_ = data_.find("textures"); if ( texturesIt_ != data_.end() ) { // Multi-Atlas if more than one texture // Count the sources std::size_t size_ = data_["textures"].size(); // Assumes the textures are in the same order in the source array as in the // json data for (std::size_t i_ = 0; i_ < size_; i_++) { if ( ParseJsonArray(texture_, i_, data_["textures"][i_]) ) return entt::null; } } else { // frames if ( ParseJsonArray(texture_, 0, data_) ) return entt::null; } emit("add", key_); return texture_; } Entity TextureManager::addAtlasJSONHash ( std::string key_, std::vector<std::string> sources_, nlohmann::json data_) { Entity texture_ = entt::null; if (checkKey(key_)) { texture_ = create(key_, sources_); if ( ParseJsonHash(texture_, 0, data_) ) return entt::null; emit("add", key_); } return texture_; } Entity TextureManager::addAtlasJSONHash ( std::string key_, std::vector<std::string> sources_, std::vector<nlohmann::json> data_) { Entity texture_ = entt::null; if (checkKey(key_)) { texture_ = create(key_, sources_); for (std::size_t i_ = 0; i_ < data_.size(); i_++) { if ( ParseJsonHash(texture_, i_, data_[i_]) ) return entt::null; } emit("add", key_); } return texture_; } Entity TextureManager::addSpriteSheet (std::string key_, std::string path_, SpriteSheetConfig config_) { Entity texture_ = entt::null; if (!checkKey(key_)) return entt::null; texture_ = create(key_, path_); // Get the source Components::TextureSource *source_ = nullptr; for (auto entity_ : g_registry.view<Components::TextureSource>()) { auto& src_ = g_registry.get<Components::TextureSource>(entity_); if (src_.texture == texture_) { source_ = &src_; break; } } int width_ = source_->width; int height_ = source_->height; if ( ParseSpriteSheet(texture_, 0, 0, 0, width_, height_, config_) ) return entt::null; emit("add", key_); return texture_; } Entity TextureManager::addSpriteSheetFromAtlas (std::string key_, SpriteSheetConfig config_) { if (!checkKey(key_)) return entt::null; std::string atlasKey_ = config_.atlas; std::string atlasFrame_ = config_.frame; if (atlasKey_ == "" || atlasFrame_ == "") { MessageError("The spritsheet \"", key_, "\" cannot be created from no atlas texture or frame."); return entt::null; } Entity atlas_ = get(atlasKey_); Entity sheet_ = GetFrame(atlas_, atlasFrame_); if (sheet_ == entt::null) { MessageError("In atlas \"", atlasKey_, "\"", "frame \"", atlasFrame_, "\" do not exist."); return entt::null; } auto& spritesheet_ = g_registry.get<Components::Frame>(sheet_); auto& source_ = g_registry.get<Components::TextureSource>(spritesheet_.source); Entity texture_ = create(key_, source_.source); if (IsFrameTrimmed(sheet_)) { // If trimmed, we need to help the parser adjust if ( ParseSpriteSheetFromAtlas(texture_, sheet_, config_) ) return entt::null; } else { if ( ParseSpriteSheet(texture_, 0, spritesheet_.cutX, spritesheet_.cutY, spritesheet_.cutWidth, spritesheet_.cutHeight, config_) ) return entt::null; } emit("add", key_); return texture_; } Entity TextureManager::create (std::string key_, std::vector<std::string> sources_) { Entity *texture_ = nullptr; if (checkKey(key_)) { /* TODO remove this auto [it, _] = list.emplace( key_, CreateTexture(key_, sources_) ); // Check if the Texture was created successfuly if (it->second == entt::null) list.erase(it); else texture_ = list.find(key_)->second; */ texture_ = Emplace(&list, key_, CreateTexture(key_, sources_)); if (!texture_) list.erase(list.find(key_)); } return *texture_; } Entity TextureManager::create (std::string key_, std::string source_) { return create(key_, std::vector<std::string> {source_}); } Entity TextureManager::create (std::string key_, Entity renderTexture_) { // TODO return entt::null; } bool TextureManager::exists (std::string key_) { return (list.find(key_) != list.end()); } Entity TextureManager::get (std::string key_) { auto textureIterator_ = list.find(key_); if (textureIterator_ != list.end()) { return list[key_]; } else { return list["__MISSING"]; } } Entity TextureManager::getFrame (std::string key_, std::string frame_) { auto textureIterator_ = list.find(key_); if (textureIterator_ != list.end()) { return GetFrame(list.find(key_)->second, frame_); } else { return entt::null; } } Entity TextureManager::getFrame (std::string key_, int frame_) { return getFrame(key_, std::to_string(frame_)); } std::vector<std::string> TextureManager::getTextureKeys () { std::vector<std::string> out_; for (auto it_ = list.begin(); it_ != list.end(); it_++) { if (it_->first != "__DEFAULT" && it_->first != "__MISSING") out_.emplace_back(it_->first); } return out_; } Color TextureManager::getPixel (int x_, int y_, std::string key_, std::string frameName_) { auto textureFrame_ = getFrame(key_, frameName_); auto frame_ = g_registry.try_get<Components::Frame>(textureFrame_); Color out_; return out_; /* TODO getPixel if (frame_) { // Adjust for trim (if not trimmed x and y are just zero) x_ -= frame_->x; y_ -= frame_->y; auto data_ = frame_->data.cut; x_ += data_.x; y_ += data_.y; if (x_ >= data_.x && x_ < GetRight(data_) && y_ >= data_.y && y_ < GetBottom(data_)) { void *pixels_ = nullptr; int pitch_ = 0; // Get the frame's source texture auto& source_ = g_registry.get<Components::TextureSource>(frame_->source); SDL_Texture *texture_ = source_.sdlTexture; // Check if the texture exists if (!texture_) { MessageError("The frame has no source texture: ", SDL_GetError()); return out_; } // Allocate format from window Uint32 uformat_ = SDL_GetWindowPixelFormat(g_window.window); SDL_PixelFormat *format_ = SDL_AllocFormat(uformat_); // Lock texture for manipulation if (SDL_LockTexture(texture_, nullptr, &pixels_, &pitch_) != 0) { MessageError("Unable to lock texture: ", SDL_GetError()); SDL_FreeFormat(format_); return out_; } // Get pixels in unsigned int of 32 bits Uint32 *upixels_ = static_cast<Uint32*>(pixels_); // Read the pixel in `x` and `y` Uint32 pixel_ = upixels_[y_ * pitch_ + x_]; // Get the color components of the pixel Uint8 r_ = 0, g_ = 0, b_ = 0, a_ = 0; SDL_GetRGBA(pixel_, format_, &r_, &g_, &b_, &a_); // Unlock texture SDL_UnlockTexture(texture_); pixels_ = nullptr; upixels_ = nullptr; // Free the allocated format SDL_FreeFormat(format_); // Save the color components to the output color object SetTo(&out_, r_, g_, b_, a_); } } return out_; */ } Color TextureManager::getPixel (int x_, int y_, std::string key_, int frameIndex_) { // Get the frame's name Entity f_ = getFrame(key_, frameIndex_); auto frame_ = g_registry.try_get<Components::Frame>(f_); if (frame_) return getPixel(x_, y_, key_, frame_->name); else return Color (); } int TextureManager::getPixelAlpha (int x_, int y_, Entity textureFrame_) { int out_ = -1; if (textureFrame_ != entt::null) { auto& frame_ = g_registry.get<Components::Frame>(textureFrame_); auto cache_ = alphaCache.find(frame_.source); if (cache_ == alphaCache.end()) { auto& src_ = g_registry.get<Components::TextureSource>(frame_.source); auto& txt_ = g_registry.get<Components::Texture>(src_.texture); MessageError("Reading pixel alpha values can only be done for cached " "textures! Load the texture \"", txt_.key, "\" with `true` " "as the last parameter to cache it."); return -1; } if (alphaCache[frame_.source] == nullptr) { MessageError("No surface is present in the requested alpha cache."); return -1; } // Adjust for trim (if not trimmed x and y are just zero) x_ -= frame_.x; y_ -= frame_.y; // Position in atlas auto data_ = frame_.data.cut; double w_ = data_.width; double h_ = data_.height; // Adjust for rotation if (frame_.rotated) { double Y_ = y_; y_ = x_; x_ = data_.height - Y_; // Swap width and height Y_ = w_; w_ = h_; h_ = Y_; } // Offset in atlas x_ += data_.x; y_ += data_.y; if (x_ >= data_.x && x_ < (data_.x + w_) && y_ >= data_.y && y_ < (data_.y + h_)) { // Get pixels in unsigned int of 32 bits Uint32 *upixels_ = static_cast<Uint32*>(cache_->second->pixels); // Read the pixel in `x` and `y` Uint32 pixel_ = upixels_[y_ * (cache_->second->pitch/4) + x_]; // Get the color components of the pixel Uint8 r_ = 0; Uint8 g_ = 0; Uint8 b_ = 0; Uint8 a_ = 0; SDL_GetRGBA(pixel_, cache_->second->format, &r_, &g_, &b_, &a_); // Save the color components to the output variable out_ = a_; } } return out_; } /* int TextureManager::getPixelAlpha (int x_, int y_, Entity textureFrame_) { int out_ = -1; if (textureFrame_ != entt::null) { auto& frame_ = g_registry.get<Components::Frame>(textureFrame_); // Adjust for trim (if not trimmed x and y are just zero) x_ -= frame_.x; y_ -= frame_.y; auto data_ = frame_.data.cut; x_ += data_.x; y_ += data_.y; if (x_ >= data_.x && x_ < GetRight(data_) && y_ >= data_.y && y_ < GetBottom(data_)) { void *pixels_ = nullptr; int pitch_ = 0; // Get the frame's source SDL texture auto& source_ = g_registry.get<Components::TextureSource>(frame_.source); SDL_Texture *texture_ = source_.sdlTexture; // Check if the texture exists if (!texture_) { MessageError("The frame has no source texture: ", SDL_GetError()); return out_; } // Allocate format from window Uint32 uformat_ = SDL_GetWindowPixelFormat(g_window.window); SDL_PixelFormat *format_ = SDL_AllocFormat(uformat_); // Lock texture for manipulation if (SDL_LockTexture(texture_, nullptr, &pixels_, &pitch_) != 0) { MessageError("Unable to lock texture: ", SDL_GetError()); SDL_FreeFormat(format_); return out_; } // Get pixels in unsigned int of 32 bits Uint32 *upixels_ = static_cast<Uint32*>(pixels_); // Read the pixel in `x` and `y` Uint32 pixel_ = upixels_[y_ * pitch_ + x_]; // Get the color components of the pixel Uint8 a_ = 0; SDL_GetRGBA(pixel_, format_, nullptr, nullptr, nullptr, &a_); // Unlock texture SDL_UnlockTexture(texture_); pixels_ = nullptr; upixels_ = nullptr; // Free the allocated format SDL_FreeFormat(format_); // Save the color components to the output variable out_ = a_; } } return out_; } */ int TextureManager::getPixelAlpha (int x_, int y_, std::string key_, std::string frameName_) { Entity frame_ = getFrame(key_, frameName_); return getPixelAlpha(x_, y_, frame_); } int TextureManager::getPixelAlpha (int x_, int y_, std::string key_, int frameIndex_) { Entity frame_ = getFrame(key_, frameIndex_); return getPixelAlpha(x_, y_, frame_); } void TextureManager::createAlphaCache (std::string key_) { // Get texture entity Entity texture_ = get(key_); // Get _ALL_ image files (Multi Atlases have many sources) std::vector<Entity> sources_ = GetTextureSources(texture_); // For each image: for (auto& source_ : sources_) { auto& src_ = g_registry.get<Components::TextureSource>(source_); // Create a surface alphaCache[source_] = IMG_Load(src_.source.c_str()); if (alphaCache[source_] == nullptr) { MessageError("Unable to load image ", src_.source.c_str(), ": ", IMG_GetError()); return; } } } /* bool TextureManager::renameTexture (std::string currentKey_, std::string newKey_) { Entity texture_ = get(currentKey_); if (texture_ != entt::null && currentKey_ != newKey_) { texture_->key = newKey_; // Move the node containing the texture without copying auto nodeHandler_ = list.extract(currentKey_); nodeHandler_.key() = newKey_; list.insert(std::move(nodeHandler_)); return true; } return false; } */ } // namespace Zen
21.62249
132
0.670877
hexoctal
ee116c9530d7aa604ff1d9e7c2232379ba40de99
245
cpp
C++
Classes/Background.cpp
hrdktg/JATG
be50cea235d48c3e4f95dee87e9542fb53902fe6
[ "MIT" ]
null
null
null
Classes/Background.cpp
hrdktg/JATG
be50cea235d48c3e4f95dee87e9542fb53902fe6
[ "MIT" ]
null
null
null
Classes/Background.cpp
hrdktg/JATG
be50cea235d48c3e4f95dee87e9542fb53902fe6
[ "MIT" ]
null
null
null
#include "Background.h" Background::Background(std::string sname, cocos2d::Vec2 pos, cocos2d::Node *s) { img = cocos2d::Sprite::create(sname); img->setAnchorPoint(cocos2d::Vec2(0, 0)); img->setPosition(pos); s->addChild(img); }
27.222222
80
0.669388
hrdktg
ee1319fa24f4bbf8df1c1635716b34861c6cd904
421
cpp
C++
Source/RevenantWeapon.cpp
Project2CITM/Proyecto2
a10c78fded2b226629a817c4e9cd46ed9e8b5bc8
[ "MIT" ]
2
2022-03-13T20:31:50.000Z
2022-03-28T06:43:45.000Z
Source/RevenantWeapon.cpp
Project2CITM/The-last-purifier
e082e8ce6d6aa90b1d232cd9e15f4bec994556ed
[ "MIT" ]
null
null
null
Source/RevenantWeapon.cpp
Project2CITM/The-last-purifier
e082e8ce6d6aa90b1d232cd9e15f4bec994556ed
[ "MIT" ]
null
null
null
#include "RevenantWeapon.h" #include "PlayerController.h" RevenantWeapon::RevenantWeapon(PlayerController* playerController) { this->playerController = playerController; app = Application::GetInstance(); } bool RevenantWeapon::Attack(int chargedTime) { return true; } void RevenantWeapon::PreUpdate() { } void RevenantWeapon::Update() { } void RevenantWeapon::PostUpdate() { } void RevenantWeapon::CleanUp() { }
14.033333
66
0.75772
Project2CITM
ee144c9a501b4cce331b98c5332b55d7adf73fd3
589
hpp
C++
Sources/Device/MidiOutDevice.hpp
Ardakaniz/RPiSequencer
d9e20344e693d0677af2f3e719767dc82543eab1
[ "MIT" ]
7
2019-03-24T16:28:37.000Z
2020-08-15T00:57:35.000Z
Sources/Device/MidiOutDevice.hpp
Ardakaniz/RPiSequencer
d9e20344e693d0677af2f3e719767dc82543eab1
[ "MIT" ]
null
null
null
Sources/Device/MidiOutDevice.hpp
Ardakaniz/RPiSequencer
d9e20344e693d0677af2f3e719767dc82543eab1
[ "MIT" ]
null
null
null
#pragma once #include "Device/Device.hpp" #include "RtMidi/RtMidi.hpp" #include <memory> class MidiOutDevice : public OutputDevice { public: void Open(unsigned int index) override; bool IsOpen() const override; void Close() override; std::string GetDeviceType() const override; std::string GetDeviceName() const override; std::vector<std::string> GetDeviceList() override; void PlayNote(const Core::Note& note) override; void StopNote(const Core::Note& note) override; private: std::unique_ptr<RtMidiOut> _midi{ std::make_unique<RtMidiOut>() }; unsigned int _index{ 0 }; };
24.541667
67
0.745331
Ardakaniz
ee169631e8a3b33e8e615b94e98d3c60977abb1a
2,542
cpp
C++
Code In C [Basics]/CPP Format/NON-WEIGHTED GRAPH/NON-WEIGHTED GRAPH/FRONT_BACK_EDGE_DFSNUMBERING.cpp
vsourav/daa_2019-Jan-March-
a9cb31b24b96a57a9d28176fc64d9a53141f7e19
[ "MIT" ]
1
2019-11-11T15:43:09.000Z
2019-11-11T15:43:09.000Z
Code In C [Basics]/CPP Format/NON-WEIGHTED GRAPH/NON-WEIGHTED GRAPH/FRONT_BACK_EDGE_DFSNUMBERING.cpp
vsourav/daa_2019-Jan-March-
a9cb31b24b96a57a9d28176fc64d9a53141f7e19
[ "MIT" ]
null
null
null
Code In C [Basics]/CPP Format/NON-WEIGHTED GRAPH/NON-WEIGHTED GRAPH/FRONT_BACK_EDGE_DFSNUMBERING.cpp
vsourav/daa_2019-Jan-March-
a9cb31b24b96a57a9d28176fc64d9a53141f7e19
[ "MIT" ]
null
null
null
#include<stdio.h> #include<stdlib.h> static int m=0; int pre[11]; int post[11]; struct node{ int dest; struct node* next; }; struct adj_list{ struct node* head; }; struct graph{ int v; struct adj_list* array; int* visited; int* parent; }; struct node* cnode(int dest){ struct node* temp=(struct node*)malloc(sizeof(struct node)); temp->dest=dest; temp->next=NULL; return(temp); } struct graph* cgraph(int v){ struct graph* gr=(struct graph*)malloc(sizeof(struct graph)); gr->v=v; gr->array=(struct adj_list*)malloc(v*sizeof(struct adj_list)); gr->visited=(int *)malloc(v*sizeof(int)); gr->parent=(int*)malloc(v*sizeof(int)); int i=0; for(i=0;i<v;++i){ gr->array[i].head=NULL; gr->visited[i]=0; gr->parent[i]=-1; } return(gr); } void add_edge(struct graph* gr,int src,int dest){ struct node* temp1=cnode(dest); temp1->next=gr->array[src].head; gr->array[src].head=temp1; /* struct node* temp2=cnode(src); temp2->next=gr->array[dest].head; gr->array[dest].head=temp2;*/ } void dfs(struct graph* gr,int s){ struct node* temp=gr->array[s].head; gr->visited[s]=1; pre[s]=m++; while(temp!=NULL){ int k=temp->dest; if(gr->visited[k]==0){ dfs(gr,k); } temp=temp->next; } post[s]=m++; } /*void searchpath(struct graph* gr,int v,int u){ struct node* temp=gr->array[v].head; while(temp!=NULL){ int k=temp->dest; if(k==u){ printf("%d---> %d",v,u); return; } else{ temp=temp->next; } } }*/ void edge(struct graph* gr){ for(int u=0;u<gr->v;++u){ struct node* temp=gr->array[u].head; while(temp!=NULL){ int v=temp->dest; if(pre[u]<pre[v]&&pre[v]<post[v]&&post[v]<post[u]){ printf("\nforward edge : %d-----> %d",u,v); } else if(pre[v]<pre[u]&&pre[u]<post[u]&&post[u]<post[v]){ printf("\nBack edge : %d<----- %d\n",v,u); // searchpath(gr,v,u); printf("\n::::::: It is also a cycle::::: (%d---<---%d)\n",v,u); } temp=temp->next; } } } int main(){ struct graph* gr = cgraph(11); add_edge(gr, 1,6); add_edge(gr, 1,3); add_edge(gr, 1,2); add_edge(gr, 2,5); add_edge(gr, 5,7); add_edge(gr, 5,8); add_edge(gr, 5,6); add_edge(gr, 6,2); add_edge(gr,6,7); add_edge(gr, 3,4); add_edge(gr, 4,8); add_edge(gr, 4,1); add_edge(gr, 8,7); dfs(gr,1); for(int i=1;i<9;i++){ printf(" %d --> [%d ,%d]\n",i,pre[i],post[i]); } edge(gr); return 0; }
20.5
70
0.549961
vsourav
ee192d426acf2a76289e74c6d730e01ee3c2392f
1,140
cc
C++
Kaleidoscope/lexer.cc
BlurryLight/compiler_practice
a88dfa0a8e31c13f48e9a97add46dd20800b7ff7
[ "MIT" ]
null
null
null
Kaleidoscope/lexer.cc
BlurryLight/compiler_practice
a88dfa0a8e31c13f48e9a97add46dd20800b7ff7
[ "MIT" ]
null
null
null
Kaleidoscope/lexer.cc
BlurryLight/compiler_practice
a88dfa0a8e31c13f48e9a97add46dd20800b7ff7
[ "MIT" ]
null
null
null
#include "lexer.h" namespace pd { //================================ helper funcs begins static int get_next_tok() { return (CurTok = get_tok()); } std::unique_ptr<ExprAST> LogError(const char *Str) { fprintf(stderr, "LogError:%s\n", Str); return nullptr; } // PrototypeAST is not inherited from ExprAST // so an overloaded version is needed std::unique_ptr<PrototypeAST> LogErrorP(const char *Str) { fprintf(stderr, "LogError:%s\n", Str); return nullptr; } //================================ helper funcs End //================================ Parser begins static std::unique_ptr<ExprAST> ParseNumberExpr() { auto res = std::make_unique<NumberExprAST>(NumVal); get_next_tok(); // eat the number, move to next token return std::move(res); } // parenthiesis expr eg: '(' sub expr object ')' static std::unique_ptr<ExprAST> ParseParenExpr() { get_next_tok(); // eat the ( // parse some expr here std::unique_ptr<ExprAST> sub_expr; // = parse..... // parse ended in the ')' if (CurTok != ')') return LogError("EXPECTED ')"); get_next_tok(); // eat the ')' return sub_expr; } }; // namespace pd
24.782609
58
0.614035
BlurryLight
ee1bcc06a8a60b9ca6a4aaa30d3ecebce7d99ab6
24,824
cpp
C++
Official Windows Driver Kit Sample/Windows Driver Kit (WDK) 8.0 Samples/[C++]-Windows Driver Kit (WDK) 8.0 Samples/C++/WDK 8.0 Samples/Sensors geolocation sample driver/Solution/Device.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
2
2022-01-21T01:40:58.000Z
2022-01-21T01:41:10.000Z
Official Windows Driver Kit Sample/Windows Driver Kit (WDK) 8.0 Samples/[C++]-Windows Driver Kit (WDK) 8.0 Samples/C++/WDK 8.0 Samples/Sensors geolocation sample driver/Solution/Device.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
1
2022-03-15T04:21:41.000Z
2022-03-15T04:21:41.000Z
Official Windows Driver Kit Sample/Windows Driver Kit (WDK) 8.0 Samples/[C++]-Windows Driver Kit (WDK) 8.0 Samples/C++/WDK 8.0 Samples/Sensors geolocation sample driver/Solution/Device.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
2
2020-10-19T23:36:26.000Z
2020-10-22T12:59:37.000Z
// // Copyright (C) Microsoft. All rights reserved. // /*++ // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. Module Name: Device.cpp Abstract: This module contains the implementation for the sensor service driver device callback object. --*/ #include "internal.h" #include "SensorManager.h" #include "Device.h" #include "Queue.h" #include "Device.tmh" #include <setupapi.h> #include <devpkey.h> #include <strsafe.h> ///////////////////////////////////////////////////////////////////////// // // CMyDevice::CMyDevice // // Object constructor function // ///////////////////////////////////////////////////////////////////////// CMyDevice::CMyDevice() : m_spWdfDevice(NULL), m_pSensorManager(NULL), m_spQueue(nullptr), m_dwShutdownControlFlags(0) { } ///////////////////////////////////////////////////////////////////////// // // CMyDevice::~CMyDevice // // Object destructor function // ///////////////////////////////////////////////////////////////////////// CMyDevice::~CMyDevice() { SAFE_RELEASE(m_pSensorManager); } ///////////////////////////////////////////////////////////////////////// // // CMyDevice::CreateInstance // // This static method is used to create and initialize an instance of // CMyDevice for use with a given hardware device. // // Parameters: // // pDeviceInit - pointer to an interface used to intialize the device // pDriver - pointer to an IWDFDriver interface // // Return Values: // S_OK: object created successfully // ///////////////////////////////////////////////////////////////////////// HRESULT CMyDevice::CreateInstance( _In_ IWDFDriver* pDriver, _In_ IWDFDeviceInitialize* pDeviceInit ) { Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Entry"); CComObject<CMyDevice>* pMyDevice = NULL; HRESULT hr = CComObject<CMyDevice>::CreateInstance(&pMyDevice); if (SUCCEEDED(hr) && (nullptr != pMyDevice)) { pMyDevice->AddRef(); // Prepare device parameters pDeviceInit->SetLockingConstraint(None); pDeviceInit->SetPowerPolicyOwnership(TRUE); // Power policy // pDeviceInit->SetFilter(); // If you're writing a filter driver then set this flag // pDeviceInit->AutoForwardCreateCleanupClose(WdfTrue); CComPtr<IUnknown> spCallback; hr = pMyDevice->QueryInterface(IID_IUnknown, (void**)&spCallback); CComPtr<IWDFDevice> spIWDFDevice; if (SUCCEEDED(hr)) { // Create the IWDFDevice object hr = pDriver->CreateDevice(pDeviceInit, spCallback, &spIWDFDevice); } if (SUCCEEDED(hr)) { // Apply power policy settings WUDF_DEVICE_POWER_POLICY_IDLE_SETTINGS idleSettings; WUDF_DEVICE_POWER_POLICY_IDLE_SETTINGS_INIT( &idleSettings, SENSOR_POWER_POLICY_S0_IDLE_CAPABILITIES ); idleSettings.IdleTimeout = SENSOR_POWER_POLICY_IDLE_TIMEOUT; idleSettings.ExcludeD3Cold = SENSOR_POWER_POLICY_EXCLUDE_D3_COLD; CComPtr<IWDFDevice3> spIWDFDevice3; hr = spIWDFDevice->QueryInterface(IID_PPV_ARGS(&spIWDFDevice3)); if (SUCCEEDED(hr)) { hr = spIWDFDevice3->AssignS0IdleSettingsEx(&idleSettings); } } //Release the pMyDevice pointer when done. Note: UMDF holds a reference to it above SAFE_RELEASE(pMyDevice); } return hr; } ///////////////////////////////////////////////////////////////////////// // // CMyDevice::OnPrepareHardware // // Called by UMDF to prepare the hardware for use. In our case // we create the SensorDDI object and initialize the Sensor Class Extension // // Parameters: // pWdfDevice - pointer to an IWDFDevice object representing the // device // // Return Values: // S_OK: success // ///////////////////////////////////////////////////////////////////////// HRESULT CMyDevice::OnPrepareHardware( _In_ IWDFDevice* pWdfDevice ) { Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Entry"); HRESULT hr = (NULL != pWdfDevice) ? S_OK : E_UNEXPECTED; if (SUCCEEDED(hr)) { hr = EnterProcessing(PROCESSING_IPNPCALLBACKHARDWARE); if (SUCCEEDED(hr)) { if( NULL != pWdfDevice ) { // Store the IWDFDevice pointer m_spWdfDevice = pWdfDevice; } // Create & Configure the default IO Queue if (SUCCEEDED(hr)) { hr = ConfigureQueue(); } // Create the sensor manager object if (SUCCEEDED(hr)) { hr = CComObject<CSensorManager>::CreateInstance(&m_pSensorManager); if (nullptr != m_pSensorManager) { if ((SUCCEEDED(hr)) && (NULL != m_pSensorManager)) { m_pSensorManager->AddRef(); } // Initialize the sensor manager object if(SUCCEEDED(hr)) { hr = m_pSensorManager->Initialize(m_spWdfDevice, this); } } else { hr = E_POINTER; } } if (SUCCEEDED(hr)) { hr = StringCchCopy(m_pSensorManager->m_wszDeviceName, MAX_PATH, DEFAULT_DEVICE_MODEL_VALUE); if (SUCCEEDED(hr)) { ULONG ulCchInstanceId = 0; BOOL fResult = FALSE; WCHAR* wszInstanceId = nullptr; WCHAR* tempStr = nullptr; try { wszInstanceId = new WCHAR[MAX_PATH]; } catch(...) { hr = E_UNEXPECTED; Trace(TRACE_LEVEL_ERROR, "Failed to allocate memory for instance ID string, hr = %!HRESULT!", hr); if (nullptr != wszInstanceId) { delete[] wszInstanceId; } } try { tempStr = new WCHAR[MAX_PATH]; } catch(...) { hr = E_UNEXPECTED; Trace(TRACE_LEVEL_ERROR, "Failed to allocate memory for instance ID temp string, hr = %!HRESULT!", hr); if (nullptr != tempStr) { delete[] tempStr; } } if (SUCCEEDED(pWdfDevice->RetrieveDeviceInstanceId(NULL, &ulCchInstanceId))) { if (SUCCEEDED(pWdfDevice->RetrieveDeviceInstanceId(wszInstanceId, &ulCchInstanceId))) { HDEVINFO hDeviceInfo = INVALID_HANDLE_VALUE; if (INVALID_HANDLE_VALUE != (hDeviceInfo = ::SetupDiCreateDeviceInfoList(NULL, NULL))) { SP_DEVINFO_DATA deviceInfo = {sizeof(SP_DEVINFO_DATA)}; if (TRUE == ::SetupDiOpenDeviceInfo(hDeviceInfo, wszInstanceId, NULL, 0, &deviceInfo)) { DEVPROPTYPE propType; ULONG ulSize; fResult = ::SetupDiGetDeviceProperty(hDeviceInfo, &deviceInfo, &DEVPKEY_Device_DeviceDesc, &propType, (PBYTE)tempStr, MAX_PATH*sizeof(WCHAR), &ulSize, 0); if (FALSE == fResult) { hr = HRESULT_FROM_WIN32(GetLastError()); } #pragma warning(suppress: 26035) //possible failure to null terminate string if (SUCCEEDED(hr) && (wcscmp(tempStr, L"") != 0)) { wcscpy_s(m_pSensorManager->m_wszDeviceName, MAX_PATH, tempStr); } ::SetupDiDestroyDeviceInfoList(hDeviceInfo); } } } } #pragma warning(suppress: 6001) //using unitialized memory if (nullptr != wszInstanceId) { delete[] wszInstanceId; } #pragma warning(suppress: 6001) //using unitialized memory if (nullptr != tempStr) { delete[] tempStr; } } } } // processing in progress ExitProcessing(PROCESSING_IPNPCALLBACKHARDWARE); } if (FAILED(hr)) { Trace(TRACE_LEVEL_CRITICAL, "Abnormal results during hardware initialization, hr = %!HRESULT!", hr); } Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Exit, hr = %!HRESULT!", hr); return hr; } ///////////////////////////////////////////////////////////////////////// // // CMyDevice::OnReleaseHardware // // Called by UMDF to uninitialize the hardware. // // Parameters: // pWdfDevice - pointer to an IWDFDevice object for the device // // Return Values: // S_OK: // ///////////////////////////////////////////////////////////////////////// HRESULT CMyDevice::OnReleaseHardware( _In_ IWDFDevice* pWdfDevice ) { Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Entry"); HRESULT hr = S_OK; EnterShutdown(); // Stop the device and uninitialize the sensor manager object if(NULL != m_pSensorManager) { hr = m_pSensorManager->Stop(WdfPowerDeviceMaximum); m_pSensorManager->Uninitialize(); SAFE_RELEASE(m_pSensorManager); } // Release the IWDFDevice handle, if it matches if (pWdfDevice == m_spWdfDevice.p) { m_spWdfDevice.Release(); } Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Exit, hr = %!HRESULT!", hr); Trace(TRACE_LEVEL_CRITICAL, "SensorsGeolocationDriverSample - Trace log ending for this instance of driver"); Trace(TRACE_LEVEL_CRITICAL, "------------------------------- END -------------------------------------------"); return hr; } ///////////////////////////////////////////////////////////////////////// // // CMyDevice::OnD0Entry // // This method is called after a new device enters the system // // Parameters: // pWdfDevice - pointer to a device object // // ///////////////////////////////////////////////////////////////////////// HRESULT CMyDevice::OnD0Entry( _In_ IWDFDevice* pWdfDevice, _In_ WDF_POWER_DEVICE_STATE previousState ) { Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Entry"); UNREFERENCED_PARAMETER(pWdfDevice); UNREFERENCED_PARAMETER(previousState); HRESULT hr = S_OK; hr = EnterProcessing(PROCESSING_IPNPCALLBACK); if (SUCCEEDED(hr)) { if( SUCCEEDED(hr) && NULL != m_pSensorManager) { hr = m_pSensorManager->Start(); if (FAILED(hr)) { Trace(TRACE_LEVEL_CRITICAL, "Failed to initialize sensors, hr = %!HRESULT!", hr); } } } // processing in progress ExitProcessing(PROCESSING_IPNPCALLBACK); Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Exit, hr = %!HRESULT!", hr); return hr; } ///////////////////////////////////////////////////////////////////////// // // CMyDevice::OnD0Exit // // This method is called when a device leaves the system // // Parameters: // pWdfDevice - pointer to a device object // // // ///////////////////////////////////////////////////////////////////////// HRESULT CMyDevice::OnD0Exit( _In_ IWDFDevice* pWdfDevice, _In_ WDF_POWER_DEVICE_STATE newState ) { Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Entry"); UNREFERENCED_PARAMETER(pWdfDevice); UNREFERENCED_PARAMETER(newState); HRESULT hr = S_OK; hr = EnterProcessing(PROCESSING_IPNPCALLBACK); if (SUCCEEDED(hr)) { if( SUCCEEDED(hr) && NULL != m_pSensorManager) { hr = m_pSensorManager->Stop(newState); } } // processing in progress ExitProcessing(PROCESSING_IPNPCALLBACK); Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Exit, hr = %!HRESULT!", hr); return hr; } VOID CMyDevice::OnSurpriseRemoval( _In_ IWDFDevice* pWdfDevice ) { UNREFERENCED_PARAMETER(pWdfDevice); Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Entry"); EnterShutdown(); return; } HRESULT CMyDevice::OnQueryRemove( _In_ IWDFDevice* pWdfDevice ) { UNREFERENCED_PARAMETER(pWdfDevice); Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Entry"); return S_OK; } HRESULT CMyDevice::OnQueryStop( _In_ IWDFDevice* pWdfDevice ) { UNREFERENCED_PARAMETER(pWdfDevice); Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Entry"); return S_OK; } ///////////////////////////////////////////////////////////////////////// // // CMyDevice::OnCleanupFile // // This method is called when the file handle to the device is closed // // Parameters: // pWdfFile - pointer to a file object // ///////////////////////////////////////////////////////////////////////// VOID CMyDevice::OnCleanupFile( _In_ IWDFFile* pWdfFile ) { //Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Entry"); HRESULT hr = S_OK; hr = EnterProcessing(PROCESSING_IFILECALLBACKCLEANUP); if (SUCCEEDED(hr)) { if (NULL != m_pSensorManager) { m_pSensorManager->CleanupFile(pWdfFile); } } // processing in progress ExitProcessing(PROCESSING_IFILECALLBACKCLEANUP); return; } ///////////////////////////////////////////////////////////////////////// // // CMyDevice::ConfigureQueue // // This method is called after the device callback object has been initialized // and returned to the driver. It would setup the device's queues and their // corresponding callback objects. // // Parameters: // // Return Values: // S_OK: success // ///////////////////////////////////////////////////////////////////////// HRESULT CMyDevice::ConfigureQueue() { HRESULT hr = S_OK; CComPtr<IWDFIoQueue> spIoQueue; if ( NULL != m_spWdfDevice ) { m_spWdfDevice->GetDefaultIoQueue(&spIoQueue); } else { hr = E_UNEXPECTED; } if ( SUCCEEDED(hr) && ( NULL == spIoQueue )) { hr = CMyQueue::CreateInstance(m_spWdfDevice, this, &m_spQueue); } return hr; } ///////////////////////////////////////////////////////////////////////// // // CMyDevice::ProcessIoControl // // This method is a helper that takes the incoming IOCTL and forwards // it to the Windows Sensor Class Extension for processing. // // Parameters: // pQueue - [in] pointer to the UMDF queue that handled the request // pRequest - [in] pointer to the request // ControlCode - [in] the IOCTL code // InputBufferSizeInBytes - [in] size of the incoming IOCTL buffer // OutputBufferSizeInBytes - [out] size of the outgoing IOCTL buffer // pcbWritten - pointer to a DWORD containing the number of bytes returned // // Return Values: // S_OK: // ///////////////////////////////////////////////////////////////////////// HRESULT CMyDevice::ProcessIoControl(_In_ IWDFIoQueue* pQueue, _In_ IWDFIoRequest* pRequest, _In_ ULONG ControlCode, SIZE_T InputBufferSizeInBytes, SIZE_T OutputBufferSizeInBytes, DWORD* pcbWritten) { UNREFERENCED_PARAMETER(pQueue); UNREFERENCED_PARAMETER(ControlCode); UNREFERENCED_PARAMETER(InputBufferSizeInBytes); UNREFERENCED_PARAMETER(OutputBufferSizeInBytes); UNREFERENCED_PARAMETER(pcbWritten); HRESULT hr = S_OK; if(NULL != m_pSensorManager) { hr = m_pSensorManager->ProcessIoControl(pRequest); } else { hr = E_UNEXPECTED; } return hr; } ///////////////////////////////////////////////////////////////////////// // // CMyDevice::ProcessIoControlRadioManagement // // This method processes IO for Radio Management. The radio state is // either read or set on the sensor. // // Parameters: // pRequest - [in] pointer to the request // ControlCode - [in] the IOCTL code // // Return Values: // S_OK: // ///////////////////////////////////////////////////////////////////////// HRESULT CMyDevice::ProcessIoControlRadioManagement( _In_ IWDFIoRequest* pRequest, _In_ ULONG ControlCode) { HRESULT hr = S_OK; if (nullptr != m_pSensorManager) { hr = m_pSensorManager->ProcessIoControlRadioManagement(pRequest, ControlCode); } else { hr = E_UNEXPECTED; } return hr; } inline HRESULT CMyDevice::EnterProcessing(DWORD64 dwControlFlag) { //Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Entry"); HRESULT hr = S_OK; if ((InterlockedOr (&m_dwShutdownControlFlags, dwControlFlag) & SHUTDOWN_IN_PROGRESS) != 0) { hr = HRESULT_FROM_WIN32(ERROR_SHUTDOWN_IN_PROGRESS); } return hr; } inline void CMyDevice::ExitProcessing(DWORD64 dwControlFlag) { //Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Entry"); InterlockedAnd (&m_dwShutdownControlFlags, ~dwControlFlag); } inline void CMyDevice::EnterShutdown() { Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Entry"); // // Begin shutdown. Spin if control handler is in progress. // while (((InterlockedOr (&m_dwShutdownControlFlags, SHUTDOWN_IN_PROGRESS) & PROCESSING_IN_PROGRESS) != 0)) { Yield(); } } ///////////////////////////////////////////////////////////////////////// // // CMyDevice::OnSelfManagedIoCleanup // // Called by UMDF to release memory for a device's self-managed I/O // operations, after the device is removed. // // Parameters: // pWdfDevice - pointer to an IWDFDevice object representing the // device // // Return Values: // ///////////////////////////////////////////////////////////////////////// VOID CMyDevice::OnSelfManagedIoCleanup( _In_ IWDFDevice* pWdfDevice ) { UNREFERENCED_PARAMETER(pWdfDevice); } ///////////////////////////////////////////////////////////////////////// // // CMyDevice::OnSelfManagedIoFlush // // Called by UMDF to flush the device for a device's self-managed // I/O operations. // // Parameters: // pWdfDevice - pointer to an IWDFDevice object representing the // device // // Return Values: // ///////////////////////////////////////////////////////////////////////// VOID CMyDevice::OnSelfManagedIoFlush( _In_ IWDFDevice* pWdfDevice ) { UNREFERENCED_PARAMETER(pWdfDevice); Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Entry"); HRESULT hr = EnterProcessing(PROCESSING_IPNPCALLBACKSELFMANAGEDIO); if (SUCCEEDED(hr)) { if (nullptr != m_spQueue) { Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Purging queue"); m_spQueue->PurgeSynchronously(); } } ExitProcessing(PROCESSING_IPNPCALLBACKSELFMANAGEDIO); Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Exit, hr = %!HRESULT!", hr); } ///////////////////////////////////////////////////////////////////////// // // CMyDevice::OnSelfManagedIoInit // // Called by UMDF to initialize a device's self-managed I/O operations. // // Parameters: // pWdfDevice - pointer to an IWDFDevice object representing the // device // // Return Values: // S_OK: success // ///////////////////////////////////////////////////////////////////////// HRESULT CMyDevice::OnSelfManagedIoInit( _In_ IWDFDevice* pWdfDevice ) { UNREFERENCED_PARAMETER(pWdfDevice); Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Entry"); HRESULT hr = EnterProcessing(PROCESSING_IPNPCALLBACKSELFMANAGEDIO); if (SUCCEEDED(hr)) { if (nullptr != m_pSensorManager) { Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Hardware is now available"); m_pSensorManager->m_fDeviceActive = true; } } ExitProcessing(PROCESSING_IPNPCALLBACKSELFMANAGEDIO); Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Exit, hr = %!HRESULT!", hr); return hr; } ///////////////////////////////////////////////////////////////////////// // // CMyDevice::OnSelfManagedIoRestart // // Called by UMDF to restart a device's self-managed I/O operations. // // Parameters: // pWdfDevice - pointer to an IWDFDevice object representing the // device // // Return Values: // S_OK: success // ///////////////////////////////////////////////////////////////////////// HRESULT CMyDevice::OnSelfManagedIoRestart( _In_ IWDFDevice* pWdfDevice ) { UNREFERENCED_PARAMETER(pWdfDevice); Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Entry"); HRESULT hr = EnterProcessing(PROCESSING_IPNPCALLBACKSELFMANAGEDIO); if (SUCCEEDED(hr)) { if (nullptr != m_pSensorManager) { Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Hardware is now available"); m_pSensorManager->m_fDeviceActive = true; } } ExitProcessing(PROCESSING_IPNPCALLBACKSELFMANAGEDIO); Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Exit, hr = %!HRESULT!", hr); return hr; } ///////////////////////////////////////////////////////////////////////// // // CMyDevice::OnSelfManagedIoStop // // The OnSelfManagedIoStop method is not used in the current version // of the UMDF. // // Parameters: // pWdfDevice - pointer to an IWDFDevice object representing the // device // // Return Values: // S_OK: success // ///////////////////////////////////////////////////////////////////////// HRESULT CMyDevice::OnSelfManagedIoStop( _In_ IWDFDevice* pWdfDevice ) { UNREFERENCED_PARAMETER(pWdfDevice); HRESULT hr = S_OK; return hr; } ///////////////////////////////////////////////////////////////////////// // // CMyDevice::OnSelfManagedIoSuspend // // Called by UMDF to suspend a device's self-managed I/O operations. // // All outstanding I/O must be completed. The queue is stopped // to flush out in progress requests. The queue is restarted and // the driver continues to get I/O, but the m_fDeviceActive flag is // set to false so that the hardware will not be accessed. // // Parameters: // pWdfDevice - pointer to an IWDFDevice object representing the // device // // Return Values: // S_OK: success // ///////////////////////////////////////////////////////////////////////// HRESULT CMyDevice::OnSelfManagedIoSuspend( _In_ IWDFDevice* pWdfDevice ) { UNREFERENCED_PARAMETER(pWdfDevice); Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Entry"); HRESULT hr = EnterProcessing(PROCESSING_IPNPCALLBACKSELFMANAGEDIO); if (SUCCEEDED(hr)) { if (nullptr != m_pSensorManager) { Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Hardware is now not available"); m_pSensorManager->m_fDeviceActive = false; } if (nullptr != m_spQueue) { Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Flushing queue of running requests"); // TODO If all hardware requests are not guaranteed to complete within 1 second then // the queue should be stopped and all pending hardweare requests canceled //m_spQueue->Stop(nullptr); // Uncomment this line if the hardware requests need to be canceled // As noted above, cancel all pending hardware requests here to allow all ISensorDriver:: callbacks to complete m_spQueue->StopSynchronously(); // NOTE Any asynchronous work that accesses the hardware should be stopped m_spQueue->Start(); } } ExitProcessing(PROCESSING_IPNPCALLBACKSELFMANAGEDIO); Trace(TRACE_LEVEL_INFORMATION, "%!FUNC! Exit, hr = %!HRESULT!", hr); return hr; }
28.698266
190
0.528722
zzgchina888