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
108
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
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
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
1b8d63ace9bc75c1cfa2f5753b2e2b72ff29c59e
9,574
cpp
C++
modules/imgui/imguimodule.cpp
tychonaut/OpenSpace
fa5bbc5a44b3c55474a6594d8be31ce8f25150c7
[ "MIT" ]
null
null
null
modules/imgui/imguimodule.cpp
tychonaut/OpenSpace
fa5bbc5a44b3c55474a6594d8be31ce8f25150c7
[ "MIT" ]
null
null
null
modules/imgui/imguimodule.cpp
tychonaut/OpenSpace
fa5bbc5a44b3c55474a6594d8be31ce8f25150c7
[ "MIT" ]
null
null
null
/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2020 * * * * 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 <modules/imgui/imguimodule.h> #include <openspace/engine/globals.h> #include <openspace/engine/globalscallbacks.h> #include <openspace/engine/virtualpropertymanager.h> #include <openspace/engine/windowdelegate.h> #include <openspace/engine/moduleengine.h> #include <openspace/interaction/navigationhandler.h> #include <openspace/interaction/sessionrecording.h> #include <openspace/network/parallelpeer.h> #include <openspace/rendering/dashboard.h> #include <openspace/rendering/luaconsole.h> #include <openspace/rendering/renderengine.h> #include <openspace/scene/scene.h> #include <ghoul/logging/logmanager.h> #include <ghoul/misc/profiling.h> namespace openspace { ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) { addPropertySubOwner(gui); global::callback::initialize.emplace_back([&]() { LDEBUGC("ImGUIModule", "Initializing GUI"); gui.initialize(); gui._globalProperty.setSource( []() { std::vector<properties::PropertyOwner*> res = { &global::navigationHandler, &global::sessionRecording, &global::timeManager, &global::renderEngine, &global::parallelPeer, &global::luaConsole, &global::dashboard }; return res; } ); gui._screenSpaceProperty.setSource( []() { return global::screenSpaceRootPropertyOwner.propertySubOwners(); } ); gui._moduleProperty.setSource( []() { std::vector<properties::PropertyOwner*> v; v.push_back(&(global::moduleEngine)); return v; } ); gui._sceneProperty.setSource( []() { const Scene* scene = global::renderEngine.scene(); const std::vector<SceneGraphNode*>& nodes = scene ? scene->allSceneGraphNodes() : std::vector<SceneGraphNode*>(); return std::vector<properties::PropertyOwner*>( nodes.begin(), nodes.end() ); } ); gui._virtualProperty.setSource( []() { std::vector<properties::PropertyOwner*> res = { &global::virtualPropertyManager }; return res; } ); gui._featuredProperties.setSource( []() { std::vector<SceneGraphNode*> nodes = global::renderEngine.scene()->allSceneGraphNodes(); nodes.erase( std::remove_if( nodes.begin(), nodes.end(), [](SceneGraphNode* n) { const std::vector<std::string>& tags = n->tags(); const auto it = std::find( tags.begin(), tags.end(), "GUI.Interesting" ); return it == tags.end(); } ), nodes.end() ); return std::vector<properties::PropertyOwner*>( nodes.begin(), nodes.end() ); } ); }); global::callback::deinitialize.emplace_back([&]() { ZoneScopedN("ImGUI") LDEBUGC("ImGui", "Deinitialize GUI"); gui.deinitialize(); }); global::callback::initializeGL.emplace_back([&]() { ZoneScopedN("ImGUI") LDEBUGC("ImGui", "Initializing GUI OpenGL"); gui.initializeGL(); }); global::callback::deinitializeGL.emplace_back([&]() { ZoneScopedN("ImGUI") LDEBUGC("ImGui", "Deinitialize GUI OpenGL"); gui.deinitializeGL(); }); global::callback::draw2D.emplace_back([&]() { ZoneScopedN("ImGUI") // TODO emiax: Make sure this is only called for one of the eyes, in the case // of side-by-side / top-bottom stereo. WindowDelegate& delegate = global::windowDelegate; const bool showGui = delegate.hasGuiWindow() ? delegate.isGuiWindow() : true; if (delegate.isMaster() && showGui) { const glm::ivec2 windowSize = delegate.currentSubwindowSize(); const glm::ivec2 resolution = delegate.currentDrawBufferResolution(); if (windowSize.x <= 0 || windowSize.y <= 0) { return; } glm::vec2 mousePosition = delegate.mousePosition(); uint32_t mouseButtons = delegate.mouseButtons(2); const double dt = std::max(delegate.averageDeltaTime(), 0.0); if (touchInput.active && mouseButtons == 0) { mouseButtons = touchInput.action; mousePosition = touchInput.pos; } // We don't do any collection of immediate mode user interface, so it // is fine to open and close a frame immediately gui.startFrame( static_cast<float>(dt), glm::vec2(windowSize), resolution / windowSize, mousePosition, mouseButtons ); gui.endFrame(); } }); global::callback::keyboard.emplace_back( [&](Key key, KeyModifier mod, KeyAction action) -> bool { ZoneScopedN("ImGUI") // A list of all the windows that can show up by themselves if (gui.isEnabled() || gui._performance.isEnabled() || gui._sceneProperty.isEnabled()) { return gui.keyCallback(key, mod, action); } else { return false; } } ); global::callback::character.emplace_back( [&](unsigned int codepoint, KeyModifier modifier) -> bool { ZoneScopedN("ImGUI") // A list of all the windows that can show up by themselves if (gui.isEnabled() || gui._performance.isEnabled() || gui._sceneProperty.isEnabled()) { return gui.charCallback(codepoint, modifier); } else { return false; } } ); global::callback::mouseButton.emplace_back( [&](MouseButton button, MouseAction action, KeyModifier) -> bool { ZoneScopedN("ImGUI") // A list of all the windows that can show up by themselves if (gui.isEnabled() || gui._performance.isEnabled() || gui._sceneProperty.isEnabled()) { return gui.mouseButtonCallback(button, action); } else { return false; } } ); global::callback::mouseScrollWheel.emplace_back( [&](double, double posY) -> bool { ZoneScopedN("ImGUI") // A list of all the windows that can show up by themselves if (gui.isEnabled() || gui._performance.isEnabled() || gui._sceneProperty.isEnabled()) { return gui.mouseWheelCallback(posY); } else { return false; } } ); } } // namespace openspace
37.108527
90
0.488719
tychonaut
1b8f3b1c8d749cfc3834dff2ea86fd5095a91e05
2,033
cpp
C++
source/nyra/unittests/transform.cpp
LCClyde/WorkingTitle
f2d4c5e4d1eab597d45ef4ce586c1f8f17defa69
[ "MIT" ]
null
null
null
source/nyra/unittests/transform.cpp
LCClyde/WorkingTitle
f2d4c5e4d1eab597d45ef4ce586c1f8f17defa69
[ "MIT" ]
2
2015-11-02T12:41:02.000Z
2015-11-06T03:21:46.000Z
source/nyra/unittests/transform.cpp
LCClyde/WorkingTitle
f2d4c5e4d1eab597d45ef4ce586c1f8f17defa69
[ "MIT" ]
null
null
null
/* * The MIT License (MIT) * * Copyright (c) 2015 Clyde Stanfield * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <gtest/gtest.h> #include <nyra/Vector2.h> #include <nyra/Transform.h> TEST(Transform, AccessorsMutators) { nyra::Transform transform; EXPECT_EQ(transform.getPosition(), nyra::Vector2F(0.0f, 0.0f)); EXPECT_EQ(transform.getScale(), nyra::Vector2F(1.0f, 1.0f)); EXPECT_EQ(transform.getRotation(), 0.0f); EXPECT_EQ(transform.getPivot(), nyra::Vector2F(0.5f, 0.5f)); const nyra::Vector2F testVec(567.909f, -345.234f); transform.setPosition(testVec); EXPECT_EQ(transform.getPosition(), testVec); transform.setScale(testVec); EXPECT_EQ(transform.getScale(), testVec); transform.setRotation(testVec.x); EXPECT_EQ(transform.getRotation(), testVec.x); transform.setPivot(testVec); EXPECT_EQ(transform.getPivot(), testVec); } TEST(Transform, Matrix) { //TODO: Test matrix std::cout << "Need to add matrix tests\n"; }
36.963636
79
0.731923
LCClyde
1b90b4f850955002f67f0e3a3240f84c2daa8219
2,033
cpp
C++
third_party/omr/fvtest/utiltest/main.cpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
third_party/omr/fvtest/utiltest/main.cpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
third_party/omr/fvtest/utiltest/main.cpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright (c) 2015, 2018 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this * distribution and is available at http://eclipse.org/legal/epl-2.0 * or the Apache License, Version 2.0 which accompanies this distribution * and is available at https://www.apache.org/licenses/LICENSE-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License, v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception [1] and GNU General Public * License, version 2 with the OpenJDK Assembly Exception [2]. * * [1] https://www.gnu.org/software/classpath/license.html * [2] http://openjdk.java.net/legal/assembly-exception.html * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception *******************************************************************************/ #include <stdio.h> #include "omr.h" #include "omrutil.h" #include "omrTest.h" int main(int argc, char **argv, char **envp) { ::testing::InitGoogleTest(&argc, argv); OMREventListener::setDefaultTestListener(); return RUN_ALL_TESTS(); } TEST(UtilTest, detectVMDirectory) { #if defined(OMR_OS_WINDOWS) void *token = NULL; ASSERT_EQ(OMR_ERROR_NONE, OMR_Glue_GetVMDirectoryToken(&token)); wchar_t path[2048]; size_t pathMax = 2048; wchar_t *pathEnd = NULL; ASSERT_EQ(OMR_ERROR_NONE, detectVMDirectory(path, pathMax, &pathEnd)); ASSERT_TRUE((NULL == pathEnd) || (L'\0' == *pathEnd)); wprintf(L"VM Directory: '%s'\n", path); if (NULL != pathEnd) { size_t length = pathMax - wcslen(path) - 2; _snwprintf(pathEnd, length, L"\\abc"); wprintf(L"Mangled VM Directory: '%s'\n", path); } #endif /* defined(OMR_OS_WINDOWS) */ }
35.666667
135
0.671422
xiacijie
1b994fde11422c094b973ea200686c8888419e8e
6,747
cc
C++
third_party/blink/renderer/core/frame/v8_scanner/scanner-character-streams.cc
1qaz2wsx7u8i9o0p/DOM-Tree-Type
151e4c2c85bf93ba506277486d7989361d02b54c
[ "MIT" ]
null
null
null
third_party/blink/renderer/core/frame/v8_scanner/scanner-character-streams.cc
1qaz2wsx7u8i9o0p/DOM-Tree-Type
151e4c2c85bf93ba506277486d7989361d02b54c
[ "MIT" ]
null
null
null
third_party/blink/renderer/core/frame/v8_scanner/scanner-character-streams.cc
1qaz2wsx7u8i9o0p/DOM-Tree-Type
151e4c2c85bf93ba506277486d7989361d02b54c
[ "MIT" ]
null
null
null
// Copyright 2011 the V8 project 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 "third_party/blink/renderer/core/frame/v8_scanner/scanner-character-streams.h" #include <memory> #include <vector> #include "third_party/blink/renderer/core/frame/v8_scanner/globals.h" #include "third_party/blink/renderer/core/frame/v8_scanner/scanner.h" #include "third_party/blink/renderer/core/frame/v8_scanner/unicode-inl.h" namespace v8_scanner { template <typename Char> struct Range { const Char* start; const Char* end; size_t length() { return static_cast<size_t>(end - start); } bool unaligned_start() const { return reinterpret_cast<intptr_t>(start) % sizeof(Char) == 1; } }; // A Char stream backed by a C array. Testing only. template <typename Char> class TestingStream { public: TestingStream(const Char* data, size_t length) : data_(data), length_(length) {} // The no_gc argument is only here because of the templated way this class // is used along with other implementations that require V8 heap access. Range<Char> GetDataAt(size_t pos) { return {&data_[std::min(length_, pos)], &data_[length_]}; } static const bool kCanBeCloned = true; static const bool kCanAccessHeap = false; private: const Char* const data_; const size_t length_; }; // Provides a buffered utf-16 view on the bytes from the underlying ByteStream. // Chars are buffered if either the underlying stream isn't utf-16 or the // underlying utf-16 stream might move (is on-heap). template <template <typename T> class ByteStream> class BufferedCharacterStream : public Utf16CharacterStream { public: template <class... TArgs> BufferedCharacterStream(size_t pos, TArgs... args) : byte_stream_(args...) { buffer_pos_ = pos; } bool can_be_cloned() const final { return ByteStream<uint16_t>::kCanBeCloned; } std::unique_ptr<Utf16CharacterStream> Clone() const override { return std::unique_ptr<Utf16CharacterStream>( new BufferedCharacterStream<ByteStream>(*this)); } protected: bool ReadBlock() final { size_t position = pos(); buffer_pos_ = position; buffer_start_ = &buffer_[0]; buffer_cursor_ = buffer_start_; Range<uint8_t> range = byte_stream_.GetDataAt(position); if (range.length() == 0) { buffer_end_ = buffer_start_; return false; } size_t length = std::min({kBufferSize, range.length()}); for (unsigned int i = 0; i < length; ++i) { buffer_[i] = *((uc16 *)(range.start) + i); } buffer_end_ = &buffer_[length]; return true; } bool can_access_heap() const final { return ByteStream<uint8_t>::kCanAccessHeap; } private: BufferedCharacterStream(const BufferedCharacterStream<ByteStream>& other) : byte_stream_(other.byte_stream_) {} static const size_t kBufferSize = 512; uc16 buffer_[kBufferSize]; ByteStream<uint8_t> byte_stream_; }; // Provides a unbuffered utf-16 view on the bytes from the underlying // ByteStream. template <template <typename T> class ByteStream> class UnbufferedCharacterStream : public Utf16CharacterStream { public: template <class... TArgs> UnbufferedCharacterStream(size_t pos, TArgs... args) : byte_stream_(args...) { buffer_pos_ = pos; } bool can_access_heap() const final { return ByteStream<uint16_t>::kCanAccessHeap; } bool can_be_cloned() const final { return ByteStream<uint16_t>::kCanBeCloned; } std::unique_ptr<Utf16CharacterStream> Clone() const override { return std::unique_ptr<Utf16CharacterStream>( new UnbufferedCharacterStream<ByteStream>(*this)); } protected: bool ReadBlock() final { size_t position = pos(); buffer_pos_ = position; Range<uint16_t> range = byte_stream_.GetDataAt(position); buffer_start_ = range.start; buffer_end_ = range.end; buffer_cursor_ = buffer_start_; if (range.length() == 0) return false; return true; } UnbufferedCharacterStream(const UnbufferedCharacterStream<ByteStream>& other) : byte_stream_(other.byte_stream_) {} ByteStream<uint16_t> byte_stream_; }; // ---------------------------------------------------------------------------- // BufferedUtf16CharacterStreams // // A buffered character stream based on a random access character // source (ReadBlock can be called with pos() pointing to any position, // even positions before the current). // // TODO(verwaest): Remove together with Utf8 external streaming streams. class BufferedUtf16CharacterStream : public Utf16CharacterStream { public: BufferedUtf16CharacterStream(); protected: static const size_t kBufferSize = 512; bool ReadBlock() final; // FillBuffer should read up to kBufferSize characters at position and store // them into buffer_[0..]. It returns the number of characters stored. virtual size_t FillBuffer(size_t position) = 0; // Fixed sized buffer that this class reads from. // The base class' buffer_start_ should always point to buffer_. uc16 buffer_[kBufferSize]; }; BufferedUtf16CharacterStream::BufferedUtf16CharacterStream() : Utf16CharacterStream(buffer_, buffer_, buffer_, 0) {} bool BufferedUtf16CharacterStream::ReadBlock() { size_t position = pos(); buffer_pos_ = position; buffer_cursor_ = buffer_; buffer_end_ = buffer_ + FillBuffer(position); return buffer_cursor_ < buffer_end_; } std::unique_ptr<Utf16CharacterStream> ScannerStream::ForTesting( const char* data) { return ScannerStream::ForTesting(data, strlen(data)); } std::unique_ptr<Utf16CharacterStream> ScannerStream::ForTesting( const char* data, size_t length) { if (data == nullptr) { // We don't want to pass in a null pointer into the the character stream, // because then the one-past-the-end pointer is undefined, so instead pass // through this static array. static const char non_null_empty_string[1] = {0}; data = non_null_empty_string; } return std::unique_ptr<Utf16CharacterStream>( new BufferedCharacterStream<TestingStream>( 0, reinterpret_cast<const uint8_t*>(data), length)); } std::unique_ptr<Utf16CharacterStream> ScannerStream::ForTesting( const uint16_t* data, size_t length) { if (data == nullptr) { // We don't want to pass in a null pointer into the the character stream, // because then the one-past-the-end pointer is undefined, so instead pass // through this static array. static const uint16_t non_null_empty_uint16_t_string[1] = {0}; data = non_null_empty_uint16_t_string; } return std::unique_ptr<Utf16CharacterStream>( new UnbufferedCharacterStream<TestingStream>(0, data, length)); } }
31.236111
87
0.716763
1qaz2wsx7u8i9o0p
1b9a1dd180ffc6e64cb35e9b28a5e2ff3f593b13
4,242
cpp
C++
libraries/M10SevenSeg/src/M10SevenSeg.cpp
adinath1/A4Arduino
54429f095223db8016ede54188cc927784f4f02b
[ "Apache-2.0" ]
null
null
null
libraries/M10SevenSeg/src/M10SevenSeg.cpp
adinath1/A4Arduino
54429f095223db8016ede54188cc927784f4f02b
[ "Apache-2.0" ]
null
null
null
libraries/M10SevenSeg/src/M10SevenSeg.cpp
adinath1/A4Arduino
54429f095223db8016ede54188cc927784f4f02b
[ "Apache-2.0" ]
1
2021-09-06T06:20:07.000Z
2021-09-06T06:20:07.000Z
/* ############################################################################### # Copyright (c) 2018, PulseRain Technology LLC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (LGPL) as # published by the Free Software Foundation, either version 3 of the License, # or (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################### */ #include "M10SevenSeg.h" static const uint8_t seven_seg_display_encoding [16] = { 0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F, 0x77, 0x7C, 0x39, 0x5E, 0x79, 0x71 }; //---------------------------------------------------------------------------- // seven_seg_on_off() // // Parameters: // on_off_mask : mask for power on/off // // Return Value: // None // // Remarks: // This function assumes power on/off control is in the lower // two bits of Port 2 //---------------------------------------------------------------------------- static void seven_seg_on_off (uint8_t on_off_mask) __reentrant { P2 &= 0xFC; P2 |= on_off_mask & 0x3; } // End of seven_seg_on_off() //---------------------------------------------------------------------------- // seven_seg_init() // // Parameters: // None // // Return Value: // None // // Remarks: // This function assumes Port 0 and Port 1 are connected to 7-seg display, // and assumes on/off control is in the lower two bits of Port 2 //---------------------------------------------------------------------------- static void seven_seg_init() __reentrant { P0_DIRECTION = 0xFF; P1_DIRECTION = 0xFF; P2_DIRECTION |= 0x3; seven_seg_on_off (3); } // End of seven_seg_init() //---------------------------------------------------------------------------- // seven_seg_dp() // // Parameters: // mask : mask for the decimal points // // Return Value: // None // // Remarks: // This function assumes Port 0 and Port 1 are connected to 7-seg display, // and assumes decimal point is controlled by bit 7 in each port //---------------------------------------------------------------------------- static void seven_seg_dp (uint8_t mask) __reentrant { P0_7 = mask & 0x1; P1_7 = (mask >> 1) & 0x1; } // End of seven_seg_dp() //---------------------------------------------------------------------------- // seven_seg_display() // // Parameters: // number : hex number (0 ~ 15) to be displayed // index : 0 or 1 for display position // // Return Value: // None // // Remarks: // This function assumes Port 0 and Port 1 are connected to 7-seg display. //---------------------------------------------------------------------------- static void seven_seg_display (uint8_t number, uint8_t index) __reentrant { uint8_t t; t = number & 0xF; if (index == 0) { P0 &= 0x80; P0 |= seven_seg_display_encoding[t]; } else if (index == 1) { P1 &= 0x80; P1 |= seven_seg_display_encoding[t]; } } // End of seven_seg_display() //---------------------------------------------------------------------------- // seven_seg_hex_byte_display() // // Parameters: // number : hex number (0 ~ 255) to be displayed // // Return Value: // None // // Remarks: // This function assumes Port 0 and Port 1 are connected to 7-seg display. //---------------------------------------------------------------------------- static void seven_seg_hex_byte_display (uint8_t num) __reentrant { seven_seg_display (num, 1); seven_seg_display (num >> 4, 0); } // End of seven_seg_hex_byte_display() const SEVEN_SEG_STRUCT SEVEN_SEG = { .init = seven_seg_init, .onOff = seven_seg_on_off, .byteHex = seven_seg_hex_byte_display, .decimalPoint = seven_seg_dp };
28.28
97
0.519802
adinath1
1b9a58d856a3f425718cfa0a31c8e43e354fc25f
664
cpp
C++
cpp/0_check/johnstonc_programmingtoday_sourcecode/chapter04_pointers/ch4_moreptrs/ch.cpp
shadialameddin/numerical_tools_and_friends
cc9f10f58886ee286ed89080e38ebd303d3c72a5
[ "Unlicense" ]
null
null
null
cpp/0_check/johnstonc_programmingtoday_sourcecode/chapter04_pointers/ch4_moreptrs/ch.cpp
shadialameddin/numerical_tools_and_friends
cc9f10f58886ee286ed89080e38ebd303d3c72a5
[ "Unlicense" ]
null
null
null
cpp/0_check/johnstonc_programmingtoday_sourcecode/chapter04_pointers/ch4_moreptrs/ch.cpp
shadialameddin/numerical_tools_and_friends
cc9f10f58886ee286ed89080e38ebd303d3c72a5
[ "Unlicense" ]
null
null
null
//Program 4-6 What are pointers pointing to? #include <iostream.h> #include <iomanip.h> int main() { //set up variables and assign addresses into pointers int m , *m_ptr = &m; float p, *p_ptr = &p; //assign values where the pointers are pointing *m_ptr = 4; *p_ptr = (float)3.14159; //write each pointer's value, address and what the pointer is pointing to cout << "\nPtr Name Value Address Pointing to \n" << "\n m_ptr " << m_ptr << setw(12) << &m_ptr << setw(10) << *m_ptr << "\n p_ptr " << p_ptr << setw(12) << &p_ptr << setw(10) << *p_ptr << endl; return 0; }
24.592593
75
0.555723
shadialameddin
1b9a6243f32680942c0ef65acfeef60fc5cefc65
1,080
cpp
C++
src/pcc/psb_cc_base.cpp
uyjulian/psbfile
1f7a6f14a698f160b99198d985f9fa0938c5b910
[ "MIT" ]
41
2016-10-10T12:36:48.000Z
2022-02-20T00:56:08.000Z
src/pcc/psb_cc_base.cpp
uyjulian/psbfile
1f7a6f14a698f160b99198d985f9fa0938c5b910
[ "MIT" ]
3
2018-03-21T16:15:35.000Z
2021-11-17T22:49:08.000Z
src/pcc/psb_cc_base.cpp
uyjulian/psbfile
1f7a6f14a698f160b99198d985f9fa0938c5b910
[ "MIT" ]
12
2016-12-29T02:34:10.000Z
2021-12-04T06:44:12.000Z
/* KRKR PSBFILE Compiler/Decompiler Author:201724 QQ:495159 EMail:number201724@me.com */ #include "def.h" #include "psb_cc_base.h" psb_cc_base::psb_cc_base(psb_value_t::type_t type) : _data(NULL), _length(0), _type(type), _cc(NULL) { } psb_cc_base::psb_cc_base(psb_cc* cc, psb_value_t::type_t type) :_cc(cc), _data(NULL), _length(0), _type(type) { } psb_cc_base::psb_cc_base(psb_cc* cc, Json::Value &src, psb_value_t::type_t type) :_cc(cc), _src(src), _data(NULL), _length(0), _type(type) { } psb_cc_base::~psb_cc_base() { if (_data) { delete[] _data; } } unsigned char* psb_cc_base::get_data() { return _data; } void psb_cc_base::reset_data() { if (_data) { delete[] _data; _data = NULL; } _length = 0; } uint32_t psb_cc_base::get_length() { return _length; } psb_value_t::type_t psb_cc_base::get_type() { return _type; } Json::Value psb_cc_base::get_source() { return _src; } void psb_cc_base::dump() { #ifdef _DEBUG printf("%s:", get_class_name()); for (uint32_t i = 0; i < _length; i++) { printf("%02X ", _data[i]); } printf("\n"); #endif }
15
138
0.676852
uyjulian
1b9a6a9711be571fa5c98cf70546f9764438d1ae
119
cpp
C++
sources/kimpc/ardsim/Keypad.cpp
BleuLlama/kim_uno_remix
908c9e770a9980a88f0663b3ad67cec507cd8301
[ "MIT" ]
5
2015-04-07T02:20:05.000Z
2021-03-06T09:09:59.000Z
sources/kimpc/ardsim/Keypad.cpp
BleuLlama/kim_uno_remix
908c9e770a9980a88f0663b3ad67cec507cd8301
[ "MIT" ]
null
null
null
sources/kimpc/ardsim/Keypad.cpp
BleuLlama/kim_uno_remix
908c9e770a9980a88f0663b3ad67cec507cd8301
[ "MIT" ]
4
2016-03-02T03:07:33.000Z
2021-03-06T09:12:29.000Z
#include "Keypad.h" Keypad::Keypad(char *userKeymap, byte *row, byte *col, byte rows, byte cols) { /* nothing */ }
14.875
77
0.647059
BleuLlama
1ba21795be4e33ff522d8b9084a0393c0cf8a96c
5,041
hpp
C++
cpp/subprojects/common/include/common/data/view_csr_binary.hpp
mrapp-ke/SyndromeLearner
ed18c282949bebbc8e1dd5d2ddfb0b224ee71293
[ "MIT" ]
null
null
null
cpp/subprojects/common/include/common/data/view_csr_binary.hpp
mrapp-ke/SyndromeLearner
ed18c282949bebbc8e1dd5d2ddfb0b224ee71293
[ "MIT" ]
null
null
null
cpp/subprojects/common/include/common/data/view_csr_binary.hpp
mrapp-ke/SyndromeLearner
ed18c282949bebbc8e1dd5d2ddfb0b224ee71293
[ "MIT" ]
1
2022-03-08T22:06:56.000Z
2022-03-08T22:06:56.000Z
/* * @author Michael Rapp (mrapp@ke.tu-darmstadt.de) */ #pragma once #include "common/indices/index_forward_iterator.hpp" /** * Implements row-wise read-only access to binary values that are stored in a pre-allocated matrix in the compressed * sparse row (CSR) format. */ class BinaryCsrConstView { protected: uint32 numRows_; uint32 numCols_; uint32* rowIndices_; uint32* colIndices_; public: /** * @param numRows The number of rows in the view * @param numCols The number of columns in the view * @param rowIndices A pointer to an array of type `uint32`, shape `(numRows + 1)`, that stores the indices * of the first element in `colIndices` that corresponds to a certain row. The index at the * last position is equal to `num_non_zero_values` * @param colIndices A pointer to an array of type `uint32`, shape `(num_non_zero_values)`, that stores the * column-indices, the non-zero elements correspond to */ BinaryCsrConstView(uint32 numRows, uint32 numCols, uint32* rowIndices, uint32* colIndices); /** * An iterator that provides read-only access to the indices in the view. */ typedef const uint32* index_const_iterator; /** * An iterator that provides read-only access to the values in the view. */ typedef IndexForwardIterator<index_const_iterator> value_const_iterator; /** * Returns an `index_const_iterator` to the beginning of the indices at a specific row. * * @param row The row * @return An `index_const_iterator` to the beginning of the indices */ index_const_iterator row_indices_cbegin(uint32 row) const; /** * Returns an `index_const_iterator` to the end of the indices at a specific row. * * @param row The row * @return An `index_const_iterator` to the end of the indices */ index_const_iterator row_indices_cend(uint32 row) const; /** * Returns a `value_const_iterator` to the beginning of the values at a specific row. * * @param row The row * @return A `value_const_iterator` to the beginning of the values */ value_const_iterator row_values_cbegin(uint32 row) const; /** * Returns a `value_const_iterator` to the end of the values at a specific row. * * @param row The row * @return A `value_const_iterator` to the end of the values */ value_const_iterator row_values_cend(uint32 row) const; /** * Returns the number of rows in the view. * * @return The number of rows */ uint32 getNumRows() const; /** * Returns the number of columns in the view. * * @return The number of columns */ uint32 getNumCols() const; /** * Returns the number of non-zero elements in the view. * * @return The number of non-zero elements */ uint32 getNumNonZeroElements() const; }; /** * Implements row-wise read and write access to binary values that are stored in a pre-allocated matrix in the * compressed sparse row (CSR) format. */ class BinaryCsrView final : public BinaryCsrConstView { public: /** * @param numRows The number of rows in the view * @param numCols The number of columns in the view * @param rowIndices A pointer to an array of type `uint32`, shape `(numRows + 1)`, that stores the indices * of the first element in `colIndices` that corresponds to a certain row. The index at the * last position is equal to `num_non_zero_values` * @param colIndices A pointer to an array of type `uint32`, shape `(num_non_zero_values)`, that stores the * column-indices, the non-zero elements correspond to */ BinaryCsrView(uint32 numRows, uint32 numCols, uint32* rowIndices, uint32* colIndices); /** * An iterator that provides access to the indices of the view and allows to modify them. */ typedef uint32* index_iterator; /** * Returns an `index_iterator` to the beginning of the indices at a specific row. * * @param row The row * @return An `index_iterator` to the beginning of the indices */ index_iterator row_indices_begin(uint32 row); /** * Returns an `index_iterator` to the end of the indices at a specific row. * * @param row The row * @return An `index_iterator` to the end of the indices */ index_iterator row_indices_end(uint32 row); };
35.006944
120
0.594922
mrapp-ke
1ba25478ed9db1f61a3e9c49e3dd72b0103eea87
2,915
cpp
C++
Tutorials/AMR_Adv_C/Source/Adv_advance.cpp
Voskrese/BoxLib-old-msvc
da83349af10ef8f951b7a5b3182fc7cd710abeec
[ "BSD-3-Clause-LBNL" ]
null
null
null
Tutorials/AMR_Adv_C/Source/Adv_advance.cpp
Voskrese/BoxLib-old-msvc
da83349af10ef8f951b7a5b3182fc7cd710abeec
[ "BSD-3-Clause-LBNL" ]
null
null
null
Tutorials/AMR_Adv_C/Source/Adv_advance.cpp
Voskrese/BoxLib-old-msvc
da83349af10ef8f951b7a5b3182fc7cd710abeec
[ "BSD-3-Clause-LBNL" ]
1
2019-08-06T13:09:09.000Z
2019-08-06T13:09:09.000Z
#include <Adv.H> #include <Adv_F.H> Real Adv::advance (Real time, Real dt, int iteration, int ncycle) { for (int k = 0; k < NUM_STATE_TYPE; k++) { state[k].allocOldData(); state[k].swapTimeLevels(dt); } MultiFab& S_new = get_new_data(State_Type); const Real prev_time = state[State_Type].prevTime(); const Real cur_time = state[State_Type].curTime(); const Real ctr_time = 0.5*(prev_time + cur_time); const Real* dx = geom.CellSize(); const Real* prob_lo = geom.ProbLo(); // // Get pointers to Flux registers, or set pointer to zero if not there. // FluxRegister *fine = 0; FluxRegister *current = 0; int finest_level = parent->finestLevel(); if (do_reflux && level < finest_level) { fine = &getFluxReg(level+1); fine->setVal(0.0); } if (do_reflux && level > 0) { current = &getFluxReg(level); } MultiFab fluxes[BL_SPACEDIM]; if (do_reflux) { for (int j = 0; j < BL_SPACEDIM; j++) { BoxArray ba = S_new.boxArray(); ba.surroundingNodes(j); fluxes[j].define(ba, NUM_STATE, 0, Fab_allocate); } } // State with ghost cells MultiFab Sborder(grids, NUM_STATE, NUM_GROW); FillPatch(*this, Sborder, NUM_GROW, time, State_Type, 0, NUM_STATE); #ifdef _OPENMP #pragma omp parallel #endif { FArrayBox flux[BL_SPACEDIM], uface[BL_SPACEDIM]; for (MFIter mfi(S_new, true); mfi.isValid(); ++mfi) { const Box& bx = mfi.tilebox(); const FArrayBox& statein = Sborder[mfi]; FArrayBox& stateout = S_new[mfi]; // Allocate fabs for fluxes and Godunov velocities. for (int i = 0; i < BL_SPACEDIM ; i++) { const Box& bxtmp = BoxLib::surroundingNodes(bx,i); flux[i].resize(bxtmp,NUM_STATE); uface[i].resize(BoxLib::grow(bxtmp,1),1); } BL_FORT_PROC_CALL(GET_FACE_VELOCITY,get_face_velocity) (level, ctr_time, D_DECL(BL_TO_FORTRAN(uface[0]), BL_TO_FORTRAN(uface[1]), BL_TO_FORTRAN(uface[2])), dx, prob_lo); BL_FORT_PROC_CALL(ADVECT,advect) (time, bx.loVect(), bx.hiVect(), BL_TO_FORTRAN_3D(statein), BL_TO_FORTRAN_3D(stateout), D_DECL(BL_TO_FORTRAN_3D(uface[0]), BL_TO_FORTRAN_3D(uface[1]), BL_TO_FORTRAN_3D(uface[2])), D_DECL(BL_TO_FORTRAN_3D(flux[0]), BL_TO_FORTRAN_3D(flux[1]), BL_TO_FORTRAN_3D(flux[2])), dx, dt); if (do_reflux) { for (int i = 0; i < BL_SPACEDIM ; i++) fluxes[i][mfi].copy(flux[i],mfi.nodaltilebox(i)); } } } if (do_reflux) { if (current) { for (int i = 0; i < BL_SPACEDIM ; i++) current->FineAdd(fluxes[i],i,0,0,NUM_STATE,1.); } if (fine) { for (int i = 0; i < BL_SPACEDIM ; i++) fine->CrseInit(fluxes[i],i,0,0,NUM_STATE,-1.); } } return dt; }
24.91453
75
0.592453
Voskrese
1ba2a2866b3a3a4557bc420ed3df7293d4522457
2,128
cc
C++
arch/mx/decoder.cc
Gandalf-ND/fluxengine
683bdcdf7f9147b43da90467e545fe0c78d6dcd1
[ "MIT" ]
null
null
null
arch/mx/decoder.cc
Gandalf-ND/fluxengine
683bdcdf7f9147b43da90467e545fe0c78d6dcd1
[ "MIT" ]
null
null
null
arch/mx/decoder.cc
Gandalf-ND/fluxengine
683bdcdf7f9147b43da90467e545fe0c78d6dcd1
[ "MIT" ]
null
null
null
#include "globals.h" #include "decoders/decoders.h" #include "mx/mx.h" #include "crc.h" #include "fluxmap.h" #include "decoders/fluxmapreader.h" #include "sector.h" #include "record.h" #include "track.h" #include <string.h> const int SECTOR_SIZE = 256; /* * MX disks are a bunch of sectors glued together with no gaps or sync markers, * following a single beginning-of-track synchronisation and identification * sequence. */ /* FM beginning of track marker: * 1010 1010 1010 1010 1111 1111 1010 1111 * a a a a f f a f */ const FluxPattern ID_PATTERN(32, 0xaaaaffaf); void MxDecoder::beginTrack() { _currentSector = -1; _clock = 0; } AbstractDecoder::RecordType MxDecoder::advanceToNextRecord() { if (_currentSector == -1) { /* First sector in the track: look for the sync marker. */ const FluxMatcher* matcher = nullptr; _sector->clock = _clock = _fmr->seekToPattern(ID_PATTERN, matcher); readRawBits(32); /* skip the ID mark */ _logicalTrack = decodeFmMfm(readRawBits(32)).reader().read_be16(); } else if (_currentSector == 10) { /* That was the last sector on the disk. */ return UNKNOWN_RECORD; } else { /* Otherwise we assume the clock from the first sector is still valid. * The decoder framwork will automatically stop when we hit the end of * the track. */ _sector->clock = _clock; } _currentSector++; return SECTOR_RECORD; } void MxDecoder::decodeSectorRecord() { auto bits = readRawBits((SECTOR_SIZE+2)*16); auto bytes = decodeFmMfm(bits).slice(0, SECTOR_SIZE+2).swab(); uint16_t gotChecksum = 0; ByteReader br(bytes); for (int i=0; i<(SECTOR_SIZE/2); i++) gotChecksum += br.read_le16(); uint16_t wantChecksum = br.read_le16(); _sector->logicalTrack = _logicalTrack; _sector->logicalSide = _track->physicalSide; _sector->logicalSector = _currentSector; _sector->data = bytes.slice(0, SECTOR_SIZE); _sector->status = (gotChecksum == wantChecksum) ? Sector::OK : Sector::BAD_CHECKSUM; }
28
88
0.656955
Gandalf-ND
1ba4197170a3c0d9c397896e00527355f5165170
4,942
cc
C++
src/ufo/filters/obsfunctions/BgdDepartureAnomaly.cc
NOAA-EMC/ufo
3bf1407731b79eab16ceff64129552577d9cfcd0
[ "Apache-2.0" ]
null
null
null
src/ufo/filters/obsfunctions/BgdDepartureAnomaly.cc
NOAA-EMC/ufo
3bf1407731b79eab16ceff64129552577d9cfcd0
[ "Apache-2.0" ]
10
2020-12-10T22:57:51.000Z
2020-12-17T15:57:04.000Z
src/ufo/filters/obsfunctions/BgdDepartureAnomaly.cc
NOAA-EMC/ufo
3bf1407731b79eab16ceff64129552577d9cfcd0
[ "Apache-2.0" ]
3
2020-12-10T18:38:22.000Z
2020-12-11T01:36:37.000Z
/* * (C) Copyright 2021 Met Office UK * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. */ #include <memory> #include "ioda/distribution/Accumulator.h" #include "ioda/ObsDataVector.h" #include "oops/util/missingValues.h" #include "ufo/filters/ObsFilterData.h" #include "ufo/filters/obsfunctions/BgdDepartureAnomaly.h" #include "ufo/filters/Variable.h" namespace ufo { static ObsFunctionMaker<BgdDepartureAnomaly> makerBgdDepartureAnomaly_("BgdDepartureAnomaly"); BgdDepartureAnomaly::BgdDepartureAnomaly(const eckit::LocalConfiguration & conf) : invars_() { // Initialize options options_.deserialize(conf); // Get channels for computing the background departure channels_ = {options_.obslow.value(), options_.obshigh.value()}; // Use default or test version of HofX const std::string & hofxopt = options_.testHofX.value(); // Include list of required data from ObsSpace invars_ += Variable("brightness_temperature@ObsValue", channels_); invars_ += Variable("brightness_temperature@"+hofxopt, channels_); if (options_.ObsBias.value().size()) { // Get optional bias correction const std::string & biasopt = options_.ObsBias.value(); invars_ += Variable("brightness_temperature@"+biasopt, channels_); } } // ----------------------------------------------------------------------------- void BgdDepartureAnomaly::compute(const ObsFilterData & in, ioda::ObsDataVector<float> & out) const { // Get dimension const size_t nlocs = in.nlocs(); const float missing = util::missingValue(missing); // Get obs space auto & obsdb = in.obsspace(); ASSERT(channels_.size() == 2); // Get observation values for required channels const std::string & hofxopt = options_.testHofX.value(); std::vector<float> obslow(nlocs), obshigh(nlocs); std::vector<float> bgdlow(nlocs), bgdhigh(nlocs); in.get(Variable("brightness_temperature@ObsValue", channels_)[0], obslow); in.get(Variable("brightness_temperature@ObsValue", channels_)[1], obshigh); in.get(Variable("brightness_temperature@"+hofxopt, channels_)[0], bgdlow); in.get(Variable("brightness_temperature@"+hofxopt, channels_)[1], bgdhigh); // Get bias correction if ObsBias is present in filter options if (options_.ObsBias.value().size()) { const std::string & biasopt = options_.ObsBias.value(); std::vector<float> biaslow(nlocs), biashigh(nlocs); in.get(Variable("brightness_temperature@"+biasopt, channels_)[0], biaslow); in.get(Variable("brightness_temperature@"+biasopt, channels_)[1], biashigh); // Apply bias correction for (size_t iloc = 0; iloc < nlocs; ++iloc) { bgdlow[iloc] -= biaslow[iloc]; bgdhigh[iloc] -= biashigh[iloc]; } } // Compute background departures // To calculate mean departures, we need to know the number of observations with non-missing // departures (taking into account all MPI ranks)... std::unique_ptr<ioda::Accumulator<size_t>> countAccumulator = obsdb.distribution()->createAccumulator<size_t>(); // ... and the sum of all non-missing departures enum {OMB_LOW, OMB_HIGH, NUM_OMBS}; std::unique_ptr<ioda::Accumulator<std::vector<double>>> totalsAccumulator = obsdb.distribution()->createAccumulator<double>(NUM_OMBS); // First, perform local reductions... std::vector<float> omblow(nlocs), ombhigh(nlocs); for (size_t iloc = 0; iloc < nlocs; ++iloc) { if (obslow[iloc] == missing || bgdlow[iloc] == missing || obshigh[iloc] == missing || bgdhigh[iloc] == missing) { omblow[iloc] = missing; ombhigh[iloc] = missing; } else { omblow[iloc] = obslow[iloc] - bgdlow[iloc]; ombhigh[iloc] = obshigh[iloc] - bgdhigh[iloc]; totalsAccumulator->addTerm(iloc, OMB_LOW, omblow[iloc]); totalsAccumulator->addTerm(iloc, OMB_HIGH, ombhigh[iloc]); countAccumulator->addTerm(iloc, 1); } } // ... and then global reductions. const std::size_t count = countAccumulator->computeResult(); const std::vector<double> totals = totalsAccumulator->computeResult(); // Calculate the means const double MeanOmbLow = totals[OMB_LOW] / count; const double MeanOmbHigh = totals[OMB_HIGH] / count; // Compute anomaly difference for (size_t iloc = 0; iloc < nlocs; ++iloc) { if (obslow[iloc] == missing || bgdlow[iloc] == missing || obshigh[iloc] == missing || bgdhigh[iloc] == missing) { out[0][iloc] = missing; } else { out[0][iloc] = std::abs((omblow[iloc]-MeanOmbLow) - (ombhigh[iloc]-MeanOmbHigh)); } } } // ----------------------------------------------------------------------------- const ufo::Variables & BgdDepartureAnomaly::requiredVariables() const { return invars_; } // ----------------------------------------------------------------------------- } // namespace ufo
36.880597
94
0.660461
NOAA-EMC
1ba4b8b102907257247ea72aee9b2eaa89429156
6,905
cc
C++
tensorflow_io/bigquery/kernels/test_kernels/bigquery_test_client_op.cc
rjpower/tensorflow-io
39aa0b46cfaa403121fdddbd491a03d2f3190a87
[ "Apache-2.0" ]
null
null
null
tensorflow_io/bigquery/kernels/test_kernels/bigquery_test_client_op.cc
rjpower/tensorflow-io
39aa0b46cfaa403121fdddbd491a03d2f3190a87
[ "Apache-2.0" ]
null
null
null
tensorflow_io/bigquery/kernels/test_kernels/bigquery_test_client_op.cc
rjpower/tensorflow-io
39aa0b46cfaa403121fdddbd491a03d2f3190a87
[ "Apache-2.0" ]
null
null
null
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <grpcpp/grpcpp.h> #include <cstring> #include <iostream> #include <memory> #include <string> #include "api/Compiler.hh" #include "api/DataFile.hh" #include "api/Decoder.hh" #include "api/Encoder.hh" #include "api/Generic.hh" #include "api/Specific.hh" #include "api/ValidSchema.hh" #include "google/cloud/bigquery/storage/v1beta1/storage.grpc.pb.h" #include "tensorflow/core/framework/dataset.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/platform/net.h" #include "tensorflow_io/bigquery/kernels/bigquery_lib.h" #include "tensorflow_io/bigquery/kernels/test_kernels/fake_bigquery_storage_service.h" namespace tensorflow { namespace { namespace apiv1beta1 = ::google::cloud::bigquery::storage::v1beta1; class BigQueryTestClientResource : public BigQueryClientResource { public: explicit BigQueryTestClientResource( std::shared_ptr<apiv1beta1::BigQueryStorage::Stub> stub, std::unique_ptr<grpc::Server> server, std::unique_ptr<FakeBigQueryStorageService> fake_service) : BigQueryClientResource(stub), server_(std::move(server)), fake_service_(std::move(fake_service)) {} string DebugString() const override { return "BigQueryTestClientResource"; } protected: ~BigQueryTestClientResource() override { server_->Shutdown(); } private: std::unique_ptr<grpc::Server> server_; std::unique_ptr<FakeBigQueryStorageService> fake_service_; }; class BigQueryTestClientOp : public OpKernel { public: explicit BigQueryTestClientOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("avro_schema", &avro_schema_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("avro_serialized_rows_per_stream", &avro_serialized_rows_per_stream_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("avro_serialized_rows_count_per_stream", &avro_serialized_rows_count_per_stream_)); OP_REQUIRES( ctx, avro_serialized_rows_per_stream_.size() == avro_serialized_rows_count_per_stream_.size(), errors::InvalidArgument("avro_serialized_rows_per_stream and " "avro_serialized_rows_count_per_stream lists " "should have same length")); } ~BigQueryTestClientOp() override { if (cinfo_.resource_is_private_to_kernel()) { if (!cinfo_.resource_manager() ->Delete<BigQueryClientResource>(cinfo_.container(), cinfo_.name()) .ok()) { // Do nothing; the resource can have been deleted by session resets. } } } void Compute(OpKernelContext* ctx) override LOCKS_EXCLUDED(mu_) { mutex_lock l(mu_); if (!initialized_) { ResourceMgr* mgr = ctx->resource_manager(); OP_REQUIRES_OK(ctx, cinfo_.Init(mgr, def())); BigQueryTestClientResource* test_resource; OP_REQUIRES_OK( ctx, mgr->LookupOrCreate<BigQueryTestClientResource>( cinfo_.container(), cinfo_.name(), &test_resource, [this](BigQueryTestClientResource** ret) EXCLUSIVE_LOCKS_REQUIRED( mu_) { auto fake_service = absl::make_unique<FakeBigQueryStorageService>(); fake_service->SetAvroSchema(this->avro_schema_); fake_service->SetAvroRowsPerStream( this->avro_serialized_rows_per_stream_, this->avro_serialized_rows_count_per_stream_); grpc::ServerBuilder server_builder; int port = internal::PickUnusedPortOrDie(); string server_address = absl::StrCat("localhost:", port); server_builder.AddListeningPort( server_address, ::grpc::InsecureServerCredentials(), &port); server_builder.RegisterService(fake_service.get()); std::unique_ptr<grpc::Server> server = server_builder.BuildAndStart(); string address = absl::StrCat("localhost:", port); std::shared_ptr<grpc::Channel> channel = ::grpc::CreateChannel( address, grpc::InsecureChannelCredentials()); auto stub = absl::make_unique<apiv1beta1::BigQueryStorage::Stub>( channel); channel->WaitForConnected( gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_seconds(5, GPR_TIMESPAN))); VLOG(3) << "Done creating Fake client"; *ret = new BigQueryTestClientResource(std::move(stub), std::move(server), std::move(fake_service)); return Status::OK(); })); BigQueryClientResource* resource; OP_REQUIRES_OK(ctx, mgr->LookupOrCreate<BigQueryClientResource>( cinfo_.container(), cinfo_.name(), &resource, [test_resource](BigQueryClientResource** ret) EXCLUSIVE_LOCKS_REQUIRED(mu_) { *ret = new BigQueryClientResource( test_resource->get_stub()); return Status::OK(); })); core::ScopedUnref unref_resource(resource); core::ScopedUnref unref_test_resource(test_resource); initialized_ = true; } OP_REQUIRES_OK(ctx, MakeResourceHandleToOutput( ctx, 0, cinfo_.container(), cinfo_.name(), MakeTypeIndex<BigQueryClientResource>())); } private: mutex mu_; ContainerInfo cinfo_ GUARDED_BY(mu_); bool initialized_ GUARDED_BY(mu_) = false; string avro_schema_; std::vector<string> avro_serialized_rows_per_stream_; std::vector<int> avro_serialized_rows_count_per_stream_; }; REGISTER_KERNEL_BUILDER(Name("BigQueryTestClient").Device(DEVICE_CPU), BigQueryTestClientOp); } // namespace } // namespace tensorflow
41.10119
86
0.623461
rjpower
1ba9757b17aa5ed9852294b0a4d569ae7aaa3de2
5,074
hpp
C++
include/EntryPoint.hpp
NaioTechnologies/camCapture
2af0ecbfe3b84fdeed8667ee73401cbfe22766cc
[ "MIT" ]
1
2019-08-28T13:42:21.000Z
2019-08-28T13:42:21.000Z
include/EntryPoint.hpp
NaioTechnologies/camCapture
2af0ecbfe3b84fdeed8667ee73401cbfe22766cc
[ "MIT" ]
null
null
null
include/EntryPoint.hpp
NaioTechnologies/camCapture
2af0ecbfe3b84fdeed8667ee73401cbfe22766cc
[ "MIT" ]
1
2021-02-18T23:17:45.000Z
2021-02-18T23:17:45.000Z
//================================================================================================== // // Copyright(c) 2013 - 2015 Naïo Technologies // // 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 3 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, see <http://www.gnu.org/licenses/>. // //================================================================================================== #ifndef ENTRYPOINT_HPP #define ENTRYPOINT_HPP //================================================================================================== // I N C L U D E F I L E S #include "Core/COProcessUnit.hpp" #include "Importer/IMImporter.hpp" #include "IO/IOTiffWriter.hpp" #include "HTCmdLineParser.h" #include "HTLogger.h" #include "HTSignalHandler.hpp" #include "CLFileSystem.h" #include "CLPrint.hpp" //================================================================================================== // F O R W A R D D E C L A R A T I O N S //================================================================================================== // C O N S T A N T S //================================================================================================== // C L A S S E S class FileOutput : public co::ProcessUnit { //--Methods----------------------------------------------------------------------------------------- public: FileOutput( const std::string& folderPath ) : folderPath_{ folderPath } { } ~FileOutput(){ } virtual bool compute_result( co::ParamContext& context, const co::OutputResult& inResult ) final { const cm::BitmapPairEntry* bmEntry = dynamic_cast<cm::BitmapPairEntry*>( &(*inResult.get_cached_entries().begin()->second) ); co::OutputResult result; result.start_benchmark(); const cm::BitmapPairEntry::ID* id = dynamic_cast<cm::BitmapPairEntry::ID*>( &(*inResult.get_cached_entries().begin()->first) ); std::string filepathL, filepathR; bool generatedL = im::AsyncImporter::generate_filename( folderPath_, "", id->get_index(), id->get_timestamp(), "l", "tif", filepathL ); bool generatedR = im::AsyncImporter::generate_filename( folderPath_, "", id->get_index(), id->get_timestamp(), "r", "tif", filepathR ); if( generatedL && generatedR ) { io::TiffWriter tiffWriterL{ filepathL }; tiffWriterL.write_to_file( bmEntry->bitmap_left(), id->get_index(), id->get_timestamp(), 22.f ); io::TiffWriter tiffWriterR{ filepathR }; tiffWriterR.write_to_file( bmEntry->bitmap_right(), id->get_index(), id->get_timestamp(), 22.f ); } else { return false; } result.stop_benchmark(); //result.print_benchmark( "FileOuput:" ); for( auto& iter : get_output_list() ) { if( iter ) { if( !iter->compute_result( context, result ) ) { return false; } } } return true; } virtual bool query_output_metrics( co::OutputMetrics& outputMetrics ) final { cl::ignore( outputMetrics ); return false; } virtual bool query_output_format( co::OutputFormat& outputFormat ) final { cl::ignore( outputFormat ); return false; } //--Data members------------------------------------------------------------------------------------ private: const std::string folderPath_; }; class EntryPoint : private co::ProcessUnit { //--Methods----------------------------------------------------------------------------------------- public: EntryPoint(); ~EntryPoint(); void set_signal(); bool is_signaled() const; /// Outputs a header for the program on the standard output stream. void print_header() const; bool handle_parameters( const std::string& option, const std::string& type ); /// Main entry point of the application. int32_t run( int32_t argc, const char** argv ); private: virtual bool compute_result( co::ParamContext& context, const co::OutputResult& result ) final; virtual bool query_output_metrics( co::OutputMetrics& om ) final; virtual bool query_output_format( co::OutputFormat& of ) final; //--Data members------------------------------------------------------------------------------------ private: /// Command line parser, logger and debugger for the application HTCmdLineParser parser_; HTCmdLineParser::Visitor handler_; ht::SignalHandler signalHandler_; volatile bool signaled_; }; //================================================================================================== // I N L I N E F U N C T I O N S C O D E S E C T I O N #endif // ENTRYPOINT_HPP
29.847059
100
0.539417
NaioTechnologies
1baacc10653cb8db8cbbb6feb1b11b4bb3beebfc
1,357
cpp
C++
Source/DACore/DUtil.cpp
XDApp/DawnAppFramework
8655de88200e847ce0e822899395247ade515bc6
[ "MIT" ]
1
2015-07-13T11:45:18.000Z
2015-07-13T11:45:18.000Z
Source/DACore/DUtil.cpp
XDApp/DawnAppFramework
8655de88200e847ce0e822899395247ade515bc6
[ "MIT" ]
null
null
null
Source/DACore/DUtil.cpp
XDApp/DawnAppFramework
8655de88200e847ce0e822899395247ade515bc6
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "DUtil.h" std::wstring_convert<std::codecvt_utf16<wchar_t>> DUtil::converter; DUtil::DUtil() { } DUtil::~DUtil() { } std::wstring DUtil::StringAtoW(const std::string &Origin) { return DUtil::converter.from_bytes(Origin); } std::string DUtil::StringWtoA(const std::wstring &Origin) { return DUtil::converter.to_bytes(Origin); } std::wstring DUtil::ANSIToUnicode(const std::string& str) { int len = 0; len = str.length(); int unicodeLen = ::MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0); wchar_t * pUnicode; pUnicode = new wchar_t[unicodeLen + 1]; memset(pUnicode, 0, (unicodeLen + 1)*sizeof(wchar_t)); ::MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, (LPWSTR)pUnicode, unicodeLen); std::wstring rt; rt = (wchar_t*)pUnicode; delete pUnicode; return rt; } std::string DUtil::UnicodeToANSI(const std::wstring& str) { char* pElementText; int iTextLen; // wide char to multi char iTextLen = WideCharToMultiByte(CP_ACP, 0, str.c_str(), -1, NULL, 0, NULL, NULL); pElementText = new char[iTextLen + 1]; memset((void*)pElementText, 0, sizeof(char) * (iTextLen + 1)); ::WideCharToMultiByte(CP_ACP, 0, str.c_str(), -1, pElementText, iTextLen, NULL, NULL); std::string strText; strText = pElementText; delete[] pElementText; return strText; }
17.623377
67
0.676492
XDApp
1babcf3f19fc09aa66c30129945e65a4c3f29318
2,848
hh
C++
src/c++/include/main/GenomeMutatorOptions.hh
sequencing/EAGLE
6da0438c1f7620ea74dec1f34baf20bb0b14b110
[ "BSD-3-Clause" ]
28
2015-05-22T16:03:29.000Z
2022-01-15T12:12:46.000Z
src/c++/include/main/GenomeMutatorOptions.hh
sequencing/EAGLE
6da0438c1f7620ea74dec1f34baf20bb0b14b110
[ "BSD-3-Clause" ]
15
2015-10-21T11:19:09.000Z
2020-07-15T05:01:12.000Z
src/c++/include/main/GenomeMutatorOptions.hh
sequencing/EAGLE
6da0438c1f7620ea74dec1f34baf20bb0b14b110
[ "BSD-3-Clause" ]
8
2017-01-21T00:31:17.000Z
2018-08-12T13:28:57.000Z
/** ** Copyright (c) 2014 Illumina, Inc. ** ** This file is part of Illumina's Enhanced Artificial Genome Engine (EAGLE), ** covered by the "BSD 2-Clause License" (see accompanying LICENSE file) ** ** \description Command line options for 'variantModelling' ** ** \author Mauricio Varea **/ #ifndef EAGLE_MAIN_GENOME_MUTATOR_OPTIONS_HH #define EAGLE_MAIN_GENOME_MUTATOR_OPTIONS_HH #include <string> #include <map> #include <boost/filesystem.hpp> #include "common/Program.hh" namespace eagle { namespace main { class GenomeMutatorOptions : public eagle::common::Options { public: enum Modes { SAFE_MODE, WHOLE_DIR }; GenomeMutatorOptions(); std::map<std::string,unsigned int> exceptionPloidy() const; private: std::string usagePrefix() const {return std::string("Usage:\n") + std::string(" applyVariants [parameters] [options]");} std::string usageSuffix() const {std::stringstream usage; usage << "Examples:" << std::endl; usage << " * Safe Mode" << std::endl; usage << " applyVariants -v /path/to/VariantList.vcf \\" << std::endl; usage << " -r /path/to/ReferenceDir/reference_1.fa \\" << std::endl; usage << " -r /path/to/ReferenceDir/reference_2.fa \\" << std::endl; usage << " ... etc ... \\" << std::endl; usage << " [options]" << std::endl; usage << " * Whole-dir Mode" << std::endl; usage << " applyVariants -v /path/to/VariantList.vcf \\" << std::endl; usage << " -R /path/to/ReferenceDir \\" << std::endl; usage << " [options]" << std::endl; return usage.str();} void postProcess(boost::program_options::variables_map &vm); public: std::vector<boost::filesystem::path> referenceGenome; boost::filesystem::path wholeGenome; boost::filesystem::path sampleGenome; std::vector<boost::filesystem::path> variantList; boost::filesystem::path annotatedVariantList; unsigned int organismPloidy; std::vector<std::string> ploidyChromosome; std::vector<unsigned int> ploidyLevel; std::string prefixToAdd; bool noTranslocationError; bool onlyPrintOutputContigNames; //bool withGenomeSize; bool force; Modes mode; }; } // namespace main } // namespace eagle #endif // EAGLE_MAIN_GENOME_MUTATOR_OPTIONS_HH
37.473684
125
0.534059
sequencing
1bb15126aaa1a5bc5954e1580b36ffb405c2244a
4,864
cpp
C++
Mongoose/Source/Mongoose_IO.cpp
gabrielfougeron/SuiteSparse
f196042715861c28846f3e01a394931c00860de2
[ "Apache-2.0" ]
370
2015-01-30T01:04:37.000Z
2022-03-26T18:48:39.000Z
Mongoose/Source/Mongoose_IO.cpp
gabrielfougeron/SuiteSparse
f196042715861c28846f3e01a394931c00860de2
[ "Apache-2.0" ]
85
2015-02-03T22:57:35.000Z
2021-12-17T12:39:55.000Z
Mongoose/Source/Mongoose_IO.cpp
gabrielfougeron/SuiteSparse
f196042715861c28846f3e01a394931c00860de2
[ "Apache-2.0" ]
234
2015-01-14T15:09:09.000Z
2022-03-26T18:48:41.000Z
/* ========================================================================== */ /* === Source/Mongoose_IO.cpp =============================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * Mongoose Graph Partitioning Library Copyright (C) 2017-2018, * Scott P. Kolodziej, Nuri S. Yeralan, Timothy A. Davis, William W. Hager * Mongoose is licensed under Version 3 of the GNU General Public License. * Mongoose is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /** * Simplified I/O functions for reading matrices and graphs * * For reading Matrix Market files into Mongoose, read_graph and read_matrix * are provided (depending on if a Graph class instance or CSparse matrix * instance is needed). The filename can be specified as either a const char* * (easier for C programmers) or std::string (easier from C++). */ #include "Mongoose_IO.hpp" #include "Mongoose_Internal.hpp" #include "Mongoose_Logger.hpp" #include "Mongoose_Sanitize.hpp" #include <iostream> using namespace std; namespace Mongoose { Graph *read_graph(const std::string &filename) { return read_graph(filename.c_str()); } cs *read_matrix(const std::string &filename, MM_typecode &matcode) { return read_matrix(filename.c_str(), matcode); } Graph *read_graph(const char *filename) { Logger::tic(IOTiming); LogInfo("Reading graph from file " << std::string(filename) << "\n"); MM_typecode matcode; cs *A = read_matrix(filename, matcode); if (!A) { LogError("Error reading matrix from file\n"); return NULL; } cs *sanitized_A = sanitizeMatrix(A, mm_is_symmetric(matcode), false); cs_spfree(A); if (!sanitized_A) return NULL; Graph *G = Graph::create(sanitized_A, true); if (!G) { LogError("Ran out of memory in Mongoose::read_graph\n"); cs_spfree(sanitized_A); Logger::toc(IOTiming); return NULL; } sanitized_A->p = NULL; sanitized_A->i = NULL; sanitized_A->x = NULL; cs_spfree(sanitized_A); Logger::toc(IOTiming); return G; } cs *read_matrix(const char *filename, MM_typecode &matcode) { LogInfo("Reading Matrix from " << std::string(filename) << "\n"); FILE *file = fopen(filename, "r"); if (!file) { LogError("Error: Cannot read file " << std::string(filename) << "\n"); return NULL; } LogInfo("Reading Matrix Market banner..."); if (mm_read_banner(file, &matcode) != 0) { LogError("Error: Could not process Matrix Market banner\n"); fclose(file); return NULL; } if (!mm_is_matrix(matcode) || !mm_is_sparse(matcode) || mm_is_complex(matcode)) { LogError( "Error: Unsupported matrix format - Must be real and sparse\n"); fclose(file); return NULL; } Int M, N, nz; if ((mm_read_mtx_crd_size(file, &M, &N, &nz)) != 0) { LogError("Error: Could not parse matrix dimension and size.\n"); fclose(file); return NULL; } if (M != N) { LogError("Error: Matrix must be square.\n"); fclose(file); return NULL; } LogInfo("Reading matrix data...\n"); Int *I = (Int *)SuiteSparse_malloc(static_cast<size_t>(nz), sizeof(Int)); Int *J = (Int *)SuiteSparse_malloc(static_cast<size_t>(nz), sizeof(Int)); double *val = (double *)SuiteSparse_malloc(static_cast<size_t>(nz), sizeof(double)); if (!I || !J || !val) { LogError("Error: Ran out of memory in Mongoose::read_matrix\n"); SuiteSparse_free(I); SuiteSparse_free(J); SuiteSparse_free(val); fclose(file); return NULL; } mm_read_mtx_crd_data(file, M, N, nz, I, J, val, matcode); fclose(file); // Close the file for (Int k = 0; k < nz; k++) { --I[k]; --J[k]; if (mm_is_pattern(matcode)) val[k] = 1; } cs *A = (cs *)SuiteSparse_malloc(1, sizeof(cs)); if (!A) { LogError("Error: Ran out of memory in Mongoose::read_matrix\n"); SuiteSparse_free(I); SuiteSparse_free(J); SuiteSparse_free(val); return NULL; } A->nzmax = nz; A->m = M; A->n = N; A->p = J; A->i = I; A->x = val; A->nz = nz; LogInfo("Compressing matrix from triplet to CSC format...\n"); cs *compressed_A = cs_compress(A); cs_spfree(A); if (!compressed_A) { LogError("Error: Ran out of memory in Mongoose::read_matrix\n"); return NULL; } return compressed_A; } } // end namespace Mongoose
27.480226
80
0.558388
gabrielfougeron
1bb4055254f0051d2870fbe910e9acb35bca88dc
1,579
cpp
C++
Gep/Source/ps2/file.cpp
Sunlitspace542/SNESticle
9590ebf3bf768424ebd6cb018f322e724a7aade3
[ "MIT" ]
318
2022-01-15T23:35:01.000Z
2022-03-24T13:37:20.000Z
Gep/Source/ps2/file.cpp
Sunlitspace542/SNESticle
9590ebf3bf768424ebd6cb018f322e724a7aade3
[ "MIT" ]
2
2022-01-25T23:58:23.000Z
2022-01-30T21:59:09.000Z
Gep/Source/ps2/file.cpp
Sunlitspace542/SNESticle
9590ebf3bf768424ebd6cb018f322e724a7aade3
[ "MIT" ]
46
2022-01-17T22:46:08.000Z
2022-03-06T16:52:00.000Z
//#include <sys/stat.h> //#include <stdlib.h> //#include <stdio.h> #include <fileio.h> #include "types.h" #include "file.h" Bool FileReadMem(Char *pFilePath, void *pMem, Uint32 nBytes) { #if 0 FILE *pFile; pFile = fopen(pFilePath, "rb"); if (pFile) { Uint32 nReadBytes; nReadBytes = fread(pMem, 1, nBytes, pFile); fclose(pFile); return (nBytes == nReadBytes); } return FALSE; #else int hFile; unsigned int nReadBytes; hFile = fioOpen(pFilePath, O_RDONLY); if (hFile < 0) { return FALSE; } nReadBytes = fioRead(hFile, pMem, nBytes); fioClose(hFile); return (nReadBytes == nBytes); #endif } Bool FileWriteMem(Char *pFilePath, void *pMem, Uint32 nBytes) { #if 0 FILE *pFile; Uint32 nWriteBytes; pFile = fopen(pFilePath, "wb"); if (pFile) { nWriteBytes = fwrite(pMem, 1, nBytes, pFile); fclose(pFile); return (nBytes == nWriteBytes); } return FALSE; #else int hFile; unsigned int nWriteBytes; hFile = fioOpen(pFilePath, O_CREAT | O_WRONLY); if (hFile < 0) { return FALSE; } nWriteBytes = fioWrite(hFile, pMem, nBytes); fioClose(hFile); return (nWriteBytes == nBytes); #endif } Bool FileExists(Char *pFilePath) { #if 0 FILE *pFile; pFile = fopen(pFilePath, "rb"); if (pFile) { fclose(pFile); return true; } else { return false; } #else int hFile; hFile = fioOpen(pFilePath, O_RDONLY); if (hFile < 0) { return FALSE; } fioClose(hFile); return TRUE; #endif }
15.182692
62
0.602913
Sunlitspace542
1bb5f45c42ace30cd11f4ba10eff08925e217de5
5,137
cpp
C++
holdem/src/LYHoldemTrunk.cpp
caiqingfeng/libpoker
a2c60884fc5c8e31455fb39e432c49e0df55956b
[ "Apache-2.0" ]
1
2021-04-20T06:22:30.000Z
2021-04-20T06:22:30.000Z
holdem/src/LYHoldemTrunk.cpp
caiqingfeng/libpoker
a2c60884fc5c8e31455fb39e432c49e0df55956b
[ "Apache-2.0" ]
null
null
null
holdem/src/LYHoldemTrunk.cpp
caiqingfeng/libpoker
a2c60884fc5c8e31455fb39e432c49e0df55956b
[ "Apache-2.0" ]
2
2020-10-29T08:21:22.000Z
2020-12-02T06:40:18.000Z
/* * LYHoldemTrunk.cpp * * Created on: 2013-7-5 * Author: caiqingfeng */ #include <cstdlib> #include "LYHoldemTrunk.h" #include "LYHoldemTable.h" #include "LYHoldemGame.h" //#include <boost/foreach.hpp> //#include "common/src/my_log.h" LYHoldemTrunk:: LYHoldemTrunk(const std::string &trunk_id, const std::string &trunk_name, LYHoldemTable *tbl, unsigned int &ts, std::vector<LYSeatPtr> &all_seats, const std::string &player, const std::string &pf) : LYTrunk(trunk_id, trunk_name, (LYTable *)tbl, ts, all_seats, player, pf) { // TODO Auto-generated constructor stub if (NULL == tbl->profileMgr) { profile = NULL; } else { if ("" != pf) { profile = (LYHoldemProfile *)tbl->profileMgr->getHoldemProfileById(pf).get(); } } } LYHoldemTrunk::~LYHoldemTrunk() { // TODO Auto-generated destructor stub } /* * Game设计只处理当前的Action,可以保证Server和Client代码一致 */ bool LYHoldemTrunk::playGame(LYHoldemAction &action) { // LY_LOG_DBG("enter LYHoldemTrunk::playGame"); if (currentGame == NULL) return false; bool validAction = ((LYHoldemGame *)currentGame)->onAction(action); if (!validAction) { // LY_LOG_INF("invalid action"); return false; } return true; } void LYHoldemTrunk::createGame(const std::string &game_id, LYHoldemAlgorithmDelegate *had) { if (!this->ready2go()) { // LY_LOG_DBG("not ready to go"); return; } this->resetAllSeatsForNewGame(); if (lastGame != NULL) { delete lastGame; lastGame = NULL; } lastGame = currentGame; LYHoldemGame *last_game = (LYHoldemGame *)lastGame; LYSeatPtr btnSeat; LYSeatPtr sbSeat; LYSeatPtr bbSeat; if (lastGame != NULL) { //brand new game btnSeat = ((LYHoldemTable *)this->table)->fetchNextOccupiedSeat(last_game->btnSeatNo); } else { srand(time(NULL)); LYApplicant random_seat = (enum LYApplicant)(rand()%9+1); btnSeat = ((LYHoldemTable *)this->table)->fetchNextOccupiedSeat(random_seat); } sbSeat = ((LYHoldemTable *)this->table)->fetchNextOccupiedSeat(btnSeat->seatNo); bbSeat = ((LYHoldemTable *)this->table)->fetchNextOccupiedSeat(sbSeat->seatNo); if (sbSeat->seatNo == btnSeat->seatNo || bbSeat->seatNo == btnSeat->seatNo) { //20160413增加,只有2个人的时候,Btn小盲 sbSeat = btnSeat; bbSeat = ((LYHoldemTable *)this->table)->fetchNextOccupiedSeat(btnSeat->seatNo); } currentGame = new LYHoldemGame(game_id, seats, this->getSmallBlindPrice(), this->getBigBlindPrice(), btnSeat, sbSeat, bbSeat, (LYHoldemTable *)table, had); } unsigned int LYHoldemTrunk::getSmallBlindPrice() { //此处应该调用ProfileMgr的接口 if (NULL == profile) { return 10; } return profile->get_small_blind(); } unsigned int LYHoldemTrunk::getBigBlindPrice() { //此处应该调用ProfileMgr的接口 if (NULL == profile) { return 25; } return profile->get_big_blind(); } unsigned int LYHoldemTrunk::getCurrentMaxBuyin() { //此处应该调用ProfileMgr的接口 if (NULL == profile) { return 0; } return profile->get_max_chips(); } unsigned int LYHoldemTrunk::getCurrentMinBuyin() { //此处应该调用ProfileMgr的接口 if (NULL == profile) { return 0; } return profile->get_min_chips(); } bool LYHoldemTrunk::ready2go() { if (currentGame != NULL) { enum LYGameRound round = ((LYHoldemGame *)currentGame)->getRound(); if (round != LYGameWaiting && round != LYGameClosed && round != LYGameInit) { // LY_LOG_ERR("there is a game ongoing ... round=" << ((LYHoldemGame *)currentGame)->getRound()); return false; } } unsigned int seated = 0; std::vector<LYSeatPtr>::iterator it = seats.begin(); for (; it!=seats.end(); it++) { LYSeatPtr st = *it; if (st->status != LYSeatOpen && st->chipsAtHand > 0) { seated++; } } if (seated < 2) { // LY_LOG_ERR("seated:" << seated << " must be greater than 2" ); return false; } return true; } bool LYHoldemTrunk::isGameOver() { if (currentGame == NULL || ((LYHoldemGame *)currentGame)->getRound() == LYGameClosed) { return true; } return false; } void LYHoldemTrunk::resetAllSeatsForNewGame() { std::vector<LYSeatPtr>::iterator it = seats.begin(); for(; it != seats.end(); it++) { LYSeatPtr st = *it; LYHoldemSeat *holdemSeat = (LYHoldemSeat *)st.get(); holdemSeat->resetForNewGame(); } } void LYHoldemTrunk::activeProfile() { if ("" != profile_id && ((LYHoldemTable *)table)->profileMgr != NULL) { profile = (LYHoldemProfile *)(((LYHoldemTable *)table)->profileMgr->getHoldemProfileById(profile_id).get()); } } /* * 只是给客户端从空口中创建实例用,或者服务器侧从数据库中恢复实例 * 所有状态都在后续tableFromOta或者tableFromDb中设置 */ void LYHoldemTrunk::createGameInstance(const std::string &game_id) { if (lastGame != NULL) { delete lastGame; lastGame = NULL; } lastGame = currentGame; LYHoldemGame *last_game = (LYHoldemGame *)lastGame; currentGame = new LYHoldemGame(game_id, seats, (LYHoldemTable *)table); } /* * 只是给客户端从空口中创建实例用,或者服务器侧从数据库中恢复实例 * 20160311 */ void LYHoldemTrunk::createGameInstance(const std::string &game_id, std::vector < std::pair<std::string, std::string> >& kvps) { if (lastGame != NULL) { delete lastGame; lastGame = NULL; } lastGame = currentGame; LYHoldemGame *last_game = (LYHoldemGame *)lastGame; currentGame = new LYHoldemGame(game_id, seats, (LYHoldemTable *)table, kvps); }
25.058537
125
0.696905
caiqingfeng
1bb8d67c0f9a83627c2c6eddd412be78c9295d64
5,467
cpp
C++
src/frameworks/av/media/libmedia/IMediaHTTPConnection.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
src/frameworks/av/media/libmedia/IMediaHTTPConnection.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
src/frameworks/av/media/libmedia/IMediaHTTPConnection.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //#define LOG_NDEBUG 0 #define LOG_TAG "IMediaHTTPConnection" #include <utils/Log.h> #include <media/IMediaHTTPConnection.h> #include <binder/IMemory.h> #include <binder/Parcel.h> #include <utils/String8.h> #include <media/stagefright/foundation/ADebug.h> #include <media/stagefright/MediaErrors.h> namespace android { enum { CONNECT = IBinder::FIRST_CALL_TRANSACTION, DISCONNECT, READ_AT, GET_SIZE, GET_MIME_TYPE, GET_URI }; struct BpMediaHTTPConnection : public BpInterface<IMediaHTTPConnection> { explicit BpMediaHTTPConnection(const sp<IBinder> &impl) : BpInterface<IMediaHTTPConnection>(impl) { } virtual bool connect( const char *uri, const KeyedVector<String8, String8> *headers) { Parcel data, reply; data.writeInterfaceToken( IMediaHTTPConnection::getInterfaceDescriptor()); String16 tmp(uri); data.writeString16(tmp); tmp = String16(""); if (headers != NULL) { for (size_t i = 0; i < headers->size(); ++i) { String16 key(headers->keyAt(i).string()); String16 val(headers->valueAt(i).string()); tmp.append(key); tmp.append(String16(": ")); tmp.append(val); tmp.append(String16("\r\n")); } } data.writeString16(tmp); remote()->transact(CONNECT, data, &reply); int32_t exceptionCode = reply.readExceptionCode(); if (exceptionCode) { return false; } sp<IBinder> binder = reply.readStrongBinder(); mMemory = interface_cast<IMemory>(binder); return mMemory != NULL; } virtual void disconnect() { Parcel data, reply; data.writeInterfaceToken( IMediaHTTPConnection::getInterfaceDescriptor()); remote()->transact(DISCONNECT, data, &reply); } virtual ssize_t readAt(off64_t offset, void *buffer, size_t size) { Parcel data, reply; data.writeInterfaceToken( IMediaHTTPConnection::getInterfaceDescriptor()); data.writeInt64(offset); data.writeInt32(size); status_t err = remote()->transact(READ_AT, data, &reply); if (err != OK) { ALOGE("remote readAt failed"); return UNKNOWN_ERROR; } int32_t exceptionCode = reply.readExceptionCode(); if (exceptionCode) { return UNKNOWN_ERROR; } int32_t lenOrErrorCode = reply.readInt32(); // Negative values are error codes if (lenOrErrorCode < 0) { return lenOrErrorCode; } size_t len = lenOrErrorCode; if (len > size) { ALOGE("requested %zu, got %zu", size, len); return ERROR_OUT_OF_RANGE; } if (len > mMemory->size()) { ALOGE("got %zu, but memory has %zu", len, mMemory->size()); return ERROR_OUT_OF_RANGE; } if(buffer == NULL) { ALOGE("readAt got a NULL buffer"); return UNKNOWN_ERROR; } if (mMemory->pointer() == NULL) { ALOGE("readAt got a NULL mMemory->pointer()"); return UNKNOWN_ERROR; } memcpy(buffer, mMemory->pointer(), len); return len; } virtual off64_t getSize() { Parcel data, reply; data.writeInterfaceToken( IMediaHTTPConnection::getInterfaceDescriptor()); remote()->transact(GET_SIZE, data, &reply); int32_t exceptionCode = reply.readExceptionCode(); if (exceptionCode) { return UNKNOWN_ERROR; } return reply.readInt64(); } virtual status_t getMIMEType(String8 *mimeType) { *mimeType = String8(""); Parcel data, reply; data.writeInterfaceToken( IMediaHTTPConnection::getInterfaceDescriptor()); remote()->transact(GET_MIME_TYPE, data, &reply); int32_t exceptionCode = reply.readExceptionCode(); if (exceptionCode) { return UNKNOWN_ERROR; } *mimeType = String8(reply.readString16()); return OK; } virtual status_t getUri(String8 *uri) { *uri = String8(""); Parcel data, reply; data.writeInterfaceToken( IMediaHTTPConnection::getInterfaceDescriptor()); remote()->transact(GET_URI, data, &reply); int32_t exceptionCode = reply.readExceptionCode(); if (exceptionCode) { return UNKNOWN_ERROR; } *uri = String8(reply.readString16()); return OK; } private: sp<IMemory> mMemory; }; IMPLEMENT_META_INTERFACE( MediaHTTPConnection, "android.media.IMediaHTTPConnection"); } // namespace android
26.668293
76
0.600878
dAck2cC2
1bb9a61043791730943e9a2018a2d27aec1a13d0
12,855
cpp
C++
MATLAB Files/StarshotACS1_ert_rtw/StarshotACS1.cpp
Natsoulas/ACS
aac4468e2bcd71eee61d89e9483a5dc9ef7302c1
[ "MIT" ]
null
null
null
MATLAB Files/StarshotACS1_ert_rtw/StarshotACS1.cpp
Natsoulas/ACS
aac4468e2bcd71eee61d89e9483a5dc9ef7302c1
[ "MIT" ]
null
null
null
MATLAB Files/StarshotACS1_ert_rtw/StarshotACS1.cpp
Natsoulas/ACS
aac4468e2bcd71eee61d89e9483a5dc9ef7302c1
[ "MIT" ]
1
2022-03-18T18:57:10.000Z
2022-03-18T18:57:10.000Z
// // Academic License - for use in teaching, academic research, and meeting // course requirements at degree granting institutions only. Not for // government, commercial, or other organizational use. // // File: StarshotACS1.cpp // // Code generated for Simulink model 'StarshotACS1'. // // Model version : 1.75 // Simulink Coder version : 8.12 (R2017a) 16-Feb-2017 // C/C++ source code generated on : Sun May 20 23:34:07 2018 // // Target selection: ert.tlc // Embedded hardware selection: ARM Compatible->ARM Cortex // Code generation objectives: // 1. Execution efficiency // 2. RAM efficiency // Validation result: Not run // #include "StarshotACS1.h" // Model step function void StarshotACS1ModelClass::step() { real_T rtb_Gain[3]; real_T rtb_TSamp[3]; real_T rtb_VectorConcatenate[9]; real_T rtb_Saturation3; real_T rtb_TrigonometricFunction5; real_T rtb_TSamp_o; real_T rtb_Gain_0; int32_T i; real_T rtb_VectorConcatenate_0[9]; real_T rtb_Product1_f; real_T rtb_Gain8_idx_1; real_T rtb_Gain8_idx_2; real_T rtb_Gain8_idx_0; real_T rtb_Product1_i_idx_0; real_T rtb_Product1_i_idx_1; int32_T tmp; // Outputs for Atomic SubSystem: '<Root>/StarshotACS' // Gain: '<S2>/Kane damping' incorporates: // DiscreteIntegrator: '<S2>/Discrete-Time Integrator' // Gain: '<S2>/Gain 2' rtb_Gain8_idx_0 = 0.41837 * -rtDW.DiscreteTimeIntegrator_DSTATE[0]; // Gain: '<S2>/Gain 2' incorporates: // DiscreteIntegrator: '<S2>/Discrete-Time Integrator' rtb_Product1_i_idx_0 = -rtDW.DiscreteTimeIntegrator_DSTATE[0]; // Gain: '<S2>/Kane damping' incorporates: // DiscreteIntegrator: '<S2>/Discrete-Time Integrator' // Gain: '<S2>/Gain 2' rtb_Gain8_idx_1 = 0.41837 * -rtDW.DiscreteTimeIntegrator_DSTATE[1]; // Gain: '<S2>/Gain 2' incorporates: // DiscreteIntegrator: '<S2>/Discrete-Time Integrator' rtb_Product1_i_idx_1 = -rtDW.DiscreteTimeIntegrator_DSTATE[1]; rtb_Product1_f = -rtDW.DiscreteTimeIntegrator_DSTATE[2]; // Gain: '<S2>/Kane damping' incorporates: // DiscreteIntegrator: '<S2>/Discrete-Time Integrator' // Gain: '<S2>/Gain 2' rtb_Gain8_idx_2 = 0.41837 * -rtDW.DiscreteTimeIntegrator_DSTATE[2]; // S-Function (sdsp2norm2): '<S2>/Normalization' incorporates: // Inport: '<Root>/Bfield_body' rtb_Saturation3 = 1.0 / (((rtU.Bfield_body[0] * rtU.Bfield_body[0] + rtU.Bfield_body[1] * rtU.Bfield_body[1]) + rtU.Bfield_body[2] * rtU.Bfield_body[2]) + 1.0E-10); rtb_Gain[0] = rtU.Bfield_body[0] * rtb_Saturation3; // SampleTimeMath: '<S5>/TSamp' incorporates: // Inport: '<Root>/angularvelocity' // // About '<S5>/TSamp': // y = u * K where K = 1 / ( w * Ts ) rtb_TSamp[0] = rtU.w[0] * 100.0; // S-Function (sdsp2norm2): '<S2>/Normalization' incorporates: // Inport: '<Root>/Bfield_body' rtb_Gain[1] = rtU.Bfield_body[1] * rtb_Saturation3; // SampleTimeMath: '<S5>/TSamp' incorporates: // Inport: '<Root>/angularvelocity' // // About '<S5>/TSamp': // y = u * K where K = 1 / ( w * Ts ) rtb_TSamp[1] = rtU.w[1] * 100.0; // S-Function (sdsp2norm2): '<S2>/Normalization' incorporates: // Inport: '<Root>/Bfield_body' rtb_Gain[2] = rtU.Bfield_body[2] * rtb_Saturation3; // SampleTimeMath: '<S5>/TSamp' incorporates: // Inport: '<Root>/angularvelocity' // // About '<S5>/TSamp': // y = u * K where K = 1 / ( w * Ts ) rtb_TSamp[2] = rtU.w[2] * 100.0; // Product: '<S4>/Product2' rtb_TrigonometricFunction5 = rtb_Gain[0]; // Product: '<S4>/Product4' rtb_TSamp_o = rtb_Gain[1]; // Product: '<S4>/Product5' rtb_Gain_0 = rtb_Gain[0]; // Gain: '<S2>/Gain' incorporates: // Product: '<S4>/Product' // Product: '<S4>/Product1' // Product: '<S4>/Product2' // Product: '<S4>/Product3' // Sum: '<S4>/Sum' // Sum: '<S4>/Sum1' rtb_Gain[0] = (rtb_Gain8_idx_1 * rtb_Gain[2] - rtb_Gain8_idx_2 * rtb_Gain[1]) * 0.025063770565652812; rtb_Gain[1] = (rtb_Gain8_idx_2 * rtb_TrigonometricFunction5 - rtb_Gain8_idx_0 * rtb_Gain[2]) * 0.025063770565652812; // SignalConversion: '<S6>/ConcatBufferAtVector ConcatenateIn1' incorporates: // Constant: '<S6>/Constant3' // Gain: '<S6>/Gain' // Inport: '<Root>/angularvelocity' rtb_VectorConcatenate[0] = 0.0; rtb_VectorConcatenate[1] = rtU.w[2]; rtb_VectorConcatenate[2] = -rtU.w[1]; // SignalConversion: '<S6>/ConcatBufferAtVector ConcatenateIn2' incorporates: // Constant: '<S6>/Constant3' // Gain: '<S6>/Gain1' // Inport: '<Root>/angularvelocity' rtb_VectorConcatenate[3] = -rtU.w[2]; rtb_VectorConcatenate[4] = 0.0; rtb_VectorConcatenate[5] = rtU.w[0]; // SignalConversion: '<S6>/ConcatBufferAtVector ConcatenateIn3' incorporates: // Constant: '<S6>/Constant3' // Gain: '<S6>/Gain2' // Inport: '<Root>/angularvelocity' rtb_VectorConcatenate[6] = rtU.w[1]; rtb_VectorConcatenate[7] = -rtU.w[0]; rtb_VectorConcatenate[8] = 0.0; // Saturate: '<S2>/Saturation3' rtb_Gain8_idx_2 = rtb_Gain[0]; // Saturate: '<S2>/Saturation4' rtb_Saturation3 = rtb_Gain[1]; // Saturate: '<S2>/Saturation5' incorporates: // Gain: '<S2>/Gain' // Product: '<S4>/Product4' // Product: '<S4>/Product5' // Sum: '<S4>/Sum2' rtb_Gain8_idx_0 = (rtb_Gain8_idx_0 * rtb_TSamp_o - rtb_Gain8_idx_1 * rtb_Gain_0) * 0.025063770565652812; // Sqrt: '<S8>/Sqrt4' incorporates: // DotProduct: '<S8>/Dot Product6' // Inport: '<Root>/Bfield_body' rtb_Gain8_idx_1 = std::sqrt((rtU.Bfield_body[0] * rtU.Bfield_body[0] + rtU.Bfield_body[1] * rtU.Bfield_body[1]) + rtU.Bfield_body[2] * rtU.Bfield_body[2]); // DotProduct: '<S9>/Dot Product6' rtb_TSamp_o = 0.0; for (i = 0; i < 3; i++) { // Product: '<S3>/Product6' incorporates: // Inport: '<Root>/Bfield_body' // Product: '<S3>/Product4' rtb_TrigonometricFunction5 = ((rtConstB.VectorConcatenate[i + 3] * rtU.Bfield_body[1] + rtConstB.VectorConcatenate[i] * rtU.Bfield_body[0]) + rtConstB.VectorConcatenate[i + 6] * rtU.Bfield_body[2]) / rtb_Gain8_idx_1; // DotProduct: '<S9>/Dot Product6' rtb_TSamp_o += rtb_TrigonometricFunction5 * rtb_TrigonometricFunction5; // Product: '<S3>/Product6' incorporates: // Inport: '<Root>/Bfield_body' // Inport: '<Root>/angularvelocity' // Product: '<S11>/Product3' // Product: '<S3>/Product4' rtb_Gain[i] = rtU.w[i] * rtU.Bfield_body[i]; } // Sqrt: '<S9>/Sqrt4' incorporates: // DotProduct: '<S9>/Dot Product6' rtb_TrigonometricFunction5 = std::sqrt(rtb_TSamp_o); // Trigonometry: '<S3>/Trigonometric Function5' if (rtb_TrigonometricFunction5 > 1.0) { rtb_TrigonometricFunction5 = 1.0; } else { if (rtb_TrigonometricFunction5 < -1.0) { rtb_TrigonometricFunction5 = -1.0; } } rtb_TrigonometricFunction5 = std::asin(rtb_TrigonometricFunction5); // End of Trigonometry: '<S3>/Trigonometric Function5' // SampleTimeMath: '<S7>/TSamp' // // About '<S7>/TSamp': // y = u * K where K = 1 / ( w * Ts ) rtb_TSamp_o = rtb_TrigonometricFunction5 * 100.0; // Switch: '<S12>/Switch1' incorporates: // Constant: '<S12>/Constant10' // Constant: '<S12>/Constant9' // Inport: '<Root>/angularvelocity' if (rtU.w[2] >= 0.0) { i = 1; } else { i = -1; } // End of Switch: '<S12>/Switch1' // Switch: '<S11>/Switch' incorporates: // Constant: '<S11>/Constant3' // Constant: '<S11>/Constant4' // DotProduct: '<S13>/Dot Product6' // DotProduct: '<S14>/Dot Product6' // Inport: '<Root>/Bfield_body' // Inport: '<Root>/angularvelocity' // Product: '<S11>/Divide6' // Sqrt: '<S13>/Sqrt4' // Sqrt: '<S14>/Sqrt4' // Sum: '<S11>/Add' if (1.0 / std::sqrt((rtU.w[0] * rtU.w[0] + rtU.w[1] * rtU.w[1]) + rtU.w[2] * rtU.w[2]) * ((rtb_Gain[0] + rtb_Gain[1]) + rtb_Gain[2]) / std::sqrt((rtU.Bfield_body[0] * rtU.Bfield_body[0] + rtU.Bfield_body[1] * rtU.Bfield_body[1]) + rtU.Bfield_body[2] * rtU.Bfield_body[2]) > 0.0) { tmp = 1; } else { tmp = -1; } // End of Switch: '<S11>/Switch' // Product: '<S3>/Product7' incorporates: // Gain: '<S3>/Gain10' // Gain: '<S3>/Gain11' // Product: '<S3>/Product8' // Sum: '<S3>/Sum7' // Sum: '<S7>/Diff' // UnitDelay: '<S7>/UD' // // Block description for '<S7>/Diff': // // Add in CPU // // Block description for '<S7>/UD': // // Store in Global RAM rtb_Gain8_idx_1 = ((rtb_TSamp_o - rtDW.UD_DSTATE_k) * 7.5058075858287763E-5 + 2.0910503844363048E-6 * rtb_TrigonometricFunction5) * (real_T)(i * tmp) / rtb_Gain8_idx_1; // Sum: '<S2>/Sum10' incorporates: // Constant: '<S2>/Identity matrix' // Product: '<S2>/Product1' for (i = 0; i < 3; i++) { rtb_VectorConcatenate_0[3 * i] = rtb_VectorConcatenate[3 * i] + rtConstP.Identitymatrix_Value[3 * i]; rtb_VectorConcatenate_0[1 + 3 * i] = rtb_VectorConcatenate[3 * i + 1] + rtConstP.Identitymatrix_Value[3 * i + 1]; rtb_VectorConcatenate_0[2 + 3 * i] = rtb_VectorConcatenate[3 * i + 2] + rtConstP.Identitymatrix_Value[3 * i + 2]; } // End of Sum: '<S2>/Sum10' for (i = 0; i < 3; i++) { // Update for DiscreteIntegrator: '<S2>/Discrete-Time Integrator' incorporates: // Gain: '<S2>/Gain 8' // Gain: '<S2>/Gain 9' // Gain: '<S2>/Id inverse' // Product: '<S2>/Product1' // Sum: '<S2>/Sum8' // Sum: '<S5>/Diff' // UnitDelay: '<S5>/UD' // // Block description for '<S5>/Diff': // // Add in CPU // // Block description for '<S5>/UD': // // Store in Global RAM rtDW.DiscreteTimeIntegrator_DSTATE[i] += ((0.0 - (rtb_TSamp[i] - rtDW.UD_DSTATE[i])) - ((121.13723637508934 * -rtb_Product1_i_idx_0 * 0.41837 * rtb_VectorConcatenate_0[i] + 121.13723637508934 * -rtb_Product1_i_idx_1 * 0.41837 * rtb_VectorConcatenate_0[i + 3]) + 121.13723637508934 * -rtb_Product1_f * 0.41837 * rtb_VectorConcatenate_0[i + 6])) * 0.01; // Update for UnitDelay: '<S5>/UD' // // Block description for '<S5>/UD': // // Store in Global RAM rtDW.UD_DSTATE[i] = rtb_TSamp[i]; } // Update for UnitDelay: '<S7>/UD' // // Block description for '<S7>/UD': // // Store in Global RAM rtDW.UD_DSTATE_k = rtb_TSamp_o; // Saturate: '<S2>/Saturation3' if (rtb_Gain8_idx_2 > 0.00050127541131305623) { // Outport: '<Root>/detumble' rtY.detumble[0] = 0.00050127541131305623; } else if (rtb_Gain8_idx_2 < -0.00050127541131305623) { // Outport: '<Root>/detumble' rtY.detumble[0] = -0.00050127541131305623; } else { // Outport: '<Root>/detumble' rtY.detumble[0] = rtb_Gain8_idx_2; } // Saturate: '<S2>/Saturation4' if (rtb_Saturation3 > 0.00050127541131305623) { // Outport: '<Root>/detumble' rtY.detumble[1] = 0.00050127541131305623; } else if (rtb_Saturation3 < -0.00050127541131305623) { // Outport: '<Root>/detumble' rtY.detumble[1] = -0.00050127541131305623; } else { // Outport: '<Root>/detumble' rtY.detumble[1] = rtb_Saturation3; } // Saturate: '<S2>/Saturation5' if (rtb_Gain8_idx_0 > 0.00050127541131305623) { // Outport: '<Root>/detumble' rtY.detumble[2] = 0.00050127541131305623; } else if (rtb_Gain8_idx_0 < -0.00050127541131305623) { // Outport: '<Root>/detumble' rtY.detumble[2] = -0.00050127541131305623; } else { // Outport: '<Root>/detumble' rtY.detumble[2] = rtb_Gain8_idx_0; } // Outport: '<Root>/point' incorporates: // Saturate: '<S3>/Saturation3' // Saturate: '<S3>/Saturation4' rtY.point[0] = 0.0; rtY.point[1] = 0.0; // Saturate: '<S3>/Saturation5' incorporates: // Gain: '<S3>/Gain' rtb_Gain8_idx_2 = 0.025063770565652812 * rtb_Gain8_idx_1; if (rtb_Gain8_idx_2 > 0.00050127541131305623) { // Outport: '<Root>/point' rtY.point[2] = 0.00050127541131305623; } else if (rtb_Gain8_idx_2 < -0.00050127541131305623) { // Outport: '<Root>/point' rtY.point[2] = -0.00050127541131305623; } else { // Outport: '<Root>/point' rtY.point[2] = rtb_Gain8_idx_2; } // End of Saturate: '<S3>/Saturation5' // End of Outputs for SubSystem: '<Root>/StarshotACS' } // Model initialize function void StarshotACS1ModelClass::initialize() { // (no initialization code required) } // Constructor StarshotACS1ModelClass::StarshotACS1ModelClass() { } // Destructor StarshotACS1ModelClass::~StarshotACS1ModelClass() { // Currently there is no destructor body generated. } // Real-Time Model get method RT_MODEL * StarshotACS1ModelClass::getRTM() { return (&rtM); } // // File trailer for generated code. // // [EOF] //
29.349315
83
0.629094
Natsoulas
1bbb6e029620e5e3a94d0818b318f66b513abf15
49,004
cpp
C++
src/vulkan/scene.cpp
shacklettbp/rlpbr
5d6f65ca223fccb6abeb56c63b3043eef46abf57
[ "MIT" ]
13
2022-02-04T19:26:47.000Z
2022-02-22T09:37:51.000Z
src/vulkan/scene.cpp
shacklettbp/rlpbr
5d6f65ca223fccb6abeb56c63b3043eef46abf57
[ "MIT" ]
null
null
null
src/vulkan/scene.cpp
shacklettbp/rlpbr
5d6f65ca223fccb6abeb56c63b3043eef46abf57
[ "MIT" ]
null
null
null
#include "scene.hpp" #include <vulkan/vulkan_core.h> #include "rlpbr_core/utils.hpp" #include "shader.hpp" #include "utils.hpp" #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/string_cast.hpp> #include <cassert> #include <cstring> #include <iostream> #include <unordered_map> #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" using namespace std; namespace RLpbr { namespace vk { namespace InternalConfig { constexpr float reservoirCellSize = 1.f; } static ReservoirGrid makeReservoirGrid( const DeviceState &dev, MemoryAllocator &alloc, const VulkanScene &scene) { AABB bbox = scene.envInit.defaultBBox; // Round bbox size out to reservoirCellSize glm::vec3 min_remainder = glm::vec3( fmodf(bbox.pMin.x, InternalConfig::reservoirCellSize), fmodf(bbox.pMin.y, InternalConfig::reservoirCellSize), fmodf(bbox.pMin.z, InternalConfig::reservoirCellSize)); bbox.pMin -= min_remainder; glm::vec3 max_remainder = glm::vec3( fmodf(bbox.pMax.x, InternalConfig::reservoirCellSize), fmodf(bbox.pMax.y, InternalConfig::reservoirCellSize), fmodf(bbox.pMax.z, InternalConfig::reservoirCellSize)); bbox.pMax += 1.f - max_remainder; glm::vec3 bbox_size = bbox.pMax - bbox.pMin; glm::vec3 num_cells_frac = bbox_size / InternalConfig::reservoirCellSize; glm::u32vec3 num_cells = glm::ceil(num_cells_frac); uint32_t total_cells = num_cells.x * num_cells.y * num_cells.z; total_cells = 1; // FIXME auto [grid_buffer, grid_memory] = alloc.makeDedicatedBuffer(total_cells * sizeof(Reservoir), true); VkDeviceAddress dev_addr; VkBufferDeviceAddressInfo addr_info; addr_info.sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO; addr_info.pNext = nullptr; addr_info.buffer = grid_buffer.buffer; dev_addr = dev.dt.getBufferDeviceAddress(dev.hdl, &addr_info); return ReservoirGrid { bbox, grid_memory, dev_addr, move(grid_buffer), }; } VulkanEnvironment::VulkanEnvironment(const DeviceState &d, MemoryAllocator &alloc, const VulkanScene &scene, const Camera &cam) : EnvironmentBackend {}, lights(), dev(d), tlas(), reservoirGrid(makeReservoirGrid(dev, alloc, scene)), prevCam(cam) { for (const LightProperties &light : scene.envInit.lights) { PackedLight packed; memcpy(&packed.data.x, &light.type, sizeof(uint32_t)); if (light.type == LightType::Sphere) { packed.data.y = glm::uintBitsToFloat(light.sphereVertIdx); packed.data.z = glm::uintBitsToFloat(light.sphereMatIdx); packed.data.w = light.radius; } else if (light.type == LightType::Triangle) { packed.data.y = glm::uintBitsToFloat(light.triIdxOffset); packed.data.z = glm::uintBitsToFloat(light.triMatIdx); } else if (light.type == LightType::Portal) { packed.data.y = glm::uintBitsToFloat(light.portalIdxOffset); } lights.push_back(packed); } } VulkanEnvironment::~VulkanEnvironment() { tlas.free(dev); } uint32_t VulkanEnvironment::addLight(const glm::vec3 &position, const glm::vec3 &color) { // FIXME (void)position; (void)color; lights.push_back(PackedLight { }); return lights.size() - 1; } void VulkanEnvironment::removeLight(uint32_t idx) { lights[idx] = lights.back(); lights.pop_back(); } VulkanLoader::VulkanLoader(const DeviceState &d, MemoryAllocator &alc, const QueueState &transfer_queue, const QueueState &render_queue, VkDescriptorSet scene_set, uint32_t render_qf, uint32_t max_texture_resolution) : VulkanLoader(d, alc, transfer_queue, render_queue, nullptr, scene_set, render_qf, max_texture_resolution) {} VulkanLoader::VulkanLoader(const DeviceState &d, MemoryAllocator &alc, const QueueState &transfer_queue, const QueueState &render_queue, SharedSceneState &shared_scene_state, uint32_t render_qf, uint32_t max_texture_resolution) : VulkanLoader(d, alc, transfer_queue, render_queue, &shared_scene_state, shared_scene_state.descSet, render_qf, max_texture_resolution) {} VulkanLoader::VulkanLoader(const DeviceState &d, MemoryAllocator &alc, const QueueState &transfer_queue, const QueueState &render_queue, SharedSceneState *shared_scene_state, VkDescriptorSet scene_set, uint32_t render_qf, uint32_t max_texture_resolution) : dev(d), alloc(alc), transfer_queue_(transfer_queue), render_queue_(render_queue), shared_scene_state_(shared_scene_state), scene_set_(scene_set), transfer_cmd_pool_(makeCmdPool(d, d.transferQF)), transfer_cmd_(makeCmdBuffer(dev, transfer_cmd_pool_)), render_cmd_pool_(makeCmdPool(d, render_qf)), render_cmd_(makeCmdBuffer(dev, render_cmd_pool_)), transfer_sema_(makeBinarySemaphore(dev)), fence_(makeFence(dev)), render_qf_(render_qf), max_texture_resolution_(max_texture_resolution) {} TextureData::TextureData(const DeviceState &d, MemoryAllocator &a) : dev(d), alloc(a), memory(VK_NULL_HANDLE), textures(), views() {} TextureData::TextureData(TextureData &&o) : dev(o.dev), alloc(o.alloc), memory(o.memory), textures(move(o.textures)), views(move(o.views)) { o.memory = VK_NULL_HANDLE; } TextureData::~TextureData() { if (memory == VK_NULL_HANDLE) return; for (auto view : views) { dev.dt.destroyImageView(dev.hdl, view, nullptr); } for (auto &texture : textures) { alloc.destroyTexture(move(texture)); } dev.dt.freeMemory(dev.hdl, memory, nullptr); } static tuple<uint8_t *, uint32_t, glm::u32vec2, uint32_t, float> loadTextureFromDisk(const string &tex_path, uint32_t texel_bytes, uint32_t max_texture_resolution) { ifstream tex_file(tex_path, ios::in | ios::binary); auto read_uint = [&tex_file]() { uint32_t v; tex_file.read((char *)&v, sizeof(uint32_t)); return v; }; auto magic = read_uint(); if (magic != 0x50505050) { cerr << "Invalid texture file" << endl; abort(); } auto total_num_levels = read_uint(); uint32_t x = 0; uint32_t y = 0; uint32_t num_compressed_bytes = 0; uint32_t num_decompressed_bytes = 0; uint32_t skip_bytes = 0; vector<pair<uint32_t, uint32_t>> png_pos; png_pos.reserve(total_num_levels); uint32_t num_skip_levels = 0; for (int i = 0; i < (int)total_num_levels; i++) { uint32_t level_x = read_uint(); uint32_t level_y = read_uint(); uint32_t offset = read_uint(); uint32_t lvl_compressed_bytes = read_uint(); if (level_x > max_texture_resolution && level_y > max_texture_resolution) { skip_bytes += lvl_compressed_bytes; num_skip_levels++; continue; } if (x == 0 && y == 0) { x = level_x; y = level_y; } png_pos.emplace_back(offset - skip_bytes, lvl_compressed_bytes); num_decompressed_bytes += level_x * level_y * texel_bytes; num_compressed_bytes += lvl_compressed_bytes; } int num_levels = total_num_levels - num_skip_levels; uint8_t *img_data = (uint8_t *)malloc(num_decompressed_bytes); tex_file.ignore(skip_bytes); uint8_t *compressed_data = (uint8_t *)malloc(num_compressed_bytes); tex_file.read((char *)compressed_data, num_compressed_bytes); uint32_t cur_offset = 0; for (int i = 0; i < (int)num_levels; i++) { auto [offset, num_bytes] = png_pos[i]; int lvl_x, lvl_y, tmp_n; uint8_t *decompressed = stbi_load_from_memory( compressed_data + offset, num_bytes, &lvl_x, &lvl_y, &tmp_n, 4); cur_offset = alignOffset(cur_offset, texel_bytes); for (int pix_idx = 0; pix_idx < int(lvl_x * lvl_y); pix_idx++) { uint8_t *decompressed_offset = decompressed + pix_idx * 4; uint8_t *out_offset = img_data + cur_offset + pix_idx * texel_bytes; for (int byte_idx = 0; byte_idx < (int)texel_bytes; byte_idx++) { out_offset[byte_idx] = decompressed_offset[byte_idx]; } } free(decompressed); cur_offset += lvl_x * lvl_y * texel_bytes; } assert(cur_offset == num_decompressed_bytes); free(compressed_data); return make_tuple(img_data, num_decompressed_bytes, glm::u32vec2(x, y), num_levels, -float(num_skip_levels)); } static tuple<void *, uint64_t, glm::u32vec3, void *, uint64_t, glm::u32vec3> loadEnvironmentMapFromDisk(const string &env_path) { ifstream tex_file(env_path, ios::in | ios::binary); auto read_uint = [&tex_file]() { uint32_t v; tex_file.read((char *)&v, sizeof(uint32_t)); return v; }; uint32_t num_env_mips = read_uint(); uint32_t env_width = read_uint(); uint32_t env_height = read_uint(); uint64_t env_bytes; tex_file.read((char *)&env_bytes, sizeof(uint64_t)); void *env_staging = malloc(env_bytes); tex_file.read((char *)env_staging, env_bytes); uint32_t num_imp_mips = read_uint(); uint32_t imp_width = read_uint(); uint32_t imp_height = read_uint(); assert(imp_width == imp_height); uint64_t imp_bytes; tex_file.read((char *)&imp_bytes, sizeof(uint64_t)); void *imp_staging = malloc(imp_bytes); tex_file.read((char *)imp_staging, imp_bytes); return { env_staging, env_bytes, { env_width, env_height, num_env_mips }, imp_staging, imp_bytes, { imp_width, imp_height, num_imp_mips }, }; } struct StagedTextures { HostBuffer stageBuffer; VkDeviceMemory texMemory; vector<size_t> stageOffsets; vector<LocalTexture> textures; vector<VkImageView> textureViews; vector<uint32_t> textureTexelBytes; vector<uint32_t> base; vector<uint32_t> metallicRoughness; vector<uint32_t> specular; vector<uint32_t> normal; vector<uint32_t> emittance; vector<uint32_t> transmission; vector<uint32_t> clearcoat; vector<uint32_t> anisotropic; optional<uint32_t> envMap; optional<uint32_t> importanceMap; }; static optional<StagedTextures> prepareSceneTextures(const DeviceState &dev, const TextureInfo &texture_info, uint32_t max_texture_resolution, MemoryAllocator &alloc) { uint32_t num_textures = texture_info.base.size() + texture_info.metallicRoughness.size() + texture_info.specular.size() + texture_info.normal.size() + texture_info.emittance.size() + texture_info.transmission.size() + texture_info.clearcoat.size() + texture_info.anisotropic.size(); if (!texture_info.envMap.empty()) { num_textures += 2; } if (num_textures == 0) { return optional<StagedTextures>(); } vector<void *> host_ptrs; vector<uint32_t> host_sizes; vector<size_t> stage_offsets; vector<LocalTexture> gpu_textures; vector<VkFormat> texture_formats; vector<uint32_t> texture_texel_bytes; vector<size_t> texture_offsets; vector<VkImageView> texture_views; host_ptrs.reserve(num_textures); host_sizes.reserve(num_textures); stage_offsets.reserve(num_textures); gpu_textures.reserve(num_textures); texture_formats.reserve(num_textures); texture_texel_bytes.reserve(num_textures); texture_offsets.reserve(num_textures); texture_views.reserve(num_textures); size_t cur_tex_offset = 0; auto stageTexture = [&](void *img_data, uint32_t img_bytes, uint32_t width, uint32_t height, uint32_t num_levels, VkFormat fmt, uint32_t texel_bytes) { host_ptrs.push_back(img_data); host_sizes.push_back(img_bytes); auto [gpu_tex, tex_reqs] = alloc.makeTexture2D(width, height, num_levels, fmt); gpu_textures.emplace_back(move(gpu_tex)); texture_formats.push_back(fmt); texture_texel_bytes.push_back(texel_bytes); cur_tex_offset = alignOffset(cur_tex_offset, tex_reqs.alignment); texture_offsets.push_back(cur_tex_offset); cur_tex_offset += tex_reqs.size; return gpu_textures.size() - 1; }; auto stageTextureList = [&](const vector<string> &texture_names, TextureFormat orig_fmt) { vector<uint32_t> tex_locs; tex_locs.reserve(texture_names.size()); uint32_t texel_bytes = getTexelBytes(orig_fmt); VkFormat fmt = alloc.getTextureFormat(orig_fmt); for (const string &tex_name : texture_names) { auto [img_data, num_stage_bytes, dims, num_levels, bias] = loadTextureFromDisk(texture_info.textureDir + tex_name, texel_bytes, max_texture_resolution); tex_locs.push_back( stageTexture(img_data, num_stage_bytes, dims.x, dims.y, num_levels, fmt, texel_bytes)); } return tex_locs; }; TextureFormat fourCompSRGB = TextureFormat::R8G8B8A8_SRGB; TextureFormat twoCompUnorm = TextureFormat::R8G8_UNORM; auto base_locs = stageTextureList(texture_info.base, fourCompSRGB); auto mr_locs = stageTextureList(texture_info.metallicRoughness, twoCompUnorm); auto specular_locs = stageTextureList(texture_info.specular, fourCompSRGB); auto normal_locs = stageTextureList(texture_info.normal, twoCompUnorm); auto emittance_locs = stageTextureList(texture_info.emittance, fourCompSRGB); auto transmission_locs = stageTextureList(texture_info.transmission, TextureFormat::R8_UNORM); auto clearcoat_locs = stageTextureList(texture_info.clearcoat, twoCompUnorm); auto anisotropic_locs = stageTextureList(texture_info.anisotropic, twoCompUnorm); optional<uint32_t> env_loc; optional<uint32_t> env_importance_loc; if (!texture_info.envMap.empty()) { string env_path = texture_info.textureDir + texture_info.envMap; auto [env_data, env_data_bytes, env_dims, imp_data, imp_data_bytes, imp_dims] = loadEnvironmentMapFromDisk( env_path); env_loc = stageTexture(env_data, env_data_bytes, env_dims.x, env_dims.y, env_dims.z, alloc.getTextureFormat(TextureFormat::R32G32B32A32_SFLOAT), getTexelBytes(TextureFormat::R32G32B32A32_SFLOAT)); env_importance_loc = stageTexture(imp_data, imp_data_bytes, imp_dims.x, imp_dims.y, imp_dims.z, alloc.getTextureFormat(TextureFormat::R32_SFLOAT), getTexelBytes(TextureFormat::R32_SFLOAT)); } size_t num_device_bytes = cur_tex_offset; size_t num_staging_bytes = 0; for (int i = 0; i < (int)host_sizes.size(); i++) { uint32_t num_bytes = host_sizes[i]; uint32_t texel_bytes = texture_texel_bytes[i]; uint32_t alignment = max(texel_bytes, 4u); num_staging_bytes = alignOffset(num_staging_bytes, alignment); stage_offsets.push_back(num_staging_bytes); num_staging_bytes += num_bytes; } HostBuffer texture_staging = alloc.makeStagingBuffer(num_staging_bytes); for (int i = 0 ; i < (int)num_textures; i++) { char *cur_ptr = (char *)texture_staging.ptr + stage_offsets[i]; memcpy(cur_ptr, host_ptrs[i], host_sizes[i]); free(host_ptrs[i]); } texture_staging.flush(dev); optional<VkDeviceMemory> tex_mem_opt = alloc.alloc(num_device_bytes); if (!tex_mem_opt.has_value()) { cerr << "Out of memory, failed to allocate texture memory" << endl; fatalExit(); } VkDeviceMemory tex_mem = tex_mem_opt.value(); // Bind image memory and create views for (uint32_t i = 0; i < num_textures; i++) { LocalTexture &gpu_texture = gpu_textures[i]; VkDeviceSize offset = texture_offsets[i]; REQ_VK(dev.dt.bindImageMemory(dev.hdl, gpu_texture.image, tex_mem, offset)); VkImageViewCreateInfo view_info; view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; view_info.pNext = nullptr; view_info.flags = 0; view_info.image = gpu_texture.image; view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; view_info.format = texture_formats[i]; view_info.components = { VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A, }; view_info.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, gpu_texture.mipLevels, 0, 1, }; VkImageView view; REQ_VK(dev.dt.createImageView(dev.hdl, &view_info, nullptr, &view)); texture_views.push_back(view); } return StagedTextures { move(texture_staging), tex_mem, move(stage_offsets), move(gpu_textures), move(texture_views), move(texture_texel_bytes), move(base_locs), move(mr_locs), move(specular_locs), move(normal_locs), move(emittance_locs), move(transmission_locs), move(clearcoat_locs), move(anisotropic_locs), move(env_loc), move(env_importance_loc), }; } BLASData::~BLASData() { for (const auto &blas : accelStructs) { dev.dt.destroyAccelerationStructureKHR(dev.hdl, blas.hdl, nullptr); } } static optional<tuple<BLASData, LocalBuffer, VkDeviceSize>> makeBLASes( const DeviceState &dev, MemoryAllocator &alloc, const std::vector<MeshInfo> &meshes, const std::vector<ObjectInfo> &objects, uint32_t max_num_vertices, VkDeviceAddress vert_base, VkDeviceAddress index_base, VkCommandBuffer build_cmd) { vector<VkAccelerationStructureGeometryKHR> geo_infos; vector<uint32_t> num_triangles; vector<VkAccelerationStructureBuildRangeInfoKHR> range_infos; geo_infos.reserve(meshes.size()); num_triangles.reserve(meshes.size()); range_infos.reserve(meshes.size()); vector<VkAccelerationStructureBuildGeometryInfoKHR> build_infos; vector<tuple<VkDeviceSize, VkDeviceSize, VkDeviceSize>> memory_locs; build_infos.reserve(objects.size()); memory_locs.reserve(objects.size()); VkDeviceSize total_scratch_bytes = 0; VkDeviceSize total_accel_bytes = 0; for (const ObjectInfo &object : objects) { for (int mesh_idx = 0; mesh_idx < (int)object.numMeshes; mesh_idx++) { const MeshInfo &mesh = meshes[object.meshIndex + mesh_idx]; VkDeviceAddress vert_addr = vert_base; VkDeviceAddress index_addr = index_base + mesh.indexOffset * sizeof(uint32_t); VkAccelerationStructureGeometryKHR geo_info; geo_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR; geo_info.pNext = nullptr; geo_info.geometryType = VK_GEOMETRY_TYPE_TRIANGLES_KHR; geo_info.flags = VK_GEOMETRY_OPAQUE_BIT_KHR; auto &tri_info = geo_info.geometry.triangles; tri_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_TRIANGLES_DATA_KHR; tri_info.pNext = nullptr; tri_info.vertexFormat = VK_FORMAT_R32G32B32_SFLOAT; tri_info.vertexData.deviceAddress = vert_addr; tri_info.vertexStride = sizeof(Vertex); tri_info.maxVertex = max_num_vertices; tri_info.indexType = VK_INDEX_TYPE_UINT32; tri_info.indexData.deviceAddress = index_addr; tri_info.transformData.deviceAddress = 0; geo_infos.push_back(geo_info); num_triangles.push_back(mesh.numTriangles); VkAccelerationStructureBuildRangeInfoKHR range_info; range_info.primitiveCount = mesh.numTriangles; range_info.primitiveOffset = 0; range_info.firstVertex = 0; range_info.transformOffset = 0; range_infos.push_back(range_info); } VkAccelerationStructureBuildGeometryInfoKHR build_info; build_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR; build_info.pNext = nullptr; build_info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR; build_info.flags = VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR; build_info.mode = VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR; build_info.srcAccelerationStructure = VK_NULL_HANDLE; build_info.dstAccelerationStructure = VK_NULL_HANDLE; build_info.geometryCount = object.numMeshes; build_info.pGeometries = &geo_infos[object.meshIndex]; build_info.ppGeometries = nullptr; // Set device address to 0 before space calculation build_info.scratchData.deviceAddress = 0; build_infos.push_back(build_info); VkAccelerationStructureBuildSizesInfoKHR size_info; size_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR; size_info.pNext = nullptr; dev.dt.getAccelerationStructureBuildSizesKHR( dev.hdl, VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR, &build_infos.back(), &num_triangles[object.meshIndex], &size_info); // Must be aligned to 256 as per spec total_accel_bytes = alignOffset(total_accel_bytes, 256); memory_locs.emplace_back(total_scratch_bytes, total_accel_bytes, size_info.accelerationStructureSize); total_scratch_bytes += size_info.buildScratchSize; total_accel_bytes += size_info.accelerationStructureSize; } optional<LocalBuffer> scratch_mem_opt = alloc.makeLocalBuffer(total_scratch_bytes, true); optional<LocalBuffer> accel_mem_opt = alloc.makeLocalBuffer(total_accel_bytes, true); if (!scratch_mem_opt.has_value() || !accel_mem_opt.has_value()) { return {}; } LocalBuffer &scratch_mem = scratch_mem_opt.value(); LocalBuffer &accel_mem = accel_mem_opt.value(); VkBufferDeviceAddressInfoKHR scratch_addr_info; scratch_addr_info.sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO_KHR; scratch_addr_info.pNext = nullptr; scratch_addr_info.buffer = scratch_mem.buffer; VkDeviceAddress scratch_base_addr = dev.dt.getBufferDeviceAddress(dev.hdl, &scratch_addr_info); vector<BLAS> accel_structs; vector<VkAccelerationStructureBuildRangeInfoKHR *> range_info_ptrs; accel_structs.reserve(objects.size()); range_info_ptrs.reserve(objects.size()); for (int obj_idx = 0; obj_idx < (int)objects.size(); obj_idx++) { VkAccelerationStructureCreateInfoKHR create_info; create_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR; create_info.pNext = nullptr; create_info.createFlags = 0; create_info.buffer = accel_mem.buffer; create_info.offset = get<1>(memory_locs[obj_idx]); create_info.size = get<2>(memory_locs[obj_idx]); create_info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR; create_info.deviceAddress = 0; VkAccelerationStructureKHR blas; REQ_VK(dev.dt.createAccelerationStructureKHR(dev.hdl, &create_info, nullptr, &blas)); auto &build_info = build_infos[obj_idx]; build_info.dstAccelerationStructure = blas; build_info.scratchData.deviceAddress = scratch_base_addr + get<0>(memory_locs[obj_idx]); VkAccelerationStructureDeviceAddressInfoKHR addr_info; addr_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_DEVICE_ADDRESS_INFO_KHR; addr_info.pNext = nullptr; addr_info.accelerationStructure = blas; VkDeviceAddress dev_addr = dev.dt.getAccelerationStructureDeviceAddressKHR(dev.hdl, &addr_info); accel_structs.push_back({ blas, dev_addr, }); range_info_ptrs.push_back(&range_infos[objects[obj_idx].meshIndex]); } dev.dt.cmdBuildAccelerationStructuresKHR(build_cmd, build_infos.size(), build_infos.data(), range_info_ptrs.data()); return make_tuple( BLASData { dev, move(accel_structs), move(accel_mem), }, move(scratch_mem), total_accel_bytes); } void TLAS::build(const DeviceState &dev, MemoryAllocator &alloc, const vector<ObjectInstance> &instances, const vector<InstanceTransform> &instance_transforms, const vector<InstanceFlags> &instance_flags, const vector<ObjectInfo> &objects, const BLASData &blases, VkCommandBuffer build_cmd) { int new_num_instances = instances.size(); if ((int)numBuildInstances < new_num_instances) { numBuildInstances = new_num_instances; buildStorage = alloc.makeHostBuffer( sizeof(VkAccelerationStructureInstanceKHR) * numBuildInstances, true); } VkAccelerationStructureInstanceKHR *accel_insts = reinterpret_cast<VkAccelerationStructureInstanceKHR *>( buildStorage->ptr); for (int inst_idx = 0; inst_idx < new_num_instances; inst_idx++) { const ObjectInstance &inst = instances[inst_idx]; const InstanceTransform &txfm = instance_transforms[inst_idx]; VkAccelerationStructureInstanceKHR &inst_info = accel_insts[inst_idx]; memcpy(&inst_info.transform, glm::value_ptr(glm::transpose(txfm.mat)), sizeof(VkTransformMatrixKHR)); if (instance_flags[inst_idx] & InstanceFlags::Transparent) { inst_info.mask = 2; } else { inst_info.mask = 1; } inst_info.instanceCustomIndex = inst.materialOffset; inst_info.instanceShaderBindingTableRecordOffset = objects[inst.objectIndex].meshIndex; inst_info.flags = 0; inst_info.accelerationStructureReference = blases.accelStructs[inst.objectIndex].devAddr; } buildStorage->flush(dev); VkBufferDeviceAddressInfo inst_build_addr_info { VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, buildStorage->buffer, }; VkDeviceAddress inst_build_data_addr = dev.dt.getBufferDeviceAddress(dev.hdl, &inst_build_addr_info); VkAccelerationStructureGeometryKHR tlas_geometry; tlas_geometry.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR; tlas_geometry.pNext = nullptr; tlas_geometry.geometryType = VK_GEOMETRY_TYPE_INSTANCES_KHR; tlas_geometry.flags = 0; auto &tlas_instances = tlas_geometry.geometry.instances; tlas_instances.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_INSTANCES_DATA_KHR; tlas_instances.pNext = nullptr; tlas_instances.arrayOfPointers = false; tlas_instances.data.deviceAddress = inst_build_data_addr; VkAccelerationStructureBuildGeometryInfoKHR build_info; build_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR; build_info.pNext = nullptr; build_info.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR; build_info.flags = VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR; build_info.mode = VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR; build_info.srcAccelerationStructure = VK_NULL_HANDLE; build_info.dstAccelerationStructure = VK_NULL_HANDLE; build_info.geometryCount = 1; build_info.pGeometries = &tlas_geometry; build_info.ppGeometries = nullptr; build_info.scratchData.deviceAddress = 0; VkAccelerationStructureBuildSizesInfoKHR size_info; size_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR; size_info.pNext = nullptr; dev.dt.getAccelerationStructureBuildSizesKHR(dev.hdl, VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR, &build_info, &numBuildInstances, &size_info); size_t new_storage_bytes = size_info.accelerationStructureSize + size_info.buildScratchSize; if (new_storage_bytes > numStorageBytes) { numStorageBytes = new_storage_bytes; tlasStorage = alloc.makeLocalBuffer(numStorageBytes, true); if (!tlasStorage.has_value()) { cerr << "Failed to allocate TLAS storage" << endl; fatalExit(); } } VkAccelerationStructureCreateInfoKHR create_info; create_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR; create_info.pNext = nullptr; create_info.createFlags = 0; create_info.buffer = tlasStorage->buffer; create_info.offset = 0; create_info.size = size_info.accelerationStructureSize; create_info.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR; create_info.deviceAddress = 0; REQ_VK(dev.dt.createAccelerationStructureKHR(dev.hdl, &create_info, nullptr, &hdl)); VkAccelerationStructureDeviceAddressInfoKHR accel_addr_info; accel_addr_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_DEVICE_ADDRESS_INFO_KHR; accel_addr_info.pNext = nullptr; accel_addr_info.accelerationStructure = hdl; tlasStorageDevAddr = dev.dt.getAccelerationStructureDeviceAddressKHR( dev.hdl, &accel_addr_info); VkBufferDeviceAddressInfoKHR storage_addr_info; storage_addr_info.sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO_KHR; storage_addr_info.pNext = nullptr; storage_addr_info.buffer = tlasStorage->buffer; VkDeviceAddress storage_base = dev.dt.getBufferDeviceAddress(dev.hdl, &storage_addr_info); build_info.dstAccelerationStructure = hdl; build_info.scratchData.deviceAddress = storage_base + size_info.accelerationStructureSize; VkAccelerationStructureBuildRangeInfoKHR range_info; range_info.primitiveCount = numBuildInstances; range_info.primitiveOffset = 0; range_info.firstVertex = 0; range_info.transformOffset = 0; const auto *range_info_ptr = &range_info; dev.dt.cmdBuildAccelerationStructuresKHR(build_cmd, 1, &build_info, &range_info_ptr); } void TLAS::free(const DeviceState &dev) { dev.dt.destroyAccelerationStructureKHR(dev.hdl, hdl, nullptr); } SharedSceneState::SharedSceneState(const DeviceState &dev, VkDescriptorPool scene_pool, VkDescriptorSetLayout scene_layout, MemoryAllocator &alloc) : lock(), descSet(makeDescriptorSet(dev, scene_pool, scene_layout)), addrData([&]() { size_t num_addr_bytes = sizeof(SceneAddresses) * VulkanConfig::max_scenes; HostBuffer addr_data = alloc.makeParamBuffer(num_addr_bytes); VkDescriptorBufferInfo addr_buf_info { addr_data.buffer, 0, num_addr_bytes, }; DescriptorUpdates desc_update(1); desc_update.uniform(descSet, &addr_buf_info, 0); desc_update.update(dev); return addr_data; }()), freeSceneIDs(), numSceneIDs(0) {} SceneID::SceneID(SharedSceneState &shared) : shared_(&shared), id_([&]() { if (shared_->freeSceneIDs.size() > 0) { uint32_t id = shared_->freeSceneIDs.back(); shared_->freeSceneIDs.pop_back(); return id; } else { return shared_->numSceneIDs++; } }()) {} SceneID::SceneID(SceneID &&o) : shared_(o.shared_), id_(o.id_) { o.shared_ = nullptr; } SceneID::~SceneID() { if (shared_ == nullptr) return; lock_guard<mutex> lock(shared_->lock); shared_->freeSceneIDs.push_back(id_); } shared_ptr<Scene> VulkanLoader::loadScene(SceneLoadData &&load_info) { TextureData texture_store(dev, alloc); vector<LocalTexture> &gpu_textures = texture_store.textures; vector<VkImageView> &texture_views = texture_store.views; optional<StagedTextures> staged_textures = prepareSceneTextures(dev, load_info.textureInfo, max_texture_resolution_, alloc); uint32_t num_textures = staged_textures.has_value() ? staged_textures->textures.size() : 0; if (num_textures > 0) { texture_store.memory = staged_textures->texMemory; gpu_textures = move(staged_textures->textures); texture_views = move(staged_textures->textureViews); } // Copy all geometry into single buffer optional<LocalBuffer> data_opt = alloc.makeLocalBuffer(load_info.hdr.totalBytes, true); if (!data_opt.has_value()) { cerr << "Out of memory, failed to allocate geometry storage" << endl; fatalExit(); } LocalBuffer data = move(data_opt.value()); HostBuffer data_staging = alloc.makeStagingBuffer(load_info.hdr.totalBytes); if (holds_alternative<ifstream>(load_info.data)) { ifstream &file = *get_if<ifstream>(&load_info.data); file.read((char *)data_staging.ptr, load_info.hdr.totalBytes); } else { char *data_src = get_if<vector<char>>(&load_info.data)->data(); memcpy(data_staging.ptr, data_src, load_info.hdr.totalBytes); } // Reset command buffers REQ_VK(dev.dt.resetCommandPool(dev.hdl, transfer_cmd_pool_, 0)); REQ_VK(dev.dt.resetCommandPool(dev.hdl, render_cmd_pool_, 0)); // Start recording for transfer queue VkCommandBufferBeginInfo begin_info {}; begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; REQ_VK(dev.dt.beginCommandBuffer(transfer_cmd_, &begin_info)); // Copy vertex/index buffer onto GPU VkBufferCopy copy_settings {}; copy_settings.size = load_info.hdr.totalBytes; dev.dt.cmdCopyBuffer(transfer_cmd_, data_staging.buffer, data.buffer, 1, &copy_settings); // Set initial texture layouts DynArray<VkImageMemoryBarrier> texture_barriers(num_textures); for (size_t i = 0; i < num_textures; i++) { const LocalTexture &gpu_texture = gpu_textures[i]; VkImageMemoryBarrier &barrier = texture_barriers[i]; barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barrier.pNext = nullptr; barrier.srcAccessMask = 0; barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.image = gpu_texture.image; barrier.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, gpu_texture.mipLevels, 0, 1, }; } if (num_textures > 0) { dev.dt.cmdPipelineBarrier( transfer_cmd_, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, texture_barriers.size(), texture_barriers.data()); // Record cpu -> gpu copies vector<VkBufferImageCopy> copy_infos; for (size_t i = 0; i < num_textures; i++) { const LocalTexture &gpu_texture = gpu_textures[i]; uint32_t base_width = gpu_texture.width; uint32_t base_height = gpu_texture.height; uint32_t num_levels = gpu_texture.mipLevels; uint32_t texel_bytes = staged_textures->textureTexelBytes[i]; copy_infos.resize(num_levels); size_t cur_lvl_offset = staged_textures->stageOffsets[i]; for (uint32_t level = 0; level < num_levels; level++) { uint32_t level_div = 1 << level; uint32_t level_width = max(1U, base_width / level_div); uint32_t level_height = max(1U, base_height / level_div); cur_lvl_offset = alignOffset(cur_lvl_offset, texel_bytes); // Set level copy VkBufferImageCopy copy_info {}; copy_info.bufferOffset = cur_lvl_offset; copy_info.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; copy_info.imageSubresource.mipLevel = level; copy_info.imageSubresource.baseArrayLayer = 0; copy_info.imageSubresource.layerCount = 1; copy_info.imageExtent = { level_width, level_height, 1, }; copy_infos[level] = copy_info; cur_lvl_offset += level_width * level_height * texel_bytes; } dev.dt.cmdCopyBufferToImage( transfer_cmd_, staged_textures->stageBuffer.buffer, gpu_texture.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, copy_infos.size(), copy_infos.data()); } // Transfer queue relinquish texture barriers for (VkImageMemoryBarrier &barrier : texture_barriers) { barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; barrier.dstAccessMask = 0; barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; barrier.srcQueueFamilyIndex = dev.transferQF; barrier.dstQueueFamilyIndex = render_qf_; } } // Transfer queue relinquish geometry VkBufferMemoryBarrier geometry_barrier; geometry_barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; geometry_barrier.pNext = nullptr; geometry_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; geometry_barrier.dstAccessMask = 0; geometry_barrier.srcQueueFamilyIndex = dev.transferQF; geometry_barrier.dstQueueFamilyIndex = render_qf_; geometry_barrier.buffer = data.buffer; geometry_barrier.offset = 0; geometry_barrier.size = load_info.hdr.totalBytes; // Geometry & texture barrier execute. dev.dt.cmdPipelineBarrier( transfer_cmd_, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 1, &geometry_barrier, texture_barriers.size(), texture_barriers.data()); REQ_VK(dev.dt.endCommandBuffer(transfer_cmd_)); VkSubmitInfo copy_submit {}; copy_submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; copy_submit.waitSemaphoreCount = 0; copy_submit.pWaitSemaphores = nullptr; copy_submit.pWaitDstStageMask = nullptr; copy_submit.commandBufferCount = 1; copy_submit.pCommandBuffers = &transfer_cmd_; copy_submit.signalSemaphoreCount = 1; copy_submit.pSignalSemaphores = &transfer_sema_; transfer_queue_.submit(dev, 1, &copy_submit, VK_NULL_HANDLE); // Start recording for transferring to rendering queue REQ_VK(dev.dt.beginCommandBuffer(render_cmd_, &begin_info)); // Finish moving geometry onto render queue family // geometry and textures need separate barriers due to different // dependent stages geometry_barrier.srcAccessMask = 0; geometry_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; VkPipelineStageFlags dst_geo_render_stage = VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; dev.dt.cmdPipelineBarrier(render_cmd_, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, dst_geo_render_stage, 0, 0, nullptr, 1, &geometry_barrier, 0, nullptr); if (num_textures > 0) { for (VkImageMemoryBarrier &barrier : texture_barriers) { barrier.srcAccessMask = 0; barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; barrier.srcQueueFamilyIndex = dev.transferQF; barrier.dstQueueFamilyIndex = render_qf_; } // Finish acquiring mips on render queue and transition layout dev.dt.cmdPipelineBarrier( render_cmd_, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, texture_barriers.size(), texture_barriers.data()); } VkBufferDeviceAddressInfo addr_info; addr_info.sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO; addr_info.pNext = nullptr; addr_info.buffer = data.buffer; VkDeviceAddress geometry_addr = dev.dt.getBufferDeviceAddress(dev.hdl, &addr_info); auto blas_result = makeBLASes(dev, alloc, load_info.meshInfo, load_info.objectInfo, load_info.hdr.numVertices, geometry_addr, geometry_addr + load_info.hdr.indexOffset, render_cmd_); if (!blas_result.has_value()) { cerr << "OOM while constructing bottom level acceleration structures" << endl; } auto [blases, scratch, total_blas_bytes] = move(*blas_result); // Repurpose geometry_barrier for blas barrier geometry_barrier.srcAccessMask = VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_KHR; geometry_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; geometry_barrier.srcQueueFamilyIndex = render_qf_; geometry_barrier.dstQueueFamilyIndex = render_qf_; geometry_barrier.buffer = blases.storage.buffer; geometry_barrier.offset = 0; geometry_barrier.size = total_blas_bytes; dev.dt.cmdPipelineBarrier( render_cmd_, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 1, &geometry_barrier, 0, nullptr); REQ_VK(dev.dt.endCommandBuffer(render_cmd_)); VkSubmitInfo render_submit {}; render_submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; render_submit.waitSemaphoreCount = 1; render_submit.pWaitSemaphores = &transfer_sema_; VkPipelineStageFlags sema_wait_mask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; render_submit.pWaitDstStageMask = &sema_wait_mask; render_submit.commandBufferCount = 1; render_submit.pCommandBuffers = &render_cmd_; render_queue_.submit(dev, 1, &render_submit, fence_); waitForFenceInfinitely(dev, fence_); resetFence(dev, fence_); // Set Layout // 0: Scene addresses uniform // 1: textures DescriptorUpdates desc_updates(1); vector<VkDescriptorImageInfo> descriptor_views; descriptor_views.reserve(load_info.hdr.numMaterials * 8 + 2); VkDescriptorImageInfo null_img { VK_NULL_HANDLE, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, }; if (staged_textures->envMap.has_value()) { descriptor_views.push_back({ VK_NULL_HANDLE, texture_views[staged_textures->envMap.value()], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, }); descriptor_views.push_back({ VK_NULL_HANDLE, texture_views[staged_textures->importanceMap.value()], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, }); } else { descriptor_views.push_back(null_img); descriptor_views.push_back(null_img); } for (int mat_idx = 0; mat_idx < (int)load_info.hdr.numMaterials; mat_idx++) { const MaterialTextures &tex_indices = load_info.textureIndices[mat_idx]; auto appendDescriptor = [&](uint32_t idx, const auto &texture_list) { if (idx != ~0u) { VkImageView tex_view = texture_views[texture_list[idx]]; descriptor_views.push_back({ VK_NULL_HANDLE, tex_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, }); } else { descriptor_views.push_back(null_img); } }; appendDescriptor(tex_indices.baseColorIdx, staged_textures->base); appendDescriptor(tex_indices.metallicRoughnessIdx, staged_textures->metallicRoughness); appendDescriptor(tex_indices.specularIdx, staged_textures->specular); appendDescriptor(tex_indices.normalIdx, staged_textures->normal); appendDescriptor(tex_indices.emittanceIdx, staged_textures->emittance); appendDescriptor(tex_indices.transmissionIdx, staged_textures->transmission); appendDescriptor(tex_indices.clearcoatIdx, staged_textures->clearcoat); appendDescriptor(tex_indices.anisoIdx, staged_textures->anisotropic); } optional<SceneID> scene_id_tracker; uint32_t scene_id; VkDescriptorBufferInfo vert_info; VkDescriptorBufferInfo mat_info; if (shared_scene_state_) { shared_scene_state_->lock.lock(); scene_id_tracker.emplace(*shared_scene_state_); scene_id = scene_id_tracker->getID(); } else { // FIXME, this entire special codepath for the editor needs to be // removed scene_id = 0; vert_info.buffer = data.buffer; vert_info.offset = 0; vert_info.range = load_info.hdr.numVertices * sizeof(PackedVertex); desc_updates.storage(scene_set_, &vert_info, 0); mat_info.buffer = data.buffer; mat_info.offset = load_info.hdr.materialOffset; mat_info.range = load_info.hdr.numMaterials * sizeof(MaterialParams); desc_updates.storage(scene_set_, &mat_info, 2); } if (load_info.hdr.numMaterials > 0) { assert(load_info.hdr.numMaterials < VulkanConfig::max_materials); uint32_t texture_offset = scene_id * (2 + VulkanConfig::max_materials * VulkanConfig::textures_per_material); desc_updates.textures(scene_set_, descriptor_views.data(), descriptor_views.size(), 1, texture_offset); } desc_updates.update(dev); if (shared_scene_state_) { SceneAddresses &scene_dev_addrs = ((SceneAddresses *)shared_scene_state_->addrData.ptr)[scene_id]; scene_dev_addrs.vertAddr = geometry_addr; scene_dev_addrs.idxAddr = geometry_addr + load_info.hdr.indexOffset; scene_dev_addrs.matAddr = geometry_addr + load_info.hdr.materialOffset; scene_dev_addrs.meshAddr = geometry_addr + load_info.hdr.meshOffset; shared_scene_state_->addrData.flush(dev); shared_scene_state_->lock.unlock(); } uint32_t num_meshes = load_info.meshInfo.size(); return make_shared<VulkanScene>(VulkanScene { { move(load_info.meshInfo), move(load_info.objectInfo), move(load_info.envInit), }, move(texture_store), move(data), load_info.hdr.indexOffset, num_meshes, move(scene_id_tracker), move(blases), }); } } }
35.691187
85
0.653436
shacklettbp
1bbdc79532f96536257f9f19ccabae3020b510d2
3,323
cpp
C++
src/renderer/rt/objects/extern.cpp
gartenriese2/monorenderer
56c6754b2b765d5841fe73fb43ea49438f5dd96f
[ "MIT" ]
null
null
null
src/renderer/rt/objects/extern.cpp
gartenriese2/monorenderer
56c6754b2b765d5841fe73fb43ea49438f5dd96f
[ "MIT" ]
null
null
null
src/renderer/rt/objects/extern.cpp
gartenriese2/monorenderer
56c6754b2b765d5841fe73fb43ea49438f5dd96f
[ "MIT" ]
null
null
null
#include "extern.hpp" #include <MonoEngine/core/log.hpp> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wfloat-equal" #pragma GCC diagnostic ignored "-Wconversion" #include <assimp/Importer.hpp> #include <assimp/scene.h> #pragma GCC diagnostic pop #include <assimp/postprocess.h> #include <glm/glm.hpp> namespace renderer { namespace rt { Extern::Extern(const std::string & path) { Assimp::Importer importer; const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate); if (!scene) { LOG(importer.GetErrorString()); } else { LOG_ASSERT(scene->HasMeshes(), "imported scene has no meshes"); const auto * meshes = scene->mMeshes; LOG("numMeshes:" + std::to_string(scene->mNumMeshes)); for (auto i {0u}; i < scene->mNumMeshes; ++i) { LOG_ASSERT(meshes[i]->HasPositions() && meshes[i]->HasFaces(), "mesh does not have positions or faces"); const auto hasColors {meshes[i]->HasVertexColors(0)}; const auto * faces = meshes[i]->mFaces; LOG("numFaces:" + std::to_string(meshes[i]->mNumFaces)); // for (auto j {0u}; j < meshes[i]->mNumFaces; ++j) { for (auto j {0u}; j < 125000; ++j) { LOG_ASSERT(faces[j].mNumIndices == 3, "face is not a triangle"); const auto aVec {meshes[i]->mVertices[faces[j].mIndices[0]]}; auto a {glm::vec3(aVec[0], aVec[1], aVec[2])}; const auto bVec {meshes[i]->mVertices[faces[j].mIndices[1]]}; auto b {glm::vec3(bVec[0], bVec[1], bVec[2])}; const auto cVec {meshes[i]->mVertices[faces[j].mIndices[2]]}; auto c {glm::vec3(cVec[0], cVec[1], cVec[2])}; // scaling a *= 30.f; b *= 30.f; c *= 30.f; // moving a += glm::vec3(0.f, -6.5f, -7.f); b += glm::vec3(0.f, -6.5f, -7.f); c += glm::vec3(0.f, -6.5f, -7.f); m_vertices.emplace_back(a.x); m_vertices.emplace_back(a.y); m_vertices.emplace_back(a.z); m_vertices.emplace_back(0.f); m_vertices.emplace_back(b.x); m_vertices.emplace_back(b.y); m_vertices.emplace_back(b.z); m_vertices.emplace_back(0.f); m_vertices.emplace_back(c.x); m_vertices.emplace_back(c.y); m_vertices.emplace_back(c.z); m_vertices.emplace_back(0.f); const auto n {glm::normalize(glm::cross(b - a, c - a))}; m_normals.emplace_back(n.x); m_normals.emplace_back(n.y); m_normals.emplace_back(n.z); m_normals.emplace_back(0.f); m_normals.emplace_back(n.x); m_normals.emplace_back(n.y); m_normals.emplace_back(n.z); m_normals.emplace_back(0.f); m_normals.emplace_back(n.x); m_normals.emplace_back(n.y); m_normals.emplace_back(n.z); m_normals.emplace_back(0.f); glm::vec4 col; if (!hasColors) { col = glm::vec4(1.f, 0.f, 0.f, 1.f); // default color } else { const auto color {meshes[i]->mColors[0][faces[j].mIndices[0]]}; col = glm::vec4(color.r, color.g, color.b, 1.f); } m_colors.emplace_back(col.r); m_colors.emplace_back(col.g); m_colors.emplace_back(col.b); m_colors.emplace_back(col.a); m_colors.emplace_back(col.r); m_colors.emplace_back(col.g); m_colors.emplace_back(col.b); m_colors.emplace_back(col.a); m_colors.emplace_back(col.r); m_colors.emplace_back(col.g); m_colors.emplace_back(col.b); m_colors.emplace_back(col.a); } } } } } } // namespace renderer
29.669643
107
0.647006
gartenriese2
1bbf7ecaf3a304724db01622d481b4650767f2a3
646
hpp
C++
runtime/waitgroup.hpp
vron/compute
25c57423a77171bdcf18e6ee17316cc295ea5469
[ "Unlicense" ]
6
2020-07-24T15:29:38.000Z
2021-03-09T05:16:58.000Z
runtime/waitgroup.hpp
vron/compute
25c57423a77171bdcf18e6ee17316cc295ea5469
[ "Unlicense" ]
1
2020-07-27T12:24:50.000Z
2020-08-15T11:18:22.000Z
runtime/waitgroup.hpp
vron/compute
25c57423a77171bdcf18e6ee17316cc295ea5469
[ "Unlicense" ]
1
2021-03-09T02:25:09.000Z
2021-03-09T02:25:09.000Z
#pragma once #include <condition_variable> #include <mutex> template <class T> class WaitGroup { std::mutex m; std::condition_variable cv; T counter; public: WaitGroup() : counter(0) {}; ~WaitGroup(){}; void add(T n) { std::lock_guard<std::mutex> lk(m); counter += n; } void done() { bool notify = false; { std::lock_guard<std::mutex> lk(m); counter -= 1; assert(counter>=0); if (counter == 0) notify = true; } if (notify) cv.notify_one(); } void wait() { std::unique_lock<std::mutex> lk(m); cv.wait(lk, [this] { return this->counter <= 0; }); } };
17.459459
55
0.557276
vron
1bc313d041ed043298578ce482c9df781a7a3c38
6,327
cpp
C++
src/cvar/cameraCalibration.cpp
vnm-interactive/Cinder-MarkerlessAR
28db3199d92145cfb143c4cc457e2b8b013f5729
[ "MIT" ]
null
null
null
src/cvar/cameraCalibration.cpp
vnm-interactive/Cinder-MarkerlessAR
28db3199d92145cfb143c4cc457e2b8b013f5729
[ "MIT" ]
null
null
null
src/cvar/cameraCalibration.cpp
vnm-interactive/Cinder-MarkerlessAR
28db3199d92145cfb143c4cc457e2b8b013f5729
[ "MIT" ]
null
null
null
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // // Copyright (C) 2012, Takuya MINAGAWA. // Third party copyrights are property of their respective owners. // // 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. // //M*/ #include "cameraCalibration.h" #include <stdio.h> #include <iostream> #include "opencv2/imgproc.hpp" #include "opencv2/calib3d.hpp" #include "opencv2/highgui.hpp" #include "commonCvFunctions.h" using namespace std; using namespace cv; using namespace cvar; cameraCalibration::cameraCalibration(void) { max_img_num = 25; pat_row = 7; pat_col = 10; chess_size = 23.0; camera_matrix.create(3, 3, CV_32FC1); distortion.create(1, 5, CV_32FC1); } cameraCalibration::~cameraCalibration(void) { } void cameraCalibration::setMaxImageNum(int num) { max_img_num = num; } void cameraCalibration::setBoardColsAndRows(int r, int c) { pat_row = r; pat_col = c; } void cameraCalibration::setChessSize(float size) { chess_size = size; } bool cameraCalibration::addCheckerImage(Mat& img) { if(checker_image_list.size() >= max_img_num) return false; else checker_image_list.push_back(img); return true; } void cameraCalibration::releaseCheckerImage() { checker_image_list.clear(); } bool cameraCalibration::doCalibration() { int i, j, k; bool found; int image_num = checker_image_list.size(); // int pat_size = pat_row * pat_col; // int all_points = image_num * pat_size; if(image_num < 3){ cout << "please add checkker pattern image!" << endl; return false; } // int *p_count = new int[image_num]; rotation.clear(); translation.clear(); cv::Size pattern_size(pat_col,pat_row); // Point3f *objects = new Point3f[all_points]; // Point2f *corners = new Point2f[all_points]; Point3f obj; vector<Point3f> objects; vector<vector<Point3f>> object_points; // 3D set of spatial coordinates for (j = 0; j < pat_row; j++) { for (k = 0; k < pat_col; k++) { obj.x = j * chess_size; obj.y = k * chess_size; obj.z = 0.0; objects.push_back(obj); } } vector<Point2f> corners; vector<vector<Point2f>> image_points; int found_num = 0; cvNamedWindow ("Calibration", CV_WINDOW_AUTOSIZE); auto img_itr = checker_image_list.begin(); i = 0; while (img_itr != checker_image_list.end()) { // Corner detection of chess board (calibration pattern) found = cv::findChessboardCorners(*img_itr, pattern_size, corners); cout << i << "..."; if (found) { cout << "ok" << endl; found_num++; } else { cout << "fail" << endl; } // Fixed a corner position in the sub-pixel accuracy, drawing Mat src_gray(img_itr->size(), CV_8UC1, 1); cvtColor(*img_itr, src_gray, CV_BGR2GRAY); // cvCvtColor (src_img[i], src_gray, CV_BGR2GRAY); cornerSubPix(src_gray, corners, cv::Size(3,3), cv::Size(-1,-1), TermCriteria(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.03)); // cvFindCornerSubPix (src_gray, &corners[i * PAT_SIZE], corner_count, // cvSize (3, 3), cvSize (-1, -1), cvTermCriteria (CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.03)); drawChessboardCorners(*img_itr, pattern_size, transPointVecToMat2D(corners), found); // cvDrawChessboardCorners (src_img[i], pattern_size, &corners[i * PAT_SIZE], corner_count, found); // p_count[i] = corner_count; if(found){ image_points.push_back(corners); object_points.push_back(objects); } corners.clear(); imshow("Calibration", *img_itr); cvWaitKey (0); i++; img_itr++; } cvDestroyWindow ("Calibration"); if (found_num < 3){ return false; } // cvInitMatHeader (&image_points, ALL_POINTS, 1, CV_32FC2, corners); // cvInitMatHeader (&point_counts, IMAGE_NUM, 1, CV_32SC1, p_count); // Internal parameters, distortion factor, the estimation of the external parameters // cvCalibrateCamera2 (&object_points, &image_points, &point_counts, cvSize (640, 480), intrinsic, distortion); calibrateCamera(object_points, image_points, checker_image_list[0].size(), camera_matrix, distortion, rotation, translation); /* CvMat sub_image_points, sub_object_points; int base = 0; cvGetRows (&image_points, &sub_image_points, base * PAT_SIZE, (base + 1) * PAT_SIZE); cvGetRows (&object_points, &sub_object_points, base * PAT_SIZE, (base + 1) * PAT_SIZE); cvFindExtrinsicCameraParams2 (&sub_object_points, &sub_image_points, intrinsic, distortion, rotation, translation); // (7) Export to XML file CvFileStorage *fs; fs = cvOpenFileStorage ("camera.xml", 0, CV_STORAGE_WRITE); cvWrite (fs, "intrinsic", intrinsic); cvWrite (fs, "rotation", rotation); cvWrite (fs, "translation", translation); cvWrite (fs, "distortion", distortion); cvReleaseFileStorage (&fs); */ return true; } void cameraCalibration::saveCameraMatrix(const string& filename) { FileStorage fs(filename, FileStorage::WRITE); writeCameraMatrix(fs, "camera_matrix"); } void cameraCalibration::writeCameraMatrix(FileStorage& cvfs, const string& name) { cvfs << name << camera_matrix; }
30.128571
132
0.706654
vnm-interactive
1bc55f8f655ef35887559e1a5d08e4b5cfbd86da
3,838
cpp
C++
src/mapart/map_nbt.cpp
AgustinSRG/ImageToMapMC
fbff8017e87c30baaa0c9c2327bdd28846253646
[ "MIT" ]
null
null
null
src/mapart/map_nbt.cpp
AgustinSRG/ImageToMapMC
fbff8017e87c30baaa0c9c2327bdd28846253646
[ "MIT" ]
null
null
null
src/mapart/map_nbt.cpp
AgustinSRG/ImageToMapMC
fbff8017e87c30baaa0c9c2327bdd28846253646
[ "MIT" ]
null
null
null
/* * This file is part of ImageToMapMC project * * Copyright (c) 2021 Agustin San Roman * * 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 "map_nbt.h" #include <fstream> #include <io/stream_reader.h> #include <io/stream_writer.h> #include <io/izlibstream.h> #include <io/ozlibstream.h> #include <nbt_tags.h> using namespace std; using namespace nbt; using namespace colors; using namespace mapart; using namespace minecraft; std::vector<map_color_t> mapart::readMapNBTFile(std::string fileName) { std::vector<map_color_t> result(MAP_WIDTH * MAP_HEIGHT); std::ifstream file(fileName, std::ios::binary); if (!file) { throw -1; } try { zlib::izlibstream igzs(file); auto pair = nbt::io::read_compound(igzs); nbt::tag_compound comp = *pair.second; nbt::value *colorsArray = &comp.at(std::string("data")).at(std::string("colors")); nbt::tag_byte_array colorsBytes = colorsArray->as<nbt::tag_byte_array>(); size_t map_size = MAP_WIDTH * MAP_HEIGHT; for (size_t i = 0; i < map_size; i++) { result[i] = uint8_t(colorsBytes.at(i)); } } catch (...) { throw -2; } return result; } void mapart::writeMapNBTFile(std::string fileName, const std::vector<map_color_t> &mapColors, minecraft::McVersion version) { nbt::tag_compound root; nbt::tag_compound data; // Set meta data data.insert("width", nbt::tag_int(MAP_WIDTH)); data.insert("height", nbt::tag_int(MAP_HEIGHT)); data.insert("dimension", nbt::tag_int(0)); data.insert("scale", nbt::tag_int(0)); data.insert("trackingPosition:", nbt::tag_int(0)); data.insert("unlimitedTracking", nbt::tag_int(0)); if (version >= McVersion::MC_1_14) { // If we can, prevent the map from being modified data.insert("locked", nbt::tag_int(1)); } // Set the center far away to prevent issues (20M) data.insert("xCenter", nbt::tag_int(20000000)); data.insert("zCenter", nbt::tag_int(20000000)); // Set colors array nbt::tag_byte_array byteArray; size_t size = MAP_WIDTH * MAP_HEIGHT; for (size_t i = 0; i < size; i++) { short val = mapColors[i]; int8_t ip = static_cast<int8_t>((val > 127) ? (val - 256) : val); byteArray.push_back(ip); } data.insert("colors", byteArray.clone()); // Insert tags to root root.insert("data", data.clone()); root.insert("DataVersion", minecraft::versionToDataVersion(version)); std::ofstream file(fileName, std::ios::binary); if (!file) { throw -1; } try { zlib::ozlibstream ogzs(file, -1, true); nbt::io::write_tag("", root, ogzs); } catch (...) { throw -2; } }
28.857143
123
0.656592
AgustinSRG
1bca8822cc7f4e1d41211158ff39b24eb841a77e
10,247
cpp
C++
Src/Eni/UsbDevice/Stm/USBDDevice.cpp
vlad230596/Eni
2bbd07b6e4e20b2c2a6ad6fdc9d948e6352eecb7
[ "MIT" ]
null
null
null
Src/Eni/UsbDevice/Stm/USBDDevice.cpp
vlad230596/Eni
2bbd07b6e4e20b2c2a6ad6fdc9d948e6352eecb7
[ "MIT" ]
null
null
null
Src/Eni/UsbDevice/Stm/USBDDevice.cpp
vlad230596/Eni
2bbd07b6e4e20b2c2a6ad6fdc9d948e6352eecb7
[ "MIT" ]
null
null
null
#include "EniConfig.h" #if defined(ENI_USB_DEVICE) && defined(ENI_STM) #include "UsbDDevice.h" #include "usbd_conf.h" #include "Core/usbd_def.h" #include "Core/usbd_ioreq.h" #include "Core/usbd_ctlreq.h" #include "Core/usbd_core.h" #include ENI_HAL_INCLUDE_FILE #include "USBTypes.h" #include "UsbMicrosoftTypes.h" #include <type_traits> #include <new> using namespace Eni; extern "C" { extern PCD_HandleTypeDef hpcd_USB_OTG_FS; } namespace Eni::USB { __attribute__((used)) USBD_HandleTypeDef UsbDevice::hUsbDevice{}; __attribute__((used)) UsbDDeviceContext* _context = nullptr; //For other-speed description __ALIGN_BEGIN volatile USB::DeviceQualifierDescriptor USBD_NDC_DeviceQualifierDesc __ALIGN_END { USB::UsbVersion(2), USB::UsbClass::Device::UseInterfaceClass(), 64, 1, 0 }; #define USB_VENDOR_CODE_WINUSB 'P' __ALIGN_BEGIN volatile USB::Microsoft::MicrosoftStringDescriptor NDC_StringDescriptor __ALIGN_END = { (uint8_t)USB_VENDOR_CODE_WINUSB }; extern volatile USB::DeviceQualifierDescriptor USBD_NDC_DeviceQualifierDesc; extern volatile USB::Microsoft::MicrosoftStringDescriptor NDC_StringDescriptor; __attribute__((used)) std::aligned_storage_t<USBD_MAX_STR_DESC_SIZ, 4> _descriptorsBuffer; UsbDDeviceContext* UsbDevice::getContext(){ return _context; } void hang(){ while(true){ asm("nop"); } } __attribute__((used)) const USBD_DescriptorsTypeDef UsbDevice::_descriptorsTable = { &UsbDevice::getDeviceDescriptor, &UsbDevice::getLangidStrDescriptor, &UsbDevice::getManufacturerStringDescriptor, &UsbDevice::getProductStringDescriptor, &UsbDevice::getSerialStringDescriptor, &UsbDevice::getConfigStringDescriptor, &UsbDevice::getInterfaceStringDescriptor }; __attribute__((used)) const USBD_ClassTypeDef UsbDevice::_usbClassBinding = { &UsbDevice::coreInit, &UsbDevice::coreDeinit, &UsbDevice::coreSetup, 0, //USBD_NDC_EP0_TxReady, &UsbDevice::coreEp0RxReady, &UsbDevice::coreDataIn, &UsbDevice::coreDataOut, &UsbDevice::coreSof, &UsbDevice::coreIsoInIncomplete, &UsbDevice::coreIsoOutIncomplete, &UsbDevice::coreGetCfgDesc, &UsbDevice::coreGetCfgDesc, &UsbDevice::coreGetCfgDesc, &UsbDevice::coreGetDeviceQualifierDesc, &UsbDevice::coreGetUserStringDesc }; uint8_t UsbDevice::coreInit(USBD_HandleTypeDef* pdev, uint8_t cfgidx){ //TODO: use configuration id for(size_t i = 0; i < _context->getInterfaceCount(); ++i){ auto interface = _context->getInterface(i); if(interface != nullptr){ if(!interface->init(pdev)){ return USBD_FAIL; } } } return USBD_OK; } uint8_t UsbDevice::coreDeinit(USBD_HandleTypeDef* pdev, uint8_t cfgidx){ //TODO: use configuration id for(size_t i = 0; i < _context->getInterfaceCount(); ++i){ auto interface = _context->getInterface(i); if(interface != nullptr){ if(!interface->deinit(pdev)){ //return USBD_FAIL; } } } return USBD_OK; } uint8_t UsbDevice::coreImplSetup(USBD_SetupReqTypedef request, void* data){ switch ( request.bmRequest & USB_REQ_RECIPIENT_MASK ){ case USB_REQ_RECIPIENT_INTERFACE:{ if(_context != nullptr){ auto* interface = _context->getInterface(request.wValue); if(interface != nullptr){ hang(); /*if(interface->control(&hUsbDevice, request.bRequest, (uint8_t*)data, request.wLength)){ return USBD_OK; }*/ } } break; } case USB_REQ_RECIPIENT_ENDPOINT: hang(); /*if(_usb_device_context != nullptr){ if(request.bRequest == USB_REQ_CLEAR_FEATURE){ //reset pipe is called at host side //do reset pipe if(_clearFeatureCallback != nullptr){ _clearFeatureCallback(request.wIndex); } } }*/ break; case USB_REQ_RECIPIENT_DEVICE: default: break; } return USBD_OK; } uint8_t UsbDevice::coreSetup(USBD_HandleTypeDef* pdev, USBD_SetupReqTypedef *req){ hang(); /*if (req->wLength){ //Request with data stage{ if((req->bmRequest & USB_REQ_DATA_PHASE_MASK) == USB_REQ_DATA_PHASE_DEVICE_TO_HOST){ //device to host data stage => handler should send data return coreImplSetup(*req, 0); }else{ //host to device data stage! Can't execute now, read data first & execute later in Ep0Receive callback last_request = *req; USBD_CtlPrepareRx (pdev, (uint8_t*)&ep0Buffer[0], req->wLength); } } else {//No data stage => simple request => execute now return coreImplSetup(*req, 0); }*/ return USBD_OK; } uint8_t UsbDevice::coreEp0RxReady(USBD_HandleTypeDef* pdev){ hang(); //coreImplSetup(last_request, &ep0Buffer[0]); //data in stage complete => execute request //last_request.bRequest = 0xff; return USBD_OK; } UsbDInterface* UsbDevice::findInterfaceByEndpointAddress(uint8_t address){ if(_context == nullptr){ return nullptr; } auto if_cnt = _context->getInterfaceCount(); for(uint32_t i = 0; i < if_cnt; ++i){ auto interface = _context->getInterface(i); if(interface != nullptr){ auto endpoint = interface->getEndpoint(address); if(endpoint != nullptr){ return interface; } } } return nullptr; } uint8_t UsbDevice::coreDataIn(USBD_HandleTypeDef* pdev, uint8_t epnum){ auto interface = findInterfaceByEndpointAddress(USB::EndpointAddress::makeIn(epnum));//TODO: cleanup if(interface != nullptr){ interface->txComplete(epnum | 0x80); } return USBD_OK; } uint8_t UsbDevice::coreDataOut(USBD_HandleTypeDef* pdev, uint8_t epnum){ uint32_t rxLen = USBD_LL_GetRxDataSize (pdev, epnum); auto interface = findInterfaceByEndpointAddress(USB::EndpointAddress::makeOut(epnum)); if(interface != nullptr){ interface->rxComplete(rxLen, epnum); } return USBD_OK; } uint8_t UsbDevice::coreSof(USBD_HandleTypeDef* pdev){ hang(); return USBD_OK; } uint8_t UsbDevice::coreIsoInIncomplete(USBD_HandleTypeDef* pdev, uint8_t epnum){ hang(); return USBD_OK; } uint8_t UsbDevice::coreIsoOutIncomplete(USBD_HandleTypeDef* pdev, uint8_t epnum){ hang(); return USBD_OK; } uint8_t* UsbDevice::coreGetCfgDesc(uint16_t* length){ auto* mem = reinterpret_cast<uint8_t*>(&_descriptorsBuffer); auto* buffer = mem; USB::ConfigurationDescriptor* cd = new(buffer) USB::ConfigurationDescriptor(); cd->wTotalLength = 0; cd->bNumInterfaces = (uint8_t)_context->getInterfaceCount(); cd->bConfigurationValue = 0x01; cd->iConfiguration = USBD_IDX_CONFIG_STR; cd->bmAttributes = USB::UsbAttributes().value; cd->bMaxPower = 500; buffer += sizeof(USB::ConfigurationDescriptor); for(uint32_t i = 0; i < _context->getInterfaceCount(); ++i){ auto emptySize = (mem + sizeof(_descriptorsBuffer)) - buffer; auto size = _context->getInterface(i)->getDescriptor(buffer, emptySize, i); buffer += size; cd->wTotalLength += size; } cd->wTotalLength += sizeof(USB::ConfigurationDescriptor); *length = cd->wTotalLength; return reinterpret_cast<uint8_t*>(&_descriptorsBuffer); } uint8_t* UsbDevice::getDeviceDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){ auto mem = reinterpret_cast<uint8_t*>(&_descriptorsBuffer); auto& desc = *new(mem) USB::DeviceDescriptor(); *length = sizeof(USB::DeviceDescriptor); desc.bcdUSB = 0x0200; desc.classDescription = USB::UsbClassDescriptor(0,0,0); desc.bMaxPacketSize0 = 64; desc.idVendor = _context->vid; desc.idProduct = _context->pid; desc.bcdDevice = USB::UsbVersion(2); desc.iManufacturer = USBD_IDX_MFC_STR; desc.iProduct = USBD_IDX_PRODUCT_STR; desc.iSerialNumber = USBD_IDX_SERIAL_STR; desc.bNumConfigurations = 1; return reinterpret_cast<uint8_t*>(&desc); } struct USBDDummyClassData{ uint32_t reserved; }; __attribute__((used)) static USBDDummyClassData _classData = {}; void UsbDevice::start(UsbDDeviceContext* context){ _context = context; hUsbDevice.pClassData = &_classData; //Otherwise USBD_Reset handler would not disable interfaces (( //hUsbDevice.pClassData = nullptr; //Init? hUsbDevice.dev_speed = USBD_SPEED_FULL; USBD_Init(&hUsbDevice, const_cast<USBD_DescriptorsTypeDef*>(&_descriptorsTable), 0); USBD_RegisterClass(&hUsbDevice, const_cast<USBD_ClassTypeDef*>(&_usbClassBinding)); USBD_Start(&hUsbDevice); } uint8_t* UsbDevice::coreGetDeviceQualifierDesc (uint16_t *length){ *length = sizeof (USBD_NDC_DeviceQualifierDesc); return (uint8_t*)&USBD_NDC_DeviceQualifierDesc; } uint8_t* UsbDevice::coreGetUserStringDesc(USBD_HandleTypeDef* pdev, uint8_t index, uint16_t* length){ *length = 0; if ( 0xEE == index ){ *length = sizeof (NDC_StringDescriptor); return (uint8_t*)&NDC_StringDescriptor; } return NULL; } uint8_t* UsbDevice::getLangidStrDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){ auto mem = static_cast<void*>(&_descriptorsBuffer); auto& desc = *new(mem) USB::LanguageIDStringDescriptor<1>(); *length = sizeof(USB::LanguageIDStringDescriptor<1>); desc.languages[0] = USB::LanguageID::EnglishUnitedStates; return reinterpret_cast<uint8_t*>(&desc); } uint8_t* UsbDevice::getManufacturerStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){ return USB::MakeStringDescriptor(_context->manufacturerStringDescriptor, &_descriptorsBuffer, sizeof(_descriptorsBuffer), length); } uint8_t* UsbDevice::getProductStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){ return USB::MakeStringDescriptor(_context->productStringDescriptor, &_descriptorsBuffer, sizeof(_descriptorsBuffer), length); } uint8_t* UsbDevice::getSerialStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){ return USB::MakeStringDescriptor(_context->serialStringDescriptor, &_descriptorsBuffer, sizeof(_descriptorsBuffer), length); } uint8_t* UsbDevice::getConfigStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){ return USB::MakeStringDescriptor(_context->configurationStringDescriptor, &_descriptorsBuffer, sizeof(_descriptorsBuffer), length); } uint8_t* UsbDevice::getInterfaceStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){ return USB::MakeStringDescriptor(_context->interfaceStringDescriptor, &_descriptorsBuffer, sizeof(_descriptorsBuffer), length); } USBD_StatusTypeDef UsbDevice::interfaceRequest(USBD_HandleTypeDef* pdev, USBD_SetupReqTypedef* req){ uint8_t interface_id = (uint8_t)req->wValue; //TODO: bug! wIndex == interface id auto interface = _context->getInterface(interface_id); if(interface == nullptr){ return USBD_FAIL; } return interface->interfaceRequest(pdev, req); } } #endif
29.110795
132
0.760027
vlad230596
1bcd386bae008d200b1b68a5f70bff7ccfe2d92c
706
cpp
C++
src/main.cpp
QQB17/simple_log
e800cce5bde4e04bc9d91d1180a6c28a1b658c69
[ "MIT" ]
null
null
null
src/main.cpp
QQB17/simple_log
e800cce5bde4e04bc9d91d1180a6c28a1b658c69
[ "MIT" ]
null
null
null
src/main.cpp
QQB17/simple_log
e800cce5bde4e04bc9d91d1180a6c28a1b658c69
[ "MIT" ]
null
null
null
#include <iostream> #include "logger.h" int main() { // Simple log message qlog::log("Hello world!"); // Select log_level qlog::log(log_level::level::debug, "Debuging: ", "Selected log level"); // Debug log qlog::debug("This is a debug message."); // Info log qlog::info("Information"); // Error log qlog::error("Error"); // Crititcal log qlog::critical("Critical operator: ", "1"); // Set log level to filter the output log log_level::set_level(log_level::level::critical); // Any information will not output if the the level is lower than setting level qlog::info("This message unable to log.", "Log failed"); return 0; }
22.774194
83
0.621813
QQB17
1bce55470ec93585ddba0657ed132f96c2a85aec
1,627
hpp
C++
src/MarkerInterval.hpp
rlorigro/shasta
06522d841362ee22265d006062759b0cbcf3a1ea
[ "BSD-3-Clause-Open-MPI" ]
1
2019-02-11T02:46:16.000Z
2019-02-11T02:46:16.000Z
src/MarkerInterval.hpp
rlorigro/shasta
06522d841362ee22265d006062759b0cbcf3a1ea
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
src/MarkerInterval.hpp
rlorigro/shasta
06522d841362ee22265d006062759b0cbcf3a1ea
[ "BSD-3-Clause-Open-MPI" ]
1
2019-08-14T22:56:29.000Z
2019-08-14T22:56:29.000Z
#ifndef SHASTA_MARKER_INTERVAL_HPP #define SHASTA_MARKER_INTERVAL_HPP // Shasta. #include "ReadId.hpp" #include"tuple.hpp" // Standard library. #include "array.hpp" namespace shasta { class MarkerInterval; class MarkerIntervalWithRepeatCounts; } // Class to describe the interval between // two markers on an oriented read. // The two markers are not necessarily consecutive. // HOoever, the second marker has a higher ordinal // than the first. class shasta::MarkerInterval { public: OrientedReadId orientedReadId; // The ordinals of the two markers. array<uint32_t, 2> ordinals; MarkerInterval() {} MarkerInterval( OrientedReadId orientedReadId, uint32_t ordinal0, uint32_t ordinal1) : orientedReadId(orientedReadId) { ordinals[0] = ordinal0; ordinals[1] = ordinal1; } bool operator==(const MarkerInterval& that) const { return tie(orientedReadId, ordinals[0], ordinals[1]) == tie(that.orientedReadId, that.ordinals[0], that.ordinals[1]); } bool operator<(const MarkerInterval& that) const { return tie(orientedReadId, ordinals[0], ordinals[1]) < tie(that.orientedReadId, that.ordinals[0], that.ordinals[1]); } }; class shasta::MarkerIntervalWithRepeatCounts : public MarkerInterval { public: vector<uint8_t> repeatCounts; // The constructor does not fill in the repeat counts. MarkerIntervalWithRepeatCounts(const MarkerInterval& markerInterval) : MarkerInterval(markerInterval){} }; #endif
23.57971
74
0.672403
rlorigro
1bd6375b3f8a52ee376f3ed86437ace1b3a75d38
2,788
cpp
C++
solved-lightOj/1220.cpp
Maruf-Tuhin/Online_Judge
cf9b2a522e8b1a9623d3996a632caad7fd67f751
[ "MIT" ]
1
2019-03-31T05:47:30.000Z
2019-03-31T05:47:30.000Z
solved-lightOj/1220.cpp
the-redback/competitive-programming
cf9b2a522e8b1a9623d3996a632caad7fd67f751
[ "MIT" ]
null
null
null
solved-lightOj/1220.cpp
the-redback/competitive-programming
cf9b2a522e8b1a9623d3996a632caad7fd67f751
[ "MIT" ]
null
null
null
/** * @author : Maruf Tuhin * @College : CUET CSE 11 * @Topcoder : the_redback * @CodeForces : the_redback * @UVA : the_redback * @link : http://www.fb.com/maruf.2hin */ #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long llu; #define ft first #define sd second #define mp make_pair #define pb(x) push_back(x) #define all(x) x.begin(),x.end() #define allr(x) x.rbegin(),x.rend() #define mem(a,b) memset(a,b,sizeof(a)) #define repv(i,a) for(i=0;i<(ll)a.size();i++) #define revv(i,a) for(i=(ll)a.size()-1;i>=0;i--) #define rep(i,a,b) for(i=a;i<=b;i++) #define rev(i,a,b) for(i=a;i>=b;i--) #define sf(a) scanf("%lld",&a) #define sf2(a,b) scanf("%lld %lld",&a,&b) #define sf3(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define inf 1e9 #define eps 1e-9 #define mod 1000000007 #define NN 100010 #ifdef redback #define bug printf("line=%d\n",__LINE__); #define debug(args...) {cout<<":: "; dbg,args; cerr<<endl;} struct debugger{template<typename T>debugger& operator ,(const T& v){cerr<<v<<" ";return *this;}}dbg; #else #define bug #define debug(args...) #endif //debugging macros #define NN 70000 bool p[NN+7]; //Hashing vector<ll>pr,facts; //storing prime void sieve(ll n) { ll i,j,k,l; p[1]=1; pr.push_back(2); for(i=4;i<=n;i+=2) p[i]=1; for(i=3;i<=n;i+=2) { if(p[i]==0) { pr.push_back(i); for(j=i*i;j<=n;j+=2*i) p[j]=1; } } } ll factor(ll n) { facts.clear(); ll count,k,i; for(i=0;i<pr.size() && pr[i]*pr[i]<=n;i++) { k=pr[i]; count=0; while(n%k==0) { n/=k; count++; } facts.pb(count); if(n==1) break; } if(n>1) facts.pb(1); } int main() { //ios_base::sync_with_stdio(0); cin.tie(0); #ifdef redback freopen("C:\\Users\\Maruf\\Desktop\\in.txt","r",stdin); #endif sieve(NN); ll t=1,tc; sf(tc); ll l,m,n; while(tc--) { ll i,j,l; sf(n); ll minusFlag=0; if(n<0) { n*=-1; minusFlag=1; } factor(n); ll ans=0; for(i=1;i<34;i++) { ll flag=1; for(j=0;j<facts.size();j++) { if(facts[j]%i!=0) { flag=0; break; } } if(minusFlag && i%2==0) continue; if(flag) ans=max(ans,i); } printf("Case %lld: %lld\n",t++,ans); } return 0; }
20.350365
102
0.455524
Maruf-Tuhin
1bd89cca521d094d1cd134dc7bfc1de501552147
948
hpp
C++
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/dawn/string_method.hpp
yklishevich/RubetekIOS-CPP-releases
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
[ "MIT" ]
null
null
null
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/dawn/string_method.hpp
yklishevich/RubetekIOS-CPP-releases
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
[ "MIT" ]
null
null
null
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/dawn/string_method.hpp
yklishevich/RubetekIOS-CPP-releases
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
[ "MIT" ]
null
null
null
#pragma once #include <string> namespace dawn { inline void string_pop_front(std::string& s, size_t n) { s = s.substr(n); } inline bool string_pop_front_if_find(std::string& s, std::string const& w) { size_t const pos = s.find(w); if (pos == std::string::npos) return false; string_pop_front(s, pos + w.size()); return true; } inline bool string_pop_front_if_find_backward(std::string& s, std::string const& w) { size_t const pos = s.rfind(w); if (pos == std::string::npos) return false; string_pop_front(s, pos + w.size()); return true; } inline bool string_pop_front_equal(std::string& s, std::string const& w) { if (w.empty()) return true; if (s.size() >= w.size() && s.compare(0, w.size() - 1, w)) { s = s.substr(w.size()); return true; } return false; } }
25.621622
87
0.549578
yklishevich
1bdb8642d7c9b5cf912f7b4b68073aa0aa0c49e6
1,560
cpp
C++
homework/Pashchenko/01/hw02.cpp
nkotelevskii/msu_cpp_spring_2018
b5d84447f9b8c7f3615b421c51cf4192f1b90342
[ "MIT" ]
12
2018-02-20T15:25:12.000Z
2022-02-15T03:31:55.000Z
homework/Pashchenko/01/hw02.cpp
nkotelevskii/msu_cpp_spring_2018
b5d84447f9b8c7f3615b421c51cf4192f1b90342
[ "MIT" ]
1
2018-02-26T12:40:47.000Z
2018-02-26T12:40:47.000Z
homework/Pashchenko/01/hw02.cpp
nkotelevskii/msu_cpp_spring_2018
b5d84447f9b8c7f3615b421c51cf4192f1b90342
[ "MIT" ]
33
2018-02-20T15:25:11.000Z
2019-02-13T22:33:36.000Z
#include <iostream> #include "numbers.dat" void sieve(bool *primes, int len) { for(int i = 0; i < len; i++) primes[i] = true; primes[0] = primes[1] = false; for (int i = 2; i < len; i++) { if (primes[i]) { for (int j = 2 * i; j < len; j += i) primes[j] = false; } } } int left(int edge) { int l = 0, r = Size, med; while(r - l > 1) { med = (l + r) / 2; if(Data[med] >= edge) r = med; else l = med; } if(edge == Data[l]) return l; if(edge == Data[r]) return r; return -1; } int right(int edge) { int l = 0, r = Size, med; while(r - l > 1) { med = (l + r) / 2; if(Data[med] <= edge) l = med; else r = med; } if(edge == Data[l]) return l; if(edge == Data[r]) return r; return -1; } int main(int argc, char *argv[]) { if(!(argc & 1) || argc == 1) return -1; const int n = Data[Size - 1]; bool *primes = new bool[n]; sieve(primes, n); int l, r, ld, rd; for(int i = 1; i < argc; i += 2) { l = std::atoi(argv[i]); r = std::atoi(argv[i + 1]); ld = left(l); rd = right(r); if(ld == -1 || rd == -1) continue; int counter = 0; for(int j = ld; j <= rd; ++j) counter += primes[Data[j]]; std::cout << counter << std::endl; } delete [] primes; return 0; }
16.595745
48
0.398077
nkotelevskii
1bdc4885c28ba7c99411d2f285e03d1db51cce5f
3,900
cc
C++
src/PhysListParticles.cc
hbidaman/detectorSimulations_v10
6ceae8e9561638d5a3c886571f60141abc09922c
[ "MIT" ]
1
2020-06-26T15:29:46.000Z
2020-06-26T15:29:46.000Z
src/PhysListParticles.cc
hbidaman/detectorSimulations_v10
6ceae8e9561638d5a3c886571f60141abc09922c
[ "MIT" ]
1
2020-08-05T18:03:43.000Z
2020-08-05T18:03:43.000Z
src/PhysListParticles.cc
hbidaman/detectorSimulations_v10
6ceae8e9561638d5a3c886571f60141abc09922c
[ "MIT" ]
1
2020-06-08T14:21:23.000Z
2020-06-08T14:21:23.000Z
// // ******************************************************************** // * License and Disclaimer * // * * // * The Geant4 software is copyright of the Copyright Holders of * // * the Geant4 Collaboration. It is provided under the terms and * // * conditions of the Geant4 Software License, included in the file * // * LICENSE and available at http://cern.ch/geant4/license . These * // * include a list of copyright holders. * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. Please see the license in the file LICENSE and URL above * // * for the full disclaimer and the limitation of liability. * // * * // * This code implementation is the result of the scientific and * // * technical work of the GEANT4 collaboration. * // * By using, copying, modifying or distributing the software (or * // * any work based on the software) you agree to acknowledge its * // * use in resulting scientific publications, and indicate your * // * acceptance of all terms of the Geant4 Software license. * // ******************************************************************** // // $Id: PhysListParticles.cc 68007 2013-03-13 11:28:03Z gcosmo $ // /// \file radioactivedecay/rdecay02/src/PhysListParticles.cc /// \brief Implementation of the PhysListParticles class // //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... #include "PhysListParticles.hh" // Bosons #include "G4ChargedGeantino.hh" #include "G4Geantino.hh" #include "G4Gamma.hh" #include "G4OpticalPhoton.hh" // leptons #include "G4MuonPlus.hh" #include "G4MuonMinus.hh" #include "G4NeutrinoMu.hh" #include "G4AntiNeutrinoMu.hh" #include "G4Electron.hh" #include "G4Positron.hh" #include "G4NeutrinoE.hh" #include "G4AntiNeutrinoE.hh" // Hadrons #include "G4MesonConstructor.hh" #include "G4BaryonConstructor.hh" #include "G4IonConstructor.hh" //ShortLived #include "G4ShortLivedConstructor.hh" //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... PhysListParticles::PhysListParticles(const G4String& name) : G4VPhysicsConstructor(name) {} //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... PhysListParticles::~PhysListParticles() {} //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void PhysListParticles::ConstructParticle() { // pseudo-particles G4Geantino::GeantinoDefinition(); G4ChargedGeantino::ChargedGeantinoDefinition(); // gamma G4Gamma::GammaDefinition(); // optical photon G4OpticalPhoton::OpticalPhotonDefinition(); // leptons G4Electron::ElectronDefinition(); G4Positron::PositronDefinition(); G4MuonPlus::MuonPlusDefinition(); G4MuonMinus::MuonMinusDefinition(); G4NeutrinoE::NeutrinoEDefinition(); G4AntiNeutrinoE::AntiNeutrinoEDefinition(); G4NeutrinoMu::NeutrinoMuDefinition(); G4AntiNeutrinoMu::AntiNeutrinoMuDefinition(); // mesons G4MesonConstructor mConstructor; mConstructor.ConstructParticle(); // barions G4BaryonConstructor bConstructor; bConstructor.ConstructParticle(); // ions G4IonConstructor iConstructor; iConstructor.ConstructParticle(); // Construct resonaces and quarks G4ShortLivedConstructor pShortLivedConstructor; pShortLivedConstructor.ConstructParticle(); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
33.333333
80
0.642564
hbidaman
1bdc71c2b1af4f9a4743741f85a126d6acc92bea
2,983
cpp
C++
external/text/example/editor/curses_interface.cpp
geenen124/iresearch
f89902a156619429f9e8df94bd7eea5a78579dbc
[ "Apache-2.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
external/text/example/editor/curses_interface.cpp
geenen124/iresearch
f89902a156619429f9e8df94bd7eea5a78579dbc
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
external/text/example/editor/curses_interface.cpp
geenen124/iresearch
f89902a156619429f9e8df94bd7eea5a78579dbc
[ "Apache-2.0" ]
892
2015-01-29T16:26:19.000Z
2022-03-20T07:44:30.000Z
// Copyright (C) 2020 T. Zachary Laine // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "curses_interface.hpp" extern "C" { #include <ncurses.h> } curses_interface_t::curses_interface_t() : win_(initscr()) { if (win_ != stdscr) throw std::runtime_error("ncurses initscr() failed."); raw(); noecho(); keypad(stdscr, true); start_color(); use_default_colors(); mmask_t old_mouse_events; mousemask( BUTTON1_CLICKED | BUTTON1_DOUBLE_CLICKED | BUTTON1_TRIPLE_CLICKED | REPORT_MOUSE_POSITION, &old_mouse_events); set_tabsize(1); } curses_interface_t::~curses_interface_t() { endwin(); } screen_pos_t curses_interface_t::screen_size() const { return {getmaxy(stdscr), getmaxx(stdscr)}; } event_t curses_interface_t::next_event() const { int const k = wgetch(win_); // Mouse events. if (k == KEY_MOUSE) { MEVENT e; if (getmouse(&e) == ERR) return {key_code_t{KEY_MAX}, screen_size()}; return {key_code_t{(int)e.bstate, e.x, e.y}, screen_size()}; } // Everything else. return {key_code_t{k}, screen_size()}; } namespace { void render_text(snapshot_t const & snapshot, screen_pos_t screen_size) { int row = 0; std::vector<char> buf; std::ptrdiff_t pos = snapshot.first_char_index_; auto line_first = snapshot.first_row_; auto const line_last = std::min<std::ptrdiff_t>( line_first + screen_size.row_ - 2, snapshot.lines_.size()); for (; line_first != line_last; ++line_first) { auto const line = snapshot.lines_[line_first]; auto first = snapshot.content_.begin().base().base() + pos; auto const last = first + line.code_units_; move(row, 0); buf.clear(); std::copy(first, last, std::back_inserter(buf)); if (!buf.empty() && buf.back() == '\n') buf.pop_back(); if (!buf.empty() && buf.back() == '\r') buf.pop_back(); buf.push_back('\0'); addstr(&buf[0]); pos += line.code_units_; ++row; } } } void render(buffer_t const & buffer, screen_pos_t screen_size) { erase(); auto const size = screen_pos_t{screen_size.row_ - 2, screen_size.col_}; render_text(buffer.snapshot_, screen_size); // render the info line move(size.row_, 0); attron(A_REVERSE); printw( " %s %s (%d, %d)", dirty(buffer) ? "**" : "--", buffer.path_.c_str(), buffer.snapshot_.first_row_ + buffer.snapshot_.cursor_pos_.row_ + 1, buffer.snapshot_.cursor_pos_.col_); attroff(A_REVERSE); hline(' ', size.col_); move(buffer.snapshot_.cursor_pos_.row_, buffer.snapshot_.cursor_pos_.col_); curs_set(true); refresh(); }
27.878505
79
0.602749
geenen124
1be01f08d164fc69baeb7682f3aab33360199da3
2,887
cpp
C++
src/Http/HttpContext.cpp
MisakiOfScut/SingHttpServer
039636d7cee16ccc46c281456d71a410f3f16e23
[ "Apache-2.0" ]
1
2021-03-05T09:27:35.000Z
2021-03-05T09:27:35.000Z
src/Http/HttpContext.cpp
MisakiOfScut/SingHttpServer
039636d7cee16ccc46c281456d71a410f3f16e23
[ "Apache-2.0" ]
null
null
null
src/Http/HttpContext.cpp
MisakiOfScut/SingHttpServer
039636d7cee16ccc46c281456d71a410f3f16e23
[ "Apache-2.0" ]
null
null
null
#include "HttpContext.h" #include <unistd.h> #include <iostream> #include <bits/types/struct_iovec.h> using namespace sing; HttpContext::HttpContext(int fd) :state(REQUEST_LINE),fd(fd),working(false){ assert(fd>=0); } HttpContext::~HttpContext(){ close(fd);// FIX ME } bool HttpContext::parseRequest(){ bool ok = true; bool hasMore = true; while (hasMore) { if (state == REQUEST_LINE) { const char* crlf = input.findCRLF(); if(crlf){ ok = parseRequestLine(input.peek(),crlf); if(ok){ input.retrieveUntil(crlf + 2); state = HEADERS; }else{ hasMore = false; } }else{ hasMore = false; } }else if (state == HEADERS) { const char* crlf = input.findCRLF(); if(crlf){ const char* colon = std::find(input.peek(),crlf,':'); if(colon!=crlf){ request.addHeader(input.peek(),colon,crlf); }else{ state = BODY; hasMore = true; } input.retrieveUntil(crlf + 2); }else{ hasMore = false; } }else if (state==BODY) { //TO ADD: process requestbody state = FINSH; hasMore = false; } } return ok; } bool HttpContext::parseRequestLine(const char* begin, const char* end){ bool success = false; const char* start = begin; const char* space = std::find(start, end, ' ');//find the 1st space in a line if(space!=end && request.setMethod(start,space)){ start = space + 1; space = std::find(start, end, ' '); if(space!=end){ const char* quest = std::find(start, space, '?'); if (quest!=space) { request.setPath(start,quest); request.setQuery(quest, space); }else{ request.setPath(start, space); } //parse http version start = space + 1; success = end-start == 8 && std::equal(start, end-1, "HTTP/1."); if(success){ if(*(end-1)=='1'){ request.setVersion(HttpRequest::HTTP11); }else if(*(end-1)=='0'){ request.setVersion(HttpRequest::HTTP10); }else{ success = false; } } } } return success; } bool HttpContext::parseFinsh(){ return state == FINSH; } void HttpContext::reset(){ state = REQUEST_LINE; input.retrieveAll(); output.retrieveAll(); output.setWriteFile(NULL, 0); request.reset(); response.reset(); }
25.776786
81
0.472116
MisakiOfScut
1be0a95f175a7c09216195eede94d650accf8a95
5,230
cc
C++
third_party/chromium/mp4/src/mp4/video_codecs.cc
google/ndash
1465e2fb851ee17fd235280bdbbbf256e5af8044
[ "Apache-2.0" ]
41
2017-04-19T19:38:10.000Z
2021-09-07T02:40:27.000Z
third_party/chromium/mp4/src/mp4/video_codecs.cc
google/ndash
1465e2fb851ee17fd235280bdbbbf256e5af8044
[ "Apache-2.0" ]
8
2017-04-21T16:40:09.000Z
2019-12-09T19:48:40.000Z
third_party/chromium/mp4/src/mp4/video_codecs.cc
google/ndash
1465e2fb851ee17fd235280bdbbbf256e5af8044
[ "Apache-2.0" ]
19
2017-04-24T14:43:18.000Z
2022-03-17T19:13:45.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "mp4/video_codecs.h" #include "base/logging.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" namespace media { // The names come from src/third_party/ffmpeg/libavcodec/codec_desc.c std::string GetCodecName(VideoCodec codec) { switch (codec) { case kUnknownVideoCodec: return "unknown"; case kCodecH264: return "h264"; case kCodecHEVC: return "hevc"; case kCodecVC1: return "vc1"; case kCodecMPEG2: return "mpeg2video"; case kCodecMPEG4: return "mpeg4"; case kCodecTheora: return "theora"; case kCodecVP8: return "vp8"; case kCodecVP9: return "vp9"; } NOTREACHED(); return ""; } std::string GetProfileName(VideoCodecProfile profile) { switch (profile) { case VIDEO_CODEC_PROFILE_UNKNOWN: return "unknown"; case H264PROFILE_BASELINE: return "h264 baseline"; case H264PROFILE_MAIN: return "h264 main"; case H264PROFILE_EXTENDED: return "h264 extended"; case H264PROFILE_HIGH: return "h264 high"; case H264PROFILE_HIGH10PROFILE: return "h264 high 10"; case H264PROFILE_HIGH422PROFILE: return "h264 high 4:2:2"; case H264PROFILE_HIGH444PREDICTIVEPROFILE: return "h264 high 4:4:4 predictive"; case H264PROFILE_SCALABLEBASELINE: return "h264 scalable baseline"; case H264PROFILE_SCALABLEHIGH: return "h264 scalable high"; case H264PROFILE_STEREOHIGH: return "h264 stereo high"; case H264PROFILE_MULTIVIEWHIGH: return "h264 multiview high"; case HEVCPROFILE_MAIN: return "hevc main"; case HEVCPROFILE_MAIN10: return "hevc main 10"; case HEVCPROFILE_MAIN_STILL_PICTURE: return "hevc main still-picture"; case VP8PROFILE_ANY: return "vp8"; case VP9PROFILE_PROFILE0: return "vp9 profile0"; case VP9PROFILE_PROFILE1: return "vp9 profile1"; case VP9PROFILE_PROFILE2: return "vp9 profile2"; case VP9PROFILE_PROFILE3: return "vp9 profile3"; } NOTREACHED(); return ""; } bool ParseAVCCodecId(const std::string& codec_id, VideoCodecProfile* profile, uint8_t* level_idc) { // Make sure we have avc1.xxxxxx or avc3.xxxxxx , where xxxxxx are hex digits if (!base::StartsWith(codec_id, "avc1.", base::CompareCase::SENSITIVE) && !base::StartsWith(codec_id, "avc3.", base::CompareCase::SENSITIVE)) { return false; } uint32_t elem = 0; if (codec_id.size() != 11 || !base::HexStringToUInt(base::StringPiece(codec_id).substr(5), &elem)) { DVLOG(4) << __FUNCTION__ << ": invalid avc codec id (" << codec_id << ")"; return false; } uint8_t level_byte = elem & 0xFF; uint8_t constraints_byte = (elem >> 8) & 0xFF; uint8_t profile_idc = (elem >> 16) & 0xFF; // Check that the lower two bits of |constraints_byte| are zero (those are // reserved and must be zero according to ISO IEC 14496-10). if (constraints_byte & 3) { DVLOG(4) << __FUNCTION__ << ": non-zero reserved bits in codec id " << codec_id; return false; } VideoCodecProfile out_profile = VIDEO_CODEC_PROFILE_UNKNOWN; // profile_idc values for each profile are taken from ISO IEC 14496-10 and // https://en.wikipedia.org/wiki/H.264/MPEG-4_AVC#Profiles switch (profile_idc) { case 66: out_profile = H264PROFILE_BASELINE; break; case 77: out_profile = H264PROFILE_MAIN; break; case 83: out_profile = H264PROFILE_SCALABLEBASELINE; break; case 86: out_profile = H264PROFILE_SCALABLEHIGH; break; case 88: out_profile = H264PROFILE_EXTENDED; break; case 100: out_profile = H264PROFILE_HIGH; break; case 110: out_profile = H264PROFILE_HIGH10PROFILE; break; case 118: out_profile = H264PROFILE_MULTIVIEWHIGH; break; case 122: out_profile = H264PROFILE_HIGH422PROFILE; break; case 128: out_profile = H264PROFILE_STEREOHIGH; break; case 244: out_profile = H264PROFILE_HIGH444PREDICTIVEPROFILE; break; default: DVLOG(1) << "Warning: unrecognized AVC/H.264 profile " << profile_idc; return false; } // TODO(servolk): Take into account also constraint set flags 3 through 5. uint8_t constraint_set0_flag = (constraints_byte >> 7) & 1; uint8_t constraint_set1_flag = (constraints_byte >> 6) & 1; uint8_t constraint_set2_flag = (constraints_byte >> 5) & 1; if (constraint_set2_flag && out_profile > H264PROFILE_EXTENDED) { out_profile = H264PROFILE_EXTENDED; } if (constraint_set1_flag && out_profile > H264PROFILE_MAIN) { out_profile = H264PROFILE_MAIN; } if (constraint_set0_flag && out_profile > H264PROFILE_BASELINE) { out_profile = H264PROFILE_BASELINE; } if (level_idc) *level_idc = level_byte; if (profile) *profile = out_profile; return true; } } // namespace media
29.055556
79
0.673423
google
1be324fe4fb70a4b08022431c19002cb56571040
6,046
cpp
C++
ASSIGNMENTS_MCA_3RD_SEM/Section B/Q9/q9.cpp
therishh/Data-Structures-and-Algorithms
4e0daf666b94615268478bec8be1ca1b55f2a807
[ "MIT" ]
null
null
null
ASSIGNMENTS_MCA_3RD_SEM/Section B/Q9/q9.cpp
therishh/Data-Structures-and-Algorithms
4e0daf666b94615268478bec8be1ca1b55f2a807
[ "MIT" ]
null
null
null
ASSIGNMENTS_MCA_3RD_SEM/Section B/Q9/q9.cpp
therishh/Data-Structures-and-Algorithms
4e0daf666b94615268478bec8be1ca1b55f2a807
[ "MIT" ]
null
null
null
// // q9.cpp // Algorithm // // Created by Mohd Shoaib Rayeen on 13/11/18. // Copyright © 2018 Shoaib Rayeen. All rights reserved. // #include <iostream> #include <vector> #include <algorithm> using namespace std; class triathlon { /* ------------------------------------------------------------------------------------------------ objective : class to decide the order to minimize completion time ------------------------------------------------------------------------------------------------ input parameter : none ------------------------------------------------------------------------------------------------ output parameter : none ------------------------------------------------------------------------------------------------ approach : declaring member functions which can ve accessed publicly - mainFunction() -> to decide order display() -> print user's data helper() -> to insert dara and call member functions ------------------------------------------------------------------------------------------------ */ public: int n; void mainFunction(vector<vector<int>> &data); void display(vector<vector<int>> data); void helper(); }; bool selectColumn(const vector<int>& v1, const vector<int>& v2) { /* ------------------------------------------------------------------------------------------------ objective : select column by which sorting can be applied -> increasing order ------------------------------------------------------------------------------------------------ input parameter : none ------------------------------------------------------------------------------------------------ output parameter : false -> decreasing order true -> increasing order ------------------------------------------------------------------------------------------------ approach : return bool value which detmines which column has to sorted ------------------------------------------------------------------------------------------------ */ return v1[1] < v2[1]; } void triathlon::mainFunction(vector<vector<int>> &data) { /* ------------------------------------------------------------------------------------------------ objective : main function to decide the order ------------------------------------------------------------------------------------------------ input parameter : none ------------------------------------------------------------------------------------------------ output parameter : none ------------------------------------------------------------------------------------------------ approach : sorting according to swim time and displaying order ------------------------------------------------------------------------------------------------ */ sort(data.begin() , data.end() , selectColumn ); cout << "\nFollowings are the order of contestants for small completion time\n\n"; for (int i = 0; i < data.size(); i++) { cout << data[i][0] << "\t"; } cout << endl; } void triathlon::display(vector<vector<int>> data) { /* ------------------------------------------------------------------------------------------------ objective : print the data ------------------------------------------------------------------------------------------------ input parameter : none ------------------------------------------------------------------------------------------------ output parameter : none ------------------------------------------------------------------------------------------------ approach : displaying using loop ------------------------------------------------------------------------------------------------ */ cout << "\n-----------------------------------------------------------------"; cout << "\nContestant Number\t|\tSwim Time\t|\tBike Time\t|\tRun Time\n"; cout << "-----------------------------------------------------------------\n"; for ( int i = 0; i < data.size(); i++ ) { cout << "\t\t" << data[i][0] << "\t\t\t|\t\t" << data[i][1] << "\t\t|\t\t" << data[i][2] << "\t\t|\t" << data[i][3]; cout << endl; } } void triathlon::helper() { /* ------------------------------------------------------------------------------------------------ objective : insert the data and call member functions ------------------------------------------------------------------------------------------------ input parameter : none ------------------------------------------------------------------------------------------------ output parameter : none ------------------------------------------------------------------------------------------------ approach : insertion using loop and then calling member functions ------------------------------------------------------------------------------------------------ */ /* vector<vector<int>> data{ { 1 , 52 , 13 , 15} , { 2 , 19 , 17 , 13} , { 3 , 99 , 13 , 10 } , { 4 , 79 , 18 , 17 } , { 5 , 37 , 13 , 14 } , { 6 , 67 , 10 , 14 } , { 7 , 89 , 13 , 19} }; */ cout << "\nEnter Number of contestants\t:\t"; cin >> n; vector<vector<int>> data(n); cout << "\nEnter Value in this form\n"; cout << "\nSwim Time , Bike Time and then Run Time\n"; for ( int i = 0; i < n; i++) { data[i] = vector<int>(4); data[i][0] = i + 1; cin >> data[i][1]; cin >> data[i][2]; cin >> data[i][3]; } display(data); mainFunction(data); data.clear(); } int main() { triathlon obj; obj.helper(); return 0; }
35.775148
124
0.291598
therishh
1be5a97bef7d8c1cabb90ce9e64eb1168d42bcac
8,234
cc
C++
src/core/events.cc
tcoppex/barbu
02be5b3179a460560191818d9ee1c3ba4ee858c9
[ "MIT" ]
2
2021-04-15T04:58:01.000Z
2021-10-11T05:17:34.000Z
src/core/events.cc
tcoppex/barbu
02be5b3179a460560191818d9ee1c3ba4ee858c9
[ "MIT" ]
null
null
null
src/core/events.cc
tcoppex/barbu
02be5b3179a460560191818d9ee1c3ba4ee858c9
[ "MIT" ]
null
null
null
#include "core/events.h" #include <algorithm> #include "core/logger.h" #include "ui/imgui_wrapper.h" //<! used for UI events preemption. // ---------------------------------------------------------------------------- void Events::prepareNextFrame() { // Reset per-frame values. mouse_moved_ = false; mouse_hover_ui_ = false; has_resized_ = false; last_input_char_ = 0; mouse_wheel_delta_ = 0.0f; dropped_filenames_.clear(); // Detect if any mouse buttons are still "Pressed" or "Down". mouse_button_down_ = std::any_of(buttons_.cbegin(), buttons_.cend(), [](auto const& btn) { auto const state(btn.second); return (state == KeyState::Down) || (state == KeyState::Pressed); }); // Update "Pressed" states to "Down", "Released" states to "Up". auto const update_state{ [](auto& btn) { auto const state(btn.second); btn.second = (state == KeyState::Pressed) ? KeyState::Down : (state == KeyState::Released) ? KeyState::Up : state; }}; std::for_each(buttons_.begin(), buttons_.end(), update_state); std::for_each(keys_.begin(), keys_.end(), update_state); } // ---------------------------------------------------------------------------- /* Bypass events capture when pointer hovers UI. */ #define EVENTS_IMGUI_BYPASS_( code, bMouse, bKeyboard ) \ { \ auto &io{ImGui::GetIO()}; \ mouse_hover_ui_ = io.WantCaptureMouse; \ { code ;} \ if ((bMouse) && (bKeyboard)) { return; } \ } /* Bypass if the UI want the mouse */ #define EVENTS_IMGUI_BYPASS_MOUSE( code ) \ EVENTS_IMGUI_BYPASS_(code, io.WantCaptureMouse, true) /* Bypass if the UI want the pointer or the keyboard. */ #define EVENTS_IMGUI_BYPASS_MOUSE_KB( code ) \ EVENTS_IMGUI_BYPASS_(code, io.WantCaptureMouse, io.WantCaptureKeyboard) /* Do not bypass. */ #define EVENTS_IMGUI_CONTINUE( code ) \ EVENTS_IMGUI_BYPASS_(code, false, false) /* Dispatch event signal to sub callbacks handlers. */ #define EVENTS_DISPATCH_SIGNAL( funcName, ... ) \ static_assert( std::string_view(#funcName)==__func__, "Incorrect dispatch signal used."); \ std::for_each(event_callbacks_.begin(), event_callbacks_.end(), [__VA_ARGS__](auto &e){ e->funcName(__VA_ARGS__); }) // ---------------------------------------------------------------------------- void Events::onKeyPressed(KeyCode_t key) { EVENTS_IMGUI_CONTINUE( if (io.WantCaptureKeyboard || io.WantCaptureMouse) { io.KeysDown[key] = true; } ); keys_[key] = KeyState::Pressed; key_pressed_.push( key ); EVENTS_DISPATCH_SIGNAL(onKeyPressed, key); } void Events::onKeyReleased(KeyCode_t key) { EVENTS_IMGUI_CONTINUE( if (io.WantCaptureKeyboard || io.WantCaptureMouse) { io.KeysDown[key] = false; } ); keys_[key] = KeyState::Released; EVENTS_DISPATCH_SIGNAL(onKeyReleased, key); } void Events::onInputChar(uint16_t c) { EVENTS_IMGUI_BYPASS_MOUSE_KB( if (io.WantCaptureKeyboard) { io.AddInputCharacter(c); } ); last_input_char_ = c; EVENTS_DISPATCH_SIGNAL(onInputChar, c); } void Events::onMousePressed(int x, int y, KeyCode_t button) { EVENTS_IMGUI_BYPASS_MOUSE( io.MouseDown[button] = true; io.MousePos = ImVec2((float)x, (float)y); ); buttons_[button] = KeyState::Pressed; EVENTS_DISPATCH_SIGNAL(onMousePressed, x, y, button); } void Events::onMouseReleased(int x, int y, KeyCode_t button) { EVENTS_IMGUI_BYPASS_MOUSE( io.MouseDown[button] = false; io.MousePos = ImVec2((float)x, (float)y); ); buttons_[button] = KeyState::Released; EVENTS_DISPATCH_SIGNAL(onMouseReleased, x, y, button); } void Events::onMouseEntered(int x, int y) { EVENTS_DISPATCH_SIGNAL(onMouseEntered, x, y); } void Events::onMouseExited(int x, int y) { EVENTS_DISPATCH_SIGNAL(onMouseExited, x, y); } void Events::onMouseMoved(int x, int y) { EVENTS_IMGUI_BYPASS_MOUSE(); mouse_x_ = x; mouse_y_ = y; mouse_moved_ = true; EVENTS_DISPATCH_SIGNAL(onMouseMoved, x, y); } void Events::onMouseDragged(int x, int y, KeyCode_t button) { EVENTS_IMGUI_BYPASS_MOUSE( io.MouseDown[button] = true; io.MousePos = ImVec2((float)x, (float)y); ); mouse_x_ = x; mouse_y_ = y; mouse_moved_ = true; // (note : the button should already be registered as pressed / down) EVENTS_DISPATCH_SIGNAL(onMouseDragged, x, y, button); } void Events::onMouseWheel(float dx, float dy) { EVENTS_IMGUI_BYPASS_MOUSE( io.MouseWheelH += dx; io.MouseWheel += dy; ); mouse_wheel_delta_ = dy; mouse_wheel_ += dy; EVENTS_DISPATCH_SIGNAL(onMouseWheel, dx, dy); } void Events::onResize(int w, int h) { // EVENTS_IMGUI_CONTINUE( // io.DisplaySize = ImVec2(static_cast<float>(w), static_cast<float>(h)); // io.DisplayFramebufferScale = ImVec2( 1.0f, 1.0f); // // ); // [beware : downcast from int32 to int16] surface_w_ = static_cast<SurfaceSize>(w); surface_h_ = static_cast<SurfaceSize>(h); has_resized_ = true; EVENTS_DISPATCH_SIGNAL(onResize, w, h); } void Events::onFilesDropped(int count, char const** paths) { for (int i=0; i<count; ++i) { dropped_filenames_.push_back(std::string(paths[i])); } EVENTS_DISPATCH_SIGNAL(onFilesDropped, count, paths); } #undef EVENTS_IMGUI_BYPASS #undef EVENTS_DISPATCH_SIGNAL // ---------------------------------------------------------------------------- bool Events::buttonDown(KeyCode_t button) const noexcept { return checkButtonState( button, [](KeyState state) { return (state == KeyState::Pressed) || (state == KeyState::Down); }); } bool Events::buttonPressed(KeyCode_t button) const noexcept { return checkButtonState( button, [](KeyState state) { return (state == KeyState::Pressed); }); } bool Events::buttonReleased(KeyCode_t button) const noexcept { return checkButtonState( button, [](KeyState state) { return (state == KeyState::Released); }); } // ---------------------------------------------------------------------------- bool Events::keyDown(KeyCode_t key) const noexcept { return checkKeyState( key, [](KeyState state) { return (state == KeyState::Pressed) || (state == KeyState::Down); }); } bool Events::keyPressed(KeyCode_t key) const noexcept { return checkKeyState( key, [](KeyState state) { return (state == KeyState::Pressed); }); } bool Events::keyReleased(KeyCode_t key) const noexcept { return checkKeyState( key, [](KeyState state) { return (state == KeyState::Released); }); } // ---------------------------------------------------------------------------- bool Events::checkButtonState(KeyCode_t button, StatePredicate_t predicate) const noexcept { if (auto search = buttons_.find(button); search != buttons_.end()) { return predicate(search->second); } return false; } bool Events::checkKeyState(KeyCode_t key, StatePredicate_t predicate) const noexcept { if (auto search = keys_.find(key); search != keys_.end()) { return predicate(search->second); } return false; } // ---------------------------------------------------------------------------- #if 0 namespace { void keyboard_cb(GLFWwindow *window, int key, int, int action, int) { // [temporary] if ((key >= GLFW_KEY_KP_0) && (key <= GLFW_KEY_KP_9)) { s_Global.bKeypad |= (action == GLFW_PRESS); s_Global.bKeypad &= (action != GLFW_RELEASE); } // When the UI capture keyboard, don't process it. ImGuiIO& io = ImGui::GetIO(); if (io.WantCaptureKeyboard || io.WantCaptureMouse) { io.KeysDown[key] = (action == GLFW_PRESS); io.KeyCtrl = io.KeysDown[GLFW_KEY_LEFT_CONTROL] || io.KeysDown[GLFW_KEY_RIGHT_CONTROL]; io.KeyShift = io.KeysDown[GLFW_KEY_LEFT_SHIFT] || io.KeysDown[GLFW_KEY_RIGHT_SHIFT]; io.KeyAlt = io.KeysDown[GLFW_KEY_LEFT_ALT] || io.KeysDown[GLFW_KEY_RIGHT_ALT]; io.KeySuper = io.KeysDown[GLFW_KEY_LEFT_SUPER] || io.KeysDown[GLFW_KEY_RIGHT_SUPER]; //return; } UpdateButton(key, action, GLFW_KEY_LEFT_CONTROL, s_Global.bLeftCtrl); UpdateButton(key, action, GLFW_KEY_LEFT_ALT, s_Global.bLeftAlt); UpdateButton(key, action, GLFW_KEY_LEFT_SHIFT, s_Global.bLeftShift); } } // namespace // ---------------------------------------------------------------------------- #endif
28.992958
118
0.63845
tcoppex
1bea047d1eaa1f89b50ad105e7e550ee6f5e9005
5,063
cpp
C++
obvclip/tests/test_convex_polytope.cpp
javierdelapuente/tfm_ode_bullet
cc0d40b9a91e43b5045c10903b5244e680d909ef
[ "Zlib" ]
1
2021-04-08T11:22:13.000Z
2021-04-08T11:22:13.000Z
obvclip/tests/test_convex_polytope.cpp
javierdelapuente/tfm_ode_bullet
cc0d40b9a91e43b5045c10903b5244e680d909ef
[ "Zlib" ]
null
null
null
obvclip/tests/test_convex_polytope.cpp
javierdelapuente/tfm_ode_bullet
cc0d40b9a91e43b5045c10903b5244e680d909ef
[ "Zlib" ]
null
null
null
#include "gtest/gtest.h" #include <fstream> #include "polytope.hpp" #include "polytope_examples.hpp" using namespace OB; TEST(TESTConvexPolytope, basicTest) { std::vector<Point> points; points.push_back(Point(-1, -1, -1)); points.push_back(Point(-1, -1, 1)); points.push_back(Point(-1, 1, -1)); points.push_back(Point(-1, 1, 1)); points.push_back(Point(1, -1, -1)); points.push_back(Point(1, -1, 1)); points.push_back(Point(1, 1, -1)); points.push_back(Point(1, 1, 1)); ConvexPolytope poly; poly.generate_from_vertices(points); ASSERT_EQ(poly.euler_number_correct(), true); //TODO ASSERT, 8 VERTICES, 6 FACES //TODO CHECK ONE FACE CCW. //TODO ASSERT EULER NUMBER std::vector<std::pair<Feature, Plane>> allfacesplanes = poly.get_faces_with_planes(); ASSERT_EQ(allfacesplanes.size(), 6); Feature f0 = allfacesplanes[0].first; ASSERT_EQ(poly.get_face_edgepoints(f0).size(), 4); ASSERT_EQ(poly.get_scan_face(f0).size(), 8); std::cout << poly << std::endl; } TEST(TESTConvexPolytope, testPrismPolytope) { std::shared_ptr<OB::ConvexPolytope> prism = std::make_shared<OB::ConvexPolytope>(create_prism_polytope (3)); //std::cout << "PRISM: " << *prism << std::endl; } TEST(TESTConvexPolytope, shortestBetweenPointEdge) { // distance equal segment and line Point point{1,1,1}; Point tail{7, 7, 7}; Point head{1, 0, -1}; Vector director = head - tail; EdgePoints edge {tail, head}; std::cout << "distance from point " << point.transpose() << " to segment: " << edge << std::endl; ASSERT_FLOAT_EQ(dist_point_edge(point, edge), 1.2040201117631721); // now one in which the distance is smaller in the head head = head + (tail - director*0.3); edge = EdgePoints{tail, head}; std::cout << "distance from point " << point.transpose() << " to segment: " << edge << std::endl; ASSERT_FLOAT_EQ(dist_point_edge(point, edge), 10.392304); // now one in which the distance is smaller in the tail head = Point{1, 0, -1} + (tail + director*10); tail = tail + (tail + director*10); edge = EdgePoints{tail, head}; std::cout << "distance from point " << point.transpose() << " to segment: " << edge << std::endl; ASSERT_FLOAT_EQ(dist_point_edge(point, edge), 99.73465); // one with the point in the line point = Point {1,1,1}; edge = EdgePoints{{0,1,1}, {2,1,1}}; ASSERT_FLOAT_EQ(dist_point_edge(point, edge), 0.0); // one with the point in the line not in segment point = Point {0,1,1}; edge = EdgePoints{{1,1,1}, {2,1,1}}; ASSERT_FLOAT_EQ(dist_point_edge(point, edge), 1.0); } TEST(TESTConvexPolytope, shortestBetweenEdgeEdge) { // for line - line, we can use https://keisan.casio.com/exec/system/1223531414# // caso degenerado, segmentos paralelos EdgePoints edge1{Point{0, 0, 1}, Point{0, 2, 1}}; EdgePoints edge2{Point{1, 1, 0}, Point{1, -1, 0}}; std::cout << "distance from segment: " << edge1 << " to segment: " << edge2 << std::endl; ASSERT_FLOAT_EQ(dist_edge_edge(edge1, edge2), 1.4142135); // otro caso degenerado, pero el punto mas cercano // no pertenece a los segmentos. edge1 = EdgePoints{Point{0, 0, 1}, Point{0, 2, 1}}; edge2 = EdgePoints{Point{1, -1, 0}, Point{1, -2, 0}}; std::cout << "distance from segment: " << edge1 << " to segment: " << edge2 << std::endl; ASSERT_FLOAT_EQ(dist_edge_edge(edge1, edge2), 1.7320508); // mismo segmento edge1 = EdgePoints{Point{0, 0, 1}, Point{0, 2, 1}}; edge2 = EdgePoints{Point{0, 0, 1}, Point{0, 2, 1}}; std::cout << "distance from segment: " << edge1 << " to segment: " << edge2 << std::endl; ASSERT_FLOAT_EQ(dist_edge_edge(edge1, edge2), 0.0); // minimum points inside both segments edge1 = EdgePoints{Point{0,4,2}, Point{0,0,2}}; edge2 = EdgePoints{Point{-1,3,0}, Point{2,0,0}}; std::cout << "distance from segment: " << edge1 << " to segment: " << edge2 << std::endl; ASSERT_FLOAT_EQ(dist_edge_edge(edge1, edge2), 2.0); // minimum points in only one segment and one of the edges edge1 = EdgePoints{Point{0,1.5,2}, Point{0,0,2}}; edge2 = EdgePoints{Point{-1,3,0}, Point{2,0,0}}; std::cout << "distance from segment: " << edge1 << " to segment: " << edge2 << std::endl; ASSERT_FLOAT_EQ(dist_edge_edge(edge1, edge2), 2.0310097); // minimum points in two edge points edge1 = EdgePoints{Point{0,0,1}, Point{0,0,0}}; edge2 = EdgePoints{Point{1,1,-1}, Point{1,2,-1}}; std::cout << "distance from segment: " << edge1 << " to segment: " << edge2 << std::endl; ASSERT_FLOAT_EQ(dist_edge_edge(edge1, edge2), 1.7320508); } TEST(TESTConvexPolytope, readwritefromfile) { std::ostringstream oss; OB::ConvexPolytope tetrahedron = create_tetrahedron_polytope(1.0); tetrahedron.write(oss); std::string first = oss.str(); std::istringstream iss{first}; OB::ConvexPolytope leido = OB::ConvexPolytope::create(iss); std::ostringstream oss2; leido.write(oss2); std::string second = oss2.str(); ASSERT_EQ(first, second); }
32.455128
110
0.6508
javierdelapuente
1bea19058f4b17ba0b19109b788f5a10cc5e9a62
1,269
cc
C++
Mu2eUtilities/src/RandomUnitSphere.cc
resnegfk/Offline
4ba81dad54486188fa83fea8c085438d104afbbc
[ "Apache-2.0" ]
9
2020-03-28T00:21:41.000Z
2021-12-09T20:53:26.000Z
Mu2eUtilities/src/RandomUnitSphere.cc
resnegfk/Offline
4ba81dad54486188fa83fea8c085438d104afbbc
[ "Apache-2.0" ]
684
2019-08-28T23:37:43.000Z
2022-03-31T22:47:45.000Z
Mu2eUtilities/src/RandomUnitSphere.cc
resnegfk/Offline
4ba81dad54486188fa83fea8c085438d104afbbc
[ "Apache-2.0" ]
61
2019-08-16T23:28:08.000Z
2021-12-20T08:29:48.000Z
// // Return CLHEP::Hep3Vector objects that are unit vectors uniformly // distributed over the unit sphere. // // // Original author Rob Kutschke // #include "Offline/Mu2eUtilities/inc/RandomUnitSphere.hh" #include "Offline/Mu2eUtilities/inc/ThreeVectorUtil.hh" namespace CLHEP { class HepRandomEngine; } using CLHEP::Hep3Vector; using CLHEP::RandFlat; namespace mu2e{ RandomUnitSphere::RandomUnitSphere( CLHEP::HepRandomEngine& engine, double czmin, double czmax, double phimin, double phimax): _czmin(czmin), _czmax(czmax), _phimin(phimin), _phimax(phimax), _randFlat( engine ){ } RandomUnitSphere::RandomUnitSphere( CLHEP::HepRandomEngine& engine, const RandomUnitSphereParams& pars): _czmin(pars.czmin), _czmax(pars.czmax), _phimin(pars.phimin), _phimax(pars.phimax), _randFlat( engine ){ } CLHEP::Hep3Vector RandomUnitSphere::fire(){ double cz = _czmin + ( _czmax - _czmin )*_randFlat.fire(); double phi = _phimin + ( _phimax - _phimin )*_randFlat.fire(); return polar3Vector ( 1., cz, phi); } }
25.897959
74
0.602049
resnegfk
1bea191f3634094731b743274e4e9f4050db1f5b
1,273
cpp
C++
projects/hydra/src/Hydra/Debug/Logging/Logger.cpp
Drischdaan/HydraEngine
587f5d61d9b2f0c3951db3467d839ba39896e44f
[ "Apache-2.0" ]
null
null
null
projects/hydra/src/Hydra/Debug/Logging/Logger.cpp
Drischdaan/HydraEngine
587f5d61d9b2f0c3951db3467d839ba39896e44f
[ "Apache-2.0" ]
null
null
null
projects/hydra/src/Hydra/Debug/Logging/Logger.cpp
Drischdaan/HydraEngine
587f5d61d9b2f0c3951db3467d839ba39896e44f
[ "Apache-2.0" ]
null
null
null
#include "hypch.h" #include <Hydra/Debug/Logging/Logger.h> #include "spdlog/sinks/stdout_color_sinks.h" void Hydra::Debug::Logger::Initialize() { const auto consoleSink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>(); consoleSink->set_level(static_cast<spdlog::level::level_enum>(LOGGER_ACTIVE_LEVEL)); consoleSink->set_pattern("%^[%H:%M:%S] [%n] [%s:%#] %8l:%$ %v"); const spdlog::sinks_init_list sinkList = { consoleSink }; s_EngineLogger = std::make_shared<spdlog::logger>("ENGINE:CORE", sinkList.begin(), sinkList.end()); s_EngineLogger->set_level(static_cast<spdlog::level::level_enum>(LOGGER_ACTIVE_LEVEL)); s_ApplicationLogger = std::make_shared<spdlog::logger>("APPLICATION", sinkList.begin(), sinkList.end()); s_ApplicationLogger->set_level(static_cast<spdlog::level::level_enum>(LOGGER_ACTIVE_LEVEL)); spdlog::register_logger(s_EngineLogger); spdlog::register_logger(s_ApplicationLogger); spdlog::set_default_logger(s_EngineLogger); spdlog::set_level(static_cast<spdlog::level::level_enum>(LOGGER_ACTIVE_LEVEL)); spdlog::set_pattern("%^[%H:%M:%S] [%n] [%s:%#] %8l:%$ %v"); LOG_ENGINE_DEBUG("Logging initialized"); } void Hydra::Debug::Logger::Shutdown() { spdlog::shutdown(); }
36.371429
108
0.714061
Drischdaan
1bebbbc9d211a9e8a751dbb00cfd610b27ee39fb
75,396
cpp
C++
src/core/particle.cpp
jojoelfe/cisTEM
6d5bc5803fd726022c381e65a721a24661b48639
[ "BSD-3-Clause" ]
null
null
null
src/core/particle.cpp
jojoelfe/cisTEM
6d5bc5803fd726022c381e65a721a24661b48639
[ "BSD-3-Clause" ]
9
2022-03-21T13:16:20.000Z
2022-03-31T00:07:13.000Z
src/core/particle.cpp
jojoelfe/cisTEM
6d5bc5803fd726022c381e65a721a24661b48639
[ "BSD-3-Clause" ]
null
null
null
#include "core_headers.h" ParameterMap::ParameterMap( ) { phi = false; theta = false; psi = false; x_shift = false; y_shift = false; } void ParameterMap::SetAllTrue( ) { phi = true; theta = true; psi = true; x_shift = true; y_shift = true; } Particle::Particle( ) { Init( ); } Particle::Particle(int wanted_logical_x_dimension, int wanted_logical_y_dimension) { Init( ); AllocateImage(wanted_logical_x_dimension, wanted_logical_y_dimension); } Particle::~Particle( ) { if ( particle_image != NULL ) { delete particle_image; } if ( ctf_image != NULL ) { delete ctf_image; } if ( beamtilt_image != NULL ) { delete beamtilt_image; } if ( bin_index != NULL ) { delete[] bin_index; } } void Particle::CopyAllButImages(const Particle* other_particle) { // Check for self assignment if ( this != other_particle ) { origin_micrograph = other_particle->origin_micrograph; origin_x_coordinate = other_particle->origin_x_coordinate; origin_y_coordinate = other_particle->origin_y_coordinate; location_in_stack = other_particle->location_in_stack; pixel_size = other_particle->pixel_size; sigma_signal = other_particle->sigma_signal; sigma_noise = other_particle->sigma_noise; snr = other_particle->snr; logp = other_particle->logp; particle_occupancy = other_particle->particle_occupancy; particle_score = other_particle->particle_score; alignment_parameters = other_particle->alignment_parameters; scaled_noise_variance = other_particle->scaled_noise_variance; parameter_constraints = other_particle->parameter_constraints; ctf_parameters = other_particle->ctf_parameters; current_ctf = other_particle->current_ctf; ctf_is_initialized = other_particle->ctf_is_initialized; ctf_image_calculated = false; beamtilt_image_calculated = false; includes_reference_ssnr_weighting = false; is_normalized = false; is_phase_flipped = false; is_masked = false; mask_radius = other_particle->mask_radius; mask_falloff = other_particle->mask_falloff; mask_volume = other_particle->mask_volume; molecular_mass_kDa = other_particle->molecular_mass_kDa; is_filtered = false; filter_radius_low = other_particle->filter_radius_low; filter_radius_high = other_particle->filter_radius_high; filter_falloff = other_particle->filter_falloff; filter_volume = other_particle->filter_volume; signed_CC_limit = other_particle->signed_CC_limit; is_ssnr_filtered = false; is_centered_in_box = true; shift_counter = 0; insert_even = other_particle->insert_even; target_phase_error = other_particle->target_phase_error; current_parameters = other_particle->current_parameters; temp_parameters = other_particle->temp_parameters; parameter_average = other_particle->parameter_average; parameter_variance = other_particle->parameter_variance; parameter_map = other_particle->parameter_map; constraints_used = other_particle->constraints_used; number_of_search_dimensions = other_particle->number_of_search_dimensions; mask_center_2d_x = other_particle->mask_center_2d_x; mask_center_2d_y = other_particle->mask_center_2d_y; mask_center_2d_z = other_particle->mask_center_2d_z; mask_radius_2d = other_particle->mask_radius_2d; apply_2D_masking = other_particle->apply_2D_masking; no_ctf_weighting = false; complex_ctf = other_particle->complex_ctf; if ( particle_image != NULL ) { delete particle_image; particle_image = NULL; } if ( ctf_image != NULL ) { delete ctf_image; ctf_image = NULL; } if ( beamtilt_image != NULL ) { delete beamtilt_image; beamtilt_image = NULL; } if ( bin_index != NULL ) { delete[] bin_index; bin_index = NULL; } } } void Particle::Init( ) { target_phase_error = 45.0; origin_micrograph = -1; origin_x_coordinate = -1; origin_y_coordinate = -1; location_in_stack = -1; pixel_size = 0.0; sigma_signal = 0.0; sigma_noise = 0.0; snr = 0.0; logp = -std::numeric_limits<float>::max( ); ; particle_occupancy = 0.0; particle_score = 0.0; particle_image = NULL; scaled_noise_variance = 0.0; ctf_is_initialized = false; ctf_image = NULL; ctf_image_calculated = false; beamtilt_image = NULL; beamtilt_image_calculated = false; includes_reference_ssnr_weighting = false; is_normalized = false; is_phase_flipped = false; is_masked = false; mask_radius = 0.0; mask_falloff = 0.0; mask_volume = 0.0; molecular_mass_kDa = 0.0; is_filtered = false; filter_radius_low = 0.0; filter_radius_high = 0.0; filter_falloff = 0.0; filter_volume = 0.0; signed_CC_limit = 0.0; is_ssnr_filtered = false; is_centered_in_box = true; shift_counter = 0; insert_even = false; number_of_search_dimensions = 0; bin_index = NULL; mask_center_2d_x = 0.0; mask_center_2d_y = 0.0; mask_center_2d_z = 0.0; mask_radius_2d = 0.0; apply_2D_masking = false; no_ctf_weighting = false; complex_ctf = false; } void Particle::AllocateImage(int wanted_logical_x_dimension, int wanted_logical_y_dimension) { if ( particle_image == NULL ) { particle_image = new Image; } particle_image->Allocate(wanted_logical_x_dimension, wanted_logical_y_dimension, 1, true); } void Particle::AllocateCTFImage(int wanted_logical_x_dimension, int wanted_logical_y_dimension) { if ( ctf_image == NULL ) { ctf_image = new Image; } ctf_image->Allocate(wanted_logical_x_dimension, wanted_logical_y_dimension, 1, false); if ( beamtilt_image == NULL ) { beamtilt_image = new Image; } beamtilt_image->Allocate(wanted_logical_x_dimension, wanted_logical_y_dimension, 1, false); } void Particle::Allocate(int wanted_logical_x_dimension, int wanted_logical_y_dimension) { AllocateImage(wanted_logical_x_dimension, wanted_logical_y_dimension); AllocateCTFImage(wanted_logical_x_dimension, wanted_logical_y_dimension); } void Particle::Deallocate( ) { if ( particle_image != NULL ) { delete particle_image; particle_image = NULL; } if ( ctf_image != NULL ) { delete ctf_image; ctf_image = NULL; } if ( beamtilt_image != NULL ) { delete beamtilt_image; beamtilt_image = NULL; } } void Particle::ResetImageFlags( ) { includes_reference_ssnr_weighting = false; is_normalized = false; is_phase_flipped = false; if ( is_masked ) { is_masked = false; mask_radius = 0.0; mask_falloff = 0.0; mask_volume = 0.0; }; if ( is_filtered ) { is_filtered = false; filter_radius_low = 0.0; filter_radius_high = 0.0; filter_falloff = 0.0; filter_volume = 0.0; }; is_ssnr_filtered = false; is_centered_in_box = true; shift_counter = 0; logp = -std::numeric_limits<float>::max( ); ; insert_even = false; no_ctf_weighting = false; } void Particle::PhaseShift( ) { MyDebugAssertTrue(particle_image->is_in_memory, "Memory not allocated"); MyDebugAssertTrue(abs(shift_counter) < 2, "Image already shifted"); if ( particle_image->is_in_real_space ) particle_image->ForwardFFT( ); particle_image->PhaseShift(alignment_parameters.ReturnShiftX( ) / pixel_size, alignment_parameters.ReturnShiftY( ) / pixel_size); shift_counter += 1; } void Particle::PhaseShiftInverse( ) { MyDebugAssertTrue(particle_image->is_in_memory, "Memory not allocated"); MyDebugAssertTrue(abs(shift_counter) < 2, "Image already shifted"); if ( particle_image->is_in_real_space ) particle_image->ForwardFFT( ); particle_image->PhaseShift(-alignment_parameters.ReturnShiftX( ) / pixel_size, -alignment_parameters.ReturnShiftY( ) / pixel_size); shift_counter -= 1; } void Particle::Whiten(float resolution_limit) { MyDebugAssertTrue(particle_image->is_in_memory, "Memory not allocated"); MyDebugAssertTrue(! particle_image->is_in_real_space, "Image not in Fourier space"); particle_image->Whiten(resolution_limit); } void Particle::ForwardFFT(bool do_scaling) { MyDebugAssertTrue(particle_image->is_in_memory, "Memory not allocated"); MyDebugAssertTrue(particle_image->is_in_real_space, "Image not in real space"); particle_image->ForwardFFT(do_scaling); } void Particle::BackwardFFT( ) { MyDebugAssertTrue(particle_image->is_in_memory, "Memory not allocated"); MyDebugAssertTrue(! particle_image->is_in_real_space, "Image not in Fourier space"); particle_image->BackwardFFT( ); } void Particle::CosineMask(bool invert, bool force_mask_value, float wanted_mask_value) { MyDebugAssertTrue(particle_image->is_in_memory, "Memory not allocated"); MyDebugAssertTrue(! is_masked, "Image already masked"); if ( ! particle_image->is_in_real_space ) particle_image->BackwardFFT( ); mask_volume = particle_image->CosineMask(mask_radius / pixel_size, mask_falloff / pixel_size, invert, force_mask_value, wanted_mask_value); is_masked = true; } void Particle::CenterInBox( ) { MyDebugAssertTrue(particle_image->is_in_memory, "Memory not allocated"); MyDebugAssertTrue(! particle_image->object_is_centred_in_box, "Image already centered"); MyDebugAssertTrue(! is_centered_in_box, "Image already centered"); if ( particle_image->is_in_real_space ) particle_image->ForwardFFT( ); particle_image->SwapRealSpaceQuadrants( ); is_centered_in_box = true; } void Particle::CenterInCorner( ) { MyDebugAssertTrue(particle_image->is_in_memory, "Memory not allocated"); MyDebugAssertTrue(particle_image->object_is_centred_in_box, "Image already centered"); MyDebugAssertTrue(is_centered_in_box, "Image already in corner"); if ( particle_image->is_in_real_space ) particle_image->ForwardFFT( ); particle_image->SwapRealSpaceQuadrants( ); is_centered_in_box = false; } void Particle::InitCTF(float voltage_kV, float spherical_aberration_mm, float amplitude_contrast, float defocus_1, float defocus_2, float astigmatism_angle, float phase_shift, float beam_tilt_x, float beam_tilt_y, float particle_shift_x, float particle_shift_y) { // MyDebugAssertTrue(! ctf_is_initialized, "CTF already initialized"); ctf_parameters.Init(voltage_kV, spherical_aberration_mm, amplitude_contrast, defocus_1, defocus_2, astigmatism_angle, 0.0, 0.0, 0.0, pixel_size, phase_shift, beam_tilt_x, beam_tilt_y, particle_shift_x, particle_shift_y); ctf_is_initialized = true; } void Particle::SetDefocus(float defocus_1, float defocus_2, float astigmatism_angle, float phase_shift) { MyDebugAssertTrue(ctf_is_initialized, "CTF not initialized"); ctf_parameters.SetDefocus(defocus_1 / pixel_size, defocus_2 / pixel_size, deg_2_rad(astigmatism_angle)); ctf_parameters.SetAdditionalPhaseShift(phase_shift); } void Particle::SetBeamTilt(float beam_tilt_x, float beam_tilt_y, float particle_shift_x, float particle_shift_y) { MyDebugAssertTrue(ctf_is_initialized, "CTF not initialized"); ctf_parameters.SetBeamTilt(beam_tilt_x, beam_tilt_y, particle_shift_x / pixel_size, particle_shift_y / pixel_size); } void Particle::SetLowResolutionContrast(float low_resolution_contrast) { MyDebugAssertTrue(ctf_is_initialized, "CTF not initialized"); ctf_parameters.SetLowResolutionContrast(low_resolution_contrast); } void Particle::InitCTFImage(float voltage_kV, float spherical_aberration_mm, float amplitude_contrast, float defocus_1, float defocus_2, float astigmatism_angle, float phase_shift, float beam_tilt_x, float beam_tilt_y, float particle_shift_x, float particle_shift_y, bool calculate_complex_ctf) { MyDebugAssertTrue(ctf_image->is_in_memory, "ctf_image memory not allocated"); MyDebugAssertTrue(beamtilt_image->is_in_memory, "beamtilt_image memory not allocated"); MyDebugAssertTrue(! ctf_image->is_in_real_space, "ctf_image not in Fourier space"); MyDebugAssertTrue(! beamtilt_image->is_in_real_space, "beamtilt_image not in Fourier space"); InitCTF(voltage_kV, spherical_aberration_mm, amplitude_contrast, defocus_1, defocus_2, astigmatism_angle, phase_shift, beam_tilt_x, beam_tilt_y, particle_shift_x, particle_shift_y); complex_ctf = calculate_complex_ctf; if ( ctf_parameters.IsAlmostEqualTo(&current_ctf, 1 / pixel_size) == false || ! ctf_image_calculated ) // Need to calculate current_ctf_image to be inserted into ctf_reconstruction { current_ctf = ctf_parameters; ctf_image->CalculateCTFImage(current_ctf, complex_ctf); } if ( ctf_parameters.BeamTiltIsAlmostEqualTo(&current_ctf) == false || ! beamtilt_image_calculated ) // Need to calculate current_beamtilt_image to correct input image for beam tilt { beamtilt_image->CalculateBeamTiltImage(current_ctf); } ctf_image_calculated = true; beamtilt_image_calculated = true; } void Particle::PhaseFlipImage( ) { MyDebugAssertTrue(ctf_image_calculated, "CTF image not calculated"); if ( particle_image->is_in_real_space ) particle_image->ForwardFFT( ); particle_image->PhaseFlipPixelWise(*ctf_image); } void Particle::CTFMultiplyImage( ) { MyDebugAssertTrue(ctf_image_calculated, "CTF image not calculated"); if ( particle_image->is_in_real_space ) particle_image->ForwardFFT( ); particle_image->MultiplyPixelWiseReal(*ctf_image); } void Particle::BeamTiltMultiplyImage( ) { MyDebugAssertTrue(beamtilt_image_calculated, "Beamtilt image not calculated"); if ( particle_image->is_in_real_space ) particle_image->ForwardFFT( ); particle_image->MultiplyPixelWise(*beamtilt_image); } void Particle::SetIndexForWeightedCorrelation(bool limit_resolution) { MyDebugAssertTrue(particle_image->is_in_memory, "Image memory not allocated"); int i; int j; int k; int bin; float x; float y; float z; float frequency; float frequency_squared; float low_limit2; float high_limit2 = fminf(powf(pixel_size / filter_radius_high, 2), 0.25); int number_of_bins = particle_image->ReturnLargestLogicalDimension( ) / 2 + 1; int number_of_bins2 = 2 * (number_of_bins - 1); long pixel_counter = 0; low_limit2 = 0.0; if ( filter_radius_low != 0.0 ) low_limit2 = powf(pixel_size / filter_radius_low, 2); if ( bin_index != NULL ) delete[] bin_index; bin_index = new int[particle_image->real_memory_allocated / 2]; for ( k = 0; k <= particle_image->physical_upper_bound_complex_z; k++ ) { z = powf(particle_image->ReturnFourierLogicalCoordGivenPhysicalCoord_Z(k) * particle_image->fourier_voxel_size_z, 2); for ( j = 0; j <= particle_image->physical_upper_bound_complex_y; j++ ) { y = powf(particle_image->ReturnFourierLogicalCoordGivenPhysicalCoord_Y(j) * particle_image->fourier_voxel_size_y, 2); for ( i = 0; i <= particle_image->physical_upper_bound_complex_x; i++ ) { x = powf(i * particle_image->fourier_voxel_size_x, 2); frequency_squared = x + y + z; if ( (frequency_squared >= low_limit2 && frequency_squared <= high_limit2) || ! limit_resolution ) { bin_index[pixel_counter] = int(sqrtf(frequency_squared) * number_of_bins2); } else { bin_index[pixel_counter] = -1; } pixel_counter++; } } } } void Particle::WeightBySSNR(Curve& SSNR, int include_reference_weighting, bool no_ctf) { MyDebugAssertTrue(particle_image->is_in_memory, "Memory not allocated"); MyDebugAssertTrue(ctf_image->is_in_memory, "CTF image memory not allocated"); MyDebugAssertTrue(ctf_image_calculated, "CTF image not initialized"); MyDebugAssertTrue(! is_ssnr_filtered, "Already SSNR filtered"); int i; // mask_volume = number of pixels in 2D mask applied to input images // (4.0 * PI / 3.0 * powf(mask_volume / PI, 1.5)) = volume (number of voxels) inside sphere with radius of 2D mask // kDa_to_Angstrom3(molecular_mass_kDa) / powf(pixel_size,3) = volume (number of pixels) inside the particle envelope float particle_area_in_pixels = PI * powf(3.0 * (kDa_to_Angstrom3(molecular_mass_kDa) / powf(pixel_size, 3)) / 4.0 / PI, 2.0 / 3.0); // float ssnr_scale_factor = particle_area_in_pixels / mask_volume; float ssnr_scale_factor = particle_area_in_pixels / particle_image->logical_x_dimension / particle_image->logical_y_dimension; // wxPrintf("particle_area_in_pixels = %g, mask_volume = %g\n", particle_area_in_pixels, mask_volume); // float ssnr_scale_factor_old = kDa_to_Angstrom3(molecular_mass_kDa) / 4.0 / PI / powf(pixel_size,3) / (4.0 * PI / 3.0 * powf(mask_volume / PI, 1.5)); // wxPrintf("old = %g, new = %g\n", ssnr_scale_factor_old, ssnr_scale_factor); // float ssnr_scale_factor = PI * powf( powf(3.0 * kDa_to_Angstrom3(molecular_mass_kDa) / 4.0 / PI / powf(pixel_size,3) ,1.0 / 3.0) ,2) / mask_volume; // float ssnr_scale_factor = particle_image->logical_x_dimension * particle_image->logical_y_dimension / mask_volume; if ( particle_image->is_in_real_space ) particle_image->ForwardFFT( ); Image* snr_image = new Image; snr_image->Allocate(ctf_image->logical_x_dimension, ctf_image->logical_y_dimension, false); particle_image->Whiten( ); // snr_image->CopyFrom(ctf_image); if ( no_ctf ) { snr_image->SetToConstant(1.0); no_ctf_weighting = true; } else { for ( i = 0; i < ctf_image->real_memory_allocated / 2; i++ ) { snr_image->complex_values[i] = ctf_image->complex_values[i] * conj(ctf_image->complex_values[i]); } no_ctf_weighting = false; } snr_image->MultiplyByWeightsCurve(SSNR, ssnr_scale_factor); particle_image->OptimalFilterBySNRImage(*snr_image, include_reference_weighting); is_ssnr_filtered = true; if ( include_reference_weighting != 0 ) includes_reference_ssnr_weighting = true; else includes_reference_ssnr_weighting = false; // Apply cosine filter to reduce ringing when resolution limit higher than 7 A // if (filter_radius_high > 0.0) particle_image->CosineMask(std::max(pixel_size / filter_radius_high, pixel_size / 7.0f + pixel_size / mask_falloff) - pixel_size / (2.0 * mask_falloff), pixel_size / mask_falloff); delete snr_image; } void Particle::WeightBySSNR(Curve& SSNR, Image& projection_image, bool weight_particle_image, bool weight_projection_image) { MyDebugAssertTrue(ctf_image_calculated, "CTF image not initialized"); MyDebugAssertTrue(! is_ssnr_filtered, "Already SSNR filtered"); particle_image->WeightBySSNR(*ctf_image, molecular_mass_kDa, pixel_size, SSNR, projection_image, weight_particle_image, weight_projection_image); if ( weight_particle_image ) is_ssnr_filtered = true; else is_ssnr_filtered = false; includes_reference_ssnr_weighting = false; } void Particle::CalculateProjection(Image& projection_image, ReconstructedVolume& input_3d) { MyDebugAssertTrue(projection_image.is_in_memory, "Projection image memory not allocated"); MyDebugAssertTrue(input_3d.density_map->is_in_memory, "3D reconstruction memory not allocated"); MyDebugAssertTrue(ctf_image->is_in_memory, "CTF image memory not allocated"); MyDebugAssertTrue(ctf_image_calculated, "CTF image not initialized"); input_3d.CalculateProjection(projection_image, *ctf_image, alignment_parameters, 0.0, 0.0, 1.0, true, true, false, true, false); if ( current_ctf.GetBeamTiltX( ) != 0.0f || current_ctf.GetBeamTiltY( ) != 0.0f ) projection_image.ConjugateMultiplyPixelWise(*beamtilt_image); } void Particle::GetParameters(cisTEMParameterLine& output_parameters) { output_parameters = current_parameters; } void Particle::SetParameters(cisTEMParameterLine& wanted_parameters, bool initialize_scores) { current_parameters = wanted_parameters; if ( initialize_scores ) { current_parameters.logp = -std::numeric_limits<float>::max( ); current_parameters.sigma = -std::numeric_limits<float>::max( ); current_parameters.score = -std::numeric_limits<float>::max( ); } alignment_parameters.Init(current_parameters.phi, current_parameters.theta, current_parameters.psi, current_parameters.x_shift, current_parameters.y_shift); } void Particle::SetAlignmentParameters(float wanted_euler_phi, float wanted_euler_theta, float wanted_euler_psi, float wanted_shift_x, float wanted_shift_y) { alignment_parameters.Init(wanted_euler_phi, wanted_euler_theta, wanted_euler_psi, wanted_shift_x, wanted_shift_y); } void Particle::SetParameterStatistics(cisTEMParameterLine& wanted_averages, cisTEMParameterLine& wanted_variances) { parameter_average = wanted_averages; parameter_variance = wanted_variances; } void Particle::SetParameterConstraints(float wanted_noise_variance) { MyDebugAssertTrue(! constraints_used.phi || parameter_variance.phi > 0.0, "Phi variance not positive"); MyDebugAssertTrue(! constraints_used.theta || parameter_variance.theta > 0.0, "Theta variance not positive"); MyDebugAssertTrue(! constraints_used.psi || parameter_variance.psi > 0.0, "Psi variance not positive"); MyDebugAssertTrue(! constraints_used.x_shift || parameter_variance.x_shift > 0.0, "Shift_X variance not positive"); MyDebugAssertTrue(! constraints_used.y_shift || parameter_variance.y_shift > 0.0, "Shift_Y variance not positive"); scaled_noise_variance = wanted_noise_variance; if ( constraints_used.phi ) parameter_constraints.InitPhi(parameter_average.phi, parameter_variance.phi, scaled_noise_variance); if ( constraints_used.theta ) parameter_constraints.InitTheta(parameter_average.theta, parameter_variance.theta, scaled_noise_variance); if ( constraints_used.psi ) parameter_constraints.InitPsi(parameter_average.psi, parameter_variance.psi, scaled_noise_variance); if ( constraints_used.x_shift ) parameter_constraints.InitShiftX(parameter_average.x_shift, parameter_variance.x_shift, scaled_noise_variance); if ( constraints_used.y_shift ) parameter_constraints.InitShiftY(parameter_average.y_shift, parameter_variance.y_shift, scaled_noise_variance); } float Particle::ReturnParameterPenalty(cisTEMParameterLine& parameters) { float penalty = 0.0; // Assume that sigma_noise is approximately equal to sigma_image, i.e. the SNR in the image is very low if ( constraints_used.phi ) penalty += sigma_noise / mask_volume * parameter_constraints.ReturnPhiAngleLogP(parameters.phi); if ( constraints_used.theta ) penalty += sigma_noise / mask_volume * parameter_constraints.ReturnThetaAngleLogP(parameters.theta); if ( constraints_used.psi ) penalty += sigma_noise / mask_volume * parameter_constraints.ReturnPsiAngleLogP(parameters.psi); if ( constraints_used.x_shift ) penalty += sigma_noise / mask_volume * parameter_constraints.ReturnShiftXLogP(parameters.x_shift); if ( constraints_used.y_shift ) penalty += sigma_noise / mask_volume * parameter_constraints.ReturnShiftYLogP(parameters.y_shift); return penalty; } float Particle::ReturnParameterLogP(cisTEMParameterLine& parameters) { float logp = 0.0; if ( constraints_used.phi ) logp += parameter_constraints.ReturnPhiAngleLogP(parameters.phi); if ( constraints_used.theta ) logp += parameter_constraints.ReturnThetaAngleLogP(parameters.theta); if ( constraints_used.psi ) logp += parameter_constraints.ReturnPsiAngleLogP(parameters.psi); if ( constraints_used.x_shift ) logp += parameter_constraints.ReturnShiftXLogP(parameters.x_shift); if ( constraints_used.y_shift ) logp += parameter_constraints.ReturnShiftYLogP(parameters.y_shift); return logp; } int Particle::MapParameterAccuracy(float* accuracies) { cisTEMParameterLine accuracy_line; accuracy_line.psi = target_phase_error / (1.0 / filter_radius_high * 2.0 * PI * mask_radius) / 5.0; accuracy_line.theta = target_phase_error / (1.0 / filter_radius_high * 2.0 * PI * mask_radius) / 5.0; accuracy_line.phi = target_phase_error / (1.0 / filter_radius_high * 2.0 * PI * mask_radius) / 5.0; accuracy_line.x_shift = deg_2_rad(target_phase_error) / (1.0 / filter_radius_high * 2.0 * PI * pixel_size) / 5.0; accuracy_line.y_shift = deg_2_rad(target_phase_error) / (1.0 / filter_radius_high * 2.0 * PI * pixel_size) / 5.0; number_of_search_dimensions = MapParametersFromExternal(accuracy_line, accuracies); return number_of_search_dimensions; } int Particle::MapParametersFromExternal(cisTEMParameterLine& input_parameters, float* mapped_parameters) { int i; int j = 0; if ( parameter_map.phi == true ) { mapped_parameters[j] = input_parameters.phi; j++; } if ( parameter_map.theta == true ) { mapped_parameters[j] = input_parameters.theta; j++; } if ( parameter_map.psi == true ) { mapped_parameters[j] = input_parameters.psi; j++; } if ( parameter_map.x_shift == true ) { mapped_parameters[j] = input_parameters.x_shift; j++; } if ( parameter_map.y_shift == true ) { mapped_parameters[j] = input_parameters.y_shift; j++; } return j; } int Particle::MapParameters(float* mapped_parameters) { int i; int j = 0; if ( parameter_map.phi == true ) { mapped_parameters[j] = current_parameters.phi; j++; } if ( parameter_map.theta == true ) { mapped_parameters[j] = current_parameters.theta; j++; } if ( parameter_map.psi == true ) { mapped_parameters[j] = current_parameters.psi; j++; } if ( parameter_map.x_shift == true ) { mapped_parameters[j] = current_parameters.x_shift; j++; } if ( parameter_map.y_shift == true ) { mapped_parameters[j] = current_parameters.y_shift; j++; } return j; } int Particle::UnmapParametersToExternal(cisTEMParameterLine& output_parameters, float* mapped_parameters) { int i; int j = 0; if ( parameter_map.phi == true ) { output_parameters.phi = mapped_parameters[j]; j++; } if ( parameter_map.theta == true ) { output_parameters.theta = mapped_parameters[j]; j++; } if ( parameter_map.psi == true ) { output_parameters.psi = mapped_parameters[j]; j++; } if ( parameter_map.x_shift == true ) { output_parameters.x_shift = mapped_parameters[j]; j++; } if ( parameter_map.y_shift == true ) { output_parameters.y_shift = mapped_parameters[j]; j++; } return j; } int Particle::UnmapParameters(float* mapped_parameters) { int i; int j = 0; if ( parameter_map.phi == true ) { current_parameters.phi = mapped_parameters[j]; j++; } if ( parameter_map.theta == true ) { current_parameters.theta = mapped_parameters[j]; j++; } if ( parameter_map.psi == true ) { current_parameters.psi = mapped_parameters[j]; j++; } if ( parameter_map.x_shift == true ) { current_parameters.x_shift = mapped_parameters[j]; j++; } if ( parameter_map.y_shift == true ) { current_parameters.y_shift = mapped_parameters[j]; j++; } alignment_parameters.Init(current_parameters.phi, current_parameters.theta, current_parameters.psi, current_parameters.x_shift, current_parameters.y_shift); return j; } float Particle::ReturnLogLikelihood(Image& input_image, CTF& input_ctf, ReconstructedVolume& input_3d, ResolutionStatistics& statistics, float classification_resolution_limit, float* frealign_score) { //!!! MyDebugAssertTrue(is_ssnr_filtered, "particle_image not filtered"); float number_of_independent_pixels; float variance_masked; float variance_difference; float variance_particle; float variance_projection; float rotated_center_x; float rotated_center_y; float rotated_center_z; float alpha; float sigma; float original_pixel_size = pixel_size * float(particle_image->logical_x_dimension) / float(input_image.logical_x_dimension); // float effective_bfactor; float pixel_center_2d_x = mask_center_2d_x / original_pixel_size - input_image.physical_address_of_box_center_x; float pixel_center_2d_y = mask_center_2d_y / original_pixel_size - input_image.physical_address_of_box_center_y; // Assumes cubic reference volume float pixel_center_2d_z = mask_center_2d_z / original_pixel_size - input_image.physical_address_of_box_center_x; float pixel_radius_2d = mask_radius_2d / original_pixel_size; Image* temp_image1 = new Image; temp_image1->Allocate(particle_image->logical_x_dimension, particle_image->logical_y_dimension, false); Image* temp_image2 = new Image; // temp_image2->Allocate(binned_image_box_size, binned_image_box_size, false); Image* projection_image = new Image; projection_image->Allocate(input_image.logical_x_dimension, input_image.logical_y_dimension, false); Image* temp_projection = new Image; temp_projection->Allocate(input_image.logical_x_dimension, input_image.logical_y_dimension, false); Image* temp_particle = new Image; temp_particle->Allocate(input_image.logical_x_dimension, input_image.logical_y_dimension, false); Image* ctf_input_image = new Image; ctf_input_image->Allocate(input_image.logical_x_dimension, input_image.logical_y_dimension, false); Image* beamtilt_input_image = new Image; beamtilt_input_image->Allocate(input_image.logical_x_dimension, input_image.logical_y_dimension, false); // if (filter_radius_high != 0.0) // { // effective_bfactor = 2.0 * powf(original_pixel_size / filter_radius_high, 2); // } // else // { // effective_bfactor = 0.0; // } // ResetImageFlags(); // mask_volume = PI * powf(mask_radius / original_pixel_size, 2); // is_ssnr_filtered = false; // is_centered_in_box = true; // CenterInCorner(); // input_3d.CalculateProjection(*projection_image, *ctf_image, alignment_parameters, mask_radius, mask_falloff, original_pixel_size / filter_radius_high, false, true); input_3d.density_map->ExtractSlice(*temp_image1, alignment_parameters, pixel_size / filter_radius_high); if ( frealign_score != NULL ) { temp_image2->Allocate(particle_image->logical_x_dimension, particle_image->logical_y_dimension, false); temp_image2->CopyFrom(temp_image1); if ( no_ctf_weighting ) input_3d.CalculateProjection(*temp_image2, *ctf_image, alignment_parameters, 0.0, 0.0, pixel_size / filter_radius_high, false, false, false, false, false, false); // Case for normal parameter refinement with weighting applied to particle images and 3D reference else if ( includes_reference_ssnr_weighting ) input_3d.CalculateProjection(*temp_image2, *ctf_image, alignment_parameters, 0.0, 0.0, pixel_size / filter_radius_high, false, true, true, false, false, false); // Case for normal parameter refinement with weighting applied only to particle images else input_3d.CalculateProjection(*temp_image2, *ctf_image, alignment_parameters, 0.0, 0.0, pixel_size / filter_radius_high, false, true, false, true, true, false); *frealign_score = -particle_image->GetWeightedCorrelationWithImage(*temp_image2, bin_index, pixel_size / signed_CC_limit) - ReturnParameterPenalty(current_parameters); // wxPrintf("pixel_size, signed_CC_limit, filter_radius_high, frealign_score = %g %g %g\n", pixel_size, signed_CC_limit, filter_radius_high, *frealign_score); } temp_image1->SwapRealSpaceQuadrants( ); temp_image1->BackwardFFT( ); temp_image1->AddConstant(-temp_image1->ReturnAverageOfRealValues(mask_radius / pixel_size, true)); temp_image1->CosineMask(mask_radius / pixel_size, mask_falloff / pixel_size, false, true, 0.0); temp_image1->ForwardFFT( ); temp_image2->CopyFrom(temp_image1); ctf_input_image->CalculateCTFImage(input_ctf); beamtilt_input_image->CalculateBeamTiltImage(input_ctf); if ( includes_reference_ssnr_weighting ) temp_image1->Whiten(pixel_size / filter_radius_high); // temp_image1->PhaseFlipPixelWise(*ctf_image); // if (input_3d.density_map->logical_x_dimension != padded_unbinned_image.logical_x_dimension) temp_image1->CosineMask(0.5 - pixel_size / 20.0, pixel_size / 10.0); if ( input_3d.density_map->logical_x_dimension != input_image.logical_x_dimension ) temp_image1->CosineMask(0.45, 0.1); // temp_image1->ClipInto(&padded_unbinned_image); // padded_unbinned_image.BackwardFFT(); // padded_unbinned_image.ClipInto(projection_image); // projection_image->ForwardFFT(); temp_image1->ClipInto(projection_image); projection_image->PhaseFlipPixelWise(*ctf_input_image); projection_image->MultiplyPixelWise(*beamtilt_input_image); // temp_image2->MultiplyPixelWiseReal(*ctf_image); // if (input_3d.density_map->logical_x_dimension != padded_unbinned_image.logical_x_dimension) temp_image2->CosineMask(0.5 - pixel_size / 20.0, pixel_size / 10.0); if ( particle_image->logical_x_dimension != input_image.logical_x_dimension ) temp_image2->CosineMask(0.45, 0.1); // temp_image2->ClipInto(&padded_unbinned_image); // padded_unbinned_image.BackwardFFT(); // padded_unbinned_image.ClipInto(temp_projection); // temp_projection->ForwardFFT(); temp_image2->ClipInto(temp_projection); temp_projection->MultiplyPixelWiseReal(*ctf_input_image); temp_projection->MultiplyPixelWise(*beamtilt_input_image); // temp_projection->CopyFrom(projection_image); // projection_image->PhaseFlipPixelWise(*ctf_image); // temp_projection->MultiplyPixelWiseReal(*ctf_image); // temp_projection->CopyFrom(projection_image); if ( input_image.is_in_real_space ) input_image.ForwardFFT( ); input_image.PhaseShift(-current_parameters.x_shift / original_pixel_size, -current_parameters.y_shift / original_pixel_size); temp_particle->CopyFrom(&input_image); // if (includes_reference_ssnr_weighting) temp_projection->Whiten(pixel_size / filter_radius_high); // WeightBySSNR(statistics.part_SSNR, *temp_projection, false, includes_reference_ssnr_weighting); input_image.WeightBySSNR(*ctf_input_image, molecular_mass_kDa, original_pixel_size, statistics.part_SSNR, *projection_image, true, includes_reference_ssnr_weighting); // if (includes_reference_ssnr_weighting) projection_image->Whiten(original_pixel_size / filter_radius_high); // WeightBySSNR(statistics.part_SSNR, *projection_image, true, includes_reference_ssnr_weighting); // particle_image->SwapRealSpaceQuadrants(); // particle_image->PhaseShift(- current_parameters[4] / pixel_size, - current_parameters[5] / pixel_size); input_image.BackwardFFT( ); // temp_particle->BackwardFFT(); // projection_image->SwapRealSpaceQuadrants(); projection_image->BackwardFFT( ); // Apply some low-pass filtering to improve classification // temp_projection->ApplyBFactor(effective_bfactor); // temp_projection->BackwardFFT(); // input_image.QuickAndDirtyWriteSlice("part.mrc", 1); // projection_image->QuickAndDirtyWriteSlice("proj.mrc", 1); // temp_particle->QuickAndDirtyWriteSlice("part2.mrc", 1); // temp_projection->QuickAndDirtyWriteSlice("proj2.mrc", 1); // exit(0); // Calculate LogP // variance_masked = temp_particle->ReturnVarianceOfRealValues(mask_radius / pixel_size, 0.0, 0.0, 0.0, true); // wxPrintf("variance_masked = %g\n", variance_masked); // temp_particle->MultiplyByConstant(1.0 / sqrtf(variance_masked)); // alpha = temp_particle->ReturnImageScale(*temp_projection, mask_radius / pixel_size); // temp_projection->MultiplyByConstant(alpha); // This scaling according to the average sqrtf(SNR) should take care of variable signal strength in the images // However, it seems to lead to some oscillatory behavior of the occupancies (from cycle to cycle) // if (current_parameters[7] >= 0 && current_parameters[14] > 0.0) temp_projection->MultiplyByConstant(parameter_average[14] / current_parameters[14]); // wxPrintf("alpha for logp, scaling factor = %g %g\n", alpha, parameter_average[14] / current_parameters[14]); if ( apply_2D_masking ) { AnglesAndShifts reverse_alignment_parameters; reverse_alignment_parameters.Init(-current_parameters.psi, -current_parameters.theta, -current_parameters.phi, 0.0, 0.0); reverse_alignment_parameters.euler_matrix.RotateCoords(pixel_center_2d_x, pixel_center_2d_y, pixel_center_2d_z, rotated_center_x, rotated_center_y, rotated_center_z); // variance_masked = particle_image->ReturnVarianceOfRealValues(pixel_radius_2d, rotated_center_x + particle_image->physical_address_of_box_center_x, // rotated_center_y + particle_image->physical_address_of_box_center_y, 0.0); } // else // { // variance_masked = particle_image->ReturnVarianceOfRealValues(mask_radius / pixel_size); // } temp_particle->BackwardFFT( ); temp_projection->BackwardFFT( ); // temp_particle->QuickAndDirtyWriteSlice("temp_particle.mrc", 1); // temp_projection->QuickAndDirtyWriteSlice("temp_projection.mrc", 1); // phase_difference->QuickAndDirtyWriteSlice("phase_difference.mrc", 1); // exit(0); temp_particle->SubtractImage(temp_projection); // particle_image->QuickAndDirtyWriteSlice("diff.mrc", 1); // This low-pass filter reduces the number of independent pixels. It should therefore be applied only to // the reference (temp_projection), and not to the difference (temp_particle - temp_projection), as is done here... // temp_particle->ForwardFFT(); // if (classification_resolution_limit < 20.0f) temp_particle->CosineMask(original_pixel_size / 20.0f, original_pixel_size / 10.0f, true); if ( classification_resolution_limit > 0.0f ) { temp_particle->ForwardFFT( ); temp_particle->CosineMask(original_pixel_size / classification_resolution_limit, original_pixel_size / mask_falloff); // temp_particle->CosineMask(0.75f * original_pixel_size / classification_resolution_limit, original_pixel_size / classification_resolution_limit); temp_particle->BackwardFFT( ); } // temp_particle->BackwardFFT(); if ( apply_2D_masking ) { variance_difference = temp_particle->ReturnSumOfSquares(pixel_radius_2d, rotated_center_x + temp_particle->physical_address_of_box_center_x, rotated_center_y + temp_particle->physical_address_of_box_center_y, 0.0); // sigma = sqrtf(variance_difference / temp_projection->ReturnVarianceOfRealValues(pixel_radius_2d, rotated_center_x + temp_particle->physical_address_of_box_center_x, // rotated_center_y + temp_particle->physical_address_of_box_center_y, 0.0)); number_of_independent_pixels = PI * powf(pixel_radius_2d, 2); } else { variance_difference = temp_particle->ReturnSumOfSquares(mask_radius / original_pixel_size); // sigma = sqrtf(variance_difference / temp_projection->ReturnVarianceOfRealValues(mask_radius / pixel_size)); number_of_independent_pixels = PI * powf(mask_radius / original_pixel_size, 2); // number_of_independent_pixels = mask_volume; } logp = -0.5 * (variance_difference + logf(2.0 * PI)) * number_of_independent_pixels; // This penalty term assumes a Gaussian x,y distribution that is probably not correct in most cases. Better to leave it out. // + ReturnParameterLogP(current_parameters); // Calculate SNR used for particle weighting during reconstruction input_image.CosineMask(mask_radius / original_pixel_size, mask_falloff / original_pixel_size); // alpha = input_image.ReturnImageScale(*projection_image); // variance_masked = projection_image->ReturnVarianceOfRealValues(mask_radius / original_pixel_size); // projection_image->MultiplyByConstant(1.0 / sqrtf(variance_masked)); // wxPrintf("var = %g\n", variance_masked); // alpha = input_image.ReturnImageScale(*projection_image, mask_radius / original_pixel_size); alpha = input_image.ReturnImageScale(*projection_image); projection_image->MultiplyByConstant(alpha); // if (origin_micrograph < 0) origin_micrograph = 0; // origin_micrograph++; // input_image.QuickAndDirtyWriteSlice("part.mrc", origin_micrograph); // projection_image->QuickAndDirtyWriteSlice("proj.mrc", origin_micrograph); input_image.SubtractImage(projection_image); // input_image.QuickAndDirtyWriteSlice("diff.mrc", origin_micrograph); // exit(0); // variance_difference = input_image.ReturnVarianceOfRealValues(); // sigma = sqrtf(variance_difference / projection_image->ReturnVarianceOfRealValues()); // variance_difference = input_image.ReturnVarianceOfRealValues(mask_radius / original_pixel_size); // sigma = sqrtf(variance_difference / projection_image->ReturnVarianceOfRealValues(mask_radius / original_pixel_size)); variance_difference = input_image.ReturnVarianceOfRealValues( ); sigma = sqrtf(variance_difference / projection_image->ReturnVarianceOfRealValues( )); // sigma = sqrtf(variance_difference / powf(alpha, 2)); // wxPrintf("variance_difference, alpha for sigma, sigma = %g %g %g\n", variance_difference, alpha, sigma); // Prevent rare occurrences of unrealistically high sigmas if ( sigma > 100.0 ) sigma = 100.0; if ( sigma > 0.0 ) snr = powf(1.0 / sigma, 2); else snr = 0.0; // wxPrintf("number_of_independent_pixels = %g, variance_difference = %g, variance_masked = %g, logp = %g\n", number_of_independent_pixels, // variance_difference, variance_masked, -number_of_independent_pixels * variance_difference / variance_masked / 2.0); // exit(0); // return - number_of_independent_pixels * variance_difference / variance_masked / 2.0 // + ReturnParameterLogP(current_parameters); delete temp_image1; delete temp_image2; delete projection_image; delete temp_particle; delete temp_projection; delete ctf_input_image; delete beamtilt_input_image; return logp; } void Particle::CalculateMaskedLogLikelihood(Image& projection_image, ReconstructedVolume& input_3d, float classification_resolution_limit) { //!!! MyDebugAssertTrue(is_ssnr_filtered, "particle_image not filtered"); // float ssq_XA, ssq_A2; float alpha; float variance_masked; float variance_difference; float rotated_center_x; float rotated_center_y; float rotated_center_z; float pixel_center_2d_x = mask_center_2d_x / pixel_size - particle_image->physical_address_of_box_center_x; float pixel_center_2d_y = mask_center_2d_y / pixel_size - particle_image->physical_address_of_box_center_y; // Assumes cubic reference volume float pixel_center_2d_z = mask_center_2d_z / pixel_size - particle_image->physical_address_of_box_center_x; float pixel_radius_2d = mask_radius_2d / pixel_size; AnglesAndShifts reverse_alignment_parameters; reverse_alignment_parameters.Init(-current_parameters.psi, -current_parameters.theta, -current_parameters.phi, 0.0, 0.0); reverse_alignment_parameters.euler_matrix.RotateCoords(pixel_center_2d_x, pixel_center_2d_y, pixel_center_2d_z, rotated_center_x, rotated_center_y, rotated_center_z); input_3d.CalculateProjection(projection_image, *ctf_image, alignment_parameters, 0.0, 0.0, pixel_size / classification_resolution_limit, false, false, false, true, is_phase_flipped); particle_image->PhaseShift(-current_parameters.x_shift / pixel_size, -current_parameters.y_shift / pixel_size); particle_image->BackwardFFT( ); // wxPrintf("ssq part = %g var part = %g\n", particle_image->ReturnSumOfSquares(pixel_radius_2d, rotated_center_x + particle_image->physical_address_of_box_center_x, // rotated_center_y + particle_image->physical_address_of_box_center_y, 0.0), particle_image->ReturnVarianceOfRealValues()); projection_image.SwapRealSpaceQuadrants( ); projection_image.BackwardFFT( ); // particle_image->QuickAndDirtyWriteSlice("part2.mrc", 1); // projection_image.QuickAndDirtyWriteSlice("proj2.mrc", 1); // exit(0); // variance_masked = particle_image->ReturnVarianceOfRealValues(pixel_radius_2d, rotated_center_x + particle_image->physical_address_of_box_center_x, // rotated_center_y + particle_image->physical_address_of_box_center_y, 0.0); // particle_image->QuickAndDirtyWriteSlice("part.mrc", 1); // projection_image.AddConstant(- projection_image.ReturnAverageOfRealValues(0.45 * projection_image.logical_x_dimension, true)); // projection_image.MultiplyByConstant(0.02); // float min = 100.0; // for (int i = 0; i < 100; i++) // { // particle_image->SubtractImage(&projection_image); // sigma_signal = sqrtf(projection_image.ReturnVarianceOfRealValues(mask_radius / pixel_size)); // sigma_noise = sqrtf(particle_image->ReturnVarianceOfRealValues(mask_radius / pixel_size)); // if (sigma_noise < min) {min = sigma_noise; wxPrintf("i, sigma_noise = %i %g\n", i, sigma_noise);} // } // ssq_XA = particle_image->ReturnPixelWiseProduct(projection_image); // ssq_A2 = projection_image.ReturnPixelWiseProduct(projection_image); // alpha = ssq_XA / ssq_A2; alpha = particle_image->ReturnImageScale(projection_image, mask_radius / pixel_size); projection_image.MultiplyByConstant(alpha); particle_image->SubtractImage(&projection_image); sigma_signal = sqrtf(projection_image.ReturnVarianceOfRealValues(mask_radius / pixel_size)); sigma_noise = sqrtf(particle_image->ReturnVarianceOfRealValues(mask_radius / pixel_size)); if ( sigma_noise > 0.0 ) snr = powf(sigma_signal / sigma_noise, 2); else snr = 0.0; // wxPrintf("mask_radius, pixel_size, alpha, sigma_noise = %g %g %g %g\n", mask_radius, pixel_size, alpha, sigma_noise); // particle_image->QuickAndDirtyWriteSlice("diff.mrc", 1); // exit(0); // wxPrintf("number_of_independent_pixels = %g, variance_difference = %g, variance_masked = %g, logp = %g\n", number_of_independent_pixels, // variance_difference, variance_masked, -number_of_independent_pixels * variance_difference / variance_masked / 2.0); // wxPrintf("sum = %g pix = %li penalty = %g indep = %g\n", particle_image->ReturnSumOfSquares(pixel_radius_2d, rotated_center_x + particle_image->physical_address_of_box_center_x, // rotated_center_y + particle_image->physical_address_of_box_center_y, 0.0), particle_image->number_of_real_space_pixels, // ReturnParameterLogP(current_parameters), mask_volume); // exit(0); if ( mask_radius_2d > 0.0 ) { logp = -0.5 * (particle_image->ReturnSumOfSquares(pixel_radius_2d, rotated_center_x + particle_image->physical_address_of_box_center_x, rotated_center_y + particle_image->physical_address_of_box_center_y, 0.0) + logf(2.0 * PI)) * PI * powf(pixel_radius_2d, 2) + ReturnParameterLogP(current_parameters); } else { logp = -0.5 * (particle_image->ReturnSumOfSquares(mask_radius / pixel_size) + logf(2.0 * PI)) * PI * powf(mask_radius / pixel_size, 2) + ReturnParameterLogP(current_parameters); } } float Particle::MLBlur(Image* input_classes_cache, float ssq_X, Image& cropped_input_image, Image* rotation_cache, Image& blurred_image, int current_class, int number_of_rotations, float psi_step, float psi_start, float smoothing_factor, float& max_logp_particle, int best_class, float best_psi, Image& best_correlation_map, bool calculate_correlation_map_only, bool uncrop, bool apply_ctf_to_classes, Image* image_to_blur, Image* diff_image_to_blur, float max_shift_in_angstroms) { MyDebugAssertTrue(cropped_input_image.is_in_memory, "cropped_input_image: memory not allocated"); MyDebugAssertTrue(rotation_cache[0].is_in_memory, "rotation_cache: memory not allocated"); MyDebugAssertTrue(blurred_image.is_in_memory, "blurred_image: memory not allocated"); MyDebugAssertTrue(input_classes_cache[0].is_in_memory, "input_classes_cache: memory not allocated"); MyDebugAssertTrue(! ctf_image->is_in_real_space, "ctf_image in real space"); MyDebugAssertTrue(! input_classes_cache[0].is_in_real_space, "input_classes_cache not in Fourier space"); int i, j; int pixel_counter; int current_rotation; int non_zero_pixels; float binning_factor; float snr_psi = -std::numeric_limits<float>::max( ); float snr_class; float log_threshold; float old_max_logp; float log_range = 20.0; float var_A; float ssq_A; float ssq_A_rot0; float ssq_XA2; float psi; float rmdr; float number_of_pixels = particle_image->number_of_real_space_pixels * smoothing_factor; bool new_max_found; bool use_best_psi; float dx, dy; float mid_x; float mid_y; float rvar2_x = powf(pixel_size, 2) / parameter_variance.x_shift / 2.0; float rvar2_y = powf(pixel_size, 2) / parameter_variance.y_shift / 2.0; float penalty_x, penalty_y; float number_of_independent_pixels; float norm_X, norm_A; double sump_psi; double sump_class; double min_float = std::numeric_limits<float>::min( ); double scale; AnglesAndShifts rotation_angle; Image* correlation_map = new Image; correlation_map->Allocate(particle_image->logical_x_dimension, particle_image->logical_y_dimension, false); Image* temp_image = new Image; temp_image->Allocate(particle_image->logical_x_dimension, particle_image->logical_y_dimension, false); Image* sum_image = new Image; sum_image->Allocate(particle_image->logical_x_dimension, particle_image->logical_y_dimension, true); // wxPrintf("Max shift in angstoms = %f\n", max_shift_in_angstroms); float max_radius_squared = powf(max_shift_in_angstroms / pixel_size, 2); float current_squared_radius; #ifndef MKL float* temp_k1 = new float[particle_image->real_memory_allocated]; float* temp_k2; temp_k2 = temp_k1 + 1; float* real_a; float* real_b; float* real_c; float* real_d; float* real_r; float* real_i; #endif if ( is_filtered ) number_of_independent_pixels = filter_volume; else number_of_independent_pixels = particle_image->number_of_real_space_pixels; if ( is_masked ) number_of_independent_pixels *= mask_volume / particle_image->number_of_real_space_pixels; // Determine sum of squares of reference after CTF multiplication temp_image->CopyFrom(&input_classes_cache[current_class]); if ( apply_ctf_to_classes ) temp_image->MultiplyPixelWiseReal(*ctf_image); ssq_A = temp_image->ReturnSumOfSquares( ); temp_image->BackwardFFT( ); var_A = temp_image->ReturnVarianceOfRealValues( ); norm_A = 0.5 * number_of_pixels * ssq_A; ssq_XA2 = sqrtf(ssq_X * ssq_A); // Prevent collapse of x,y distribution to 0 due to limited resolution if ( rvar2_x > 1.0 ) rvar2_x = 1.0; if ( rvar2_y > 1.0 ) rvar2_y = 1.0; rvar2_x *= smoothing_factor; rvar2_y *= smoothing_factor; snr_class = -std::numeric_limits<float>::max( ); sum_image->SetToConstant(0.0); sump_class = 0.0; old_max_logp = max_logp_particle; if ( log_range == 0.0 ) { log_range = 0.0001; } for ( current_rotation = 0; current_rotation < number_of_rotations; current_rotation++ ) { if ( calculate_correlation_map_only ) { psi = best_psi; current_rotation = number_of_rotations; } else psi = 360.0 - current_rotation * psi_step - psi_start; rotation_angle.GenerateRotationMatrix2D(psi); rotation_angle.euler_matrix.RotateCoords2D(parameter_average.x_shift, parameter_average.y_shift, mid_x, mid_y); mid_x /= pixel_size; mid_y /= pixel_size; rotation_angle.GenerateRotationMatrix2D(-psi); // wxPrintf("current_rotation = %i ssq_X = %g ssq_A = %g\n", current_rotation, rotation_cache[current_rotation].ReturnSumOfSquares(), input_classes_cache[current_class].ReturnSumOfSquares()); // wxPrintf("number_of_pixels = %g, ssq_X = %g ssq_A = %g\n", number_of_pixels, ssq_X, ssq_A); // Calculate X.A #ifdef MKL vmcMulByConj(particle_image->real_memory_allocated / 2, reinterpret_cast<MKL_Complex8*>(input_classes_cache[current_class].complex_values), reinterpret_cast<MKL_Complex8*>(rotation_cache[current_rotation].complex_values), reinterpret_cast<MKL_Complex8*>(correlation_map->complex_values), VML_EP | VML_FTZDAZ_ON | VML_ERRMODE_IGNORE); #else real_a = input_classes_cache[current_class].real_values; real_b = input_classes_cache[current_class].real_values + 1; real_c = rotation_cache[current_rotation].real_values; real_d = rotation_cache[current_rotation].real_values + 1; real_r = correlation_map->real_values; real_i = correlation_map->real_values + 1; for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) { temp_k1[pixel_counter] = real_a[pixel_counter] + real_b[pixel_counter]; }; for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) { temp_k2[pixel_counter] = real_b[pixel_counter] - real_a[pixel_counter]; }; for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) { real_r[pixel_counter] = real_a[pixel_counter] * (real_c[pixel_counter] - real_d[pixel_counter]) + real_d[pixel_counter] * temp_k1[pixel_counter]; }; for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) { real_i[pixel_counter] = real_a[pixel_counter] * (real_c[pixel_counter] - real_d[pixel_counter]) + real_c[pixel_counter] * temp_k2[pixel_counter]; }; #endif correlation_map->is_in_real_space = false; correlation_map->BackwardFFT( ); temp_image->CopyFrom(correlation_map); // Calculate LogP (excluding -0.5 * number_of_independent_pixels * (logf(2.0 * PI) + ssq_X) and apply hierarchical prior f(x,y) // ssq_X_minus_A = (ssq_X - 2.0 * correlation_map->real_values[0] + ssq_A) / 2 pixel_counter = 0; penalty_x = 0.0; penalty_y = 0.0; // The following is divided by 2 according to the LogP formula for ( j = 0; j < particle_image->logical_y_dimension; j++ ) { if ( constraints_used.y_shift ) { if ( j > particle_image->physical_address_of_box_center_y ) dy = j - particle_image->logical_y_dimension; else dy = j; penalty_y = powf(dy - mid_y, 2) * rvar2_y; } for ( i = 0; i < particle_image->logical_x_dimension; i++ ) { if ( constraints_used.x_shift ) { if ( i > particle_image->physical_address_of_box_center_x ) dx = i - particle_image->logical_y_dimension; else dx = i; penalty_x = powf(dx - mid_x, 2) * rvar2_x; } correlation_map->real_values[pixel_counter] = correlation_map->real_values[pixel_counter] * number_of_pixels - norm_A - penalty_x - penalty_y; pixel_counter++; } pixel_counter += particle_image->padding_jump_value; } // Find correlation maximum to threshold LogP, and find best alignment parameters pixel_counter = 0; new_max_found = false; for ( j = 0; j < particle_image->logical_y_dimension; j++ ) { if ( j > particle_image->physical_address_of_box_center_y ) dy = j - particle_image->logical_y_dimension; else dy = j; for ( i = 0; i < particle_image->logical_x_dimension; i++ ) { if ( i > particle_image->physical_address_of_box_center_x ) dx = i - particle_image->logical_y_dimension; else dx = i; current_squared_radius = powf(dx, 2) + powf(dy, 2); if ( current_squared_radius > max_radius_squared ) { correlation_map->real_values[pixel_counter] = 0.0f; } else if ( correlation_map->real_values[pixel_counter] > max_logp_particle ) { new_max_found = true; max_logp_particle = correlation_map->real_values[pixel_counter]; // Store correlation coefficient that corresponds to highest likelihood snr_psi = temp_image->real_values[pixel_counter]; rotation_angle.euler_matrix.RotateCoords2D(dx, dy, current_parameters.x_shift, current_parameters.y_shift); current_parameters.x_shift *= pixel_size; current_parameters.y_shift *= pixel_size; current_parameters.psi = psi; current_parameters.best_2d_class = current_class + 1; } pixel_counter++; } pixel_counter += particle_image->padding_jump_value; } // // To get normalized correlation coefficient, need to divide by sigmas of particle and reference // To get sigma^2, need to calculate ssq_X - 2XA + ssq_A if ( new_max_found ) { // wxPrintf("ssq_X, snr_psi, ssq_A, number_of_real_space_pixels, number_of_independent_pixels, var_A = %g %g %g %li %g %g\n", // ssq_X, snr_psi, ssq_A, particle_image->number_of_real_space_pixels, number_of_independent_pixels, var_A); snr_psi = (ssq_X - 2.0 * snr_psi + ssq_A) * particle_image->number_of_real_space_pixels / number_of_independent_pixels / var_A; // Update SIGMA (SNR) if ( snr_psi >= 0.0 ) current_parameters.sigma = sqrtf(snr_psi); // Update SCORE current_parameters.score = 100.0 * (max_logp_particle + norm_A) / number_of_pixels / ssq_XA2; } rmdr = remainderf(best_psi - psi, 360.0); use_best_psi = false; if ( ! calculate_correlation_map_only && best_class == current_class && ! new_max_found && rmdr < psi_step / 2.0 && rmdr >= -psi_step / 2.0 ) { use_best_psi = true; snr_psi = snr; correlation_map->CopyFrom(&best_correlation_map); } if ( calculate_correlation_map_only ) { snr = snr_psi; best_correlation_map.CopyFrom(correlation_map); // Update SIGMA (SNR) if ( snr_psi >= 0.0 ) current_parameters.sigma = sqrtf(snr_psi); // Update SCORE current_parameters.score = 100.0 * (max_logp_particle + norm_A) / number_of_pixels / ssq_XA2; break; } else { // Calculate thresholded LogP log_threshold = max_logp_particle - log_range; pixel_counter = 0; non_zero_pixels = 0; sump_psi = 0.0; for ( j = 0; j < particle_image->logical_y_dimension; j++ ) { if ( j > particle_image->physical_address_of_box_center_y ) dy = particle_image->logical_y_dimension - j; else dy = j; for ( i = 0; i < particle_image->logical_x_dimension; i++ ) { if ( i > particle_image->physical_address_of_box_center_x ) dx = particle_image->logical_y_dimension - i; else dx = i; if ( correlation_map->real_values[pixel_counter] >= log_threshold && correlation_map->real_values[pixel_counter] != 0.0f ) { correlation_map->real_values[pixel_counter] = exp(correlation_map->real_values[pixel_counter] - max_logp_particle); sump_psi += correlation_map->real_values[pixel_counter]; non_zero_pixels++; } else { correlation_map->real_values[pixel_counter] = 0.0; } pixel_counter++; } pixel_counter += particle_image->padding_jump_value; } if ( non_zero_pixels > 0 ) { // correlation_map->QuickAndDirtyWriteSlice("corr.mrc", 1); // exit(0); // correlation_map->SetToConstant(0.0); // correlation_map->real_values[0] = 1.0; // sump_psi = 1.0; // if (! uncrop) correlation_map->real_values[0] += 0.01; correlation_map->ForwardFFT( ); if ( use_best_psi ) i = number_of_rotations; else i = current_rotation; if ( image_to_blur == NULL ) { #ifdef MKL vmcMul(particle_image->real_memory_allocated / 2, reinterpret_cast<MKL_Complex8*>(correlation_map->complex_values), reinterpret_cast<MKL_Complex8*>(rotation_cache[i].complex_values), reinterpret_cast<MKL_Complex8*>(temp_image->complex_values), VML_EP | VML_FTZDAZ_ON | VML_ERRMODE_IGNORE); #else real_a = correlation_map->real_values; real_b = correlation_map->real_values + 1; real_c = rotation_cache[i].real_values; real_d = rotation_cache[i].real_values + 1; real_r = temp_image->real_values; real_i = temp_image->real_values + 1; for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) { temp_k1[pixel_counter] = real_a[pixel_counter] + real_b[pixel_counter]; }; for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) { temp_k2[pixel_counter] = real_b[pixel_counter] - real_a[pixel_counter]; }; for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) { real_r[pixel_counter] = real_a[pixel_counter] * (real_c[pixel_counter] + real_d[pixel_counter]) - real_d[pixel_counter] * temp_k1[pixel_counter]; }; for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) { real_i[pixel_counter] = real_a[pixel_counter] * (real_c[pixel_counter] + real_d[pixel_counter]) + real_c[pixel_counter] * temp_k2[pixel_counter]; }; #endif } else { if ( diff_image_to_blur != NULL ) { #ifdef MKL vmcMul(particle_image->real_memory_allocated / 2, reinterpret_cast<MKL_Complex8*>(correlation_map->complex_values), reinterpret_cast<MKL_Complex8*>(diff_image_to_blur->complex_values), reinterpret_cast<MKL_Complex8*>(temp_image->complex_values), VML_EP | VML_FTZDAZ_ON | VML_ERRMODE_IGNORE); #else real_a = correlation_map->real_values; real_b = correlation_map->real_values + 1; real_c = diff_image_to_blur->real_values; real_d = diff_image_to_blur->real_values + 1; real_r = temp_image->real_values; real_i = temp_image->real_values + 1; for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) { temp_k1[pixel_counter] = real_a[pixel_counter] + real_b[pixel_counter]; }; for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) { temp_k2[pixel_counter] = real_b[pixel_counter] - real_a[pixel_counter]; }; for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) { real_r[pixel_counter] = real_a[pixel_counter] * (real_c[pixel_counter] + real_d[pixel_counter]) - real_d[pixel_counter] * temp_k1[pixel_counter]; }; for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) { real_i[pixel_counter] = real_a[pixel_counter] * (real_c[pixel_counter] + real_d[pixel_counter]) + real_c[pixel_counter] * temp_k2[pixel_counter]; }; #endif diff_image_to_blur->CopyFrom(temp_image); } #ifdef MKL vmcMul(particle_image->real_memory_allocated / 2, reinterpret_cast<MKL_Complex8*>(correlation_map->complex_values), reinterpret_cast<MKL_Complex8*>(image_to_blur->complex_values), reinterpret_cast<MKL_Complex8*>(temp_image->complex_values), VML_EP | VML_FTZDAZ_ON | VML_ERRMODE_IGNORE); #else real_a = correlation_map->real_values; real_b = correlation_map->real_values + 1; real_c = image_to_blur->real_values; real_d = image_to_blur->real_values + 1; real_r = temp_image->real_values; real_i = temp_image->real_values + 1; for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) { temp_k1[pixel_counter] = real_a[pixel_counter] + real_b[pixel_counter]; }; for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) { temp_k2[pixel_counter] = real_b[pixel_counter] - real_a[pixel_counter]; }; for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) { real_r[pixel_counter] = real_a[pixel_counter] * (real_c[pixel_counter] + real_d[pixel_counter]) - real_d[pixel_counter] * temp_k1[pixel_counter]; }; for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) { real_i[pixel_counter] = real_a[pixel_counter] * (real_c[pixel_counter] + real_d[pixel_counter]) + real_c[pixel_counter] * temp_k2[pixel_counter]; }; #endif } // max_logp_particle is the current best LogP found over all tested references, angles and x,y positions. // It is also the offset of the likelihoods in correlation_map and sump_psi (the sum of likelihoods). // old_max_log is the previous best logP and correlation_map offset used to calculate sum_image and sump_class. // First deal with case where the old offset is so low that the previous sums are not significant compared with the current reference. temp_image->is_in_real_space = false; temp_image->BackwardFFT( ); if ( old_max_logp < max_logp_particle - log_range ) { sum_image->CopyFrom(temp_image); old_max_logp = max_logp_particle; snr_class = snr_psi; sump_class = sump_psi; } else // If the old and new offsets are similar, need to calculate a weighted sum if ( fabsf(old_max_logp - max_logp_particle) <= log_range ) { // Case of old offset smaller than or equal new offset if ( old_max_logp <= max_logp_particle ) { scale = expf(old_max_logp - max_logp_particle); pixel_counter = 0; for ( j = 0; j < sum_image->logical_y_dimension; j++ ) { for ( i = 0; i < sum_image->logical_x_dimension; i++ ) { sum_image->real_values[pixel_counter] = sum_image->real_values[pixel_counter] * scale + temp_image->real_values[pixel_counter]; pixel_counter++; } pixel_counter += sum_image->padding_jump_value; } old_max_logp = max_logp_particle; snr_class = snr_psi; sump_class = sump_class * scale + sump_psi; } // Case of old offset larger than new offset else { scale = expf(max_logp_particle - old_max_logp); pixel_counter = 0; for ( j = 0; j < sum_image->logical_y_dimension; j++ ) { for ( i = 0; i < sum_image->logical_x_dimension; i++ ) { sum_image->real_values[pixel_counter] = sum_image->real_values[pixel_counter] + temp_image->real_values[pixel_counter] * scale; pixel_counter++; } pixel_counter += sum_image->padding_jump_value; } sump_class = sump_class + sump_psi * scale; } } } } } if ( sump_class > 0.0 ) { // Divide rotationally & translationally blurred image by sum of probabilities binning_factor = float(cropped_input_image.logical_x_dimension) / float(sum_image->logical_x_dimension); sum_image->MultiplyByConstant(sum_image->number_of_real_space_pixels / binning_factor / sump_class); if ( diff_image_to_blur != NULL ) diff_image_to_blur->MultiplyByConstant(sum_image->number_of_real_space_pixels / binning_factor / sump_class); sum_image->ForwardFFT( ); if ( uncrop ) { sum_image->CosineMask(0.45, 0.1); // sum_image->CosineMask(0.3, 0.4); sum_image->ClipInto(&cropped_input_image); cropped_input_image.BackwardFFT( ); cropped_input_image.ClipIntoLargerRealSpace2D(&blurred_image, cropped_input_image.ReturnAverageOfRealValuesOnEdges( )); } else { blurred_image.CopyFrom(sum_image); temp_image->CopyFrom(image_to_blur); temp_image->MultiplyByConstant(sump_class / temp_image->number_of_real_space_pixels / temp_image->number_of_real_space_pixels); blurred_image.AddImage(temp_image); } // wxPrintf("log sump_class = %g old_max_logp = %g number_of_independent_pixels = %g ssq_X = %g\n", logf(sump_class), old_max_logp, number_of_independent_pixels, ssq_X); logp = logf(sump_class) + old_max_logp - 0.5 * (number_of_independent_pixels * logf(2.0 * PI) + number_of_pixels * ssq_X); current_parameters.logp = logp; } else { blurred_image.SetToConstant(0.0); if ( diff_image_to_blur != NULL ) diff_image_to_blur->SetToConstant(0.0); logp = -std::numeric_limits<float>::max( ); } // wxPrintf("log_sum = %g, old = %g, n = %g, var = %g\n", logf(sump_class), old_max_log, number_of_independent_pixels, norm_A); delete correlation_map; delete temp_image; delete sum_image; #ifndef MKL delete[] temp_k1; #endif return logp; } void Particle::EstimateSigmaNoise( ) { MyDebugAssertTrue(particle_image->is_in_memory, "particle_image memory not allocated"); sigma_noise = particle_image->ReturnSigmaNoise( ); }
50.030524
341
0.665751
jojoelfe
1bec1a22f7bc14d6dffd47b2898b401dc7ba0a90
1,818
cpp
C++
BFLib/src/BFFileHelper.cpp
McGill-DMaS/Privacy-ITSA
ff1fc65d01660f38530256e8661831b0d3020e6e
[ "CC0-1.0" ]
null
null
null
BFLib/src/BFFileHelper.cpp
McGill-DMaS/Privacy-ITSA
ff1fc65d01660f38530256e8661831b0d3020e6e
[ "CC0-1.0" ]
null
null
null
BFLib/src/BFFileHelper.cpp
McGill-DMaS/Privacy-ITSA
ff1fc65d01660f38530256e8661831b0d3020e6e
[ "CC0-1.0" ]
1
2020-09-15T01:45:28.000Z
2020-09-15T01:45:28.000Z
//--------------------------------------------------------------------------- // File: // BFFileHelper.cpp BFFileHelper.hpp // // Module: // CBFFileHelper // // History: // May. 7, 2002 Created by Benjamin Fung //--------------------------------------------------------------------------- #include "BFPch.h" #if !defined(BFFILEHELPER_H) #include "BFFileHelper.h" #endif //-------------------------------------------------------------------- //-------------------------------------------------------------------- CBFFileHelper::CBFFileHelper() { } CBFFileHelper::~CBFFileHelper() { } //-------------------------------------------------------------------- //-------------------------------------------------------------------- bool CBFFileHelper::removeFile(LPCTSTR filename) { return _tremove(filename) == 0; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- void CBFFileHelper::splitPath(LPCTSTR fullPath, CString& drive, CString& dir, CString& fname, CString& ext) { TCHAR tDrive[_MAX_DRIVE]; TCHAR tDir[_MAX_DIR]; TCHAR tFname[_MAX_FNAME]; TCHAR tExt[_MAX_EXT]; _tsplitpath_s(fullPath, tDrive, tDir, tFname, tExt); drive = tDrive; dir = tDir; fname = tFname; ext = tExt; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- bool CBFFileHelper::replaceExtension(LPCTSTR fname, LPCTSTR ext, CString& res) { res = fname; int dotPos = res.ReverseFind(TCHAR('.')); if (dotPos == -1) { res.Empty(); return false; } res = res.Left(dotPos + 1); res += ext; return true; }
28.40625
108
0.366887
McGill-DMaS
1bec4f0f39352babd8398d5ca478fa78cb75bd0e
2,459
cc
C++
felicia/core/lib/unit/bytes.cc
chokobole/felicia
3b5eeb5f93c59c5364d3932bc407e054977aa1ec
[ "BSD-3-Clause" ]
17
2018-10-28T13:58:01.000Z
2022-03-22T07:54:12.000Z
felicia/core/lib/unit/bytes.cc
chokobole/felicia
3b5eeb5f93c59c5364d3932bc407e054977aa1ec
[ "BSD-3-Clause" ]
2
2018-11-09T04:15:58.000Z
2018-11-09T06:42:57.000Z
felicia/core/lib/unit/bytes.cc
chokobole/felicia
3b5eeb5f93c59c5364d3932bc407e054977aa1ec
[ "BSD-3-Clause" ]
5
2019-10-31T06:50:05.000Z
2022-03-22T07:54:30.000Z
// Copyright (c) 2019 The Felicia 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 "felicia/core/lib/unit/bytes.h" namespace felicia { Bytes::Bytes() = default; Bytes::Bytes(int64_t bytes) : bytes_(bytes) {} bool Bytes::operator==(Bytes other) const { return bytes_ == other.bytes_; } bool Bytes::operator!=(Bytes other) const { return bytes_ != other.bytes_; } bool Bytes::operator<(Bytes other) const { return bytes_ < other.bytes_; } bool Bytes::operator<=(Bytes other) const { return bytes_ <= other.bytes_; } bool Bytes::operator>(Bytes other) const { return bytes_ > other.bytes_; } bool Bytes::operator>=(Bytes other) const { return bytes_ >= other.bytes_; } Bytes Bytes::operator+(Bytes other) const { return Bytes(internal::SaturateAdd(bytes_, other.bytes_)); } Bytes Bytes::operator-(Bytes other) const { return Bytes(internal::SaturateSub(bytes_, other.bytes_)); } Bytes& Bytes::operator+=(Bytes other) { return *this = (*this + other); } Bytes& Bytes::operator-=(Bytes other) { return *this = (*this - other); } double Bytes::operator/(Bytes a) const { return bytes_ / a.bytes_; } int64_t Bytes::bytes() const { return bytes_; } // static Bytes Bytes::FromBytes(int64_t bytes) { return Bytes(bytes); } // static Bytes Bytes::FromKilloBytes(int64_t killo_bytes) { return Bytes(internal::FromProduct(killo_bytes, kKilloBytes)); } // static Bytes Bytes::FromKilloBytesD(double killo_bytes) { return FromDouble(killo_bytes * kKilloBytes); } // static Bytes Bytes::FromMegaBytes(int64_t mega_bytes) { return Bytes(internal::FromProduct(mega_bytes, kMegaBytes)); } // static Bytes Bytes::FromMegaBytesD(double mega_bytes) { return FromDouble(mega_bytes * kMegaBytes); } // static Bytes Bytes::FromGigaBytes(int64_t giga_bytes) { return Bytes(internal::FromProduct(giga_bytes, kGigaBytes)); } // static Bytes Bytes::FromGigaBytesD(double giga_bytes) { return FromDouble(giga_bytes * kGigaBytes); } // static Bytes Bytes::Max() { return Bytes(std::numeric_limits<int64_t>::max()); } // static Bytes Bytes::Min() { return Bytes(std::numeric_limits<int64_t>::min()); } // static Bytes Bytes::FromDouble(double value) { return Bytes(base::saturated_cast<int64_t>(value)); } std::ostream& operator<<(std::ostream& os, Bytes bytes) { os << base::NumberToString(bytes.bytes()) << " bytes"; return os; } } // namespace felicia
30.358025
76
0.721838
chokobole
1bf3169b42d205aefeeb0ccad8c4a13d4c1f0bb7
2,742
hpp
C++
wsi/surface_properties.hpp
xytovl/vulkan-wsi-layer
4030ab0c70d301695c2aaf42ac98e97184ad79d3
[ "MIT" ]
2
2021-03-27T15:18:26.000Z
2021-03-27T15:18:27.000Z
wsi/surface_properties.hpp
xytovl/vulkan-wsi-layer
4030ab0c70d301695c2aaf42ac98e97184ad79d3
[ "MIT" ]
null
null
null
wsi/surface_properties.hpp
xytovl/vulkan-wsi-layer
4030ab0c70d301695c2aaf42ac98e97184ad79d3
[ "MIT" ]
null
null
null
/* * Copyright (c) 2017-2019, 2021 Arm Limited. * * SPDX-License-Identifier: MIT * * 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. */ /** * @file surface_properties.hpp * * @brief Vulkan WSI surface query interfaces. */ #pragma once #include <vulkan/vulkan.h> #include <util/extension_list.hpp> namespace wsi { /** * @brief The base surface property query interface. */ class surface_properties { public: /** * @brief Implementation of vkGetPhysicalDeviceSurfaceCapabilitiesKHR for the specific VkSurface type. */ virtual VkResult get_surface_capabilities(VkPhysicalDevice physical_device, VkSurfaceKHR surface, VkSurfaceCapabilitiesKHR *surface_capabilities) = 0; /** * @brief Implementation of vkGetPhysicalDeviceSurfaceFormatsKHR for the specific VkSurface type. */ virtual VkResult get_surface_formats(VkPhysicalDevice physical_device, VkSurfaceKHR surface, uint32_t *surface_format_count, VkSurfaceFormatKHR *surface_formats) = 0; /** * @brief Implementation of vkGetPhysicalDeviceSurfacePresentModesKHR for the specific VkSurface type. */ virtual VkResult get_surface_present_modes(VkPhysicalDevice physical_device, VkSurfaceKHR surface, uint32_t *present_mode_count, VkPresentModeKHR *present_modes) = 0; /** * @brief Return the device extensions that this surface_properties implementation needs. */ virtual const util::extension_list &get_required_device_extensions() { static const util::extension_list empty{util::allocator::get_generic()}; return empty; } }; } /* namespace wsi */
37.054054
113
0.724654
xytovl
1bf47543d28e2addda492c2fa7444505064439ae
8,601
ipp
C++
rice/Data_Type.ipp
keyme/rice
4b5e4ad3e2294a1b58886fb946eb26e3512599d9
[ "BSD-2-Clause" ]
11
2015-02-09T12:13:45.000Z
2019-11-25T01:14:31.000Z
rice/Data_Type.ipp
jsomers/rice
6bbcc2dd85d010a1108a4d7ac7ece39b1c1210f5
[ "BSD-2-Clause" ]
null
null
null
rice/Data_Type.ipp
jsomers/rice
6bbcc2dd85d010a1108a4d7ac7ece39b1c1210f5
[ "BSD-2-Clause" ]
2
2019-11-25T01:14:35.000Z
2021-09-29T04:57:36.000Z
#ifndef Rice__Data_Type__ipp_ #define Rice__Data_Type__ipp_ #include "Class.hpp" #include "String.hpp" #include "Data_Object.hpp" #include "detail/default_allocation_func.hpp" #include "detail/creation_funcs.hpp" #include "detail/method_data.hpp" #include "detail/Caster.hpp" #include "detail/demangle.hpp" #include <stdexcept> #include <typeinfo> template<typename T> VALUE Rice::Data_Type<T>::klass_ = Qnil; template<typename T> std::auto_ptr<Rice::detail::Abstract_Caster> Rice::Data_Type<T>::caster_; template<typename T> template<typename Base_T> inline Rice::Data_Type<T> Rice::Data_Type<T>:: bind(Module const & klass) { if(klass.value() == klass_) { return Data_Type<T>(); } if(is_bound()) { std::string s; s = "Data type "; s += detail::demangle(typeid(T).name()); s += " is already bound to a different type"; throw std::runtime_error(s.c_str()); } // TODO: Make sure base type is bound; throw an exception otherwise. // We can't do this just yet, because we don't have a specialization // for binding to void. klass_ = klass; // TODO: do we need to unregister when the program exits? we have to // be careful if we do, because the ruby interpreter might have // already shut down. The correct behavior is probably to register an // exit proc with the interpreter, so the proc gets called before the // GC shuts down. rb_gc_register_address(&klass_); for(typename Instances::iterator it = unbound_instances().begin(), end = unbound_instances().end(); it != end; unbound_instances().erase(it++)) { (*it)->set_value(klass); } detail::Abstract_Caster * base_caster = Data_Type<Base_T>().caster(); caster_.reset(new detail::Caster<T, Base_T>(base_caster, klass)); Data_Type_Base::casters().insert(std::make_pair(klass, caster_.get())); return Data_Type<T>(); } template<typename T> inline Rice::Data_Type<T>:: Data_Type() : Module_impl<Data_Type_Base, Data_Type<T> >( klass_ == Qnil ? rb_cObject : klass_) { if(!is_bound()) { unbound_instances().insert(this); } } template<typename T> inline Rice::Data_Type<T>:: Data_Type(Module const & klass) : Module_impl<Data_Type_Base, Data_Type<T> >( klass) { this->bind<void>(klass); } template<typename T> inline Rice::Data_Type<T>:: ~Data_Type() { unbound_instances().erase(this); } template<typename T> Rice::Module Rice::Data_Type<T>:: klass() { if(is_bound()) { return klass_; } else { std::string s; s += detail::demangle(typeid(T *).name()); s += " is unbound"; throw std::runtime_error(s.c_str()); } } template<typename T> Rice::Data_Type<T> & Rice::Data_Type<T>:: operator=(Module const & klass) { this->bind<void>(klass); return *this; } template<typename T> template<typename Constructor_T> inline Rice::Data_Type<T> & Rice::Data_Type<T>:: define_constructor( Constructor_T /* constructor */, Arguments* arguments) { check_is_bound(); // Normal constructor pattern with new/initialize rb_define_alloc_func( static_cast<VALUE>(*this), detail::default_allocation_func<T>); this->define_method( "initialize", &Constructor_T::construct, arguments ); return *this; } template<typename T> template<typename Constructor_T> inline Rice::Data_Type<T> & Rice::Data_Type<T>:: define_constructor( Constructor_T constructor, Arg const& arg) { Arguments* args = new Arguments(); args->add(arg); return define_constructor(constructor, args); } template<typename T> template<typename Director_T> inline Rice::Data_Type<T>& Rice::Data_Type<T>:: define_director() { Rice::Data_Type<Director_T>::template bind<T>(*this); return *this; } template<typename T> inline T * Rice::Data_Type<T>:: from_ruby(Object x) { check_is_bound(); void * v = DATA_PTR(x.value()); Class klass = x.class_of(); if(klass.value() == klass_) { // Great, not converting to a base/derived type Data_Type<T> data_klass; Data_Object<T> obj(x, data_klass); return obj.get(); } Data_Type_Base::Casters::const_iterator it = Data_Type_Base::casters().begin(); Data_Type_Base::Casters::const_iterator end = Data_Type_Base::casters().end(); // Finding the bound type that relates to the given klass is // a two step process. We iterate over the list of known type casters, // looking for: // // 1) casters that handle this direct type // 2) casters that handle types that are ancestors of klass // // Step 2 allows us to handle the case where a Rice-wrapped class // is subclassed in Ruby but then an instance of that class is passed // back into C++ (say, in a Listener / callback construction) // VALUE ancestors = rb_mod_ancestors(klass.value()); long earliest = RARRAY_LEN(ancestors) + 1; int index; VALUE indexFound; Data_Type_Base::Casters::const_iterator toUse = end; for(; it != end; it++) { // Do we match directly? if(klass.value() == it->first) { toUse = it; break; } // Check for ancestors. Trick is, we need to find the lowest // ancestor that does have a Caster to make sure that we're casting // to the closest C++ type that the Ruby class is subclassing. // There might be multiple ancestors that are also wrapped in // the extension, so find the earliest in the list and use that one. indexFound = rb_funcall(ancestors, rb_intern("index"), 1, it->first); if(indexFound != Qnil) { index = NUM2INT(indexFound); if(index < earliest) { earliest = index; toUse = it; } } } if(toUse == end) { std::string s = "Class "; s += klass.name().str(); s += " is not registered/bound in Rice"; throw std::runtime_error(s); } detail::Abstract_Caster * caster = toUse->second; if(caster) { T * result = static_cast<T *>(caster->cast_to_base(v, klass_)); return result; } else { return static_cast<T *>(v); } } template<typename T> inline bool Rice::Data_Type<T>:: is_bound() { return klass_ != Qnil; } template<typename T> inline Rice::detail::Abstract_Caster * Rice::Data_Type<T>:: caster() const { check_is_bound(); return caster_.get(); } namespace Rice { template<> inline detail::Abstract_Caster * Data_Type<void>:: caster() const { return 0; } template<typename T> void Data_Type<T>:: check_is_bound() { if(!is_bound()) { std::string s; s = "Data type "; s += detail::demangle(typeid(T).name()); s += " is not bound"; throw std::runtime_error(s.c_str()); } } } // Rice template<typename T> inline Rice::Data_Type<T> Rice:: define_class_under( Object module, char const * name) { Class c(define_class_under(module, name, rb_cObject)); c.undef_creation_funcs(); return Data_Type<T>::template bind<void>(c); } template<typename T, typename Base_T> inline Rice::Data_Type<T> Rice:: define_class_under( Object module, char const * name) { Data_Type<Base_T> base_dt; Class c(define_class_under(module, name, base_dt)); c.undef_creation_funcs(); return Data_Type<T>::template bind<Base_T>(c); } template<typename T> inline Rice::Data_Type<T> Rice:: define_class( char const * name) { Class c(define_class(name, rb_cObject)); c.undef_creation_funcs(); return Data_Type<T>::template bind<void>(c); } template<typename T, typename Base_T> inline Rice::Data_Type<T> Rice:: define_class( char const * name) { Data_Type<Base_T> base_dt; Class c(define_class(name, base_dt)); c.undef_creation_funcs(); return Data_Type<T>::template bind<Base_T>(c); } template<typename From_T, typename To_T> inline void Rice::define_implicit_cast() { // As Rice currently expects only one entry into // this list for a given klass VALUE, we need to get // the current caster for From_T and insert in our // new caster as the head of the caster list Class from_class = Data_Type<From_T>::klass().value(); Class to_class = Data_Type<To_T>::klass().value(); detail::Abstract_Caster* from_caster = Data_Type<From_T>::caster_.release(); detail::Abstract_Caster* new_caster = new detail::Implicit_Caster<To_T, From_T>(from_caster, to_class); // Insert our new caster into the list for the from class Data_Type_Base::casters().erase(from_class); Data_Type_Base::casters().insert( std::make_pair( from_class, new_caster ) ); // And make sure the from_class has direct access to the // updated caster list Data_Type<From_T>::caster_.reset(new_caster); } #endif // Rice__Data_Type__ipp_
23.5
81
0.679921
keyme
1bf49ec926522d878d1647d282675fffdf09c433
240
cpp
C++
Source/InventorySystem/Private/Inventory/DataTypes/StackData.cpp
spencer-melnick/Threshold
b0178e322548ca7cbe31cbf26943df3d4c616c8a
[ "MIT" ]
3
2020-09-16T02:33:59.000Z
2021-11-24T02:38:17.000Z
Source/InventorySystem/Private/Inventory/DataTypes/StackData.cpp
spencer-melnick/Threshold
b0178e322548ca7cbe31cbf26943df3d4c616c8a
[ "MIT" ]
29
2020-08-03T19:35:28.000Z
2020-11-18T15:41:13.000Z
Source/InventorySystem/Private/Inventory/DataTypes/StackData.cpp
spencer-melnick/Threshold
b0178e322548ca7cbe31cbf26943df3d4c616c8a
[ "MIT" ]
3
2021-03-19T14:23:10.000Z
2021-11-24T02:38:34.000Z
// Copyright (c) 2020 Spencer Melnick #include "Inventory/DataTypes/StackData.h" bool FInventoryStackData::NetSerialize(FArchive& Ar, UPackageMap* PackageMap, bool& bOutSuccess) { Ar << StackCount; bOutSuccess = true; return true; }
20
96
0.754167
spencer-melnick
1bf68601f4d5e4898fad071812db64978e2b0f4f
597
hpp
C++
QQDemo/color_skin.hpp
auxs2015/DuiDesign
fb98c38dacae7d77a603a325f635135b54f3f898
[ "BSD-2-Clause" ]
11
2017-05-26T06:52:32.000Z
2021-07-01T00:39:27.000Z
QQDemo/color_skin.hpp
auxs2015/DuiDesign
fb98c38dacae7d77a603a325f635135b54f3f898
[ "BSD-2-Clause" ]
null
null
null
QQDemo/color_skin.hpp
auxs2015/DuiDesign
fb98c38dacae7d77a603a325f635135b54f3f898
[ "BSD-2-Clause" ]
24
2016-12-12T02:56:31.000Z
2021-12-06T01:23:52.000Z
#ifndef COLORSKIN_HPP #define COLORSKIN_HPP class MainFrame; using namespace DuiLib; class ColorSkinWindow : public WindowImplBase { public: ColorSkinWindow(MainFrame* main_frame, RECT rcParentWindow); LPCTSTR GetWindowClassName() const; virtual void OnFinalMessage(HWND hWnd); void Notify(TNotifyUI& msg); virtual void InitWindow(); virtual CDuiString GetSkinFile(); virtual CDuiString GetSkinFolder(); virtual LRESULT OnKillFocus(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); private: RECT parent_window_rect_; MainFrame* main_frame_; }; #endif // COLORSKIN_HPP
18.65625
86
0.788945
auxs2015
1bf847e6322659bc044bd9b9912da9b0933757b0
803
hpp
C++
bintree_cpp/test/testavl01.hpp
thanhit95/data-structures-algorithms
87e9680cb1d5cdb93d23131c2345237582d5f6d2
[ "BSD-3-Clause" ]
28
2021-02-26T15:03:45.000Z
2021-07-12T06:13:21.000Z
bintree_cpp/test/testavl01.hpp
thanhit95/data-structures-algorithms
87e9680cb1d5cdb93d23131c2345237582d5f6d2
[ "BSD-3-Clause" ]
null
null
null
bintree_cpp/test/testavl01.hpp
thanhit95/data-structures-algorithms
87e9680cb1d5cdb93d23131c2345237582d5f6d2
[ "BSD-3-Clause" ]
3
2021-04-26T13:40:41.000Z
2021-04-26T15:43:44.000Z
#ifndef __TEST_AVL_01_HPP__ #define __TEST_AVL_01_HPP__ #include <iostream> #include "testbase.hpp" #include "binarytree/avltree.hpp" using namespace my::test; using namespace my::bt; namespace my { namespace test { namespace avl01 { void doTask() { auto avl = AvlTree<int>(); for ( auto &&value : {10, 20, 30, 40, 50, 25} ) avl.insert(value); std::cout << "\n size: " << avl.size() << std::endl; std::cout << "\n min: " << avl.min() << std::endl; std::cout << "\n max: " << avl.max() << std::endl; std::cout << "\n contain: " << avl.contain(50) << std::endl; std::cout << "\n height: " << avl.height() << std::endl; std::cout << "\n print tree:" << std::endl; base::printTree(avl); std::cout << std::endl; } } } // test } // my #endif
15.745098
64
0.56538
thanhit95
1bfb4d5a42c697404908a83b68183377f8036d13
980
cpp
C++
Programas de aceptaelreto/418. RENUM/renum.cpp
marcosherreroa/Competitive-Programming
26b0f0f211172a06cc2e498a7aa8706f7fbf0038
[ "CC0-1.0" ]
null
null
null
Programas de aceptaelreto/418. RENUM/renum.cpp
marcosherreroa/Competitive-Programming
26b0f0f211172a06cc2e498a7aa8706f7fbf0038
[ "CC0-1.0" ]
null
null
null
Programas de aceptaelreto/418. RENUM/renum.cpp
marcosherreroa/Competitive-Programming
26b0f0f211172a06cc2e498a7aa8706f7fbf0038
[ "CC0-1.0" ]
null
null
null
//Marcos Herrro #include <iostream> #include <string> #include <queue> #include <unordered_map> void resuelveCaso() { std::unordered_map<int, int> tabla; std::queue<std::string> instrucciones; std::queue<int> lineasSaltos; int num, renum = 10; std::string instr; std::cin >> num; while (num != 0) { tabla[num] = renum; renum += 10; std::cin >> instr; instrucciones.push(instr); if (instr == "GOTO" || instr == "GOSUB") { std::cin >> num; lineasSaltos.push(num); } std::cin>> num; } renum = 10; while (!instrucciones.empty()) { std::cout <<renum<<' '<< instrucciones.front(); if (instrucciones.front() == "GOTO" || instrucciones.front() == "GOSUB") { std::cout <<' '<< tabla[lineasSaltos.front()]; lineasSaltos.pop(); } std::cout << '\n'; renum += 10; instrucciones.pop(); } std::cout << "---\n"; } int main() { int n; std::cin >> n; for (int i = 0; i < n; ++i)resuelveCaso(); }
21.304348
77
0.566327
marcosherreroa
1bfb951530f712545adc5d4d58f1d520c9b5314d
11,690
hpp
C++
heart/test/extended_bidomain/TestExtendedBidomainProblem.hpp
mdp19pn/Chaste
f7b6bafa64287d567125b587b29af6d8bd7aeb90
[ "Apache-2.0", "BSD-3-Clause" ]
100
2015-02-23T08:32:23.000Z
2022-02-25T11:39:26.000Z
heart/test/extended_bidomain/TestExtendedBidomainProblem.hpp
mdp19pn/Chaste
f7b6bafa64287d567125b587b29af6d8bd7aeb90
[ "Apache-2.0", "BSD-3-Clause" ]
11
2017-06-14T13:48:43.000Z
2022-03-10T10:42:07.000Z
heart/test/extended_bidomain/TestExtendedBidomainProblem.hpp
mdp19pn/Chaste
f7b6bafa64287d567125b587b29af6d8bd7aeb90
[ "Apache-2.0", "BSD-3-Clause" ]
53
2015-02-23T13:52:44.000Z
2022-02-28T18:57:35.000Z
/* Copyright (c) 2005-2021, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. 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 University of Oxford 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. */ #ifndef _TESTEXTENDEDBIDOMAINPROBLEM_HPP_ #define _TESTEXTENDEDBIDOMAINPROBLEM_HPP_ #include "UblasIncludes.hpp" #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include "PetscSetupAndFinalize.hpp" #include "HeartConfig.hpp" #include "SimpleStimulus.hpp" #include "CorriasBuistSMCModified.hpp" #include "CorriasBuistICCModified.hpp" #include "CompareHdf5ResultsFiles.hpp" #include "ExtendedBidomainProblem.hpp" #include "PlaneStimulusCellFactory.hpp" #include "LuoRudy1991.hpp" #include "FaberRudy2000.hpp" #include "OutputFileHandler.hpp" #include "Hdf5DataReader.hpp" #include <string> #include <sstream> #include <iostream> #include <fstream> class ICC_Cell_factory : public AbstractCardiacCellFactory<1> { public: ICC_Cell_factory() : AbstractCardiacCellFactory<1>() { } AbstractCardiacCell* CreateCardiacCellForTissueNode(Node<1>* pNode) { CorriasBuistICCModified *cell; cell = new CorriasBuistICCModified(mpSolver, mpZeroStimulus); double x = pNode->rGetLocation()[0]; double IP3_initial = 0.00067; double IP3_final = 0.00065; double cable_length = 10.0; //calculate the concentration gradient... double IP3_conc = IP3_initial + x*(IP3_final - IP3_initial)/cable_length; //..and set it cell->SetIP3Concentration(IP3_conc); cell->SetFractionOfVDDRInPU(0.04); return cell; } }; class SMC_Cell_factory : public AbstractCardiacCellFactory<1> { public: SMC_Cell_factory() : AbstractCardiacCellFactory<1>() { } AbstractCardiacCell* CreateCardiacCellForTissueNode(Node<1>* pNode) { CorriasBuistSMCModified *cell; cell = new CorriasBuistSMCModified(mpSolver, mpZeroStimulus); cell->SetFakeIccStimulusPresent(false);//it will get it from the real ICC, via gap junction return cell; } }; class TestExtendedBidomainProblem: public CxxTest::TestSuite { public: void SetupParameters() { HeartConfig::Instance()->Reset(); HeartConfig::Instance()->SetIntracellularConductivities(Create_c_vector(5.0)); HeartConfig::Instance()->SetExtracellularConductivities(Create_c_vector(1.0)); HeartConfig::Instance()->SetOdePdeAndPrintingTimeSteps(0.1,0.1,10.0); //HeartConfig::Instance()->SetKSPSolver("gmres"); HeartConfig::Instance()->SetUseAbsoluteTolerance(1e-5); HeartConfig::Instance()->SetKSPPreconditioner("bjacobi"); } /** * This test is aimed at comparing the extended bidomain implementation in Chaste with * the original Finite Difference code developed by Martin Buist. * * All the parameters are chosen to replicate the same conditions as in his code. */ void TestExtendedProblemVsMartincCode() { SetupParameters(); TetrahedralMesh<1,1> mesh; unsigned number_of_elements = 100;//this is nGrid in Martin's code double length = 10.0;//100mm as in Martin's code mesh.ConstructRegularSlabMesh(length/number_of_elements, length); TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), number_of_elements + 1); double Am_icc = 1000.0; double Am_smc = 1000.0; double Am_gap = 1.0; double Cm_icc = 1.0; double Cm_smc = 1.0; double G_gap = 20.0;//mS/cm^2 HeartConfig::Instance()->SetSimulationDuration(1000.0); //ms. ICC_Cell_factory icc_factory; SMC_Cell_factory smc_factory; std::string dir = "ICCandSMC"; std::string filename = "extended1d"; HeartConfig::Instance()->SetOutputDirectory(dir); HeartConfig::Instance()->SetOutputFilenamePrefix(filename); ExtendedBidomainProblem<1> extended_problem( &icc_factory , &smc_factory); extended_problem.SetMesh(&mesh); extended_problem.SetExtendedBidomainParameters(Am_icc,Am_smc, Am_gap, Cm_icc, Cm_smc, G_gap); extended_problem.SetIntracellularConductivitiesForSecondCell(Create_c_vector(1.0)); std::vector<unsigned> outputnodes; outputnodes.push_back(50u); HeartConfig::Instance()->SetRequestedNodalTimeTraces(outputnodes); extended_problem.Initialise(); extended_problem.Solve(); HeartEventHandler::Headings(); HeartEventHandler::Report(); /** * Compare with valid data. * As Martin's code is an FD code, results will never match exactly. * The comparison below is done against a 'valid' h5 file. * * The h5 file (1DValid.h5) is a Chaste (old phi_i formulation) file with is valid because, when extrapolating results from it, they look very similar * (except for a few points at the end of the upstroke) to the results taken * directly from Martin's code. * A plot of Chaste results versus Martin's result (at node 50) is stored * in the file 1DChasteVsMartin.eps for reference. * * A second plot comparing the old formulation (with phi_i) to the new formulation with V_m is contained in *.1DChasteNewFormulation.png * */ TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/extendedbidomain", "1DValid", false, dir, filename, true, 0.2)); /* * Here we compare the new formulation (V_m1, V_m2, phi_e) * with the previous formulation (phi_i1, phi_i2, phi_e) running with GMRES and an absolute KSP tolerance of 1e-8. */ TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/extendedbidomain", "extended1d_previous_chaste_formulation_abs_tol_1e-8", false, dir, filename, true, 1e-2)); } // Test the functionality for outputting the values of requested cell state variables void TestExtendedBidomainProblemPrintsMultipleVariables() { // Get the singleton in a clean state HeartConfig::Instance()->Reset(); // Set configuration file std::string dir = "ExtBidoMultiVars"; std::string filename = "extended"; HeartConfig::Instance()->SetOutputDirectory(dir); HeartConfig::Instance()->SetOutputFilenamePrefix(filename); HeartConfig::Instance()->SetSimulationDuration(0.1); // HeartConfig::Instance()->SetKSPSolver("gmres"); HeartConfig::Instance()->SetUseAbsoluteTolerance(2e-4); HeartConfig::Instance()->SetKSPPreconditioner("jacobi"); /** Check that also the converters handle multiple variables**/ HeartConfig::Instance()->SetVisualizeWithCmgui(true); HeartConfig::Instance()->SetVisualizeWithMeshalyzer(true); TetrahedralMesh<1,1> mesh; unsigned number_of_elements = 100; double length = 10.0; mesh.ConstructRegularSlabMesh(length/number_of_elements, length); // Override the variables we are interested in writing. std::vector<std::string> output_variables; output_variables.push_back("calcium_dynamics__Ca_NSR"); output_variables.push_back("ionic_concentrations__Nai"); output_variables.push_back("fast_sodium_current_j_gate__j"); output_variables.push_back("ionic_concentrations__Ki"); HeartConfig::Instance()->SetOutputVariables( output_variables ); // Set up problem PlaneStimulusCellFactory<CellFaberRudy2000FromCellML, 1> cell_factory_1(-60, 0.5); PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 1> cell_factory_2(0.0,0.5); ExtendedBidomainProblem<1> ext_problem( &cell_factory_1, &cell_factory_2 ); ext_problem.SetMesh(&mesh); // Solve ext_problem.Initialise(); ext_problem.Solve(); // Get a reference to a reader object for the simulation results Hdf5DataReader data_reader1 = ext_problem.GetDataReader(); std::vector<double> times = data_reader1.GetUnlimitedDimensionValues(); // Check there is information about 11 timesteps (0, 0.01, 0.02, ...) unsigned num_steps = 11u; TS_ASSERT_EQUALS( times.size(), num_steps); TS_ASSERT_DELTA( times[0], 0.0, 1e-12); TS_ASSERT_DELTA( times[1], 0.01, 1e-12); TS_ASSERT_DELTA( times[2], 0.02, 1e-12); TS_ASSERT_DELTA( times[3], 0.03, 1e-12); // There should be 11 values per variable and node. std::vector<double> node_5_v = data_reader1.GetVariableOverTime("V", 5); TS_ASSERT_EQUALS( node_5_v.size(), num_steps); std::vector<double> node_5_v_2 = data_reader1.GetVariableOverTime("V_2", 5); TS_ASSERT_EQUALS( node_5_v_2.size(), num_steps); std::vector<double> node_5_phi = data_reader1.GetVariableOverTime("Phi_e", 5); TS_ASSERT_EQUALS( node_5_phi.size(), num_steps); for (unsigned i=0; i<output_variables.size(); i++) { unsigned global_index = 2+i*2; std::vector<double> values = data_reader1.GetVariableOverTime(output_variables[i], global_index); TS_ASSERT_EQUALS( values.size(), num_steps); // Check the last values match the cells' state if (ext_problem.rGetMesh().GetDistributedVectorFactory()->IsGlobalIndexLocal(global_index)) { AbstractCardiacCellInterface* p_cell = ext_problem.GetTissue()->GetCardiacCell(global_index); TS_ASSERT_DELTA(values.back(), p_cell->GetAnyVariable(output_variables[i],0), 1e-12); } //check the extra files for extra variables are there (the content is tested in the converter's tests) FileFinder file(dir + "/output/"+ filename +"_"+ output_variables[i] + ".dat", RelativeTo::ChasteTestOutput); TS_ASSERT(file.Exists()); } } }; #endif /*_TESTEXTENDEDBIDOMAINPROBLEM_HPP_*/
40.731707
158
0.688452
mdp19pn
1bfef9640fa774dd0e2336d062ae546865f5d710
11,053
cc
C++
cpp/oop/object_two.cc
Mobink980/C-C-Development
ecb86f31c608b1c69a0c3332dfabcb7abb7b7b96
[ "MIT" ]
1
2020-02-08T10:36:01.000Z
2020-02-08T10:36:01.000Z
cpp/oop/object_two.cc
Mobink980/C-C-Development
ecb86f31c608b1c69a0c3332dfabcb7abb7b7b96
[ "MIT" ]
null
null
null
cpp/oop/object_two.cc
Mobink980/C-C-Development
ecb86f31c608b1c69a0c3332dfabcb7abb7b7b96
[ "MIT" ]
null
null
null
#include <functional> // reference_wrapper #include <iostream> #include <string> #include <vector> //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Association @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ //Object composition is used to model relationships where a complex object is built from one or more simpler //objects (parts). In this lesson, we’ll take a look at a weaker type of relationship between two otherwise //unrelated objects, called an association. Unlike object composition relationships, in an association, there is //no implied whole/part relationship. //To qualify as an association, an object and another object must have the following relationship: // The associated object (member) is otherwise unrelated to the object (class) ==> not part of the object // The associated object (member) can belong to more than one object (class) at a time // The associated object (member) does not have its existence managed by the object (class) // The associated object (member) may or may not know about the existence of the object (class) //The relationship between doctors and patients is a great example of an association. The doctor clearly has a //relationship with his patients, but conceptually it’s not a part/whole (object composition) relationship. A //doctor can see many patients in a day, and a patient can see many doctors (perhaps they want a second opinion, //or they are visiting different types of doctors). Neither of the object’s lifespans are tied to the other. //We can say that association models as “uses-a” relationship. The doctor “uses” the patient (to earn income). //The patient uses the doctor (for whatever health purposes they need). //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // Composition ==> part-of // Aggregation ==> has-a // Association ==> uses-a //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ //Because associations are a broad type of relationship, they can be implemented in //many different ways. However, most often, associations are implemented using pointers, //where the object points at the associated object. //In this example, we’ll implement a bi-directional Doctor/Patient relationship, since it //makes sense for the Doctors to know who their Patients are, and vice-versa. // Since Doctor and Patient have a circular dependency, we're going to forward declare Patient class Patient; class Doctor { private: std::string m_name{}; std::vector<std::reference_wrapper<const Patient>> m_patient{}; public: Doctor(const std::string& name) : m_name{ name } { } void addPatient(Patient& patient); // We'll implement this function below Patient since we need Patient to be defined at that point friend std::ostream& operator<<(std::ostream& out, const Doctor& doctor); const std::string& getName() const { return m_name; } }; class Patient { private: std::string m_name{}; std::vector<std::reference_wrapper<const Doctor>> m_doctor{}; // so that we can use it here // We're going to make addDoctor private because we don't want the public to use it. // They should use Doctor::addPatient() instead, which is publicly exposed void addDoctor(const Doctor& doctor) { m_doctor.push_back(doctor); } public: Patient(const std::string& name) : m_name{ name } { } // We'll implement this function below Doctor since we need Doctor to be defined at that point friend std::ostream& operator<<(std::ostream& out, const Patient& patient); const std::string& getName() const { return m_name; } // We'll friend Doctor::addPatient() so it can access the private function Patient::addDoctor() friend void Doctor::addPatient(Patient& patient); }; void Doctor::addPatient(Patient& patient) { // Our doctor will add this patient m_patient.push_back(patient); // and the patient will also add this doctor patient.addDoctor(*this); } std::ostream& operator<<(std::ostream& out, const Doctor& doctor) { if (doctor.m_patient.empty()) { out << doctor.m_name << " has no patients right now"; return out; } out << doctor.m_name << " is seeing patients: "; for (const auto& patient : doctor.m_patient) out << patient.get().getName() << ' '; return out; } std::ostream& operator<<(std::ostream& out, const Patient& patient) { if (patient.m_doctor.empty()) { out << patient.getName() << " has no doctors right now"; return out; } out << patient.m_name << " is seeing doctors: "; for (const auto& doctor : patient.m_doctor) out << doctor.get().getName() << ' '; return out; } //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ //In general, you should avoid bidirectional associations if a unidirectional one will do, as they add complexity //and tend to be harder to write without making errors. //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ //****************************************************************************************************************** //************************************* Reflexive association **************************************************** //****************************************************************************************************************** //Sometimes objects may have a relationship with other objects of the same type. This is called a reflexive //association. A good example of a reflexive association is the relationship between a university course and //its prerequisites (which are also university courses). //****************************************************************************************************************** //Consider the simplified case where a Course can only have one prerequisite. We can do something like this: class Course { private: std::string m_name; const Course* m_prerequisite; public: Course(const std::string& name, const Course* prerequisite = nullptr): m_name{ name }, m_prerequisite{ prerequisite } { } void printPrerequisites() const { if (m_prerequisite) { std::cout << m_name << " has a prerequisite of " << m_prerequisite->m_name << std::endl; } else { std::cout << m_name << " has no prerequisite" << std::endl; } } }; //This can lead to a chain of associations (a course has a prerequisite, which has a prerequisite, etc…) //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ //Associations can be indirect //In all of the previous cases, we’ve used either pointers or references to directly link objects together. //However, in an association, this is not strictly required. Any kind of data that allows you to link two //objects together suffices. In the following example, we show how a Driver class can have a unidirectional //association with a Car without actually including a Car pointer or reference member: class Car { private: std::string m_name; int m_id; public: Car(const std::string& name, int id) : m_name{ name }, m_id{ id } { } const std::string& getName() const { return m_name; } int getId() const { return m_id; } }; // Our CarLot is essentially just a static array of Cars and a lookup function to retrieve them. // Because it's static, we don't need to allocate an object of type CarLot to use it class CarLot { private: static Car s_carLot[4]; public: CarLot() = delete; // Ensure we don't try to create a CarLot static Car* getCar(int id) { for (int count{ 0 }; count < 4; ++count) { if (s_carLot[count].getId() == id) { return &(s_carLot[count]); } } return nullptr; } }; Car CarLot::s_carLot[4]{ { "Prius", 4 }, { "Corolla", 17 }, { "Accord", 84 }, { "Matrix", 62 } }; class Driver { private: std::string m_name; int m_carId; // we're associated with the Car by ID rather than pointer public: Driver(const std::string& name, int carId) : m_name{ name }, m_carId{ carId } { } const std::string& getName() const { return m_name; } int getCarId() const { return m_carId; } }; int main() { // Create a Patient outside the scope of the Doctor Patient dave{ "Dave" }; Patient frank{ "Frank" }; Patient betsy{ "Betsy" }; Patient jane{ "Jane" }; Patient john{ "John" }; Patient joan{ "Joan" }; Patient sally{ "Sally" }; Patient raj{ "Raj" }; Doctor james{ "James" }; Doctor scott{ "Scott" }; Doctor karim{ "Karim" }; Doctor akram{ "Akram" }; Doctor collete{ "Collete" }; james.addPatient(dave); scott.addPatient(dave); scott.addPatient(betsy); karim.addPatient(jane); karim.addPatient(betsy); akram.addPatient(john); akram.addPatient(joan); collete.addPatient(joan); collete.addPatient(sally); collete.addPatient(raj); //doctors std::cout << "==========================================================" << '\n'; std::cout << "======================== Doctors =========================" << '\n'; std::cout << "==========================================================" << '\n'; std::cout << james << '\n'; std::cout << scott << '\n'; std::cout << karim << '\n'; std::cout << akram << '\n'; std::cout << collete << '\n'; //patients std::cout << "==========================================================" << '\n'; std::cout << "======================== Patients ========================" << '\n'; std::cout << "==========================================================" << '\n'; std::cout << dave << '\n'; std::cout << frank << '\n'; std::cout << betsy << '\n'; std::cout << jane << '\n'; std::cout << john << '\n'; std::cout << joan << '\n'; std::cout << sally << '\n'; std::cout << raj << '\n'; std::cout << "==========================================================" << '\n'; std::cout << "==========================================================" << '\n'; //******************************************************************************** Course computerArch { "Computer Architecture" }; Course advancedComputerArch{ "Advanced Computer Architecture" , &computerArch }; computerArch.printPrerequisites(); advancedComputerArch.printPrerequisites(); //******************************************************************************** Driver d{ "Franz", 17 }; // Franz is driving the car with ID 17 Car* car{ CarLot::getCar(d.getCarId()) }; // Get that car from the car lot if (car) std::cout << d.getName() << " is driving a " << car->getName() << '\n'; else std::cout << d.getName() << " couldn't find his car\n"; return 0; }
34.757862
116
0.55632
Mobink980
1bff06ba9de6103e50970d6f75693784c19cd27f
3,773
cpp
C++
toolboxes/operators/cpu/hoWaveletOperator.cpp
roopchansinghv/gadgetron
fb6c56b643911152c27834a754a7b6ee2dd912da
[ "MIT" ]
1
2022-02-22T21:06:36.000Z
2022-02-22T21:06:36.000Z
toolboxes/operators/cpu/hoWaveletOperator.cpp
apd47/gadgetron
073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2
[ "MIT" ]
null
null
null
toolboxes/operators/cpu/hoWaveletOperator.cpp
apd47/gadgetron
073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2
[ "MIT" ]
null
null
null
#include "hoWaveletOperator.h" namespace Gadgetron { template <typename T> hoWaveletOperator<T>::hoWaveletOperator(std::vector<size_t> *dims) : input_in_kspace_(false), no_null_space_(true), num_of_wav_levels_(1), with_approx_coeff_(false), proximity_across_cha_(false), BaseClass(dims) { p_active_wav_ = &harr_wav_; //gt_timer1_.set_timing_in_destruction(false); //gt_timer2_.set_timing_in_destruction(false); //gt_timer3_.set_timing_in_destruction(false); } template <typename T> hoWaveletOperator<T>::~hoWaveletOperator() { } template <typename T> void hoWaveletOperator<T>::select_wavelet(const std::string& wav_name) { if (wav_name == "db2" || wav_name == "db3" || wav_name == "db4" || wav_name == "db5") { redundant_wav_.compute_wavelet_filter(wav_name); p_active_wav_ = &redundant_wav_; } else { p_active_wav_ = &harr_wav_; } } template <typename T> void hoWaveletOperator<T>::restore_acquired_kspace(const ARRAY_TYPE& acquired, ARRAY_TYPE& y) { try { GADGET_CHECK_THROW(acquired.get_number_of_elements() == y.get_number_of_elements()); size_t N = acquired.get_number_of_elements(); const T* pA = acquired.get_data_ptr(); T* pY = y.get_data_ptr(); int n(0); #pragma omp parallel for default(none) private(n) shared(N, pA, pY) for (n = 0; n<(int)N; n++) { if (std::abs(pA[n]) > 0) { pY[n] = pA[n]; } } } catch (...) { GADGET_THROW("Errors happened in hoWaveletOperator<T>::restore_acquired_kspace(...) ... "); } } template <typename T> void hoWaveletOperator<T>::restore_acquired_kspace(ARRAY_TYPE& y) { this->restore_acquired_kspace(acquired_points_, y); } template <typename T> void hoWaveletOperator<T>::set_acquired_points(ARRAY_TYPE& kspace) { try { std::vector<size_t> dim; kspace.get_dimensions(dim); acquired_points_.create(dim, kspace.begin()); acquired_points_indicator_.create(kspace.dimensions()); Gadgetron::clear(acquired_points_indicator_); unacquired_points_indicator_.create(kspace.dimensions()); Gadgetron::clear(unacquired_points_indicator_); size_t N = kspace.get_number_of_elements(); long long ii(0); #pragma omp parallel for default(shared) private(ii) shared(N, kspace) for (ii = 0; ii<(long long)N; ii++) { if (std::abs(kspace(ii)) < DBL_EPSILON) { unacquired_points_indicator_(ii) = T(1.0); } else { acquired_points_indicator_(ii) = T(1.0); } } // allocate the helper memory kspace_.create(kspace.dimensions()); complexIm_.create(kspace.dimensions()); } catch (...) { GADGET_THROW("Errors in hoWaveletOperator<T>::set_acquired_points(...) ... "); } } // ------------------------------------------------------------ // Instantiation // ------------------------------------------------------------ template class EXPORTCPUOPERATOR hoWaveletOperator< float >; template class EXPORTCPUOPERATOR hoWaveletOperator< double >; template class EXPORTCPUOPERATOR hoWaveletOperator< std::complex<float> >; template class EXPORTCPUOPERATOR hoWaveletOperator< std::complex<double> >; }
30.92623
215
0.559237
roopchansinghv
1bffb4ca3421346685f6d2dce8fd3c74ace3a015
3,090
cpp
C++
scrimmage/plugins/autonomy/Straight/Straight.cpp
ddfan/swarm_evolve
cd2d972c021e9af5946673363fbfd39cff18f13f
[ "MIT" ]
10
2019-04-29T03:01:19.000Z
2022-03-22T03:11:30.000Z
scrimmage/plugins/autonomy/Straight/Straight.cpp
lyers179/swarm_evolve
cd2d972c021e9af5946673363fbfd39cff18f13f
[ "MIT" ]
3
2018-10-29T02:14:10.000Z
2020-11-23T02:36:14.000Z
scrimmage/plugins/autonomy/Straight/Straight.cpp
lyers179/swarm_evolve
cd2d972c021e9af5946673363fbfd39cff18f13f
[ "MIT" ]
8
2018-10-29T02:07:56.000Z
2022-01-04T06:37:53.000Z
/// --------------------------------------------------------------------------- /// @section LICENSE /// /// Copyright (c) 2016 Georgia Tech Research Institute (GTRI) /// All Rights Reserved /// /// 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. /// --------------------------------------------------------------------------- /// @file filename.ext /// @author Kevin DeMarco <kevin.demarco@gtri.gatech.edu> /// @author Eric Squires <eric.squires@gtri.gatech.edu> /// @version 1.0 /// --------------------------------------------------------------------------- /// @brief A brief description. /// /// @section DESCRIPTION /// A long description. /// --------------------------------------------------------------------------- #include <scrimmage/common/Utilities.h> #include <scrimmage/plugin_manager/RegisterPlugin.h> #include <scrimmage/math/State.h> #include <scrimmage/parse/ParseUtils.h> #include "Straight.h" #include <iostream> using std::cout; using std::endl; REGISTER_PLUGIN(scrimmage::Autonomy, Straight, Straight_plugin) Straight::Straight() { } void Straight::init(std::map<std::string,std::string> &params) { speed_ = scrimmage::get("speed", params, 0.0); desired_state_->vel() = speed_*Eigen::Vector3d::UnitX(); desired_state_->quat().set(0,0,state_->quat().yaw()); desired_state_->pos() = (state_->pos()(2))*Eigen::Vector3d::UnitZ(); // Project goal in front... Eigen::Vector3d rel_pos = Eigen::Vector3d::UnitX()*2000; Eigen::Vector3d unit_vector = rel_pos.normalized(); unit_vector = state_->quat().rotate(unit_vector); goal_ = state_->pos() + unit_vector * rel_pos.norm(); } bool Straight::step_autonomy(double t, double dt) { Eigen::Vector3d diff = goal_ - state_->pos(); Eigen::Vector3d v = speed_ * diff.normalized(); /////////////////////////////////////////////////////////////////////////// // Convert desired velocity to desired speed, heading, and pitch controls /////////////////////////////////////////////////////////////////////////// desired_state_->vel()(0) = v.norm(); // Desired heading double heading = scrimmage::Angles::angle_2pi(atan2(v(1), v(0))); // Desired pitch Eigen::Vector2d xy(v(0), v(1)); double pitch = scrimmage::Angles::angle_2pi(atan2(v(2), xy.norm())); // Set Desired Altitude to goal's z-position desired_state_->pos()(2) = goal_(2); // Set the desired pitch and heading desired_state_->quat().set(0, pitch, heading); return true; }
36.352941
79
0.585761
ddfan
4005555dc194543c8ad6dbb0ee639e958efc922c
13,064
cpp
C++
GROMACS/nonbonded_benchmark/gromacs_source_code/src/programs/view/dialogs.cpp
berkhess/bioexcel-exascale-co-design-benchmarks
c32f811d41a93fb69e49b3e7374f6028e37970d2
[ "MIT" ]
1
2020-04-20T04:33:11.000Z
2020-04-20T04:33:11.000Z
GROMACS/nonbonded_benchmark/gromacs_source_code/src/programs/view/dialogs.cpp
berkhess/bioexcel-exascale-co-design-benchmarks
c32f811d41a93fb69e49b3e7374f6028e37970d2
[ "MIT" ]
8
2019-07-10T15:18:21.000Z
2019-07-31T13:38:09.000Z
GROMACS/nonbonded_benchmark/gromacs_source_code/src/programs/view/dialogs.cpp
berkhess/bioexcel-exascale-co-design-benchmarks
c32f811d41a93fb69e49b3e7374f6028e37970d2
[ "MIT" ]
3
2019-07-10T10:50:25.000Z
2020-12-08T13:42:52.000Z
/* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2013, The GROMACS development team. * Copyright (c) 2013,2014,2015,2016,2017, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * GROMACS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ #include "gmxpre.h" #include "dialogs.h" #include "config.h" #include <cstdio> #include <cstdlib> #include <cstring> #ifdef HAVE_UNISTD_H #include <unistd.h> // for fork() #endif #include "gromacs/mdtypes/md_enums.h" #include "gromacs/utility/arraysize.h" #include "gromacs/utility/cstringutil.h" #include "gromacs/utility/dir_separator.h" #include "gromacs/utility/fatalerror.h" #include "gromacs/utility/futil.h" #include "gromacs/utility/smalloc.h" #include "manager.h" #include "nmol.h" #include "x11.h" #include "xdlghi.h" #include "xmb.h" #define MBFLAGS /* MB_APPLMODAL | */ MB_DONTSHOW void write_gmx(t_x11 *x11, t_gmx *gmx, int mess) { XEvent letter; letter.type = ClientMessage; letter.xclient.display = x11->disp; letter.xclient.window = gmx->wd->self; letter.xclient.message_type = 0; letter.xclient.format = 32; letter.xclient.data.l[0] = mess; letter.xclient.data.l[1] = Button1; XSendEvent(x11->disp, letter.xclient.window, True, 0, &letter); } static void shell_comm(const char *title, const char *script, int nsleep) { FILE *tfil; char command[STRLEN]; char tmp[32]; std::strcpy(tmp, "dialogXXXXXX"); tfil = gmx_fopen_temporary(tmp); fprintf(tfil, "%s\n", script); fprintf(tfil, "sleep %d\n", nsleep); gmx_ffclose(tfil); std::sprintf(command, "xterm -title %s -e sh %s", title, tmp); #ifdef DEBUG std::fprintf(stderr, "command: %s\n", command); #endif if (0 != std::system(command)) { gmx_fatal(FARGS, "Failed to execute command: %s", command); } #ifdef DEBUG unlink(tmp) #endif } void show_mb(t_gmx *gmx, int mb) { if (mb >= 0 && mb < emNR) { gmx->which_mb = mb; ShowDlg(gmx->mboxes[mb]); } } static void hide_mb(t_gmx *gmx) { if (gmx->which_mb >= 0 && gmx->which_mb < emNR) { HideDlg(gmx->mboxes[gmx->which_mb]); gmx->which_mb = -1; } } static void MBCallback(t_x11 * /*x11*/, int dlg_mess, int /*item_id*/, char * /*set*/, void *data) { t_gmx *gmx; gmx = static_cast<t_gmx *>(data); if (dlg_mess == DLG_EXIT) { hide_mb(gmx); } } static t_dlg *about_mb(t_x11 *x11, t_gmx *gmx) { const char *lines[] = { " G R O M A C S", " Machine for Simulating Chemistry", " Copyright (c) 1992-2013", " Berk Hess, David van der Spoel, Erik Lindahl", " and many collaborators!" }; return MessageBox(x11, gmx->wd->self, gmx->wd->text, asize(lines), lines, MB_OK | MB_ICONGMX | MBFLAGS, MBCallback, gmx); } static void QuitCB(t_x11 *x11, int dlg_mess, int /*item_id*/, char *set, void *data) { t_gmx *gmx; gmx = static_cast<t_gmx *>(data); hide_mb(gmx); if (dlg_mess == DLG_EXIT) { if (gmx_strcasecmp("yes", set) == 0) { write_gmx(x11, gmx, IDTERM); } } } static t_dlg *quit_mb(t_x11 *x11, t_gmx *gmx) { const char *lines[] = { " Do you really want to Quit ?" }; return MessageBox(x11, gmx->wd->self, gmx->wd->text, asize(lines), lines, MB_YESNO | MB_ICONSTOP | MBFLAGS, QuitCB, gmx); } static t_dlg *help_mb(t_x11 *x11, t_gmx *gmx) { const char *lines[] = { " Help will soon be added" }; return MessageBox(x11, gmx->wd->self, gmx->wd->text, asize(lines), lines, MB_OK | MB_ICONINFORMATION | MBFLAGS, MBCallback, gmx); } static t_dlg *ni_mb(t_x11 *x11, t_gmx *gmx) { const char *lines[] = { " This feature has not been", " implemented yet." }; return MessageBox(x11, gmx->wd->self, gmx->wd->text, asize(lines), lines, MB_OK | MB_ICONEXCLAMATION | MBFLAGS, MBCallback, gmx); } enum { eExE, eExGrom, eExPdb, eExConf, eExNR }; static void ExportCB(t_x11 *x11, int dlg_mess, int item_id, char *set, void *data) { bool bOk; t_gmx *gmx; t_dlg *dlg; gmx = static_cast<t_gmx *>(data); dlg = gmx->dlgs[edExport]; switch (dlg_mess) { case DLG_SET: switch (item_id) { case eExGrom: gmx->ExpMode = eExpGromos; break; case eExPdb: gmx->ExpMode = eExpPDB; break; default: break; } #ifdef DEBUG std::fprintf(stderr, "exportcb: item_id=%d\n", item_id); #endif break; case DLG_EXIT: if ((bOk = gmx_strcasecmp("ok", set)) == 0) { std::strcpy(gmx->confout, EditText(dlg, eExConf)); } HideDlg(dlg); if (bOk) { write_gmx(x11, gmx, IDDOEXPORT); } break; } } enum { eg0, egTOPOL, egCONFIN, egPARAM, eg1, eg1PROC, eg32PROC }; enum bond_set { ebShowH = 11, ebDPlus, ebRMPBC, ebCue, ebSkip, ebWait }; static void BondsCB(t_x11 *x11, int dlg_mess, int item_id, char *set, void *data) { static int ebond = -1; static int ebox = -1; bool bOk, bBond = false; int nskip, nwait; t_gmx *gmx; char *endptr; gmx = static_cast<t_gmx *>(data); if (ebond == -1) { ebond = gmx->man->molw->bond_type; ebox = gmx->man->molw->boxtype; } switch (dlg_mess) { case DLG_SET: if (item_id <= eBNR) { ebond = item_id-1; bBond = false; } else if (item_id <= eBNR+esbNR+1) { ebox = item_id-eBNR-2; bBond = true; } else { #define DO_NOT(b) (b) = (!(b)) switch (item_id) { case ebShowH: toggle_hydrogen(x11, gmx->man->molw); break; case ebDPlus: DO_NOT(gmx->man->bPlus); #ifdef DEBUG std::fprintf(stderr, "gmx->man->bPlus=%s\n", gmx->man->bPlus ? "true" : "false"); #endif break; case ebRMPBC: toggle_pbc(gmx->man); break; case ebCue: DO_NOT(gmx->man->bSort); #ifdef DEBUG std::fprintf(stderr, "gmx->man->bSort=%s\n", gmx->man->bSort ? "true" : "false"); #endif break; case ebSkip: nskip = std::strtol(set, &endptr, 10); if (endptr != set) { #ifdef DEBUG std::fprintf(stderr, "nskip: %d frames\n", nskip); #endif if (nskip >= 0) { gmx->man->nSkip = nskip; } } break; case ebWait: nwait = std::strtol(set, &endptr, 10); if (endptr != set) { #ifdef DEBUG std::fprintf(stderr, "wait: %d ms\n", nwait); #endif if (nwait >= 0) { gmx->man->nWait = nwait; } } default: #ifdef DEBUG std::fprintf(stderr, "item_id: %d, set: %s\n", item_id, set); #endif break; } } break; case DLG_EXIT: bOk = (gmx_strcasecmp("ok", set) == 0); HideDlg(gmx->dlgs[edBonds]); if (bOk) { if (bBond) { switch (ebond) { case eBThin: write_gmx(x11, gmx, IDTHIN); break; case eBFat: write_gmx(x11, gmx, IDFAT); break; case eBVeryFat: write_gmx(x11, gmx, IDVERYFAT); break; case eBSpheres: write_gmx(x11, gmx, IDBALLS); break; default: gmx_fatal(FARGS, "Invalid bond type %d at %s, %d", ebond, __FILE__, __LINE__); } } else { switch (ebox) { case esbNone: write_gmx(x11, gmx, IDNOBOX); break; case esbRect: write_gmx(x11, gmx, IDRECTBOX); break; case esbTri: write_gmx(x11, gmx, IDTRIBOX); break; case esbTrunc: write_gmx(x11, gmx, IDTOBOX); break; default: gmx_fatal(FARGS, "Invalid box type %d at %s, %d", ebox, __FILE__, __LINE__); } } } break; } } enum { esFUNCT = 1, esBSHOW, esINFIL, esINDEXFIL, esLSQ, esSHOW, esPLOTFIL }; typedef t_dlg *t_mmb (t_x11 *x11, t_gmx *gmx); typedef struct { const char *dlgfile; DlgCallback *cb; } t_dlginit; void init_dlgs(t_x11 *x11, t_gmx *gmx) { static t_dlginit di[] = { { "export.dlg", ExportCB }, { "bonds.dlg", BondsCB } }; static t_mmb *mi[emNR] = { quit_mb, help_mb, about_mb, ni_mb }; unsigned int i; snew(gmx->dlgs, edNR); for (i = 0; (i < asize(di)); i++) { gmx->dlgs[i] = ReadDlg(x11, gmx->wd->self, di[i].dlgfile, di[i].dlgfile, 0, 0, true, false, di[i].cb, gmx); } gmx->dlgs[edFilter] = select_filter(x11, gmx); snew(gmx->mboxes, emNR); for (i = 0; (i < emNR); i++) { gmx->mboxes[i] = mi[i](x11, gmx); } gmx->which_mb = -1; } void done_dlgs(t_gmx *gmx) { int i; for (i = 0; (i < edNR); i++) { FreeDlg(gmx->dlgs[i]); } for (i = 0; (i < emNR); i++) { FreeDlg(gmx->mboxes[i]); } } void edit_file(const char *fn) { if (fork() == 0) { char script[256]; std::sprintf(script, "vi %s", fn); shell_comm(fn, script, 0); std::exit(0); } }
28.155172
85
0.481705
berkhess
4005dae3af059be1fc2fcef53024776fd0e2429a
6,436
cpp
C++
src/engine/toppane.cpp
FreeAllegiance/AllegianceDX7
3955756dffea8e7e31d3a55fcf6184232b792195
[ "MIT" ]
76
2015-08-18T19:18:40.000Z
2022-01-08T12:47:22.000Z
src/engine/toppane.cpp
StudentAlleg/Allegiance
e91660a471eb4e57e9cea4c743ad43a82f8c7b18
[ "MIT" ]
37
2015-08-14T22:44:12.000Z
2020-01-21T01:03:06.000Z
src/engine/toppane.cpp
StudentAlleg/Allegiance
e91660a471eb4e57e9cea4c743ad43a82f8c7b18
[ "MIT" ]
42
2015-08-13T23:31:35.000Z
2022-03-17T02:20:26.000Z
#include "toppane.h" #include "engine.h" #include "enginep.h" #include "surface.h" ///////////////////////////////////////////////////////////////////////////// // // TopPane // ///////////////////////////////////////////////////////////////////////////// class TopPaneSurfaceSite : public SurfaceSite { private: TopPane* m_ptopPane; public: TopPaneSurfaceSite(TopPane* ptopPane) : m_ptopPane(ptopPane) { } void UpdateSurface(Surface* psurface) { m_ptopPane->RepaintSurface(); } }; ///////////////////////////////////////////////////////////////////////////// // // TopPane // ///////////////////////////////////////////////////////////////////////////// TopPane::TopPane(Engine* pengine, bool bColorKey, TopPaneSite* psite, Pane* pchild) : Pane(pchild), m_pengine(pengine), // m_psurface(pengine->CreateSurface(WinPoint(1, 1), stype, new TopPaneSurfaceSite(this))), m_psurface(NULL), m_psite(psite), m_bColorKey(bColorKey), m_bNeedLayout(true) { //Fix memory leak -Imago 8/2/09 SetSize(WinPoint(0, 0)); } void TopPane::RepaintSurface() { m_bNeedPaint = true; m_bPaintAll = true; } void TopPane::NeedLayout() { if (!m_bNeedLayout) { m_bNeedLayout = true; m_psite->SizeChanged(); } } void TopPane::NeedPaintInternal() { if (!m_bNeedPaint) { m_bNeedPaint = true; m_psite->SurfaceChanged(); } } void TopPane::Paint(Surface* psurface) { // psurface->FillSurface(Color(0.8f, 0.5f, 1.0f)); } void TopPane::Evaluate() { if (m_bNeedLayout) { m_bNeedLayout = false; WinPoint sizeOld = GetSize(); UpdateLayout(); WinPoint sizeNew = GetSize(); // This creates the top level surface. Create a new render target for now. if ( ( sizeNew != sizeOld ) && ( sizeNew != WinPoint(0,0) ) ) { m_bNeedPaint = true; m_bPaintAll = true; /* if( sizeNew == CD3DDevice9::GetCurrentResolution() ) { m_psurface = m_pengine->CreateDummySurface( sizeNew, new TopPaneSurfaceSite( this ) ); } else*/ { m_psurface = m_pengine->CreateRenderTargetSurface( sizeNew, new TopPaneSurfaceSite( this ) ); } } } } void TopPane::UpdateLayout() { DefaultUpdateLayout(); } bool g_bPaintAll = false; bool g_bUpdateOffset = false; void TopPane::UpdateBits() { /* ORIGINAL ALLEGIANCE VERSION. ZEnter("TopPane::UpdateBits()"); if (m_bNeedPaint) { ZTrace("m_bNeedPaint == true"); if (CalcPaint()) { m_bNeedPaint = true; m_bPaintAll = true; } ZTrace("after CalcPaint() m_bNeedPaint ==" + ZString(m_bNeedPaint)); ZTrace("after CalcPaint() m_bPaintAll ==" + ZString(m_bPaintAll )); m_bPaintAll |= g_bPaintAll; InternalPaint(m_psurface); m_bNeedPaint = false; } ZExit("TopPane::UpdateBits()");*/ ZEnter("TopPane::UpdateBits()"); { HRESULT hr; bool bRenderTargetRequired; ZAssert(m_psurface != NULL); PrivateSurface* pprivateSurface; CastTo(pprivateSurface, m_psurface); bRenderTargetRequired = pprivateSurface->GetSurfaceType().Test(SurfaceTypeRenderTarget() ) == true; if( bRenderTargetRequired == true ) { TEXHANDLE hTexture = pprivateSurface->GetTexHandle( ); ZAssert( hTexture != INVALID_TEX_HANDLE ); hr = CVRAMManager::Get()->PushRenderTarget( hTexture ); } ZTrace("m_bNeedPaint == true"); CalcPaint(); m_bNeedPaint = true; m_bPaintAll = true; ZTrace("after CalcPaint() m_bPaintAll ==" + ZString(m_bPaintAll )); WinPoint offset( 0, 0 ); // Call InternalPaint() with the child offset and parent size as params and create initial clipping rect. WinRect rectClip( 0, 0, (int) m_psurface->GetSize().X(), (int) m_psurface->GetSize().Y() ); m_bPaintAll |= g_bPaintAll; InternalPaint( m_psurface ); m_bNeedPaint = false; if( bRenderTargetRequired == true ) { CVRAMManager::Get()->PopRenderTarget( ); } } ZExit("TopPane::UpdateBits()"); /* { ZTrace("m_bNeedPaint == true"); CalcPaint(); m_bNeedPaint = true; m_bPaintAll = true; ZTrace("after CalcPaint() m_bNeedPaint ==" + ZString(m_bNeedPaint)); ZTrace("after CalcPaint() m_bPaintAll ==" + ZString(m_bPaintAll )); m_bPaintAll |= g_bPaintAll; // localOffset.SetY( localOffset.Y() - (int)m_psurface->GetSize().Y() ); // localOffset += globalOffset; WinPoint offset( localOffset ); // Remove offset now. offset.SetY( offset.Y() - (int)m_psurface->GetSize().Y() ); // Call InternalPaint() with the child offset and parent size as params and create initial clipping rect. WinRect rectClip( offset.X(), offset.Y(), offset.X() + (int) m_psurface->GetSize().X(), offset.Y() + (int) m_psurface->GetSize().Y() ); // m_psurface is a dummy surface. Store the context. InternalPaint( m_psurface, offset, rectClip ); m_bNeedPaint = false; } ZExit("TopPane::UpdateBits()");*/ } const WinPoint& TopPane::GetSurfaceSize() { Evaluate(); return GetSize(); } Surface* TopPane::GetSurface() { Evaluate(); //when the size is zero, the surface is not initialized if (m_size.X() == 0 || m_size.Y() == 0) { return NULL; } UpdateBits(); return m_psurface; } Point TopPane::TransformLocalToImage(const WinPoint& point) { return m_psite->TransformLocalToImage( GetPanePoint( Point::Cast(point) ) ); } Point TopPane::GetPanePoint(const Point& point) { return Point( point.X(), (float)GetSize().Y() - 1.0f - point.Y() ); } void TopPane::MouseEnter(IInputProvider* pprovider, const Point& point) { // m_bInside = true; /* if( m_psurface->GetSurfaceType().Test( SurfaceTypeDummy() ) == false ) { OutputDebugString("MouseEnter\n"); }*/ } MouseResult TopPane::HitTest(IInputProvider* pprovider, const Point& point, bool bCaptured) { return Pane::HitTest(pprovider, GetPanePoint(point), bCaptured); } MouseResult TopPane::Button( IInputProvider* pprovider, const Point& point, int button, bool bCaptured, bool bInside, bool bDown ) { return Pane::Button(pprovider, GetPanePoint(point), button, bCaptured, bInside, bDown); }
23.837037
107
0.596178
FreeAllegiance
4006628102af648b6603c72aced9b105bfe7fd2a
1,468
cpp
C++
region_olympiads/Vinnytsia/2016/III/Remake/palway/palway_twodimensional.cpp
mstrechen/cp
ffac439840a71f70580a0ef197e47479e167a0eb
[ "MIT" ]
null
null
null
region_olympiads/Vinnytsia/2016/III/Remake/palway/palway_twodimensional.cpp
mstrechen/cp
ffac439840a71f70580a0ef197e47479e167a0eb
[ "MIT" ]
null
null
null
region_olympiads/Vinnytsia/2016/III/Remake/palway/palway_twodimensional.cpp
mstrechen/cp
ffac439840a71f70580a0ef197e47479e167a0eb
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; const int MAXN = 128; const int MOD = 101; char state1[MAXN*MAXN], state2[MAXN*MAXN]; int field[MAXN][MAXN]; int main() { cin.tie(0); ios::sync_with_stdio(false); int n; cin >> n; for(int i = 1; i<=n; i++) for(int j = 1; j<=n; j++) cin >> field[i][j]; char *curState = state1, *nextState = state2; if(field[1][1] == field[n][n]) nextState[1*MAXN + 1] = 1; for(int diag = 3; diag<n+2; diag++) { swap(curState, nextState); for(int x = 1; x<diag; x++) { int y = diag - x; for(int x_0 = min(diag-1, n+1-x); x_0>=1 && diag + y <= n+1 + x_0; x_0--) { int x0 = n+1 - x_0; int y0 = n+1 - (diag - x_0); if(field[x][y] == field[x0][y0]) nextState[x*MAXN + x_0] = (curState[(x )*MAXN + (x_0 )]+ curState[(x )*MAXN + (x_0-1)]+ curState[(x-1)*MAXN + (x_0 )]+ curState[(x-1)*MAXN + (x_0-1)])%MOD; else nextState[x*MAXN + x_0] = 0; } } } int ans = 0; for(int i = 1; i<=n; i++) ans+=nextState[i*MAXN + n + 1 - i]; cout << ans%MOD; return 0; }
23.301587
86
0.381471
mstrechen
40080cb4299d2abfbf73f362827597e3353b56cc
2,091
cpp
C++
src/entities/splatmap.cpp
h4k1m0u/video
4739f8b1b6c837c41fdb53fc7dea97a47b285d0b
[ "MIT" ]
5
2021-11-11T23:59:38.000Z
2022-03-24T02:10:40.000Z
src/entities/splatmap.cpp
h4k1m0u/video
4739f8b1b6c837c41fdb53fc7dea97a47b285d0b
[ "MIT" ]
null
null
null
src/entities/splatmap.cpp
h4k1m0u/video
4739f8b1b6c837c41fdb53fc7dea97a47b285d0b
[ "MIT" ]
1
2022-01-15T13:31:10.000Z
2022-01-15T13:31:10.000Z
#include <glm/gtc/matrix_transform.hpp> #include "entities/splatmap.hpp" #include "shader_exception.hpp" #include "geometries/terrain.hpp" Splatmap::Splatmap(): // terrain textures (used by same shader) need to be attached to different texture units m_texture_terrain_water(Image("assets/images/terrain/water.jpg"), GL_TEXTURE0), m_texture_terrain_grass(Image("assets/images/terrain/grass.jpg"), GL_TEXTURE1), m_texture_terrain_rock(Image("assets/images/terrain/rock.jpg"), GL_TEXTURE2), m_texture_terrain_splatmap(Image("assets/images/terrain/splatmap.png"), GL_TEXTURE3), m_program("assets/shaders/light_terrain.vert", "assets/shaders/light_terrain.frag"), m_image("assets/images/terrain/heightmap.png"), m_vbo(Terrain(m_image)), m_renderer(m_program, m_vbo, {{0, "position", 3, 8, 0}, {1, "normal", 3, 8, 3}, {2, "texture_coord", 2, 8, 6}}) { // vertex or fragment shaders failed to compile if (m_program.has_failed()) { throw ShaderException(); } } /* delegate drawing with OpenGL (buffers & shaders) to renderer */ void Splatmap::draw(const Uniforms& uniforms) { // draw terrain using triangle strips glm::vec3 color_light(1.0f, 1.0f, 1.0f); glm::vec3 position_light(10.0f, 6.0f, 6.0f); m_renderer.draw( { {"texture2d_water", m_texture_terrain_water}, {"texture2d_grass", m_texture_terrain_grass}, {"texture2d_rock", m_texture_terrain_rock}, {"texture2d_splatmap", m_texture_terrain_splatmap}, {"light.position", position_light}, {"light.ambiant", 0.2f * color_light}, {"light.diffuse", 0.5f * color_light}, {"light.specular", color_light}, }, GL_TRIANGLE_STRIP ); } /* delegate transform to renderer */ void Splatmap::set_transform(const Transformation& t) { m_renderer.set_transform(t); } /* Free textures, renderer (vao/vbo buffers), and shader program */ void Splatmap::free() { m_image.free(); m_texture_terrain_water.free(); m_texture_terrain_grass.free(); m_texture_terrain_rock.free(); m_texture_terrain_splatmap.free(); m_program.free(); m_renderer.free(); }
34.278689
113
0.72023
h4k1m0u
400cff47ff8ca3ddfdd70bada915ff074d5654eb
6,678
cpp
C++
logs/test/main.cpp
mingkaic/travis-test
84d45f7c7a079dfd66316d7c31969b43fb9e7c7f
[ "BSL-1.0", "MIT" ]
null
null
null
logs/test/main.cpp
mingkaic/travis-test
84d45f7c7a079dfd66316d7c31969b43fb9e7c7f
[ "BSL-1.0", "MIT" ]
8
2019-11-07T03:59:17.000Z
2022-02-19T19:42:47.000Z
logs/test/main.cpp
mingkaic/travis-test
84d45f7c7a079dfd66316d7c31969b43fb9e7c7f
[ "BSL-1.0", "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "logs/logs.hpp" const std::string log_level_ret = "103272"; struct TestLogger : public logs::iLogger { static std::string latest_warning_; static std::string latest_error_; static std::string latest_fatal_; static std::string latest_log_msg_; static std::string set_log_level_; std::string get_log_level (void) const override { return log_level_ret; } void set_log_level (const std::string& log_level) override { set_log_level_ = log_level; } bool supports_level (size_t msg_level) const override { return true; } bool supports_level (const std::string& msg_level) const override { return true; } void log (size_t msg_level, const std::string& msg, const logs::SrcLocT& location = logs::SrcLocT::current()) override { switch (msg_level) { case logs::WARN: warn(msg); break; case logs::ERROR: error(msg); break; case logs::FATAL: fatal(msg); break; default: std::stringstream ss; ss << msg_level << msg; latest_log_msg_ = ss.str(); } } void log (const std::string& msg_level, const std::string& msg, const logs::SrcLocT& location = logs::SrcLocT::current()) override { log(logs::enum_log(msg_level), msg); } void warn (const std::string& msg) const { latest_warning_ = msg; } void error (const std::string& msg) const { latest_error_ = msg; } void fatal (const std::string& msg) const { latest_fatal_ = msg; } }; std::string TestLogger::latest_warning_; std::string TestLogger::latest_error_; std::string TestLogger::latest_fatal_; std::string TestLogger::latest_log_msg_; std::string TestLogger::set_log_level_ = "0"; std::shared_ptr<TestLogger> tlogger = std::make_shared<TestLogger>(); int main (int argc, char** argv) { logs::set_logger(std::static_pointer_cast<logs::iLogger>(tlogger)); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } #ifndef DISABLE_LOGS_TEST struct LOGS : public ::testing::Test { protected: void TearDown (void) override { TestLogger::latest_warning_ = ""; TestLogger::latest_error_ = ""; TestLogger::latest_fatal_ = ""; TestLogger::set_log_level_ = "0"; } }; TEST_F(LOGS, Default) { logs::DefLogger log; EXPECT_STREQ("info", log.get_log_level().c_str()); log.set_log_level("debug"); EXPECT_STREQ("debug", log.get_log_level().c_str()); log.log(logs::INFO, "log info message"); log.log(logs::WARN, "log warn message"); log.log(logs::ERROR, "log error message"); try { log.log(logs::FATAL, "log fatal message"); FAIL() << "log.fatal failed to throw error"; } catch (std::runtime_error& e) { const char* msg = e.what(); EXPECT_STREQ("log fatal message", msg); } catch (...) { FAIL() << "expected to throw runtime_error"; } } TEST_F(LOGS, Trace) { logs::trace("tracing message"); const char* cmsg = TestLogger::latest_log_msg_.c_str(); auto expect = fmts::sprintf("%dtracing message", logs::TRACE); EXPECT_STREQ(expect.c_str(), cmsg); } TEST_F(LOGS, TraceFmt) { logs::tracef("tracing %.2f message %d with format %s", 4.15, 33, "applepie"); const char* cmsg = TestLogger::latest_log_msg_.c_str(); auto expect = fmts::sprintf( "%dtracing 4.15 message 33 with format applepie", logs::TRACE); EXPECT_STREQ(expect.c_str(), cmsg); } TEST_F(LOGS, Debug) { logs::debug("debugging message"); const char* cmsg = TestLogger::latest_log_msg_.c_str(); auto expect = fmts::sprintf("%ddebugging message", logs::DEBUG); EXPECT_STREQ(expect.c_str(), cmsg); } TEST_F(LOGS, DebugFmt) { logs::debugf("debugging %.3f message %d with format %s", 0.31, 7, "orange"); const char* cmsg = TestLogger::latest_log_msg_.c_str(); auto expect = fmts::sprintf( "%ddebugging 0.310 message 7 with format orange", logs::DEBUG); EXPECT_STREQ(expect.c_str(), cmsg); } TEST_F(LOGS, Info) { logs::info("infoing message"); const char* cmsg = TestLogger::latest_log_msg_.c_str(); auto expect = fmts::sprintf("%dinfoing message", logs::INFO); EXPECT_STREQ(expect.c_str(), cmsg); } TEST_F(LOGS, InfoFmt) { logs::infof("infoing %.4f message %d with format %s", 3.1415967, -1, "plum"); const char* cmsg = TestLogger::latest_log_msg_.c_str(); auto expect = fmts::sprintf( "%dinfoing 3.1416 message -1 with format plum", logs::INFO); EXPECT_STREQ(expect.c_str(), cmsg); } TEST_F(LOGS, Warn) { logs::warn("warning message"); const char* cmsg = TestLogger::latest_warning_.c_str(); EXPECT_STREQ("warning message", cmsg); } TEST_F(LOGS, WarnFmt) { logs::warnf("warning %.2f message %d with format %s", 4.15, 33, "applepie"); const char* cmsg = TestLogger::latest_warning_.c_str(); EXPECT_STREQ("warning 4.15 message 33 with format applepie", cmsg); } TEST_F(LOGS, Error) { logs::error("erroring message"); const char* emsg = TestLogger::latest_error_.c_str(); EXPECT_STREQ("erroring message", emsg); } TEST_F(LOGS, ErrorFmt) { logs::errorf("erroring %.3f message %d with format %s", 0.31, 7, "orange"); const char* emsg = TestLogger::latest_error_.c_str(); EXPECT_STREQ("erroring 0.310 message 7 with format orange", emsg); } TEST_F(LOGS, Fatal) { logs::fatal("fatal message"); const char* fmsg = TestLogger::latest_fatal_.c_str(); EXPECT_STREQ("fatal message", fmsg); } TEST_F(LOGS, FatalFmt) { logs::fatalf("fatal %.4f message %d with format %s", 3.1415967, -1, "plum"); const char* fmsg = TestLogger::latest_fatal_.c_str(); EXPECT_STREQ("fatal 3.1416 message -1 with format plum", fmsg); } TEST_F(LOGS, GlobalGetSet) { EXPECT_STREQ(log_level_ret.c_str(), logs::get_log_level().c_str()); logs::set_log_level("1231"); EXPECT_STREQ("1231", TestLogger::set_log_level_.c_str()); } TEST(DEFAULT, Logger) { logs::DefLogger logger; EXPECT_TRUE(logger.supports_level(logs::INFO)); EXPECT_TRUE(logger.supports_level("info")); logger.log(logs::INFO, "hello"); logger.log("warn", "world"); logger.log("error", "oh no"); try { logger.log(logs::FATAL, "death"); FAIL() << "not expecting fatal to succeed"; } catch (std::exception& e) { EXPECT_STREQ("death", e.what()); } } TEST(DEFAULT, Conversions) { EXPECT_EQ(logs::INFO, logs::enum_log("info")); EXPECT_EQ(logs::WARN, logs::enum_log("warn")); EXPECT_EQ(logs::ERROR, logs::enum_log("error")); EXPECT_EQ(logs::FATAL, logs::enum_log("fatal")); EXPECT_EQ(logs::NOT_SET, logs::enum_log("hello")); EXPECT_STREQ("info", logs::name_log(logs::INFO).c_str()); EXPECT_STREQ("warn", logs::name_log(logs::WARN).c_str()); EXPECT_STREQ("error", logs::name_log(logs::ERROR).c_str()); EXPECT_STREQ("fatal", logs::name_log(logs::FATAL).c_str()); EXPECT_STREQ("", logs::name_log(logs::NOT_SET).c_str()); } #endif // DISABLE_LOGS_TEST
22.186047
76
0.690925
mingkaic
400da1c8f4866d0d34f601c3de2a2f567e600191
498
hpp
C++
src/avif/Box.hpp
link-u/libavifparser
17984420ff8806a6a852306b839219605ccc1628
[ "MIT" ]
null
null
null
src/avif/Box.hpp
link-u/libavifparser
17984420ff8806a6a852306b839219605ccc1628
[ "MIT" ]
null
null
null
src/avif/Box.hpp
link-u/libavifparser
17984420ff8806a6a852306b839219605ccc1628
[ "MIT" ]
null
null
null
// // Created by psi on 2019/11/24. // #pragma once #include <optional> #include <string> namespace avif { struct Box { struct Header { uint32_t offset = {}; uint32_t size = {}; uint32_t type = {}; [[ nodiscard ]] uint32_t end() const { return this->offset + this->size; } }; public: Header hdr = {}; public: Box() = default; Box(Box&&) = default; Box(Box const&) = default; Box& operator=(Box&&) = default; Box& operator=(Box const&) = default; }; }
15.5625
42
0.582329
link-u
400f04332708cf1d422cb448d5c0930846c4b1d4
14,333
cpp
C++
src/widgets/XMRigWidget.cpp
Midar/feather
ac9693077c338527a4b31ca6b2d85514f8fe739a
[ "BSD-3-Clause" ]
null
null
null
src/widgets/XMRigWidget.cpp
Midar/feather
ac9693077c338527a4b31ca6b2d85514f8fe739a
[ "BSD-3-Clause" ]
null
null
null
src/widgets/XMRigWidget.cpp
Midar/feather
ac9693077c338527a4b31ca6b2d85514f8fe739a
[ "BSD-3-Clause" ]
null
null
null
// SPDX-License-Identifier: BSD-3-Clause // SPDX-FileCopyrightText: 2020-2022 The Monero Project #include "XMRigWidget.h" #include "ui_XMRigWidget.h" #include <QDesktopServices> #include <QFileDialog> #include <QInputDialog> #include <QMessageBox> #include <QScrollBar> #include <QStandardItemModel> #include <QTableWidget> #include "utils/Icons.h" XMRigWidget::XMRigWidget(QSharedPointer<AppContext> ctx, QWidget *parent) : QWidget(parent) , ui(new Ui::XMRigWidget) , m_ctx(std::move(ctx)) , m_XMRig(new XmRig(Config::defaultConfigDir().path())) , m_model(new QStandardItemModel(this)) , m_contextMenu(new QMenu(this)) { ui->setupUi(this); connect(m_XMRig, &XmRig::stateChanged, this, &XMRigWidget::onXMRigStateChanged); connect(m_XMRig, &XmRig::output, this, &XMRigWidget::onProcessOutput); connect(m_XMRig, &XmRig::error, this, &XMRigWidget::onProcessError); connect(m_XMRig, &XmRig::hashrate, this, &XMRigWidget::onHashrate); // [Downloads] tab ui->tableView->setModel(m_model); m_contextMenu->addAction(icons()->icon("network.png"), "Download file", this, &XMRigWidget::linkClicked); connect(ui->tableView, &QHeaderView::customContextMenuRequested, this, &XMRigWidget::showContextMenu); connect(ui->tableView, &QTableView::doubleClicked, this, &XMRigWidget::linkClicked); // [Settings] tab ui->poolFrame->show(); ui->soloFrame->hide(); // XMRig executable connect(ui->btn_browse, &QPushButton::clicked, this, &XMRigWidget::onBrowseClicked); ui->lineEdit_path->setText(config()->get(Config::xmrigPath).toString()); // Run as admin/root bool elevated = config()->get(Config::xmrigElevated).toBool(); if (elevated) { ui->radio_elevateYes->setChecked(true); } else { ui->radio_elevateNo->setChecked(true); } connect(ui->radio_elevateYes, &QRadioButton::toggled, this, &XMRigWidget::onXMRigElevationChanged); #if defined(Q_OS_WIN) ui->radio_elevateYes->setToolTip("Not supported on Windows, yet."); ui->radio_elevateYes->setEnabled(false); ui->radio_elevateNo->setChecked(true); #endif // CPU threads ui->threadSlider->setMinimum(1); ui->threadSlider->setMaximum(QThread::idealThreadCount()); int threads = config()->get(Config::xmrigThreads).toInt(); ui->threadSlider->setValue(threads); ui->label_threads->setText(QString("CPU threads: %1").arg(threads)); connect(ui->threadSlider, &QSlider::valueChanged, this, &XMRigWidget::onThreadsValueChanged); // Mining mode connect(ui->combo_miningMode, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &XMRigWidget::onMiningModeChanged); ui->combo_miningMode->setCurrentIndex(config()->get(Config::miningMode).toInt()); // Pool/node address this->updatePools(); connect(ui->combo_pools, &QComboBox::currentTextChanged, this, &XMRigWidget::onPoolChanged); connect(ui->btn_poolConfig, &QPushButton::clicked, [this]{ QStringList pools = config()->get(Config::pools).toStringList(); bool ok; QString poolStr = QInputDialog::getMultiLineText(this, "Pool addresses", "Set pool addresses (one per line):", pools.join("\n"), &ok); if (!ok) { return; } QStringList newPools = poolStr.split("\n"); newPools.removeAll(""); newPools.removeDuplicates(); config()->set(Config::pools, newPools); this->updatePools(); }); // Network settings connect(ui->check_tls, &QCheckBox::toggled, this, &XMRigWidget::onNetworkTLSToggled); connect(ui->relayTor, &QCheckBox::toggled, this, &XMRigWidget::onNetworkTorToggled); ui->check_tls->setChecked(config()->get(Config::xmrigNetworkTLS).toBool()); ui->relayTor->setChecked(config()->get(Config::xmrigNetworkTor).toBool()); // Receiving address auto username = m_ctx->wallet->getCacheAttribute("feather.xmrig_username"); if (!username.isEmpty()) { ui->lineEdit_address->setText(username); } connect(ui->lineEdit_address, &QLineEdit::textChanged, [=]() { m_ctx->wallet->setCacheAttribute("feather.xmrig_username", ui->lineEdit_address->text()); }); connect(ui->btn_fillPrimaryAddress, &QPushButton::clicked, this, &XMRigWidget::onUsePrimaryAddressClicked); // Password auto password = m_ctx->wallet->getCacheAttribute("feather.xmrig_password"); if (!password.isEmpty()) { ui->lineEdit_password->setText(password); } else { ui->lineEdit_password->setText("featherwallet"); m_ctx->wallet->setCacheAttribute("feather.xmrig_password", ui->lineEdit_password->text()); } connect(ui->lineEdit_password, &QLineEdit::textChanged, [=]() { m_ctx->wallet->setCacheAttribute("feather.xmrig_password", ui->lineEdit_password->text()); }); // [Status] tab connect(ui->btn_start, &QPushButton::clicked, this, &XMRigWidget::onStartClicked); connect(ui->btn_stop, &QPushButton::clicked, this, &XMRigWidget::onStopClicked); connect(ui->btn_clear, &QPushButton::clicked, this, &XMRigWidget::onClearClicked); ui->btn_stop->setEnabled(false); ui->check_autoscroll->setChecked(true); ui->label_status->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->label_status->hide(); this->printConsoleInfo(); } bool XMRigWidget::isMining() { return m_isMining; } void XMRigWidget::onWalletClosed() { this->onStopClicked(); } void XMRigWidget::onThreadsValueChanged(int threads) { config()->set(Config::xmrigThreads, threads); ui->label_threads->setText(QString("CPU threads: %1").arg(threads)); } void XMRigWidget::onPoolChanged(const QString &pool) { if (!pool.isEmpty()) { config()->set(Config::xmrigPool, pool); } } void XMRigWidget::onXMRigElevationChanged(bool elevated) { config()->set(Config::xmrigElevated, elevated); } void XMRigWidget::onBrowseClicked() { QString fileName = QFileDialog::getOpenFileName(this, "Path to XMRig executable", QDir::homePath()); if (fileName.isEmpty()) { return; } config()->set(Config::xmrigPath, fileName); ui->lineEdit_path->setText(fileName); } void XMRigWidget::onClearClicked() { ui->console->clear(); } void XMRigWidget::onUsePrimaryAddressClicked() { ui->lineEdit_address->setText(m_ctx->wallet->address(0, 0)); } void XMRigWidget::onStartClicked() { QString xmrigPath = config()->get(Config::xmrigPath).toString(); if (!this->checkXMRigPath()) { return; } QString address = [this](){ if (ui->combo_miningMode->currentIndex() == Config::MiningMode::Pool) { return config()->get(Config::xmrigPool).toString(); } else { return ui->lineEdit_solo->text().trimmed(); } }(); if (address.isEmpty()) { ui->console->appendPlainText("No pool or node address set. Please configure on the Settings tab."); return; } // username is receiving address usually auto username = m_ctx->wallet->getCacheAttribute("feather.xmrig_username"); auto password = m_ctx->wallet->getCacheAttribute("feather.xmrig_password"); if (username.isEmpty()) { ui->console->appendPlainText("Please specify a receiving address on the Settings screen."); return; } if (address.contains("cryptonote.social") && !username.contains(".")) { // cryptonote social requires <addr>.<username>, we'll just grab a few chars from primary addy username = QString("%1.%2").arg(username, m_ctx->wallet->address(0, 0).mid(0, 6)); } int threads = ui->threadSlider->value(); m_XMRig->start(xmrigPath, threads, address, username, password, ui->relayTor->isChecked(), ui->check_tls->isChecked(), ui->radio_elevateYes->isChecked()); } void XMRigWidget::onStopClicked() { m_XMRig->stop(); } void XMRigWidget::onProcessOutput(const QByteArray &data) { auto output = Utils::barrayToString(data); if(output.endsWith("\n")) output = output.trimmed(); ui->console->appendPlainText(output); if(ui->check_autoscroll->isChecked()) ui->console->verticalScrollBar()->setValue(ui->console->verticalScrollBar()->maximum()); } void XMRigWidget::onProcessError(const QString &msg) { ui->console->appendPlainText("\n" + msg); ui->btn_start->setEnabled(true); ui->btn_stop->setEnabled(false); this->setMiningStopped(); } void XMRigWidget::onHashrate(const QString &hashrate) { ui->label_status->show(); ui->label_status->setText(QString("Mining at %1").arg(hashrate)); } void XMRigWidget::onDownloads(const QJsonObject &data) { // For the downloads table we'll manually update the table // with items once, as opposed to creating a class in // src/models/. Saves effort; full-blown model // is unnecessary in this case. m_model->clear(); m_urls.clear(); auto version = data.value("version").toString(); ui->label_latest_version->setText(QString("Latest version: %1").arg(version)); QJsonObject assets = data.value("assets").toObject(); const auto _linux = assets.value("linux").toArray(); const auto macos = assets.value("macos").toArray(); const auto windows = assets.value("windows").toArray(); auto info = QSysInfo::productType(); QJsonArray *os_assets; if(info == "osx") { os_assets = const_cast<QJsonArray *>(&macos); } else if (info == "windows") { os_assets = const_cast<QJsonArray *>(&windows); } else { // assume linux os_assets = const_cast<QJsonArray *>(&_linux); } int i = 0; for(const auto &entry: *os_assets) { auto _obj = entry.toObject(); auto _name = _obj.value("name").toString(); auto _url = _obj.value("url").toString(); auto _created_at = _obj.value("created_at").toString(); m_urls.append(_url); auto download_count = _obj.value("download_count").toInt(); m_model->setItem(i, 0, Utils::qStandardItem(_name)); m_model->setItem(i, 1, Utils::qStandardItem(_created_at)); m_model->setItem(i, 2, Utils::qStandardItem(QString::number(download_count))); i++; } m_model->setHeaderData(0, Qt::Horizontal, tr("Filename"), Qt::DisplayRole); m_model->setHeaderData(1, Qt::Horizontal, tr("Date"), Qt::DisplayRole); m_model->setHeaderData(2, Qt::Horizontal, tr("Downloads"), Qt::DisplayRole); ui->tableView->verticalHeader()->setVisible(false); ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows); ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); ui->tableView->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); ui->tableView->setColumnWidth(2, 100); } void XMRigWidget::showContextMenu(const QPoint &pos) { QModelIndex index = ui->tableView->indexAt(pos); if (!index.isValid()) { return; } m_contextMenu->exec(ui->tableView->viewport()->mapToGlobal(pos)); } void XMRigWidget::updatePools() { QStringList pools = config()->get(Config::pools).toStringList(); if (pools.isEmpty()) { pools = m_defaultPools; config()->set(Config::pools, pools); } ui->combo_pools->clear(); ui->combo_pools->insertItems(0, pools); QString preferredPool = config()->get(Config::xmrigPool).toString(); if (pools.contains(preferredPool)) { ui->combo_pools->setCurrentIndex(pools.indexOf(preferredPool)); } else { preferredPool = pools.at(0); config()->set(Config::xmrigPool, preferredPool); } } void XMRigWidget::printConsoleInfo() { ui->console->appendPlainText(QString("Detected %1 CPU threads.").arg(QThread::idealThreadCount())); if (this->checkXMRigPath()) { QString path = config()->get(Config::xmrigPath).toString(); ui->console->appendPlainText(QString("XMRig path set to %1").arg(path)); } } void XMRigWidget::onMiningModeChanged(int mode) { config()->set(Config::miningMode, mode); if (mode == Config::MiningMode::Pool) { ui->poolFrame->show(); ui->soloFrame->hide(); ui->label_poolNodeAddress->setText("Pool address:"); ui->check_tls->setChecked(true); } else { // Solo mining ui->poolFrame->hide(); ui->soloFrame->show(); ui->label_poolNodeAddress->setText("Node address:"); ui->check_tls->setChecked(false); } } void XMRigWidget::onNetworkTLSToggled(bool checked) { config()->set(Config::xmrigNetworkTLS, checked); } void XMRigWidget::onNetworkTorToggled(bool checked) { config()->set(Config::xmrigNetworkTor, checked); } void XMRigWidget::onXMRigStateChanged(QProcess::ProcessState state) { if (state == QProcess::ProcessState::Starting) { ui->btn_start->setEnabled(false); ui->btn_stop->setEnabled(false); this->setMiningStarted(); } else if (state == QProcess::ProcessState::Running) { ui->btn_start->setEnabled(false); ui->btn_stop->setEnabled(true); this->setMiningStarted(); } else if (state == QProcess::ProcessState::NotRunning) { ui->btn_start->setEnabled(true); // todo ui->btn_stop->setEnabled(false); ui->label_status->hide(); this->setMiningStopped(); } } void XMRigWidget::setMiningStopped() { m_isMining = false; emit miningEnded(); } void XMRigWidget::setMiningStarted() { m_isMining = true; emit miningStarted(); } bool XMRigWidget::checkXMRigPath() { QString path = config()->get(Config::xmrigPath).toString(); if (path.isEmpty()) { ui->console->appendPlainText("No XMRig executable is set. Please configure on the Settings tab."); return false; } else if (!Utils::fileExists(path)) { ui->console->appendPlainText("Invalid path to XMRig executable detected. Please reconfigure on the Settings tab."); return false; } else { return true; } } void XMRigWidget::linkClicked() { QModelIndex index = ui->tableView->currentIndex(); auto download_link = m_urls.at(index.row()); Utils::externalLinkWarning(this, download_link); } QStandardItemModel *XMRigWidget::model() { return m_model; } XMRigWidget::~XMRigWidget() = default;
35.477723
142
0.669155
Midar
400f3ad1b8bbd7ff2e3e1015d72397aca32a6e11
8,490
cpp
C++
src/core/application.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
2
2019-06-22T23:29:44.000Z
2019-07-07T18:34:04.000Z
src/core/application.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
src/core/application.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
/** * @file application.cpp * @brief * @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org) * @date 2001-12-25 * @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved. * @details */ #include "o3d/core/precompiled.h" #include "o3d/core/application.h" #include "o3d/core/classfactory.h" #include "o3d/core/taskmanager.h" #include "o3d/core/display.h" #include "o3d/core/filemanager.h" #include "o3d/core/thread.h" #include "o3d/core/timer.h" #include "o3d/core/uuid.h" #include "o3d/core/date.h" #include "o3d/core/datetime.h" #include "o3d/core/math.h" #include "o3d/core/stringmap.h" #include "o3d/core/appwindow.h" #include "o3d/core/debug.h" #include "o3d/core/gl.h" #include <algorithm> using namespace o3d; String *Application::ms_appsName = nullptr; String *Application::ms_appsPath = nullptr; Application::T_AppWindowMap Application::ms_appWindowMap; _DISP Application::ms_display = NULL_DISP; Activity *Application::ms_activity = nullptr; void* Application::ms_app = nullptr; Int32 Application::ms_appState = 0; AppWindow* Application::ms_currAppWindow = nullptr; CommandLine *Application::ms_appsCommandLine = nullptr; Bool Application::ms_init = False; Bool Application::ms_displayInit = False; StringMap<BaseObject*> *ms_mappedObject = nullptr; Bool Application::ms_displayError = False; Activity::~Activity() { } // Objective-3D initialization void Application::init(AppSettings settings, Int32 argc, Char **argv, void *app) { if (ms_init) { return; } ms_appState = 0; ms_app = app; ms_mappedObject = new StringMap<BaseObject*>; // get the main thread id ThreadManager::init(); System::initTime(); Date::init(); DateTime::init(); Uuid::init(); // Get the application name and path getBaseNamePrivate(argc, argv); if (settings.clearLog) { Debug::instance()->getDefaultLog().clearLog(); } // Log start time DateTime current(True); O3D_MESSAGE(String("Starting of application on ") + current.buildString("%Y-%m-%d %H:%M:%S.%f")); // Initialize fast memory allocator MemoryManager::instance()->initFastAllocator( settings.sizeOfFastAlloc16, settings.sizeOfFastAlloc32, settings.sizeOfFastAlloc64); // Registration of the main thread to activate events EvtManager::instance()->registerThread(nullptr); #ifdef O3D_ANDROID // @todo ms_appsCommandLine = new CommandLine(""); #elif defined(O3D_WINDOWS) String commandLine(GetCommandLineW()); ms_appsCommandLine = new CommandLine(commandLine); #else ms_appsCommandLine = new CommandLine(argc, argv); #endif // Math initialization Math::init(); // only if display if (settings.useDisplay) { apiInitPrivate(); ms_displayInit = True; GL::init(); String typeString = "Undefined"; if (GL::getType() == GL::API_GL) { typeString = "GL3+"; } else if (GL::getType() == GL::API_GLES_3) { typeString = "GLES3+"; } O3D_MESSAGE(String("Choose {0} implementation with a {1} API").arg(GL::getImplementationName()).arg(typeString)); Display::instance(); } // Active the PostMessage EvtManager::instance()->enableAutoWakeUp(); ms_init = True; } // Objective-3D terminate void Application::quit() { deletePtr(ms_activity); if (!ms_init) { return; } // Log quit time DateTime current(True); O3D_MESSAGE(String("Terminating of application on ") + current.buildString("%Y-%m-%d at %H:%M:%S.%f")); ms_init = False; // Disable the PostMessage EvtManager::instance()->disableAutoWakeUp(); if (!ms_appWindowMap.empty()) { O3D_WARNING("Still always exists application windows"); } if (!ms_mappedObject->empty()) { O3D_WARNING("Still always exists mapped object"); } // terminate the task manager if running TaskManager::destroy(); // timer manager before thread TimerManager::destroy(); // wait all threads terminate ThreadManager::waitEndThreads(); // delete class factory ClassFactory::destroy(); // display manager Display::destroy(); // Specific quit if (ms_displayInit) { apiQuitPrivate(); GL::quit(); ms_displayInit = False; } // deletion of the main thread EvtManager::instance()->unRegisterThread(nullptr); // debug manager Debug::destroy(); // file manager FileManager::destroy(); // event manager EvtManager::destroy(); // math release Math::quit(); // date quit Date::quit(); DateTime::quit(); Uuid::quit(); // object mapping deletePtr(ms_mappedObject); // release memory manager allocators MemoryManager::instance()->releaseFastAllocator(); // common members deletePtr(ms_appsCommandLine); deletePtr(ms_appsName); deletePtr(ms_appsPath); ms_app = nullptr; } Bool Application::isInit() { return ms_init; } // Return the command line CommandLine* Application::getCommandLine() { return ms_appsCommandLine; } // Get the application name const String& Application::getAppName() { if (ms_appsName) { return *ms_appsName; } else { return String::getNull(); } } const String &Application::getAppPath() { if (ms_appsPath) { return *ms_appsPath; } else { return String::getNull(); } } void Application::addAppWindow(AppWindow *appWindow) { if (appWindow && appWindow->getHWND()) { if (ms_appWindowMap.find(appWindow->getHWND()) != ms_appWindowMap.end()) { O3D_ERROR(E_InvalidParameter("Cannot add an application window with a similar handle")); } ms_appWindowMap[appWindow->getHWND()] = appWindow; } else { O3D_ERROR(E_InvalidParameter("Cannot add an invalid application window")); } } void Application::removeAppWindow(_HWND hWnd) { IT_AppWindowMap it = ms_appWindowMap.find(hWnd); if (it != ms_appWindowMap.end()) { AppWindow *appWindow = it->second; ms_appWindowMap.erase(it); // and delete it deletePtr(appWindow); } else { O3D_ERROR(E_InvalidParameter("Unable to find the window handle")); } } Activity *Application::getActivity() { return ms_activity; } AppWindow* Application::getAppWindow(_HWND window) { IT_AppWindowMap it = ms_appWindowMap.find(window); if (it != ms_appWindowMap.end()) { return it->second; } else { return nullptr; } } void Application::throwDisplayError(void *generic_data) { ms_displayError = True; } // Get the default primary display. _DISP Application::getDisplay() { return ms_display; } void *Application::getApp() { return ms_app; } Bool Application::isDisplayError() { return ms_displayError; } void Application::registerObject(const String &name, BaseObject *object) { if (ms_mappedObject) { if (ms_mappedObject->find(name) != ms_mappedObject->end()) { O3D_ERROR(E_InvalidOperation(name + " is a registred object")); } ms_mappedObject->insert(std::make_pair(name, object)); } } void Application::unregisterObject(const String &name) { if (ms_mappedObject) { auto it = ms_mappedObject->find(name); if (it != ms_mappedObject->end()) { ms_mappedObject->erase(it); } } } BaseObject *Application::getObject(const String &name) { if (ms_mappedObject) { auto it = ms_mappedObject->find(name); if (it != ms_mappedObject->end()) { return it->second; } } return nullptr; } void Application::setState(Int32 state) { ms_appState = state; } Int32 Application::getState() { return ms_appState; } #ifndef O3D_ANDROID Int32 Application::startPrivate() { if (ms_activity) { return ms_activity->onStart(); } else { return 0; } } Int32 Application::stopPrivate() { if (ms_activity) { return ms_activity->onStop(); } else { return 0; } } #endif void Application::setActivity(Activity *activity) { if (ms_activity) { delete ms_activity; } ms_activity = activity; } void Application::start() { if (startPrivate() != 0) { // @todo need exit now } } void Application::run(Bool runOnce) { runPrivate(runOnce); } void Application::stop() { if (stopPrivate() != 0) { // @todo need exit now } } void Application::pushEvent(Application::EventType type, _HWND hWnd, void *data) { pushEventPrivate(type, hWnd, data); }
21.225
121
0.66384
dream-overflow
4014349595174704789f2de878af3e95cfa028cc
440
cpp
C++
9/9.45.cpp
kousikpramanik/C-_Primer_5th
e21fb665f04b26193fc13f9c2c263b782aea3f3c
[ "MIT" ]
null
null
null
9/9.45.cpp
kousikpramanik/C-_Primer_5th
e21fb665f04b26193fc13f9c2c263b782aea3f3c
[ "MIT" ]
2
2020-08-15T17:33:00.000Z
2021-07-05T14:18:26.000Z
9/9.45.cpp
kousikpramanik/C-_Primer_5th
e21fb665f04b26193fc13f9c2c263b782aea3f3c
[ "MIT" ]
1
2020-08-15T17:24:54.000Z
2020-08-15T17:24:54.000Z
#include <iostream> #include <string> void prefix_name_suffix(std::string &name, const std::string &prefix, const std::string &suffix) { name.insert(name.begin(), 1, ' '); name.insert(name.begin(), prefix.cbegin(), prefix.cend()); name.append(1, ' '); name.append(suffix); } int main() { std::string test("Stephen Inverter"); prefix_name_suffix(test, "Mr.", "III"); std::cout << test << '\n'; return 0; }
24.444444
98
0.618182
kousikpramanik
4014b0465d54eeca251524335ae005378cec2081
379
cpp
C++
src/messages/ExtSequencer.cpp
nspotrepka/ofxPDSP
e106991f4abf4314116d4e7c4ef7ad69d6ca005f
[ "MIT" ]
288
2016-02-06T18:50:47.000Z
2022-03-21T12:54:30.000Z
src/messages/ExtSequencer.cpp
nspotrepka/ofxPDSP
e106991f4abf4314116d4e7c4ef7ad69d6ca005f
[ "MIT" ]
68
2016-03-09T15:12:48.000Z
2021-11-29T14:05:49.000Z
src/messages/ExtSequencer.cpp
nspotrepka/ofxPDSP
e106991f4abf4314116d4e7c4ef7ad69d6ca005f
[ "MIT" ]
37
2016-02-11T20:36:28.000Z
2022-01-23T17:31:22.000Z
#include "ExtSequencer.h" std::vector<pdsp::ExtSequencer*> pdsp::ExtSequencer::instances; pdsp::ExtSequencer::ExtSequencer() { instances.push_back(this); } pdsp::ExtSequencer::~ExtSequencer() { for (size_t i = 0; i < instances.size(); ++i) { if (instances[i] == this) { instances.erase(instances.begin() + i); break; } } }
21.055556
63
0.591029
nspotrepka
4017a06d7784bb9ced27156a5e90a225a70002f0
3,290
cc
C++
src/um/LoginToken.cc
rchicoli/opennebula
d93f13297f4ca8448e994de34b66ca0e7a574fdd
[ "Apache-2.0" ]
1
2015-04-23T10:56:44.000Z
2015-04-23T10:56:44.000Z
src/um/LoginToken.cc
hsanjuan/one
0e7bf161095f11be0f2827527029f750cac36692
[ "Apache-2.0" ]
null
null
null
src/um/LoginToken.cc
hsanjuan/one
0e7bf161095f11be0f2827527029f750cac36692
[ "Apache-2.0" ]
17
2017-01-12T09:36:03.000Z
2019-04-18T20:52:02.000Z
/* -------------------------------------------------------------------------- */ /* Copyright 2002-2016, OpenNebula Project, OpenNebula Systems */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); you may */ /* not use this file except in compliance with the License. You may obtain */ /* a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ /* See the License for the specific language governing permissions and */ /* limitations under the License. */ /* -------------------------------------------------------------------------- */ #include <sstream> #include "LoginToken.h" #include "NebulaUtil.h" #include "ObjectXML.h" using namespace std; bool LoginToken::is_valid(const string& user_token) const { return ((user_token == token) && ((expiration_time == -1) || (time(0) < expiration_time))); } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ const std::string& LoginToken::set(const std::string& user_token, time_t valid) { if (valid == -1) { expiration_time = -1; } else if (valid > 0 ) { expiration_time = time(0) + valid; } else { expiration_time = 0; } if (!user_token.empty()) { token = user_token; } else { token = one_util::random_password(); } return token; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ void LoginToken::reset() { token.clear(); expiration_time = 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ std::string& LoginToken::to_xml(std::string& sxml) const { std::ostringstream xml; if ( expiration_time == 0 ) { xml << "<LOGIN_TOKEN/>"; } else { xml << "<LOGIN_TOKEN>" << "<TOKEN>" << token << "</TOKEN>" << "<EXPIRATION_TIME>" << expiration_time << "</EXPIRATION_TIME>" << "</LOGIN_TOKEN>"; } sxml = xml.str(); return sxml; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ void LoginToken::from_xml_node(const xmlNodePtr node) { ObjectXML oxml(node); oxml.xpath(token, "/LOGIN_TOKEN/TOKEN", ""); oxml.xpath<time_t>(expiration_time, "/LOGIN_TOKEN/EXPIRATION_TIME", 0); }
31.634615
80
0.386626
rchicoli
4017a39b14c250e5467b575075367f6cde6a683b
15,723
cpp
C++
win32-OpenGL/MotionPlanning_Project/Graph.cpp
Peanoquio/fuzzy-logic-demo
100a64094adb2d5274c32761ed4ede15b912dd90
[ "MIT" ]
null
null
null
win32-OpenGL/MotionPlanning_Project/Graph.cpp
Peanoquio/fuzzy-logic-demo
100a64094adb2d5274c32761ed4ede15b912dd90
[ "MIT" ]
null
null
null
win32-OpenGL/MotionPlanning_Project/Graph.cpp
Peanoquio/fuzzy-logic-demo
100a64094adb2d5274c32761ed4ede15b912dd90
[ "MIT" ]
null
null
null
/******************************************************************************/ /*! \file Graph.cpp \author Oliver Ryan Chong \par email: oliver.chong\@digipen.edu \par oliver.chong 900863 \par Course: CS1150 \par Project #02 \date 01/03/2012 \brief This is the graph class that will be used to generate the graph to be used by the algorithm to find the shortest path Copyright (C) 2011 DigiPen Institute of Technology Singapore */ /******************************************************************************/ #include "Graph.h" #include "MathUtility.h" //Edge class //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /******************************************************************************/ /*! The constructor for the Edge class \param \return */ /******************************************************************************/ Edge::Edge() { } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /******************************************************************************/ /*! The destructor for the Edge class \param \return */ /******************************************************************************/ Edge::~Edge() { } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /******************************************************************************/ /*! The copy constructor for the Edge class \param ed the Edge class to be assigned \return */ /******************************************************************************/ Edge::Edge(const Edge & ed) { from = ed.from; to = ed.to; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /******************************************************************************/ /*! The assignment operator overload for the Edge class \param ed the Edge class to be assigned \return Edge the Edge */ /******************************************************************************/ Edge & Edge::operator=(const Edge & ed) { if(this != &ed) { from = ed.from; to = ed.to; } return *this; } //State class //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /******************************************************************************/ /*! The constructor for the State class \param \return */ /******************************************************************************/ State::State() { } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /******************************************************************************/ /*! The destructor for the State class \param \return */ /******************************************************************************/ State::~State() { } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /******************************************************************************/ /*! The copy constructor for the State class \param st the State class to be assigned \return */ /******************************************************************************/ State::State(const State & st) { worldPositionX = st.worldPositionX; worldPositionY = st.worldPositionY; edges = st.edges; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /******************************************************************************/ /*! The assignment operator overload for the State class \param st the State class to be assigned \return State the State */ /******************************************************************************/ State & State::operator=(const State & st) { if(this != &st) { worldPositionX = st.worldPositionX; worldPositionY = st.worldPositionY; edges = st.edges; } return *this; } //Path class //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /******************************************************************************/ /*! The constructor for the Path class \param \return */ /******************************************************************************/ Path::Path() { } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /******************************************************************************/ /*! The destructor for the Path class \param \return */ /******************************************************************************/ Path::~Path() { } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /******************************************************************************/ /*! The assignment operator overload for the Path class \param pa1 the Path class to be assigned \return Path the Path */ /******************************************************************************/ Path & Path::operator=(Path & pa1) { if(this != &pa1) { } return *this; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /******************************************************************************/ /*! Initializes the distance and path matrices based on the number of states in the path \param \return */ /******************************************************************************/ void Path::InitMatrix( void ) { unsigned noOfStates = this->states.size(); //initialize the distance matrix based on the number of states in the path std::vector< float > floatVec; floatVec.reserve( noOfStates ); std::vector< int > intVec; intVec.reserve( noOfStates ); for ( unsigned int y = 0; y < noOfStates; ++y ) { floatVec.push_back( MAX_DISTANCE ); intVec.push_back( NO_LINK ); }//end for loop this->m_distanceMtx.reserve( noOfStates ); this->m_pathMtx.reserve( noOfStates ); for ( unsigned int x = 0; x < noOfStates; ++x ) { this->m_distanceMtx.push_back( floatVec ); this->m_pathMtx.push_back( intVec ); }//end for loop //set to identity for ( unsigned int x = 0; x < noOfStates; ++x ) { for ( unsigned int y = 0; y < noOfStates; ++y ) { if ( x == y ) { this->m_distanceMtx.at( x ).at( y ) = 0; this->m_pathMtx.at( x ).at( y ) = DIRECT_LINK; break; } }//end for loop }//end for loop } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /******************************************************************************/ /*! Populates the distance and path matrices based on the edges of each state in the path \param \return */ /******************************************************************************/ void Path::PopulateMatrix( void ) { unsigned noOfStates = this->states.size(); //populate the distance matrix based on the edges of each state in the path //loop through the states for ( unsigned stateIndex = 0; stateIndex < noOfStates; ++stateIndex ) { //get the current state const State & currState = this->states.at( stateIndex ); //loop through the edges for ( unsigned edgeIndex = 0; edgeIndex < currState.edges.size(); ++edgeIndex ) { //get the current edge const Edge & currEdge = currState.edges.at( edgeIndex ); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //traverse the row for ( unsigned x = 0; x < this->m_distanceMtx.size(); ++x ) { //if row found ( from ) if ( currEdge.from == static_cast<int>( x ) ) { std::vector< float > & colVecDM = this->m_distanceMtx.at( x ); std::vector< int> & colVecPath = this->m_pathMtx.at( x ); //traverse the column for ( unsigned y = 0; colVecDM.size(); ++y ) { //if column found ( to ) if ( currEdge.to == static_cast<int>( y ) ) { //get the x and y positions of the from and to states const State & fromState = this->states.at( currEdge.from ); const State & toState = this->states.at( currEdge.to ); //compute the distance between from and to states float xDiff = toState.worldPositionX - fromState.worldPositionX; float yDiff = toState.worldPositionY - fromState.worldPositionY; float distanceSquared = ( xDiff * xDiff ) + ( yDiff * yDiff ); //store the distance ( cost ) between the states colVecDM.at( y ) = distanceSquared; //to identify a direct path between states colVecPath.at( y ) = DIRECT_LINK; break; } }//end for loop break; } }//end for loop //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } }//end for loop } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /******************************************************************************/ /*! Generate the distance and path matrices to be used by Floyd's algorithm \param \return */ /******************************************************************************/ void Path::GenerateMatrix( void ) { this->InitMatrix(); this->PopulateMatrix(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /******************************************************************************/ /*! Floyd (or Floyd-Warshall) algorithm is a dynamic algorithm that finds the shortest paths between all pairs in a graph. \param \return */ /******************************************************************************/ void Path::FloydAlgorithm( void ) { unsigned noOfStates = this->states.size(); //loop through the intermediate nodes that could possible provide the shortest path for ( unsigned interIndex = 0; interIndex < noOfStates; ++interIndex ) { for ( unsigned fromIndex = 0; fromIndex < noOfStates; ++fromIndex ) { for ( unsigned toIndex = 0; toIndex < noOfStates; ++toIndex ) { float distFromTo = this->m_distanceMtx.at( fromIndex).at( toIndex ); float distFromInter = this->m_distanceMtx.at( fromIndex ).at( interIndex ); float distInterTo = this->m_distanceMtx.at( interIndex ).at( toIndex ); //validate if the intermediate state node will give a shorter path to the destination if ( distFromTo > distFromInter + distInterTo ) { //update the distance cost based on the new shorter path distFromTo = distFromInter + distInterTo; this->m_distanceMtx.at( fromIndex).at( toIndex ) = distFromTo; //update the path this->m_pathMtx.at( fromIndex ).at( toIndex ) = interIndex; } }//end for loop }//end for loop }//end for loop } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /******************************************************************************/ /*! Finds the shortest path based on the start and end indices. This uses the path matrix generated by Floyd's algorithm \param startIndex the start index of the path \param endIndex the end index of the path \return */ /******************************************************************************/ void Path::ComputeShortestPath( const int startIndex, const int endIndex ) { //get the path node index based on the start and end index int pathNodeIndex = this->m_pathMtx.at( startIndex ).at( endIndex ); //if there is no path if ( pathNodeIndex == NO_LINK ) { //do nothing } //if there is a direct path from start to end else if ( pathNodeIndex == DIRECT_LINK ) { //add the starting state this->shortestPathIndices.push_back( startIndex ); //add the ending state this->shortestPathIndices.push_back( endIndex ); } //if there is an intermediate node else { //find the intermediate nodes between the start and the middle state this->FindIntermediateNodes( startIndex, pathNodeIndex, true ); //find the intermediate nodes between the middle and end state this->FindIntermediateNodes( pathNodeIndex, endIndex, false ); //add the starting state //this->shortestPathIndices.push_back( startIndex ); //add the intermediate nodes for ( unsigned index = 0; index < this->intermediateNodes.size(); ++index ) { this->shortestPathIndices.push_back( this->intermediateNodes.at( index ) ); }//end for loop //clear the intermediate nodes this->intermediateNodes.clear(); //add the ending state //this->shortestPathIndices.push_back( endIndex ); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /******************************************************************************/ /*! Finds the intermediate nodes between a specified start and end state \param startIndex the start index of the path \param endIndex the end index of the path \param leftToRight if true, traverse nodes from left to right. if false, traverse from right to left \return */ /******************************************************************************/ void Path::FindIntermediateNodes( const int startIndex, const int endIndex, bool leftToRight ) { //get the path node index based on the start and end index int pathNodeIndex = this->m_pathMtx.at( startIndex ).at( endIndex ); //if there is no path if ( pathNodeIndex == NO_LINK ) { //do nothing } //if there is a direct path from start to end else if ( pathNodeIndex == DIRECT_LINK ) { int firstStateIndex = 0; int secondStateIndex = 0; if ( leftToRight == true ) { firstStateIndex = startIndex; secondStateIndex = endIndex; } else { firstStateIndex = endIndex; secondStateIndex = startIndex; } this->AddNodeIndex( firstStateIndex ); this->AddNodeIndex( secondStateIndex ); } //if there is an intermediate node else { //invoke function recursively to check for possible succeeding intermediate nodes this->FindIntermediateNodes( startIndex, pathNodeIndex, true ); this->FindIntermediateNodes( pathNodeIndex, endIndex, false ); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /******************************************************************************/ /*! Adds the state node index to the list \param stateIndex the state node index of the path \return */ /******************************************************************************/ void Path::AddNodeIndex( const int stateIndex ) { bool isExisting = false; //validate if the node to be is already existing for ( unsigned index = 0; index < this->intermediateNodes.size(); ++index ) { if ( stateIndex == this->intermediateNodes.at( index ) ) { isExisting = true; break; } }//end for loop if ( isExisting == false ) { this->intermediateNodes.push_back( stateIndex ); } }
26.694397
143
0.423011
Peanoquio
4018a792a0a6347c5f884fceecd845d56585bc05
11,424
hpp
C++
src/framework/gui/CommonControls.hpp
yslking/GPURayTraversal
cfcc825aef473318fc7eb4975c13fe40cda5c915
[ "BSD-3-Clause" ]
39
2016-07-19T15:25:16.000Z
2021-07-15T16:06:15.000Z
src/framework/gui/CommonControls.hpp
ItsHoff/BDPT
4a5ae6559764799c77182a965a674cae127e2b0e
[ "MIT" ]
null
null
null
src/framework/gui/CommonControls.hpp
ItsHoff/BDPT
4a5ae6559764799c77182a965a674cae127e2b0e
[ "MIT" ]
14
2017-12-19T03:14:50.000Z
2021-06-24T16:53:10.000Z
/* * Copyright (c) 2009-2011, NVIDIA Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of NVIDIA Corporation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "gui/Window.hpp" #include "base/Timer.hpp" #include "base/Array.hpp" #include "base/Hash.hpp" namespace FW { //------------------------------------------------------------------------ class StateDump; //------------------------------------------------------------------------ class CommonControls : public Window::Listener { public: //------------------------------------------------------------------------ enum Feature { Feature_CloseOnEsc = 1 << 0, Feature_CloseOnAltF4 = 1 << 1, Feature_RepaintOnF5 = 1 << 2, Feature_ShowFPSOnF9 = 1 << 3, Feature_HideControlsOnF10 = 1 << 4, Feature_FullScreenOnF11 = 1 << 5, Feature_ScreenshotOnPrtScn = 1 << 6, Feature_LoadStateOnNum = 1 << 7, Feature_SaveStateOnAltNum = 1 << 8, Feature_None = 0, Feature_All = (1 << 9) - 1, Feature_Default = Feature_All }; //------------------------------------------------------------------------ class StateObject { public: StateObject (void) {} virtual ~StateObject (void) {} virtual void readState (StateDump& d) = 0; virtual void writeState (StateDump& d) const = 0; }; private: struct Key; //------------------------------------------------------------------------ struct Message { String string; String volatileID; F32 highlightTime; U32 abgr; }; //------------------------------------------------------------------------ struct Toggle { bool* boolTarget; S32* enumTarget; S32 enumValue; bool* dirtyNotify; bool isButton; bool isSeparator; Key* key; String title; F32 highlightTime; bool visible; Vec2f pos; Vec2f size; }; //------------------------------------------------------------------------ struct Slider { F32* floatTarget; S32* intTarget; bool* dirtyNotify; F32 slack; F32 minValue; F32 maxValue; bool isExponential; Key* increaseKey; Key* decreaseKey; String format; F32 speed; F32 highlightTime; bool visible; bool stackWithPrevious; Vec2f pos; Vec2f size; Vec2f blockPos; Vec2f blockSize; }; //------------------------------------------------------------------------ struct Key { String id; Array<Toggle*> toggles; Array<Slider*> sliderIncrease; Array<Slider*> sliderDecrease; }; //------------------------------------------------------------------------ public: CommonControls (U32 features = Feature_Default); virtual ~CommonControls (void); virtual bool handleEvent (const Window::Event& ev); void message (const String& str, const String& volatileID = "", U32 abgr = 0xffffffffu); void addToggle (bool* target, const String& key, const String& title, bool* dirtyNotify = NULL) { FW_ASSERT(target); addToggle(target, NULL, 0, false, key, title, dirtyNotify); } void addToggle (S32* target, S32 value, const String& key, const String& title, bool* dirtyNotify = NULL) { FW_ASSERT(target); addToggle(NULL, target, value, false, key, title, dirtyNotify); } void addButton (bool* target, const String& key, const String& title, bool* dirtyNotify = NULL) { FW_ASSERT(target); addToggle(target, NULL, 0, true, key, title, dirtyNotify); } void addButton (S32* target, S32 value, const String& key, const String& title, bool* dirtyNotify = NULL) { FW_ASSERT(target); addToggle(NULL, target, value, true, key, title, dirtyNotify); } void addSeparator (void) { addToggle(NULL, NULL, 0, false, "", "", NULL); } void setControlVisibility(bool visible) { m_controlVisibility = visible; } // applies to next addXxx() void addSlider (F32* target, F32 minValue, F32 maxValue, bool isExponential, const String& increaseKey, const String& decreaseKey, const String& format, F32 speed = 0.25f, bool* dirtyNotify = NULL) { addSlider(target, NULL, minValue, maxValue, isExponential, increaseKey, decreaseKey, format, speed, dirtyNotify); } void addSlider (S32* target, S32 minValue, S32 maxValue, bool isExponential, const String& increaseKey, const String& decreaseKey, const String& format, F32 speed = 0.0f, bool* dirtyNotify = NULL) { addSlider(NULL, target, (F32)minValue, (F32)maxValue, isExponential, increaseKey, decreaseKey, format, speed, dirtyNotify); } void beginSliderStack (void) { m_sliderStackBegun = true; m_sliderStackEmpty = true; } void endSliderStack (void) { m_sliderStackBegun = false; } void removeControl (const void* target); void resetControls (void); void setStateFilePrefix (const String& prefix) { m_stateFilePrefix = prefix; } void setScreenshotFilePrefix(const String& prefix) { m_screenshotFilePrefix = prefix; } String getStateFileName (int idx) const { return sprintf("%s%03d.dat", m_stateFilePrefix.getPtr(), idx); } String getScreenshotFileName(void) const; void addStateObject (StateObject* obj) { if (obj && !m_stateObjs.contains(obj)) m_stateObjs.add(obj); } void removeStateObject (StateObject* obj) { m_stateObjs.removeItem(obj); } bool loadState (const String& fileName); bool saveState (const String& fileName); bool loadStateDialog (void); bool saveStateDialog (void); void showControls (bool show) { m_showControls = show; } void showFPS (bool show) { m_showFPS = show; } bool getShowControls (void) const { return m_showControls; } bool getShowFPS (void) const { return m_showFPS; } F32 getKeyBoost (void) const; void flashButtonTitles (void); private: bool hasFeature (Feature feature) { return ((m_features & feature) != 0); } void render (GLContext* gl); void addToggle (bool* boolTarget, S32* enumTarget, S32 enumValue, bool isButton, const String& key, const String& title, bool* dirtyNotify); void addSlider (F32* floatTarget, S32* intTarget, F32 minValue, F32 maxValue, bool isExponential, const String& increaseKey, const String& decreaseKey, const String& format, F32 speed, bool* dirtyNotify); Key* getKey (const String& id); void layout (const Vec2f& viewSize, F32 fontHeight); void clearActive (void); void updateActive (const Vec2f& mousePos); F32 updateHighlightFade (F32* highlightTime); U32 fadeABGR (U32 abgr, F32 fade); static void selectToggle (Toggle* t); F32 getSliderY (const Slider* s, bool applySlack) const; void setSliderY (Slider* s, F32 y); static F32 getSliderValue (const Slider* s, bool applySlack); static void setSliderValue (Slider* s, F32 v); static String getSliderLabel (const Slider* s); static void sliderKeyDown (Slider* s, int dir); void enterSliderValue (Slider* s); static void drawPanel (GLContext* gl, const Vec2f& pos, const Vec2f& size, U32 interiorABGR, U32 topLeftABGR, U32 bottomRightABGR); private: CommonControls (const CommonControls&); // forbidden CommonControls& operator= (const CommonControls&); // forbidden private: const U32 m_features; Window* m_window; Timer m_timer; bool m_showControls; bool m_showFPS; String m_stateFilePrefix; String m_screenshotFilePrefix; Array<Message> m_messages; Array<Toggle*> m_toggles; Array<Slider*> m_sliders; Array<StateObject*> m_stateObjs; Hash<String, Key*> m_keyHash; bool m_sliderStackBegun; bool m_sliderStackEmpty; bool m_controlVisibility; Vec2f m_viewSize; F32 m_fontHeight; F32 m_rightX; S32 m_activeSlider; S32 m_activeToggle; bool m_dragging; F32 m_avgFrameTime; bool m_screenshot; }; //------------------------------------------------------------------------ }
44.976378
349
0.523372
yslking
40198441b55144c425d6a51c11f979b7e34474ca
1,595
cpp
C++
ogsr_engine/xrGame/GraviArtifact.cpp
stepa2/OGSR-Engine
32a23aa30506684be1267d9c4fc272350cd167c5
[ "Apache-2.0" ]
247
2018-11-02T18:50:55.000Z
2022-03-15T09:11:43.000Z
ogsr_engine/xrGame/GraviArtifact.cpp
stepa2/OGSR-Engine
32a23aa30506684be1267d9c4fc272350cd167c5
[ "Apache-2.0" ]
193
2018-11-02T20:12:44.000Z
2022-03-07T13:35:17.000Z
ogsr_engine/xrGame/GraviArtifact.cpp
stepa2/OGSR-Engine
32a23aa30506684be1267d9c4fc272350cd167c5
[ "Apache-2.0" ]
106
2018-10-26T11:33:01.000Z
2022-03-19T12:34:20.000Z
/////////////////////////////////////////////////////////////// // GraviArtifact.cpp // GraviArtefact - гравитационный артефакт, прыгает на месте // и неустойчиво парит над землей /////////////////////////////////////////////////////////////// #include "stdafx.h" #include "GraviArtifact.h" #include "PhysicsShell.h" #include "level.h" #include "xrmessages.h" #include "game_cl_base.h" #include "../Include/xrRender/Kinematics.h" #include "phworld.h" extern CPHWorld* ph_world; #define CHOOSE_MAX(x,inst_x,y,inst_y,z,inst_z)\ if(x>y)\ if(x>z){inst_x;}\ else{inst_z;}\ else\ if(y>z){inst_y;}\ else{inst_z;} CGraviArtefact::CGraviArtefact(void) { shedule.t_min = 20; shedule.t_max = 50; m_fJumpHeight = 0; m_fEnergy = 1.f; } CGraviArtefact::~CGraviArtefact(void) { } void CGraviArtefact::Load(LPCSTR section) { inherited::Load(section); if(pSettings->line_exist(section, "jump_height")) m_fJumpHeight = pSettings->r_float(section,"jump_height"); // m_fEnergy = pSettings->r_float(section,"energy"); } void CGraviArtefact::UpdateCLChild() { VERIFY(!ph_world->Processing()); if (getVisible() && m_pPhysicsShell) { if (m_fJumpHeight) { Fvector dir; dir.set(0, -1.f, 0); collide::rq_result RQ; //проверить высоту артифакта if(Level().ObjectSpace.RayPick(Position(), dir, m_fJumpHeight, collide::rqtBoth, RQ, this)) { dir.y = 1.f; m_pPhysicsShell->applyImpulse(dir, 30.f * Device.fTimeDelta * m_pPhysicsShell->getMass()); } } } else if(H_Parent()) { XFORM().set(H_Parent()->XFORM()); }; }
22.152778
109
0.619436
stepa2
401a1a934270716c9dee2332135d5c7416f85b84
9,387
cpp
C++
MIDI Test/console_io_handler.cpp
MiguelGuthridge/HDSQs-MIDI-Editor
a5d6a2ea84b5123fb8f1aa0921da0b04e6e6cc27
[ "MIT" ]
null
null
null
MIDI Test/console_io_handler.cpp
MiguelGuthridge/HDSQs-MIDI-Editor
a5d6a2ea84b5123fb8f1aa0921da0b04e6e6cc27
[ "MIT" ]
1
2018-07-01T08:51:05.000Z
2018-08-18T10:40:53.000Z
MIDI Test/console_io_handler.cpp
HDSQmid/HDSQs-MIDI-Editor
a5d6a2ea84b5123fb8f1aa0921da0b04e6e6cc27
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "console_io_handler.h" #include "messageSend.h" #include "multiLingual.h" #include "settings.h" ConsoleQuit quit; ConsoleHelp help; ConsoleFileNew newFile; ConsoleFileOpen openFile; ConsoleFileClose closeFile; ConsoleFileSave saveFile; ConsoleFileSaveAs saveFileAs; ConsoleMidiMakeEdit makeEdit; ConsoleCrash crash; ConsoleInfo info; ConsoleSettingsAddLanguage addLanguage; ConsolePrintTranslation printTranslation; ConsoleMidiPattern pattern; ConsoleInputHandler* input_handlers[NUM_HANDLERS] = { &help, &quit, &openFile, &newFile, &closeFile, &saveFile, &saveFileAs, &crash, &info, &makeEdit, &addLanguage, &printTranslation, &pattern }; void handleConsoleInput(std::string input, ConsoleInputHandler ** handlerList, int numHandlers) { std::string test; std::istringstream iss{ input }; iss >> test; std::ostringstream oss; oss << iss.rdbuf(); std::string args = oss.str(); if (test == "") { sendMessage(MESSAGE_NO_COMMAND_PROVIDED, "", MESSAGE_TYPE_ERROR); return; } if(args != "") args = args.substr(1); // remove space from start of string //remove command from rest of arguments for easier processing bool foundCall = false; // bool for whether a handler was found for (int i = 0; i <numHandlers; i++) { if (handlerList[i]->getIdentifier() == test) { handlerList[i]->call(args); foundCall = 1; break; } } if (!foundCall) sendMessage(MESSAGE_NO_MATCHING_COMMAND, "", MESSAGE_TYPE_ERROR); } /***************************************/ //implement multi-layered console input handler ConsoleInputHandler::ConsoleInputHandler() { identifier = "NULL"; description = CONSOLE_INPUT_HANDLER_DEFAULT_DESCRIPTION; arguments = CONSOLE_INPUT_HANDLER_DEFAULT_ARGUMENTS; exampleUsage = CONSOLE_INPUT_HANDLER_DEFAULT_EXAMPLE_USAGE; } void ConsoleInputHandler::call(std::string args) { std::cout << "Test" << std::endl; } std::string ConsoleInputHandler::getIdentifier() { return identifier; } std::string ConsoleInputHandler::getDescription() { return translate(description); } std::string ConsoleInputHandler::getArguments() { return translate(arguments); } std::string ConsoleInputHandler::getExampleUsage() { std::string str = identifier + " " + translate(exampleUsage); return str; } /***************************************/ // files ConsoleFileOpen::ConsoleFileOpen() { identifier = "open"; description = CONSOLE_INPUT_HANDLER_FILE_OPEN_DESCRIPTION; arguments = CONSOLE_INPUT_HANDLER_FILE_OPEN_ARGUMENTS; exampleUsage = CONSOLE_INPUT_HANDLER_FILE_OPEN_EXAMPLE_USAGE; } void ConsoleFileOpen::call(std::string args) { if (args == "") { sendMessage(MESSAGE_NOT_VALID_FILENAME, "", MESSAGE_TYPE_ERROR); return; } fileOpen(args); return; } ConsoleFileClose::ConsoleFileClose() { identifier = "close"; description = CONSOLE_INPUT_HANDLER_FILE_CLOSE_DESCRIPTION; arguments = CONSOLE_INPUT_HANDLER_FILE_CLOSE_ARGUMENTS; exampleUsage = CONSOLE_INPUT_HANDLER_FILE_CLOSE_EXAMPLE_USAGE; } void ConsoleFileClose::call(std::string args) { if (currentFile == NULL) // if file is not open { sendMessage(MESSAGE_NO_FILE_OPEN, "",MESSAGE_TYPE_ERROR); return; } fileClose(); } ConsoleFileSave::ConsoleFileSave() { identifier = "save"; description = CONSOLE_INPUT_HANDLER_FILE_SAVE_DESCRIPTION; arguments = CONSOLE_INPUT_HANDLER_FILE_SAVE_ARGUMENTS; exampleUsage = CONSOLE_INPUT_HANDLER_FILE_SAVE_EXAMPLE_USAGE; } void ConsoleFileSave::call(std::string args) { if (currentFile == NULL) // if file is not open { sendMessage(MESSAGE_NO_FILE_OPEN, "", MESSAGE_TYPE_ERROR); return; } if (args != "") currentFile->saveAs(args); else currentFile->save(); } ConsoleFileSaveAs::ConsoleFileSaveAs() { identifier = "saveAs"; description = CONSOLE_INPUT_HANDLER_FILE_SAVE_AS_DESCRIPTION; arguments = CONSOLE_INPUT_HANDLER_FILE_SAVE_AS_ARGUMENTS; exampleUsage = CONSOLE_INPUT_HANDLER_FILE_SAVE_AS_EXAMPLE_USAGE; } void ConsoleFileSaveAs::call(std::string args) { if (currentFile == NULL) // if file is not open { sendMessage(MESSAGE_NO_FILE_OPEN, "",MESSAGE_TYPE_ERROR); return; } if (args == "") { // if no file name provided sendMessage(MESSAGE_NOT_VALID_FILENAME, "", MESSAGE_TYPE_ERROR); return; } currentFile->saveAs(args); } ConsoleFileNew::ConsoleFileNew() { identifier = "new"; description = CONSOLE_INPUT_HANDLER_FILE_NEW_DESCRIPTION; arguments = CONSOLE_INPUT_HANDLER_FILE_NEW_ARGUMENTS; exampleUsage = CONSOLE_INPUT_HANDLER_FILE_NEW_EXAMPLE_USAGE; } void ConsoleFileNew::call(std::string args) { fileNew(); } // program functions ConsoleQuit::ConsoleQuit() { identifier = "quit"; description = CONSOLE_INPUT_HANDLER_QUIT_DESCRIPTION; arguments = CONSOLE_INPUT_HANDLER_QUIT_ARGUMENTS; exampleUsage = CONSOLE_INPUT_HANDLER_QUIT_EXAMPLE_USAGE; } void ConsoleQuit::call(std::string args) { quit(); } ConsoleHelp::ConsoleHelp() { identifier = "help"; description = CONSOLE_INPUT_HANDLER_HELP_DESCRIPTION; arguments = CONSOLE_INPUT_HANDLER_HELP_ARGUMENTS; exampleUsage = CONSOLE_INPUT_HANDLER_HELP_EXAMPLE_USAGE; } void ConsoleHelp::call(std::string args) { //set colour to green HANDLE hConsole; int colour = 2; hConsole = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hConsole, colour); //if no argument if (args == "") { std::cout << "Help:" << std::endl; for (int i = 0; i < NUM_HANDLERS; i++) { std::cout << input_handlers[i]->getIdentifier() << ": " << input_handlers[i]->getDescription() << std::endl; } } //if argument provided else { bool foundCall = false; // bool for whether a handler was found for (int i = 0; i < NUM_HANDLERS; i++) { if (input_handlers[i]->getIdentifier() == args) { std::cout << translate(STRING_HELP_FOR) << " " << input_handlers[i]->getIdentifier() << "\n" << input_handlers[i]->getDescription() << "\n" << input_handlers[i]->getArguments() << "\n" << input_handlers[i]->getExampleUsage() << std::endl; foundCall = 1; break; } } if (!foundCall) sendMessage(MESSAGE_NO_MATCHING_COMMAND, "", MESSAGE_TYPE_ERROR); } SetConsoleTextAttribute(hConsole, 15); } ConsoleCrash::ConsoleCrash() { identifier = "crash"; description = CONSOLE_INPUT_HANDLER_CRASH_DESCRIPTION; arguments = CONSOLE_INPUT_HANDLER_CRASH_ARGUMENTS; exampleUsage = CONSOLE_INPUT_HANDLER_CRASH_EXAMPLE_USAGE; } void ConsoleCrash::call(std::string args) { throw std::exception("Manually initiated crash", ERROR_CODE_MANUAL_CRASH); } ConsoleInfo::ConsoleInfo() { identifier = "info"; description = CONSOLE_INPUT_HANDLER_INFO_DESCRIPTION; arguments = CONSOLE_INPUT_HANDLER_INFO_ARGUMENTS; exampleUsage = CONSOLE_INPUT_HANDLER_INFO_EXAMPLE_USAGE; } void ConsoleInfo::call(std::string args) { printAppInfo(); } // midi functions ConsoleMidiMakeEdit::ConsoleMidiMakeEdit() { identifier = "makeEdit"; description = CONSOLE_INPUT_HANDLER_MAKE_EDIT_DESCRIPTION; arguments = CONSOLE_INPUT_HANDLER_MAKE_EDIT_ARGUMENTS; exampleUsage = CONSOLE_INPUT_HANDLER_MAKE_EDIT_EXAMPLE_USAGE; } void ConsoleMidiMakeEdit::call(std::string args) { currentFile->makeEdit(); } ConsoleMidiTrack::ConsoleMidiTrack() { identifier = "track"; description = CONSOLE_INPUT_HANDLER_MIDI_TRACK_DESCRIPTION; arguments = CONSOLE_INPUT_HANDLER_MIDI_TRACK_ARGUMENTS; exampleUsage = CONSOLE_INPUT_HANDLER_MIDI_TRACK_EXAMPLE_USAGE; } void ConsoleMidiTrack::call(std::string args) { // determine request type // based on request type, perform action } ConsoleMidiSelect::ConsoleMidiSelect() { identifier = "select"; description = CONSOLE_INPUT_HANDLER_MIDI_SELECT_DESCRIPTION; arguments = CONSOLE_INPUT_HANDLER_MIDI_SELECT_ARGUMENTS; exampleUsage = CONSOLE_INPUT_HANDLER_MIDI_SELECT_EXAMPLE_USAGE; } void ConsoleMidiSelect::call(std::string args) { // use arguments to determine what to select, then select it } ConsoleMidiSelection::ConsoleMidiSelection() { identifier = "selection"; description = CONSOLE_INPUT_HANDLER_MIDI_SELECTION_DESCRIPTION; arguments = CONSOLE_INPUT_HANDLER_MIDI_SELECTION_ARGUMENTS; exampleUsage = CONSOLE_INPUT_HANDLER_MIDI_SELECTION_EXAMPLE_USAGE; } void ConsoleMidiSelection::call(std::string args) { // determine action to perform based on arguments } ConsoleSettingsAddLanguage::ConsoleSettingsAddLanguage() { identifier = "addLanguage"; description = CONSOLE_INPUT_HANDLER_SETTINGS_ADD_LANGUAGE_DESCRIPTION; arguments = CONSOLE_INPUT_HANDLER_SETTINGS_ADD_LANGUAGE_ARGUMENTS; exampleUsage = CONSOLE_INPUT_HANDLER_SETTINGS_ADD_LANGUAGE_EXAMPLE_USAGE; } void ConsoleSettingsAddLanguage::call(std::string args) { settings->addLanguage(args); } ConsolePrintTranslation::ConsolePrintTranslation() { identifier = "printTranslation"; description = CONSOLE_INPUT_HANDLER_PRINT_TRANSLATION_DESCRIPTION; arguments = CONSOLE_INPUT_HANDLER_PRINT_TRANSLATION_ARGUMENTS; exampleUsage = CONSOLE_INPUT_HANDLER_PRINT_TRANSLATION_EXAMPLE_USAGE; } void ConsolePrintTranslation::call(std::string args) { std::stringstream ss(args); int i; ss >> i; sendMessage(STRING_TRANSLATION, translate(i)); } ConsoleRunScript::ConsoleRunScript() { identifier = "run"; description = CONSOLE_INPUT_HANDLER_RUN_SCRIPT_DESCRIPTION; arguments = CONSOLE_INPUT_HANDLER_RUN_SCRIPT_ARGUMENTS; exampleUsage = CONSOLE_INPUT_HANDLER_RUN_SCRIPT_EXAMPLE_USAGE; } void ConsoleRunScript::call(std::string args) { }
23.12069
103
0.764994
MiguelGuthridge
401ad8c461094fc5318bf9c6a8dc60facfa68a02
3,002
cpp
C++
os/x11/event_queue.cpp
turbolent/laf
75f29b27c661e66e1549dc6e6a172f284cd9326b
[ "MIT" ]
null
null
null
os/x11/event_queue.cpp
turbolent/laf
75f29b27c661e66e1549dc6e6a172f284cd9326b
[ "MIT" ]
null
null
null
os/x11/event_queue.cpp
turbolent/laf
75f29b27c661e66e1549dc6e6a172f284cd9326b
[ "MIT" ]
null
null
null
// LAF OS Library // Copyright (C) 2016-2018 David Capello // // This file is released under the terms of the MIT license. // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "os/x11/event_queue.h" #include "os/x11/window.h" #include <X11/Xlib.h> #define EV_TRACE(...) namespace os { #if !defined(NDEBUG) namespace { const char* get_event_name(XEvent& event) { switch (event.type) { case KeyPress: return "KeyPress"; case KeyRelease: return "KeyRelease"; case ButtonPress: return "ButtonPress"; case ButtonRelease: return "ButtonRelease"; case MotionNotify: return "MotionNotify"; case EnterNotify: return "EnterNotify"; case LeaveNotify: return "LeaveNotify"; case FocusIn: return "FocusIn"; case FocusOut: return "FocusOut"; case KeymapNotify: return "KeymapNotify"; case Expose: return "Expose"; case GraphicsExpose: return "GraphicsExpose"; case NoExpose: return "NoExpose"; case VisibilityNotify: return "VisibilityNotify"; case CreateNotify: return "CreateNotify"; case DestroyNotify: return "DestroyNotify"; case UnmapNotify: return "UnmapNotify"; case MapNotify: return "MapNotify"; case MapRequest: return "MapRequest"; case ReparentNotify: return "ReparentNotify"; case ConfigureNotify: return "ConfigureNotify"; case ConfigureRequest: return "ConfigureRequest"; case GravityNotify: return "GravityNotify"; case ResizeRequest: return "ResizeRequest"; case CirculateNotify: return "CirculateNotify"; case CirculateRequest: return "CirculateRequest"; case PropertyNotify: return "PropertyNotify"; case SelectionClear: return "SelectionClear"; case SelectionRequest: return "SelectionRequest"; case SelectionNotify: return "SelectionNotify"; case ColormapNotify: return "ColormapNotify"; case ClientMessage: return "ClientMessage"; case MappingNotify: return "MappingNotify"; case GenericEvent: return "GenericEvent"; } return "Unknown"; } } // anonymous namespace #endif void X11EventQueue::getEvent(Event& ev, bool canWait) { checkResizeDisplayEventEvent(canWait); ::Display* display = X11::instance()->display(); XSync(display, False); XEvent event; int events = XEventsQueued(display, QueuedAlready); if (events == 0 && canWait) events = 1; for (int i=0; i<events; ++i) { XNextEvent(display, &event); processX11Event(event); } if (m_events.empty()) { #pragma push_macro("None") #undef None // Undefine the X11 None macro ev.setType(Event::None); #pragma pop_macro("None") } else { ev = m_events.front(); m_events.pop(); } } void X11EventQueue::processX11Event(XEvent& event) { EV_TRACE("XEvent: %s (%d)\n", get_event_name(event), event.type); X11Window* window = X11Window::getPointerFromHandle(event.xany.window); // In MappingNotify the window can be nullptr if (window) window->processX11Event(event); } } // namespace os
28.056075
73
0.713524
turbolent
401c083e6d832432cd0da8ad4d0ba575ca809608
2,194
cc
C++
chrome/browser/chromeos/net/network_diagnostics/fake_tcp_connected_socket.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
chrome/browser/chromeos/net/network_diagnostics/fake_tcp_connected_socket.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/browser/chromeos/net/network_diagnostics/fake_tcp_connected_socket.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/net/network_diagnostics/fake_tcp_connected_socket.h" #include <utility> #include "base/callback.h" #include "base/logging.h" #include "base/optional.h" #include "mojo/public/cpp/system/data_pipe.h" FakeTCPConnectedSocket::FakeTCPConnectedSocket() = default; FakeTCPConnectedSocket::~FakeTCPConnectedSocket() = default; void FakeTCPConnectedSocket::UpgradeToTLS( const net::HostPortPair& host_port_pair, network::mojom::TLSClientSocketOptionsPtr socket_options, const net::MutableNetworkTrafficAnnotationTag& traffic_annotation, mojo::PendingReceiver<network::mojom::TLSClientSocket> receiver, mojo::PendingRemote<network::mojom::SocketObserver> observer, network::mojom::TCPConnectedSocket::UpgradeToTLSCallback callback) { if (disconnect_) { receiver_.reset(); return; } // Only during no disconnects will |callback| be invoked. std::move(callback).Run(tls_upgrade_code_, mojo::ScopedDataPipeConsumerHandle(), mojo::ScopedDataPipeProducerHandle(), /*ssl_info=*/base::nullopt); } void FakeTCPConnectedSocket::SetSendBufferSize( int32_t send_buffer_size, SetSendBufferSizeCallback callback) { std::move(callback).Run(0); } void FakeTCPConnectedSocket::SetReceiveBufferSize( int32_t receive_buffer_size, SetReceiveBufferSizeCallback callback) { std::move(callback).Run(0); } void FakeTCPConnectedSocket::SetNoDelay(bool no_delay, SetNoDelayCallback callback) { std::move(callback).Run(false); } void FakeTCPConnectedSocket::SetKeepAlive(bool enable, int32_t delay_secs, SetKeepAliveCallback callback) { std::move(callback).Run(0); } void FakeTCPConnectedSocket::BindReceiver( mojo::PendingReceiver<network::mojom::TCPConnectedSocket> socket) { DCHECK(!receiver_.is_bound()); receiver_.Bind(std::move(socket)); }
34.28125
86
0.706016
Ron423c
401cf996e5148b7507fd95cdc9a84ddbc9ae99b8
1,469
hpp
C++
brainfucppk/include/implementations/StandardImplementation.hpp
Milo46/brainfuck-interpreter
55065f4ff80df229f29a35e1875fc195eb092cb8
[ "MIT" ]
null
null
null
brainfucppk/include/implementations/StandardImplementation.hpp
Milo46/brainfuck-interpreter
55065f4ff80df229f29a35e1875fc195eb092cb8
[ "MIT" ]
1
2022-02-04T14:16:44.000Z
2022-02-04T14:16:44.000Z
brainfucppk/include/implementations/StandardImplementation.hpp
Milo46/brainfuck-interpreter
55065f4ff80df229f29a35e1875fc195eb092cb8
[ "MIT" ]
1
2022-02-04T14:07:51.000Z
2022-02-04T14:07:51.000Z
#pragma once #include "core/Implementation.hpp" #include <map> BRAINFUCPPK_BEGIN enum class StandardToken : char { IncrementPointer = '>', DecrementPointer = '<', IncrementValue = '+', DecrementValue = '-', Write = '.', Read = ',', BeginLoop = '[', EndLoop = ']', End, }; class StandardImplementation : public Implementation { public: StandardImplementation(const WarpableIterator<unsigned char>& pointer, std::ostream& output, std::istream& input); protected: virtual bool ResolveToken(const std::string& source, std::size_t& index) noexcept(false) override; private: void IncrementPointer(const std::string& source, std::size_t& index); void DecrementPointer(const std::string& source, std::size_t& index); void IncrementValue(const std::string& source, std::size_t& index); void DecrementValue(const std::string& source, std::size_t& index); void Write(const std::string& source, std::size_t& index); void Read(const std::string& source, std::size_t& index); void BeginLoop(const std::string& source, std::size_t& index); void EndLoop(const std::string& source, std::size_t& index); private: /* The code isn't ready for that kind of thing yet. */ // bool IsThisLoopInfinite(const std::string& source, const std::size_t bracketPosition) const; private: std::map<std::size_t, std::size_t> m_LoopsPositions; }; BRAINFUCPPK_END
29.38
118
0.673928
Milo46
401e1cd2bde42a05fa8a0953fa5731908a00eb85
3,078
cpp
C++
source/sirtthread.cpp
drminix/ctsimulator
b6ef3feed5310ff43b60ddd039a6a187c6e60718
[ "MIT" ]
7
2017-02-10T10:12:48.000Z
2022-03-06T06:43:57.000Z
source/sirtthread.cpp
drminix/ctsimulator
b6ef3feed5310ff43b60ddd039a6a187c6e60718
[ "MIT" ]
null
null
null
source/sirtthread.cpp
drminix/ctsimulator
b6ef3feed5310ff43b60ddd039a6a187c6e60718
[ "MIT" ]
4
2017-02-21T07:31:15.000Z
2022-03-10T02:54:49.000Z
/**************************** * Author: Sanghyeb(Sam) Lee * Date: Jan/2013 * email: drminix@gmail.com * Copyright 2013 Sang hyeb(Sam) Lee MIT License * * X-ray CT simulation & reconstruction *****************************/ #include "SirtThread.h" SirtThread::SirtThread(QObject *parent) : QThread(parent) { } SirtThread::SirtThread(drawingarea* tarea,int tsweeps,double trelaxation, int twhentoshow) : maindrawingarea(tarea), sweeps(tsweeps), relaxation(trelaxation), whentoshow(twhentoshow) { A = maindrawingarea->A; //A x = new double[maindrawingarea->A_size.width()]; b = new double[maindrawingarea->sinogram_size.width()*maindrawingarea->sinogram_size.height()]; //setup it to running running = true; } inline void swap(double** x1,double** x2) { double* x_temp; x_temp = *x1; *x1 = *x2; *x2 = x_temp; } void SirtThread::setupReturnBuffer(double **pBuffer) { pX = pBuffer; } //perform art. void SirtThread::run() { //Ax = b int a_row = this->maindrawingarea->A_size.height(); int a_column = this->maindrawingarea->A_size.width(); int x_row = a_column; int b_row = a_row; std::cout<<"SirtThread: started."<<std::endl; int sino_width = maindrawingarea->sinogram_size.width(); int sino_height = maindrawingarea->sinogram_size.height(); //initialize x(estimate image) to zero memset(x,0,sizeof(double)*x_row); for(int i=0;i<sino_width;i++) { //memcpy(dest,src, number of bytes)*/ memcpy(b+(sino_height*i),this->maindrawingarea->sinogram[i],sizeof(double)*sino_height); } //now perform ART //main iteration. double rs; //residual double* diff = new double[a_row]; double Ax; double* x_prev = new double[a_column]; for(int main_iterator=0;main_iterator<sweeps&&running==true;main_iterator++) { //after this command, x_prev points to x, x point to new area swap(&x_prev,&x); for(int i=0;i<a_row;i++) { //calculate Ax Ax=0; //Ax for(int j=0;j<a_column;j++) { Ax+=A[i][j] * x_prev[j]; //Ax = Row(M) *1 } diff[i]=b[i]-Ax; //Ax-b = Row(M)*1 } for(int i=0;i<a_column;i++) { double AtAx_B=0; for(int j=0;j<a_row;j++) { AtAx_B += A[j][i] * diff[j]; } x[i]=x_prev[i]+(relaxation * AtAx_B); } //inform main window for availability if(((main_iterator+1)%this->whentoshow)==0) { if(*pX==NULL) { //if it is empty create it first *pX = new double[a_column]; } //copy the image value memcpy(*pX,x,sizeof(double)*x_row); //notify the main window emit updateReady(main_iterator+1); } //work out residual. rs=0; for(int z=0;z<x_row;z++) { rs +=fabs(this->maindrawingarea->matrix[z] - x[z]); } emit singleiteration(main_iterator+1,rs); } }
26.084746
99
0.565627
drminix
40203db47ac7f7ebe9ed5b73ddf8f75e00a5176e
3,743
cc
C++
DreamDaq/dream_to_offline/DreamDaqEventUnpacker.cc
ivivarel/DREMTubes
ac768990b4c5e2c23d986284ed10189f31796b38
[ "MIT" ]
3
2021-07-22T12:17:48.000Z
2021-07-27T07:22:54.000Z
DreamDaq/dream_to_offline/DreamDaqEventUnpacker.cc
ivivarel/DREMTubes
ac768990b4c5e2c23d986284ed10189f31796b38
[ "MIT" ]
38
2021-07-14T15:41:04.000Z
2022-03-29T14:18:20.000Z
DreamDaq/dream_to_offline/DreamDaqEventUnpacker.cc
ivivarel/DREMTubes
ac768990b4c5e2c23d986284ed10189f31796b38
[ "MIT" ]
7
2021-07-21T12:00:33.000Z
2021-11-13T10:45:30.000Z
#include <cassert> #include <cstdio> #include "DreamDaqEventUnpacker.hh" #include "DreamDaqEvent.h" #include "DaqModuleUnpackers.hh" #include "myFIFO-IOp.h" #include "myRawFile.h" DreamDaqEventUnpacker::DreamDaqEventUnpacker() : event_(0) { } DreamDaqEventUnpacker::DreamDaqEventUnpacker(DreamDaqEvent* event) : event_(0) { setDreamDaqEvent(event); } DreamDaqEventUnpacker::~DreamDaqEventUnpacker() { } void DreamDaqEventUnpacker::setDreamDaqEvent(DreamDaqEvent* event) { packSeq_.clear(); if (event) { // The sequence of unpackers does not matter. // The sequence of packers can be made correct // by calling the "setPackingSequence" method. packSeq_.push_back(std::make_pair(&event->TDC_0, &LeCroy1176_)); packSeq_.push_back(std::make_pair(&event->ADC_C1, &CaenV792_)); packSeq_.push_back(std::make_pair(&event->ADC_C2, &CaenV792_)); packSeq_.push_back(std::make_pair(&event->ADC_L, &LeCroy1182_)); packSeq_.push_back(std::make_pair(&event->SCA_0, &CaenV260_)); packSeq_.push_back(std::make_pair(&event->SCOPE_0, &TDS7254B_)); packSeq_.push_back(std::make_pair(&event->TSENS, &TemperatureSensors_)); } event_ = event; } int DreamDaqEventUnpacker::setPackingSequence( const unsigned *subEventIds, unsigned nIds) { UnpakerSequence ordered; const unsigned n_packers = packSeq_.size(); int missing_packer = 0; for (unsigned i=0; i<nIds; ++i) { const unsigned id = subEventIds[i]; unsigned packer_found = 0; for (unsigned j=0; j<n_packers; ++j) { DreamDaqModule *module = packSeq_[j].first; if (module->subEventId() == id) { packer_found = 1; ordered.push_back(packSeq_[j]); break; } } if (!packer_found) { fprintf(stderr, "Failed to find unpacker for sub event id 0x%08x\n", id); fflush(stderr); missing_packer++; } } packSeq_ = ordered; return missing_packer; } int DreamDaqEventUnpacker::unpack(unsigned *eventData) const { int status = 0; for (unsigned i=0; i<packSeq_.size(); ++i) { DreamDaqModule *module = packSeq_[i].first; const int ustat = packSeq_[i].second->unpack( event_->formatVersion, module, eventData); if (ustat == NODATA) module->setEnabled(false); else { module->setEnabled(true); if (ustat) status = 1; } } return status; } int DreamDaqEventUnpacker::pack(unsigned *buf, unsigned buflen) const { // Create the event header EventHeader evh; evh.evmark = EVENTMARKER; evh.evhsiz = sizeof(EventHeader); evh.evnum = event_->eventNumber; evh.spill = event_->spillNumber; evh.tsec = event_->timeSec; evh.tusec = event_->timeUSec; // Pack the event header int wordcount = sizeof(EventHeader)/sizeof(unsigned); assert(buflen > (unsigned)wordcount); memcpy(buf, &evh, sizeof(EventHeader)); // Pack the modules for (unsigned i=0; i<packSeq_.size(); ++i) { DreamDaqModule *module = packSeq_[i].first; if (module->enabled()) { int sz = packSeq_[i].second->pack( event_->formatVersion, module, buf+wordcount, buflen-wordcount); if (sz < 0) return sz; else wordcount += sz; } } // Set the correct event size (in bytes) buf[offsetof(EventHeader, evsiz)/sizeof(unsigned)] = wordcount*sizeof(unsigned); return wordcount; }
27.522059
85
0.604862
ivivarel
4021b6e5c0aafd3d6d9ab3325cc50dec47e6877b
4,904
hpp
C++
inc/core/setst.hpp
frang75/nappgui
fffa48d0f93f0b7db4e547838b33b625d19c2430
[ "MIT" ]
25
2020-01-31T09:23:45.000Z
2022-02-01T04:46:32.000Z
inc/core/setst.hpp
frang75/nappgui
fffa48d0f93f0b7db4e547838b33b625d19c2430
[ "MIT" ]
2
2021-10-20T13:05:18.000Z
2021-11-26T08:24:31.000Z
inc/core/setst.hpp
frang75/nappgui
fffa48d0f93f0b7db4e547838b33b625d19c2430
[ "MIT" ]
1
2020-01-31T09:22:16.000Z
2020-01-31T09:22:16.000Z
/* * NAppGUI Cross-platform C SDK * 2015-2021 Francisco Garcia Collado * MIT Licence * https://nappgui.com/en/legal/license.html * * File: setst.hpp * */ /* Set of structures */ #ifndef __SETST_HPP__ #define __SETST_HPP__ #include "bstd.h" #include "nowarn.hxx" #include <typeinfo> #include "warn.hxx" template<class type> struct SetSt { static SetSt<type>* create(int(func_compare)(const type*, const type*)); static void destroy(SetSt<type> **set, void(*func_remove)(type*)); static uint32_t size(const SetSt<type> *set); static type* get(SetSt<type> *set, const type *key); static const type* get(const SetSt<type> *set, const type *key); static bool_t ddelete(SetSt<type> *set, const type *key, void(*func_remove)(type*)); static type* first(SetSt<type> *set); static const type* first(const SetSt<type> *set); static type* last(SetSt<type> *set); static const type* last(const SetSt<type> *set); static type* next(SetSt<type> *set); static const type* next(const SetSt<type> *set); static type* prev(SetSt<type> *set); static const type* prev(const SetSt<type> *set); #if defined __ASSERTS__ // Only for debuggers inspector (non used) template<class ttype> struct TypeNode { uint32_t rb; struct TypeNode<ttype> *left; struct TypeNode<ttype> *right; ttype data; }; uint32_t elems; uint16_t esize; uint16_t ksize; TypeNode<type> *root; FPtr_compare func_compare; #endif }; /*---------------------------------------------------------------------------*/ template<typename type> static const char_t* i_settype(void) { static char_t dtype[64]; bstd_sprintf(dtype, sizeof(dtype), "SetSt<%s>", typeid(type).name()); return dtype; } /*---------------------------------------------------------------------------*/ template<typename type> SetSt<type>* SetSt<type>::create(int(func_compare)(const type*, const type*)) { return (SetSt<type>*)rbtree_create((FPtr_compare)func_compare, (uint16_t)sizeof(type), 0, i_settype<type>()); } /*---------------------------------------------------------------------------*/ template<typename type> void SetSt<type>::destroy(SetSt<type> **set, void(*func_remove)(type*)) { rbtree_destroy((RBTree**)set, (FPtr_remove)func_remove, NULL, i_settype<type>()); } /*---------------------------------------------------------------------------*/ template<typename type> uint32_t SetSt<type>::size(const SetSt<type> *set) { return rbtree_size((const RBTree*)set); } /*---------------------------------------------------------------------------*/ template<typename type> type* SetSt<type>::get(SetSt<type> *set, const type *key) { return (type*)rbtree_get((RBTree*)set, (const void*)key, FALSE); } /*---------------------------------------------------------------------------*/ template<typename type> const type* SetSt<type>::get(const SetSt<type> *set, const type *key) { return (const type*)rbtree_get((RBTree*)set, (const void*)key, FALSE); } /*---------------------------------------------------------------------------*/ template<typename type> bool_t SetSt<type>::ddelete(SetSt<type> *set, const type *key, void(*func_remove)(type*)) { return rbtree_delete((RBTree*)set, (const void*)key, (FPtr_remove)func_remove, NULL); } /*---------------------------------------------------------------------------*/ template<typename type> type* SetSt<type>::first(SetSt<type> *set) { return (type*)rbtree_first((RBTree*)set); } /*---------------------------------------------------------------------------*/ template<typename type> const type* SetSt<type>::first(const SetSt<type> *set) { return (const type*)rbtree_first((RBTree*)set); } /*---------------------------------------------------------------------------*/ template<typename type> type* SetSt<type>::last(SetSt<type> *set) { return (type*)rbtree_last((RBTree*)set); } /*---------------------------------------------------------------------------*/ template<typename type> const type* SetSt<type>::last(const SetSt<type> *set) { return (const type*)rbtree_last((RBTree*)set); } /*---------------------------------------------------------------------------*/ template<typename type> type* SetSt<type>::next(SetSt<type> *set) { return (type*)rbtree_next((RBTree*)set); } /*---------------------------------------------------------------------------*/ template<typename type> const type* SetSt<type>::next(const SetSt<type> *set) { return (const type*)rbtree_next((RBTree*)set); } /*---------------------------------------------------------------------------*/ template<typename type> type* SetSt<type>::prev(SetSt<type> *set) { return (type*)rbtree_prev((RBTree*)set); } /*---------------------------------------------------------------------------*/ template<typename type> const type* SetSt<type>::prev(const SetSt<type> *set) { return (const type*)rbtree_prev((RBTree*)set); } #endif
25.278351
113
0.530995
frang75
4022f37b7207ac5266e1e55f48ac59a382285560
700
cpp
C++
cpp/types_is_pointer_interconvertible_with_class.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
cpp/types_is_pointer_interconvertible_with_class.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
cpp/types_is_pointer_interconvertible_with_class.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
/* # g++ --std=c++20 -pthread -o ../_build/cpp/types_is_pointer_interconvertible_with_class.exe ./cpp/types_is_pointer_interconvertible_with_class.cpp && (cd ../_build/cpp/;./types_is_pointer_interconvertible_with_class.exe) https://en.cppreference.com/w/cpp/types/is_pointer_interconvertible_with_class */ #include <type_traits> #include <iostream> struct Foo { int x; }; struct Bar { int y; }; struct Baz : Foo, Bar {}; // not standard-layout int main() { std::cout << std::boolalpha << std::is_same_v<decltype(&Baz::x), int Baz::*> << std::is_pointer_interconvertible_with_class(&Baz::x) << '\n' << std::is_pointer_interconvertible_with_class<Baz>(&Baz::x) << '\n'; }
38.888889
221
0.7
rpuntaie
4024bd8f28e7e99e89a77318e4df297a76cfceda
3,779
cpp
C++
src/it/resources/expected/my_record/cwrapper/dh__map_string_int32_t.cpp
mutagene/djinni-generator
09b420537183e0f941ae55afbf15d72c3f8b76a1
[ "Apache-2.0" ]
60
2020-10-17T18:05:37.000Z
2022-03-14T22:58:27.000Z
src/it/resources/expected/my_record/cwrapper/dh__map_string_int32_t.cpp
mutagene/djinni-generator
09b420537183e0f941ae55afbf15d72c3f8b76a1
[ "Apache-2.0" ]
85
2020-10-13T21:58:40.000Z
2022-03-16T09:29:01.000Z
src/it/resources/expected/my_record/cwrapper/dh__map_string_int32_t.cpp
mutagene/djinni-generator
09b420537183e0f941ae55afbf15d72c3f8b76a1
[ "Apache-2.0" ]
24
2020-10-16T21:22:31.000Z
2022-03-02T18:15:29.000Z
// AUTOGENERATED FILE - DO NOT MODIFY! // This file was generated by Djinni from my_record.djinni #include <iostream> // for debugging #include <cassert> #include "djinni/cwrapper/wrapper_marshal.hpp" #include "../cpp-headers/my_record.hpp" #include "dh__map_string_int32_t.hpp" #include "dh__my_record.hpp" #include "dh__set_string.hpp" static void(*s_callback_map_string_int32_t___delete)(DjinniObjectHandle *); void map_string_int32_t_add_callback___delete(void(* ptr)(DjinniObjectHandle *)) { s_callback_map_string_int32_t___delete = ptr; } void map_string_int32_t___delete(DjinniObjectHandle * drh) { s_callback_map_string_int32_t___delete(drh); } void optional_map_string_int32_t___delete(DjinniOptionalObjectHandle * drh) { s_callback_map_string_int32_t___delete((DjinniObjectHandle *) drh); } static int32_t ( * s_callback_map_string_int32_t__get_value)(DjinniObjectHandle *, DjinniString *); void map_string_int32_t_add_callback__get_value(int32_t( * ptr)(DjinniObjectHandle *, DjinniString *)) { s_callback_map_string_int32_t__get_value = ptr; } static size_t ( * s_callback_map_string_int32_t__get_size)(DjinniObjectHandle *); void map_string_int32_t_add_callback__get_size(size_t( * ptr)(DjinniObjectHandle *)) { s_callback_map_string_int32_t__get_size = ptr; } static DjinniObjectHandle * ( * s_callback_map_string_int32_t__create)(void); void map_string_int32_t_add_callback__create(DjinniObjectHandle *( * ptr)(void)) { s_callback_map_string_int32_t__create = ptr; } static void ( * s_callback_map_string_int32_t__add)(DjinniObjectHandle *, DjinniString *, int32_t); void map_string_int32_t_add_callback__add(void( * ptr)(DjinniObjectHandle *, DjinniString *, int32_t)) { s_callback_map_string_int32_t__add = ptr; } static DjinniString * ( * s_callback_map_string_int32_t__next)(DjinniObjectHandle *); void map_string_int32_t_add_callback__next(DjinniString *( * ptr)(DjinniObjectHandle *)) { s_callback_map_string_int32_t__next = ptr; } djinni::Handle<DjinniObjectHandle> DjinniMapStringInt32T::fromCpp(const std::unordered_map<std::string, int32_t> & dc) { djinni::Handle<DjinniObjectHandle> _handle(s_callback_map_string_int32_t__create(), & map_string_int32_t___delete); for (const auto & it : dc) { auto _key = DjinniString::fromCpp(it.first); s_callback_map_string_int32_t__add(_handle.get(), _key.release(), it.second); } return _handle; } std::unordered_map<std::string, int32_t> DjinniMapStringInt32T::toCpp(djinni::Handle<DjinniObjectHandle> dh) { std::unordered_map<std::string, int32_t>_ret; size_t size = s_callback_map_string_int32_t__get_size(dh.get()); for (int i = 0; i < size; i++) { auto _key_c = std::unique_ptr<DjinniString>(s_callback_map_string_int32_t__next(dh.get())); // key that would potentially be surrounded by unique pointer auto _val = s_callback_map_string_int32_t__get_value(dh.get(), _key_c.get()); auto _key = DjinniString::toCpp(std::move(_key_c)); _ret.emplace(std::move(_key), std::move(_val)); } return _ret; } djinni::Handle<DjinniOptionalObjectHandle> DjinniMapStringInt32T::fromCpp(std::optional<std::unordered_map<std::string, int32_t>> dc) { if (!dc) { return nullptr; } return djinni::optionals::toOptionalHandle(DjinniMapStringInt32T::fromCpp(std::move(* dc)), optional_map_string_int32_t___delete); } std::optional<std::unordered_map<std::string, int32_t>>DjinniMapStringInt32T::toCpp(djinni::Handle<DjinniOptionalObjectHandle> dh) { if (dh) { return std::optional<std::unordered_map<std::string, int32_t>>(DjinniMapStringInt32T::toCpp(djinni::optionals::fromOptionalHandle(std::move(dh), map_string_int32_t___delete))); } return {}; }
40.634409
184
0.767399
mutagene
40257420d09a9d8802142b66e2fde1874bb642c4
59,307
cpp
C++
OgreMain/src/OgreRenderSystem.cpp
FreeNightKnight/ogre-next
f2d1a31887a87c492b4225e063325c48693fec19
[ "MIT" ]
null
null
null
OgreMain/src/OgreRenderSystem.cpp
FreeNightKnight/ogre-next
f2d1a31887a87c492b4225e063325c48693fec19
[ "MIT" ]
null
null
null
OgreMain/src/OgreRenderSystem.cpp
FreeNightKnight/ogre-next
f2d1a31887a87c492b4225e063325c48693fec19
[ "MIT" ]
null
null
null
/* ----------------------------------------------------------------------------- This source file is part of OGRE-Next (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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 "OgreStableHeaders.h" // RenderSystem implementation // Note that most of this class is abstract since // we cannot know how to implement the behaviour without // being aware of the 3D API. However there are a few // simple functions which can have a base implementation #include "OgreRenderSystem.h" #include "Compositor/OgreCompositorManager2.h" #include "Compositor/OgreCompositorWorkspace.h" #include "OgreDepthBuffer.h" #include "OgreDescriptorSetUav.h" #include "OgreException.h" #include "OgreHardwareOcclusionQuery.h" #include "OgreHlmsPso.h" #include "OgreIteratorWrappers.h" #include "OgreLogManager.h" #include "OgreLwString.h" #include "OgreMaterialManager.h" #include "OgreProfiler.h" #include "OgreRoot.h" #include "OgreTextureGpuManager.h" #include "OgreViewport.h" #include "OgreWindow.h" #include "Vao/OgreUavBufferPacked.h" #include "Vao/OgreVaoManager.h" #include "Vao/OgreVertexArrayObject.h" #if OGRE_NO_RENDERDOC_INTEGRATION == 0 # include "renderdoc/renderdoc_app.h" # if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 # define WIN32_LEAN_AND_MEAN # define VC_EXTRALEAN # define NOMINMAX # include <windows.h> # endif #endif namespace Ogre { RenderSystem::ListenerList RenderSystem::msSharedEventListeners; //----------------------------------------------------------------------- RenderSystem::RenderSystem() : mCurrentRenderPassDescriptor( 0 ), mMaxBoundViewports( 16u ), mVaoManager( 0 ), mTextureGpuManager( 0 ) #if OGRE_DEBUG_MODE >= OGRE_DEBUG_HIGH , mDebugShaders( true ) #else , mDebugShaders( false ) #endif , mWBuffer( false ), mInvertVertexWinding( false ), mDisabledTexUnitsFrom( 0 ), mCurrentPassIterationCount( 0 ), mCurrentPassIterationNum( 0 ), mDerivedDepthBias( false ), mDerivedDepthBiasBase( 0.0f ), mDerivedDepthBiasMultiplier( 0.0f ), mDerivedDepthBiasSlopeScale( 0.0f ), mUavRenderingDirty( false ), mUavStartingSlot( 1 ), mUavRenderingDescSet( 0 ), mGlobalInstanceVertexBufferVertexDeclaration( NULL ), mGlobalNumberOfInstances( 1 ), mRenderDocApi( 0 ), mVertexProgramBound( false ), mGeometryProgramBound( false ), mFragmentProgramBound( false ), mTessellationHullProgramBound( false ), mTessellationDomainProgramBound( false ), mComputeProgramBound( false ), mClipPlanesDirty( true ), mRealCapabilities( 0 ), mCurrentCapabilities( 0 ), mUseCustomCapabilities( false ), mNativeShadingLanguageVersion( 0 ), mTexProjRelative( false ), mTexProjRelativeOrigin( Vector3::ZERO ), mReverseDepth( true ), mInvertedClipSpaceY( false ) { mEventNames.push_back( "RenderSystemCapabilitiesCreated" ); } //----------------------------------------------------------------------- RenderSystem::~RenderSystem() { shutdown(); OGRE_DELETE mRealCapabilities; mRealCapabilities = 0; // Current capabilities managed externally mCurrentCapabilities = 0; } //----------------------------------------------------------------------- Window *RenderSystem::_initialise( bool autoCreateWindow, const String &windowTitle ) { // Have I been registered by call to Root::setRenderSystem? /** Don't do this anymore, just allow via Root RenderSystem* regPtr = Root::getSingleton().getRenderSystem(); if (!regPtr || regPtr != this) // Register self - library user has come to me direct Root::getSingleton().setRenderSystem(this); */ // Subclasses should take it from here // They should ALL call this superclass method from // their own initialise() implementations. mVertexProgramBound = false; mGeometryProgramBound = false; mFragmentProgramBound = false; mTessellationHullProgramBound = false; mTessellationDomainProgramBound = false; mComputeProgramBound = false; return 0; } //--------------------------------------------------------------------------------------------- void RenderSystem::useCustomRenderSystemCapabilities( RenderSystemCapabilities *capabilities ) { if( mRealCapabilities != 0 ) { OGRE_EXCEPT( Exception::ERR_INTERNAL_ERROR, "Custom render capabilities must be set before the RenderSystem is initialised.", "RenderSystem::useCustomRenderSystemCapabilities" ); } mCurrentCapabilities = capabilities; mUseCustomCapabilities = true; } //--------------------------------------------------------------------------------------------- bool RenderSystem::_createRenderWindows( const RenderWindowDescriptionList &renderWindowDescriptions, WindowList &createdWindows ) { unsigned int fullscreenWindowsCount = 0; // Grab some information and avoid duplicate render windows. for( unsigned int nWindow = 0; nWindow < renderWindowDescriptions.size(); ++nWindow ) { const RenderWindowDescription *curDesc = &renderWindowDescriptions[nWindow]; // Count full screen windows. if( curDesc->useFullScreen ) fullscreenWindowsCount++; bool renderWindowFound = false; for( unsigned int nSecWindow = nWindow + 1; nSecWindow < renderWindowDescriptions.size(); ++nSecWindow ) { if( curDesc->name == renderWindowDescriptions[nSecWindow].name ) { renderWindowFound = true; break; } } // Make sure we don't already have a render target of the // same name as the one supplied if( renderWindowFound ) { String msg; msg = "A render target of the same name '" + String( curDesc->name ) + "' already " "exists. You cannot create a new window with this name."; OGRE_EXCEPT( Exception::ERR_INTERNAL_ERROR, msg, "RenderSystem::createRenderWindow" ); } } // Case we have to create some full screen rendering windows. if( fullscreenWindowsCount > 0 ) { // Can not mix full screen and windowed rendering windows. if( fullscreenWindowsCount != renderWindowDescriptions.size() ) { OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Can not create mix of full screen and windowed rendering windows", "RenderSystem::createRenderWindows" ); } } return true; } //--------------------------------------------------------------------------------------------- void RenderSystem::destroyRenderWindow( Window *window ) { WindowSet::iterator itor = mWindows.find( window ); if( itor == mWindows.end() ) { OGRE_EXCEPT( Exception::ERR_ITEM_NOT_FOUND, "Window does not belong to us or is already deleted!", "RenderSystem::destroyRenderWindow" ); } mWindows.erase( window ); OGRE_DELETE window; } //----------------------------------------------------------------------- void RenderSystem::_setPipelineStateObject( const HlmsPso *pso ) { assert( ( !pso || pso->rsData ) && "The PipelineStateObject must have been created via " "RenderSystem::_hlmsPipelineStateObjectCreated!" ); // Disable previous state mActiveVertexGpuProgramParameters.reset(); mActiveGeometryGpuProgramParameters.reset(); mActiveTessellationHullGpuProgramParameters.reset(); mActiveTessellationDomainGpuProgramParameters.reset(); mActiveFragmentGpuProgramParameters.reset(); mActiveComputeGpuProgramParameters.reset(); if( mVertexProgramBound && !mClipPlanes.empty() ) mClipPlanesDirty = true; mVertexProgramBound = false; mGeometryProgramBound = false; mFragmentProgramBound = false; mTessellationHullProgramBound = false; mTessellationDomainProgramBound = false; mComputeProgramBound = false; // Derived class must set new state } //----------------------------------------------------------------------- void RenderSystem::_setTextureUnitSettings( size_t texUnit, TextureUnitState &tl ) { // This method is only ever called to set a texture unit to valid details // The method _disableTextureUnit is called to turn a unit off TextureGpu *tex = tl._getTexturePtr(); bool isValidBinding = false; if( mCurrentCapabilities->hasCapability( RSC_COMPLETE_TEXTURE_BINDING ) ) _setBindingType( tl.getBindingType() ); // Vertex texture binding? if( mCurrentCapabilities->hasCapability( RSC_VERTEX_TEXTURE_FETCH ) && !mCurrentCapabilities->getVertexTextureUnitsShared() ) { isValidBinding = true; if( tl.getBindingType() == TextureUnitState::BT_VERTEX ) { // Bind vertex texture _setVertexTexture( texUnit, tex ); // bind nothing to fragment unit (hardware isn't shared but fragment // unit can't be using the same index _setTexture( texUnit, 0, false ); } else { // vice versa _setVertexTexture( texUnit, 0 ); _setTexture( texUnit, tex, mCurrentRenderPassDescriptor->mDepth.texture && mCurrentRenderPassDescriptor->mDepth.texture == tex ); } } if( mCurrentCapabilities->hasCapability( RSC_GEOMETRY_PROGRAM ) ) { isValidBinding = true; if( tl.getBindingType() == TextureUnitState::BT_GEOMETRY ) { // Bind vertex texture _setGeometryTexture( texUnit, tex ); // bind nothing to fragment unit (hardware isn't shared but fragment // unit can't be using the same index _setTexture( texUnit, 0, false ); } else { // vice versa _setGeometryTexture( texUnit, 0 ); _setTexture( texUnit, tex, mCurrentRenderPassDescriptor->mDepth.texture && mCurrentRenderPassDescriptor->mDepth.texture == tex ); } } if( mCurrentCapabilities->hasCapability( RSC_TESSELLATION_DOMAIN_PROGRAM ) ) { isValidBinding = true; if( tl.getBindingType() == TextureUnitState::BT_TESSELLATION_DOMAIN ) { // Bind vertex texture _setTessellationDomainTexture( texUnit, tex ); // bind nothing to fragment unit (hardware isn't shared but fragment // unit can't be using the same index _setTexture( texUnit, 0, false ); } else { // vice versa _setTessellationDomainTexture( texUnit, 0 ); _setTexture( texUnit, tex, mCurrentRenderPassDescriptor->mDepth.texture && mCurrentRenderPassDescriptor->mDepth.texture == tex ); } } if( mCurrentCapabilities->hasCapability( RSC_TESSELLATION_HULL_PROGRAM ) ) { isValidBinding = true; if( tl.getBindingType() == TextureUnitState::BT_TESSELLATION_HULL ) { // Bind vertex texture _setTessellationHullTexture( texUnit, tex ); // bind nothing to fragment unit (hardware isn't shared but fragment // unit can't be using the same index _setTexture( texUnit, 0, false ); } else { // vice versa _setTessellationHullTexture( texUnit, 0 ); _setTexture( texUnit, tex, mCurrentRenderPassDescriptor->mDepth.texture && mCurrentRenderPassDescriptor->mDepth.texture == tex ); } } if( !isValidBinding ) { // Shared vertex / fragment textures or no vertex texture support // Bind texture (may be blank) _setTexture( texUnit, tex, mCurrentRenderPassDescriptor->mDepth.texture && mCurrentRenderPassDescriptor->mDepth.texture == tex ); } _setHlmsSamplerblock( (uint8)texUnit, tl.getSamplerblock() ); // Set blend modes // Note, colour before alpha is important _setTextureBlendMode( texUnit, tl.getColourBlendMode() ); _setTextureBlendMode( texUnit, tl.getAlphaBlendMode() ); // Set texture effects TextureUnitState::EffectMap::iterator effi; // Iterate over new effects bool anyCalcs = false; for( effi = tl.mEffects.begin(); effi != tl.mEffects.end(); ++effi ) { switch( effi->second.type ) { case TextureUnitState::ET_ENVIRONMENT_MAP: if( effi->second.subtype == TextureUnitState::ENV_CURVED ) { _setTextureCoordCalculation( texUnit, TEXCALC_ENVIRONMENT_MAP ); anyCalcs = true; } else if( effi->second.subtype == TextureUnitState::ENV_PLANAR ) { _setTextureCoordCalculation( texUnit, TEXCALC_ENVIRONMENT_MAP_PLANAR ); anyCalcs = true; } else if( effi->second.subtype == TextureUnitState::ENV_REFLECTION ) { _setTextureCoordCalculation( texUnit, TEXCALC_ENVIRONMENT_MAP_REFLECTION ); anyCalcs = true; } else if( effi->second.subtype == TextureUnitState::ENV_NORMAL ) { _setTextureCoordCalculation( texUnit, TEXCALC_ENVIRONMENT_MAP_NORMAL ); anyCalcs = true; } break; case TextureUnitState::ET_UVSCROLL: case TextureUnitState::ET_USCROLL: case TextureUnitState::ET_VSCROLL: case TextureUnitState::ET_ROTATE: case TextureUnitState::ET_TRANSFORM: break; case TextureUnitState::ET_PROJECTIVE_TEXTURE: _setTextureCoordCalculation( texUnit, TEXCALC_PROJECTIVE_TEXTURE, effi->second.frustum ); anyCalcs = true; break; } } // Ensure any previous texcoord calc settings are reset if there are now none if( !anyCalcs ) { _setTextureCoordCalculation( texUnit, TEXCALC_NONE ); } // Change tetxure matrix _setTextureMatrix( texUnit, tl.getTextureTransform() ); } //----------------------------------------------------------------------- void RenderSystem::_setBindingType( TextureUnitState::BindingType bindingType ) { OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED, "This rendersystem does not support binding texture to other shaders then fragment", "RenderSystem::_setBindingType" ); } //----------------------------------------------------------------------- void RenderSystem::_setVertexTexture( size_t unit, TextureGpu *tex ) { OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED, "This rendersystem does not support separate vertex texture samplers, " "you should use the regular texture samplers which are shared between " "the vertex and fragment units.", "RenderSystem::_setVertexTexture" ); } //----------------------------------------------------------------------- void RenderSystem::_setGeometryTexture( size_t unit, TextureGpu *tex ) { OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED, "This rendersystem does not support separate geometry texture samplers, " "you should use the regular texture samplers which are shared between " "the vertex and fragment units.", "RenderSystem::_setGeometryTexture" ); } //----------------------------------------------------------------------- void RenderSystem::_setTessellationHullTexture( size_t unit, TextureGpu *tex ) { OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED, "This rendersystem does not support separate tessellation hull texture samplers, " "you should use the regular texture samplers which are shared between " "the vertex and fragment units.", "RenderSystem::_setTessellationHullTexture" ); } //----------------------------------------------------------------------- void RenderSystem::_setTessellationDomainTexture( size_t unit, TextureGpu *tex ) { OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED, "This rendersystem does not support separate tessellation domain texture samplers, " "you should use the regular texture samplers which are shared between " "the vertex and fragment units.", "RenderSystem::_setTessellationDomainTexture" ); } //----------------------------------------------------------------------- void RenderSystem::destroyRenderPassDescriptor( RenderPassDescriptor *renderPassDesc ) { RenderPassDescriptorSet::iterator itor = mRenderPassDescs.find( renderPassDesc ); assert( itor != mRenderPassDescs.end() && "Already destroyed?" ); if( itor != mRenderPassDescs.end() ) mRenderPassDescs.erase( itor ); if( renderPassDesc->mDepth.texture ) { _dereferenceSharedDepthBuffer( renderPassDesc->mDepth.texture ); if( renderPassDesc->mStencil.texture && renderPassDesc->mStencil.texture == renderPassDesc->mDepth.texture ) { _dereferenceSharedDepthBuffer( renderPassDesc->mStencil.texture ); renderPassDesc->mStencil.texture = 0; } } if( renderPassDesc->mStencil.texture ) { _dereferenceSharedDepthBuffer( renderPassDesc->mStencil.texture ); renderPassDesc->mStencil.texture = 0; } delete renderPassDesc; } //--------------------------------------------------------------------- void RenderSystem::destroyAllRenderPassDescriptors() { RenderPassDescriptorSet::const_iterator itor = mRenderPassDescs.begin(); RenderPassDescriptorSet::const_iterator endt = mRenderPassDescs.end(); while( itor != endt ) delete *itor++; mRenderPassDescs.clear(); } //--------------------------------------------------------------------- void RenderSystem::beginRenderPassDescriptor( RenderPassDescriptor *desc, TextureGpu *anyTarget, uint8 mipLevel, const Vector4 *viewportSizes, const Vector4 *scissors, uint32 numViewports, bool overlaysEnabled, bool warnIfRtvWasFlushed ) { assert( anyTarget ); mCurrentRenderPassDescriptor = desc; for( size_t i = 0; i < numViewports; ++i ) { mCurrentRenderViewport[i].setDimensions( anyTarget, viewportSizes[i], scissors[i], mipLevel ); mCurrentRenderViewport[i].setOverlaysEnabled( overlaysEnabled ); } mMaxBoundViewports = numViewports; } //--------------------------------------------------------------------- void RenderSystem::executeRenderPassDescriptorDelayedActions() {} //--------------------------------------------------------------------- void RenderSystem::endRenderPassDescriptor() { mCurrentRenderPassDescriptor = 0; const size_t maxBoundViewports = mMaxBoundViewports; for( size_t i = 0; i < maxBoundViewports; ++i ) mCurrentRenderViewport[i].setDimensions( 0, Vector4::ZERO, Vector4::ZERO, 0u ); mMaxBoundViewports = 1u; // Where graphics ends, compute may start, or a new frame. // Very likely we'll have to flush the UAVs again, so assume we need. mUavRenderingDirty = true; } //--------------------------------------------------------------------- void RenderSystem::destroySharedDepthBuffer( TextureGpu *depthBuffer ) { TextureGpuVec &bufferVec = mDepthBufferPool2[depthBuffer->getDepthBufferPoolId()]; TextureGpuVec::iterator itor = std::find( bufferVec.begin(), bufferVec.end(), depthBuffer ); if( itor != bufferVec.end() ) { efficientVectorRemove( bufferVec, itor ); mTextureGpuManager->destroyTexture( depthBuffer ); } } //--------------------------------------------------------------------- void RenderSystem::_cleanupDepthBuffers() { TextureGpuSet::const_iterator itor = mSharedDepthBufferZeroRefCandidates.begin(); TextureGpuSet::const_iterator endt = mSharedDepthBufferZeroRefCandidates.end(); while( itor != endt ) { // When a shared depth buffer ends up in mSharedDepthBufferZeroRefCandidates, // it's because its ref. count reached 0. However it may have been reacquired. // We need to check its reference count is still 0 before deleting it. DepthBufferRefMap::iterator itMap = mSharedDepthBufferRefs.find( *itor ); if( itMap != mSharedDepthBufferRefs.end() && itMap->second == 0u ) { destroySharedDepthBuffer( *itor ); mSharedDepthBufferRefs.erase( itMap ); } ++itor; } mSharedDepthBufferZeroRefCandidates.clear(); } //--------------------------------------------------------------------- void RenderSystem::referenceSharedDepthBuffer( TextureGpu *depthBuffer ) { OGRE_ASSERT_MEDIUM( depthBuffer->getSourceType() == TextureSourceType::SharedDepthBuffer ); OGRE_ASSERT_MEDIUM( mSharedDepthBufferRefs.find( depthBuffer ) != mSharedDepthBufferRefs.end() ); ++mSharedDepthBufferRefs[depthBuffer]; } //--------------------------------------------------------------------- void RenderSystem::_dereferenceSharedDepthBuffer( TextureGpu *depthBuffer ) { if( !depthBuffer ) return; DepthBufferRefMap::iterator itor = mSharedDepthBufferRefs.find( depthBuffer ); if( itor != mSharedDepthBufferRefs.end() ) { OGRE_ASSERT_MEDIUM( depthBuffer->getSourceType() == TextureSourceType::SharedDepthBuffer ); OGRE_ASSERT_LOW( itor->second > 0u && "Releasing a shared depth buffer too much" ); --itor->second; if( itor->second == 0u ) mSharedDepthBufferZeroRefCandidates.insert( depthBuffer ); } else { // This is not a shared depth buffer (e.g. one created by the user) OGRE_ASSERT_MEDIUM( depthBuffer->getSourceType() != TextureSourceType::SharedDepthBuffer ); } } //--------------------------------------------------------------------- void RenderSystem::selectDepthBufferFormat( const uint8 supportedFormats ) { if( ( DepthBuffer::AvailableDepthFormats & DepthBuffer::DFM_D32 ) && ( supportedFormats & DepthBuffer::DFM_D32 ) ) { if( DepthBuffer::AvailableDepthFormats & DepthBuffer::DFM_S8 ) DepthBuffer::DefaultDepthBufferFormat = PFG_D32_FLOAT_S8X24_UINT; else DepthBuffer::DefaultDepthBufferFormat = PFG_D32_FLOAT; } else if( DepthBuffer::AvailableDepthFormats & ( DepthBuffer::DFM_D32 | DepthBuffer::DFM_D24 ) && ( supportedFormats & DepthBuffer::DFM_D24 ) ) { if( DepthBuffer::AvailableDepthFormats & DepthBuffer::DFM_S8 ) DepthBuffer::DefaultDepthBufferFormat = PFG_D24_UNORM_S8_UINT; else DepthBuffer::DefaultDepthBufferFormat = PFG_D24_UNORM; } else if( DepthBuffer::AvailableDepthFormats & ( DepthBuffer::DFM_D32 | DepthBuffer::DFM_D24 | DepthBuffer::DFM_D16 ) && ( supportedFormats & DepthBuffer::DFM_D16 ) ) { DepthBuffer::DefaultDepthBufferFormat = PFG_D16_UNORM; } else DepthBuffer::DefaultDepthBufferFormat = PFG_NULL; } //--------------------------------------------------------------------- TextureGpu *RenderSystem::createDepthBufferFor( TextureGpu *colourTexture, bool preferDepthTexture, PixelFormatGpu depthBufferFormat, uint16 poolId ) { uint32 textureFlags = TextureFlags::RenderToTexture; if( !preferDepthTexture ) textureFlags |= TextureFlags::NotTexture | TextureFlags::DiscardableContent; char tmpBuffer[64]; LwString depthBufferName( LwString::FromEmptyPointer( tmpBuffer, sizeof( tmpBuffer ) ) ); depthBufferName.a( "DepthBuffer_", Id::generateNewId<TextureGpu>() ); TextureGpu *retVal = mTextureGpuManager->createTexture( depthBufferName.c_str(), GpuPageOutStrategy::Discard, textureFlags, TextureTypes::Type2D ); retVal->setResolution( colourTexture->getInternalWidth(), colourTexture->getInternalHeight() ); retVal->setPixelFormat( depthBufferFormat ); retVal->_setDepthBufferDefaults( poolId, preferDepthTexture, depthBufferFormat ); retVal->_setSourceType( TextureSourceType::SharedDepthBuffer ); retVal->setSampleDescription( colourTexture->getRequestedSampleDescription() ); retVal->_transitionTo( GpuResidency::Resident, (uint8 *)0 ); // Start reference count on the depth buffer here mSharedDepthBufferRefs[retVal] = 1u; return retVal; } //--------------------------------------------------------------------- TextureGpu *RenderSystem::getDepthBufferFor( TextureGpu *colourTexture, uint16 poolId, bool preferDepthTexture, PixelFormatGpu depthBufferFormat ) { if( poolId == DepthBuffer::POOL_NO_DEPTH || depthBufferFormat == PFG_NULL ) return 0; // RenderTarget explicitly requested no depth buffer if( colourTexture->isRenderWindowSpecific() ) { Window *window; colourTexture->getCustomAttribute( "Window", &window ); return window->getDepthBuffer(); } if( poolId == DepthBuffer::POOL_NON_SHAREABLE ) { TextureGpu *retVal = createDepthBufferFor( colourTexture, preferDepthTexture, depthBufferFormat, poolId ); return retVal; } // Find a depth buffer in the pool TextureGpuVec::const_iterator itor = mDepthBufferPool2[poolId].begin(); TextureGpuVec::const_iterator endt = mDepthBufferPool2[poolId].end(); TextureGpu *retVal = 0; while( itor != endt && !retVal ) { if( preferDepthTexture == ( *itor )->isTexture() && ( depthBufferFormat == PFG_UNKNOWN || depthBufferFormat == ( *itor )->getPixelFormat() ) && ( *itor )->supportsAsDepthBufferFor( colourTexture ) ) { retVal = *itor; referenceSharedDepthBuffer( retVal ); } else { retVal = 0; } ++itor; } // Not found yet? Create a new one! if( !retVal ) { retVal = createDepthBufferFor( colourTexture, preferDepthTexture, depthBufferFormat, poolId ); mDepthBufferPool2[poolId].push_back( retVal ); if( !retVal ) { LogManager::getSingleton().logMessage( "WARNING: Couldn't create a suited " "DepthBuffer for RTT: " + colourTexture->getNameStr(), LML_CRITICAL ); } } return retVal; } //--------------------------------------------------------------------- void RenderSystem::setUavStartingSlot( uint32 startingSlot ) { mUavStartingSlot = startingSlot; mUavRenderingDirty = true; } //--------------------------------------------------------------------- void RenderSystem::queueBindUAVs( const DescriptorSetUav *descSetUav ) { if( mUavRenderingDescSet != descSetUav ) { mUavRenderingDescSet = descSetUav; mUavRenderingDirty = true; } } //----------------------------------------------------------------------- BoundUav RenderSystem::getBoundUav( size_t slot ) const { BoundUav retVal; memset( &retVal, 0, sizeof( retVal ) ); if( mUavRenderingDescSet ) { if( slot < mUavRenderingDescSet->mUavs.size() ) { if( mUavRenderingDescSet->mUavs[slot].isTexture() ) { retVal.rttOrBuffer = mUavRenderingDescSet->mUavs[slot].getTexture().texture; retVal.boundAccess = mUavRenderingDescSet->mUavs[slot].getTexture().access; } else { retVal.rttOrBuffer = mUavRenderingDescSet->mUavs[slot].getBuffer().buffer; retVal.boundAccess = mUavRenderingDescSet->mUavs[slot].getBuffer().access; } } } return retVal; } //----------------------------------------------------------------------- void RenderSystem::_beginFrameOnce() { mVaoManager->_beginFrame(); } //----------------------------------------------------------------------- void RenderSystem::_endFrameOnce() { queueBindUAVs( 0 ); } //----------------------------------------------------------------------- bool RenderSystem::getWBufferEnabled() const { return mWBuffer; } //----------------------------------------------------------------------- void RenderSystem::setWBufferEnabled( bool enabled ) { mWBuffer = enabled; } //----------------------------------------------------------------------- SampleDescription RenderSystem::validateSampleDescription( const SampleDescription &sampleDesc, PixelFormatGpu format ) { SampleDescription retVal( sampleDesc.getMaxSamples(), sampleDesc.getMsaaPattern() ); return retVal; } //----------------------------------------------------------------------- void RenderSystem::shutdown() { // Remove occlusion queries for( HardwareOcclusionQueryList::iterator i = mHwOcclusionQueries.begin(); i != mHwOcclusionQueries.end(); ++i ) { OGRE_DELETE *i; } mHwOcclusionQueries.clear(); destroyAllRenderPassDescriptors(); _cleanupDepthBuffers(); OGRE_ASSERT_LOW( mSharedDepthBufferRefs.empty() && "destroyAllRenderPassDescriptors followed by _cleanupDepthBuffers should've " "emptied mSharedDepthBufferRefs. Please report this bug to " "https://github.com/OGRECave/ogre-next/issues/" ); OGRE_DELETE mTextureGpuManager; mTextureGpuManager = 0; OGRE_DELETE mVaoManager; mVaoManager = 0; { // Remove all windows. // (destroy primary window last since others may depend on it) Window *primary = 0; WindowSet::const_iterator itor = mWindows.begin(); WindowSet::const_iterator endt = mWindows.end(); while( itor != endt ) { // Set mTextureManager to 0 as it is no longer valid on shutdown if( ( *itor )->getTexture() ) ( *itor )->getTexture()->_resetTextureManager(); if( ( *itor )->getDepthBuffer() ) ( *itor )->getDepthBuffer()->_resetTextureManager(); if( ( *itor )->getStencilBuffer() ) ( *itor )->getStencilBuffer()->_resetTextureManager(); if( !primary && ( *itor )->isPrimary() ) primary = *itor; else OGRE_DELETE *itor; ++itor; } OGRE_DELETE primary; mWindows.clear(); } } //----------------------------------------------------------------------- void RenderSystem::_resetMetrics() { const bool oldValue = mMetrics.mIsRecordingMetrics; mMetrics = RenderingMetrics(); mMetrics.mIsRecordingMetrics = oldValue; } //----------------------------------------------------------------------- void RenderSystem::_addMetrics( const RenderingMetrics &newMetrics ) { if( mMetrics.mIsRecordingMetrics ) { mMetrics.mBatchCount += newMetrics.mBatchCount; mMetrics.mFaceCount += newMetrics.mFaceCount; mMetrics.mVertexCount += newMetrics.mVertexCount; mMetrics.mDrawCount += newMetrics.mDrawCount; mMetrics.mInstanceCount += newMetrics.mInstanceCount; } } //----------------------------------------------------------------------- void RenderSystem::setMetricsRecordingEnabled( bool bEnable ) { mMetrics.mIsRecordingMetrics = bEnable; } //----------------------------------------------------------------------- const RenderingMetrics &RenderSystem::getMetrics() const { return mMetrics; } //----------------------------------------------------------------------- void RenderSystem::convertColourValue( const ColourValue &colour, uint32 *pDest ) { *pDest = v1::VertexElement::convertColourValue( colour, getColourVertexElementType() ); } //----------------------------------------------------------------------- CompareFunction RenderSystem::reverseCompareFunction( CompareFunction depthFunc ) { switch( depthFunc ) { case CMPF_LESS: return CMPF_GREATER; case CMPF_LESS_EQUAL: return CMPF_GREATER_EQUAL; case CMPF_GREATER_EQUAL: return CMPF_LESS_EQUAL; case CMPF_GREATER: return CMPF_LESS; default: return depthFunc; } return depthFunc; } //----------------------------------------------------------------------- void RenderSystem::_makeRsProjectionMatrix( const Matrix4 &matrix, Matrix4 &dest, Real nearPlane, Real farPlane, ProjectionType projectionType ) { dest = matrix; Real inv_d = 1 / ( farPlane - nearPlane ); Real q, qn; if( mReverseDepth ) { if( projectionType == PT_PERSPECTIVE ) { if( farPlane == 0 ) { // Infinite far plane // q = limit( near / (far - near), far, inf ); // qn = limit( (far * near) / (far - near), far, inf ); q = 0; qn = nearPlane; } else { // Standard Z for range [-1; 1] // q = - (far + near) / (far - near) // qn = - 2 * (far * near) / (far - near) // // Standard Z for range [0; 1] // q = - far / (far - near) // qn = - (far * near) / (far - near) // // Reverse Z for range [1; 0]: // [ 1 0 0 0 ] [ A 0 C 0 ] // [ 0 1 0 0 ] X [ 0 B D 0 ] // [ 0 0 -1 1 ] [ 0 0 q qn ] // [ 0 0 0 1 ] [ 0 0 -1 0 ] // // [ A 0 C 0 ] // [ 0 B D 0 ] // [ 0 0 -q-1 -qn ] // [ 0 0 -1 0 ] // // q' = -q - 1 // = far / (far - near) - 1 // = ( far - (far - near) ) / (far - near) // q' = near / (far - near) // qn'= -qn q = nearPlane * inv_d; qn = ( farPlane * nearPlane ) * inv_d; } } else { if( farPlane == 0 ) { // Can not do infinite far plane here, avoid divided zero only q = Frustum::INFINITE_FAR_PLANE_ADJUST / nearPlane; qn = Frustum::INFINITE_FAR_PLANE_ADJUST + 1; } else { // Standard Z for range [-1; 1] // q = - 2 / (far - near) // qn = -(far + near) / (far - near) // // Standard Z for range [0; 1] // q = - 1 / (far - near) // qn = - near / (far - near) // // Reverse Z for range [1; 0]: // q' = 1 / (far - near) // qn'= far / (far - near) q = inv_d; qn = farPlane * inv_d; } } } else { if( projectionType == PT_PERSPECTIVE ) { if( farPlane == 0 ) { // Infinite far plane q = Frustum::INFINITE_FAR_PLANE_ADJUST - 1; qn = nearPlane * ( Frustum::INFINITE_FAR_PLANE_ADJUST - 1 ); } else { q = -farPlane * inv_d; qn = -( farPlane * nearPlane ) * inv_d; } } else { if( farPlane == 0 ) { // Can not do infinite far plane here, avoid divided zero only q = -Frustum::INFINITE_FAR_PLANE_ADJUST / nearPlane; qn = -Frustum::INFINITE_FAR_PLANE_ADJUST; } else { q = -inv_d; qn = -nearPlane * inv_d; } } } dest[2][2] = q; dest[2][3] = qn; } //----------------------------------------------------------------------- void RenderSystem::_convertProjectionMatrix( const Matrix4 &matrix, Matrix4 &dest ) { dest = matrix; if( !mReverseDepth ) { // Convert depth range from [-1,+1] to [0,1] dest[2][0] = ( dest[2][0] + dest[3][0] ) / 2; dest[2][1] = ( dest[2][1] + dest[3][1] ) / 2; dest[2][2] = ( dest[2][2] + dest[3][2] ) / 2; dest[2][3] = ( dest[2][3] + dest[3][3] ) / 2; } else { // Convert depth range from [-1,+1] to [1,0] dest[2][0] = ( -dest[2][0] + dest[3][0] ) / 2; dest[2][1] = ( -dest[2][1] + dest[3][1] ) / 2; dest[2][2] = ( -dest[2][2] + dest[3][2] ) / 2; dest[2][3] = ( -dest[2][3] + dest[3][3] ) / 2; } } //----------------------------------------------------------------------- void RenderSystem::_convertOpenVrProjectionMatrix( const Matrix4 &matrix, Matrix4 &dest ) { dest = matrix; if( mReverseDepth ) { // Convert depth range from [0,1] to [1,0] dest[2][0] = ( -dest[2][0] + dest[3][0] ); dest[2][1] = ( -dest[2][1] + dest[3][1] ); dest[2][2] = ( -dest[2][2] + dest[3][2] ); dest[2][3] = ( -dest[2][3] + dest[3][3] ); } } //----------------------------------------------------------------------- void RenderSystem::_setWorldMatrices( const Matrix4 *m, unsigned short count ) { // Do nothing with these matrices here, it never used for now, // derived class should take care with them if required. // Set hardware matrix to nothing _setWorldMatrix( Matrix4::IDENTITY ); } //----------------------------------------------------------------------- void RenderSystem::setStencilBufferParams( uint32 refValue, const StencilParams &stencilParams ) { mStencilParams = stencilParams; // NB: We should always treat CCW as front face for consistent with default // culling mode. const bool mustFlip = ( ( mInvertVertexWinding && !mCurrentRenderPassDescriptor->requiresTextureFlipping() ) || ( !mInvertVertexWinding && mCurrentRenderPassDescriptor->requiresTextureFlipping() ) ); if( mustFlip ) { mStencilParams.stencilBack = stencilParams.stencilFront; mStencilParams.stencilFront = stencilParams.stencilBack; } } //----------------------------------------------------------------------- void RenderSystem::_render( const v1::RenderOperation &op ) { // Update stats size_t primCount = op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount; size_t trueInstanceNum = std::max<size_t>( op.numberOfInstances, 1 ); primCount *= trueInstanceNum; // account for a pass having multiple iterations if( mCurrentPassIterationCount > 1 ) primCount *= mCurrentPassIterationCount; mCurrentPassIterationNum = 0; switch( op.operationType ) { case OT_TRIANGLE_LIST: mMetrics.mFaceCount += ( primCount / 3u ); break; case OT_TRIANGLE_STRIP: case OT_TRIANGLE_FAN: mMetrics.mFaceCount += ( primCount - 2u ); break; default: break; } mMetrics.mVertexCount += op.vertexData->vertexCount * trueInstanceNum; mMetrics.mBatchCount += mCurrentPassIterationCount; // sort out clip planes // have to do it here in case of matrix issues if( mClipPlanesDirty ) { setClipPlanesImpl( mClipPlanes ); mClipPlanesDirty = false; } } //----------------------------------------------------------------------- /*void RenderSystem::_render( const VertexArrayObject *vao ) { // Update stats mFaceCount += vao->mFaceCount; mVertexCount += vao->mVertexBuffers[0]->getNumElements(); ++mBatchCount; }*/ //----------------------------------------------------------------------- void RenderSystem::setInvertVertexWinding( bool invert ) { mInvertVertexWinding = invert; } //----------------------------------------------------------------------- bool RenderSystem::getInvertVertexWinding() const { return mInvertVertexWinding; } //--------------------------------------------------------------------- void RenderSystem::addClipPlane( const Plane &p ) { mClipPlanes.push_back( p ); mClipPlanesDirty = true; } //--------------------------------------------------------------------- void RenderSystem::addClipPlane( Real A, Real B, Real C, Real D ) { addClipPlane( Plane( A, B, C, D ) ); } //--------------------------------------------------------------------- void RenderSystem::setClipPlanes( const PlaneList &clipPlanes ) { if( clipPlanes != mClipPlanes ) { mClipPlanes = clipPlanes; mClipPlanesDirty = true; } } //--------------------------------------------------------------------- void RenderSystem::resetClipPlanes() { if( !mClipPlanes.empty() ) { mClipPlanes.clear(); mClipPlanesDirty = true; } } //--------------------------------------------------------------------- bool RenderSystem::updatePassIterationRenderState() { if( mCurrentPassIterationCount <= 1 ) return false; --mCurrentPassIterationCount; ++mCurrentPassIterationNum; if( mActiveVertexGpuProgramParameters ) { mActiveVertexGpuProgramParameters->incPassIterationNumber(); bindGpuProgramPassIterationParameters( GPT_VERTEX_PROGRAM ); } if( mActiveGeometryGpuProgramParameters ) { mActiveGeometryGpuProgramParameters->incPassIterationNumber(); bindGpuProgramPassIterationParameters( GPT_GEOMETRY_PROGRAM ); } if( mActiveFragmentGpuProgramParameters ) { mActiveFragmentGpuProgramParameters->incPassIterationNumber(); bindGpuProgramPassIterationParameters( GPT_FRAGMENT_PROGRAM ); } if( mActiveTessellationHullGpuProgramParameters ) { mActiveTessellationHullGpuProgramParameters->incPassIterationNumber(); bindGpuProgramPassIterationParameters( GPT_HULL_PROGRAM ); } if( mActiveTessellationDomainGpuProgramParameters ) { mActiveTessellationDomainGpuProgramParameters->incPassIterationNumber(); bindGpuProgramPassIterationParameters( GPT_DOMAIN_PROGRAM ); } if( mActiveComputeGpuProgramParameters ) { mActiveComputeGpuProgramParameters->incPassIterationNumber(); bindGpuProgramPassIterationParameters( GPT_COMPUTE_PROGRAM ); } return true; } //----------------------------------------------------------------------- void RenderSystem::addSharedListener( Listener *l ) { msSharedEventListeners.push_back( l ); } //----------------------------------------------------------------------- void RenderSystem::removeSharedListener( Listener *l ) { msSharedEventListeners.remove( l ); } //----------------------------------------------------------------------- void RenderSystem::addListener( Listener *l ) { mEventListeners.push_back( l ); } //----------------------------------------------------------------------- void RenderSystem::removeListener( Listener *l ) { mEventListeners.remove( l ); } //----------------------------------------------------------------------- void RenderSystem::fireEvent( const String &name, const NameValuePairList *params ) { for( ListenerList::iterator i = mEventListeners.begin(); i != mEventListeners.end(); ++i ) { ( *i )->eventOccurred( name, params ); } fireSharedEvent( name, params ); } //----------------------------------------------------------------------- void RenderSystem::fireSharedEvent( const String &name, const NameValuePairList *params ) { for( ListenerList::iterator i = msSharedEventListeners.begin(); i != msSharedEventListeners.end(); ++i ) { ( *i )->eventOccurred( name, params ); } } //----------------------------------------------------------------------- const char *RenderSystem::getPriorityConfigOption( size_t ) const { OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "idx must be < getNumPriorityConfigOptions()", "RenderSystem::getPriorityConfigOption" ); } //----------------------------------------------------------------------- size_t RenderSystem::getNumPriorityConfigOptions() const { return 0u; } //----------------------------------------------------------------------- void RenderSystem::destroyHardwareOcclusionQuery( HardwareOcclusionQuery *hq ) { HardwareOcclusionQueryList::iterator i = std::find( mHwOcclusionQueries.begin(), mHwOcclusionQueries.end(), hq ); if( i != mHwOcclusionQueries.end() ) { mHwOcclusionQueries.erase( i ); OGRE_DELETE hq; } } //----------------------------------------------------------------------- bool RenderSystem::isGpuProgramBound( GpuProgramType gptype ) { switch( gptype ) { case GPT_VERTEX_PROGRAM: return mVertexProgramBound; case GPT_GEOMETRY_PROGRAM: return mGeometryProgramBound; case GPT_FRAGMENT_PROGRAM: return mFragmentProgramBound; case GPT_HULL_PROGRAM: return mTessellationHullProgramBound; case GPT_DOMAIN_PROGRAM: return mTessellationDomainProgramBound; case GPT_COMPUTE_PROGRAM: return mComputeProgramBound; } // Make compiler happy return false; } //--------------------------------------------------------------------- void RenderSystem::_setTextureProjectionRelativeTo( bool enabled, const Vector3 &pos ) { mTexProjRelative = enabled; mTexProjRelativeOrigin = pos; } //--------------------------------------------------------------------- RenderSystem::RenderSystemContext *RenderSystem::_pauseFrame() { _endFrame(); return new RenderSystem::RenderSystemContext; } //--------------------------------------------------------------------- void RenderSystem::_resumeFrame( RenderSystemContext *context ) { _beginFrame(); delete context; } //--------------------------------------------------------------------- void RenderSystem::_update() { OgreProfile( "RenderSystem::_update" ); mBarrierSolver.reset(); mTextureGpuManager->_update( false ); mVaoManager->_update(); } //--------------------------------------------------------------------- void RenderSystem::updateCompositorManager( CompositorManager2 *compositorManager ) { compositorManager->_updateImplementation(); } //--------------------------------------------------------------------- void RenderSystem::compositorWorkspaceBegin( CompositorWorkspace *workspace, const bool forceBeginFrame ) { workspace->_beginUpdate( forceBeginFrame, true ); } //--------------------------------------------------------------------- void RenderSystem::compositorWorkspaceUpdate( CompositorWorkspace *workspace ) { workspace->_update( true ); } //--------------------------------------------------------------------- void RenderSystem::compositorWorkspaceEnd( CompositorWorkspace *workspace, const bool forceEndFrame ) { workspace->_endUpdate( forceEndFrame, true ); } //--------------------------------------------------------------------- const String &RenderSystem::_getDefaultViewportMaterialScheme() const { #ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS if( !( getCapabilities()->hasCapability( Ogre::RSC_FIXED_FUNCTION ) ) ) { // I am returning the exact value for now - I don't want to add dependency for the RTSS just // for one string static const String ShaderGeneratorDefaultScheme = "ShaderGeneratorDefaultScheme"; return ShaderGeneratorDefaultScheme; } else #endif { return MaterialManager::DEFAULT_SCHEME_NAME; } } //--------------------------------------------------------------------- Ogre::v1::HardwareVertexBufferSharedPtr RenderSystem::getGlobalInstanceVertexBuffer() const { return mGlobalInstanceVertexBuffer; } //--------------------------------------------------------------------- void RenderSystem::setGlobalInstanceVertexBuffer( const v1::HardwareVertexBufferSharedPtr &val ) { if( val && !val->getIsInstanceData() ) { OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "A none instance data vertex buffer was set to be the global instance vertex buffer.", "RenderSystem::setGlobalInstanceVertexBuffer" ); } mGlobalInstanceVertexBuffer = val; } //--------------------------------------------------------------------- size_t RenderSystem::getGlobalNumberOfInstances() const { return mGlobalNumberOfInstances; } //--------------------------------------------------------------------- void RenderSystem::setGlobalNumberOfInstances( const size_t val ) { mGlobalNumberOfInstances = val; } v1::VertexDeclaration *RenderSystem::getGlobalInstanceVertexBufferVertexDeclaration() const { return mGlobalInstanceVertexBufferVertexDeclaration; } //--------------------------------------------------------------------- void RenderSystem::setGlobalInstanceVertexBufferVertexDeclaration( v1::VertexDeclaration *val ) { mGlobalInstanceVertexBufferVertexDeclaration = val; } //--------------------------------------------------------------------- bool RenderSystem::startGpuDebuggerFrameCapture( Window *window ) { if( !mRenderDocApi ) { loadRenderDocApi(); if( !mRenderDocApi ) return false; } #if OGRE_NO_RENDERDOC_INTEGRATION == 0 RENDERDOC_DevicePointer device = 0; RENDERDOC_WindowHandle windowHandle = 0; if( window ) { window->getCustomAttribute( "RENDERDOC_DEVICE", device ); window->getCustomAttribute( "RENDERDOC_WINDOW", windowHandle ); } mRenderDocApi->StartFrameCapture( device, windowHandle ); #endif return true; } //--------------------------------------------------------------------- void RenderSystem::endGpuDebuggerFrameCapture( Window *window ) { if( !mRenderDocApi ) return; #if OGRE_NO_RENDERDOC_INTEGRATION == 0 RENDERDOC_DevicePointer device = 0; RENDERDOC_WindowHandle windowHandle = 0; if( window ) { window->getCustomAttribute( "RENDERDOC_DEVICE", device ); window->getCustomAttribute( "RENDERDOC_WINDOW", windowHandle ); } mRenderDocApi->EndFrameCapture( device, windowHandle ); #endif } //--------------------------------------------------------------------- bool RenderSystem::loadRenderDocApi() { #if OGRE_NO_RENDERDOC_INTEGRATION == 0 if( mRenderDocApi ) return true; // Already loaded # if OGRE_PLATFORM == OGRE_PLATFORM_LINUX || OGRE_PLATFORM == OGRE_PLATFORM_ANDROID # if OGRE_PLATFORM != OGRE_PLATFORM_ANDROID void *mod = dlopen( "librenderdoc.so", RTLD_NOW | RTLD_NOLOAD ); # else void *mod = dlopen( "libVkLayer_GLES_RenderDoc.so", RTLD_NOW | RTLD_NOLOAD ); # endif if( mod ) { pRENDERDOC_GetAPI RENDERDOC_GetAPI = (pRENDERDOC_GetAPI)dlsym( mod, "RENDERDOC_GetAPI" ); const int ret = RENDERDOC_GetAPI( eRENDERDOC_API_Version_1_4_1, (void **)&mRenderDocApi ); return ret == 1; } # elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32 HMODULE mod = GetModuleHandleA( "renderdoc.dll" ); if( mod ) { pRENDERDOC_GetAPI RENDERDOC_GetAPI = (pRENDERDOC_GetAPI)GetProcAddress( mod, "RENDERDOC_GetAPI" ); const int ret = RENDERDOC_GetAPI( eRENDERDOC_API_Version_1_4_1, (void **)&mRenderDocApi ); return ret == 1; } # endif #endif return false; } //--------------------------------------------------------------------- void RenderSystem::getCustomAttribute( const String &name, void *pData ) { OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Attribute not found.", "RenderSystem::getCustomAttribute" ); } //--------------------------------------------------------------------- void RenderSystem::setDebugShaders( bool bDebugShaders ) { mDebugShaders = bDebugShaders; } //--------------------------------------------------------------------- bool RenderSystem::isSameLayout( ResourceLayout::Layout a, ResourceLayout::Layout b, const TextureGpu *texture, bool bIsDebugCheck ) const { if( ( a != ResourceLayout::Uav && b != ResourceLayout::Uav ) || bIsDebugCheck ) return true; return a == b; } //--------------------------------------------------------------------- void RenderSystem::_clearStateAndFlushCommandBuffer() {} //--------------------------------------------------------------------- RenderSystem::Listener::~Listener() {} } // namespace Ogre
41.589762
105
0.51633
FreeNightKnight
4027453f9518a17a754721bc386f6e52a00cf360
409
cpp
C++
hdu/1000/1412.cpp
TheBadZhang/OJ
b5407f2483aa630068343b412ecaf3a9e3303f7e
[ "Apache-2.0" ]
1
2020-07-22T16:54:07.000Z
2020-07-22T16:54:07.000Z
hdu/1000/1412.cpp
TheBadZhang/OJ
b5407f2483aa630068343b412ecaf3a9e3303f7e
[ "Apache-2.0" ]
1
2018-05-12T12:53:06.000Z
2018-05-12T12:53:06.000Z
hdu/1000/1412.cpp
TheBadZhang/OJ
b5407f2483aa630068343b412ecaf3a9e3303f7e
[ "Apache-2.0" ]
null
null
null
#include<iostream> #include<cstdio> #include<set> using namespace std; int main() { int temp,n1,n2; while(scanf("%d %d",&n1,&n2)!=EOF) { set<int> s; n1=n1+n2; while(n1--) { scanf("%d",&temp); s.insert(temp); } set<int>::const_iterator itor; itor=s.begin(); while(itor!=s.end()) { printf("%d",*itor); itor++; if(itor!=s.end()) printf(" "); } printf("\n"); } return 0; }
15.730769
37
0.550122
TheBadZhang
402856fb2566b33a6b8817e60d7a765c9f69c48f
3,747
hh
C++
tce/src/applibs/PlatformIntegrator/AlmaIFIntegrator.hh
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
74
2015-10-22T15:34:10.000Z
2022-03-25T07:57:23.000Z
tce/src/applibs/PlatformIntegrator/AlmaIFIntegrator.hh
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
79
2015-11-19T09:23:08.000Z
2022-01-12T14:15:16.000Z
tce/src/applibs/PlatformIntegrator/AlmaIFIntegrator.hh
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
38
2015-11-17T10:12:23.000Z
2022-03-25T07:57:24.000Z
/* Copyright (c) 2002-2016 Tampere University. This file is part of TTA-Based Codesign Environment (TCE). 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. */ /** * @file AlmaIFIntegrator.hh * * Declaration of AlmaIFIntegrator class. */ #ifndef TTA_ALMAIF_INTEGRATOR_HH #define TTA_ALMAIF_INTEGRATOR_HH #include "PlatformIntegrator.hh" #include "TCEString.hh" #include "ProGeTypes.hh" #include "DefaultProjectFileGenerator.hh" class AlmaIFIntegrator : public PlatformIntegrator { public: AlmaIFIntegrator(); AlmaIFIntegrator( const TTAMachine::Machine* machine, const IDF::MachineImplementation* idf, ProGe::HDL hdl, TCEString progeOutputDir, TCEString entityName, TCEString outputDir, TCEString programName, int targetClockFreq, std::ostream& warningStream, std::ostream& errorStream, const MemInfo& imem, MemType dmemType); virtual ~AlmaIFIntegrator(); virtual void integrateProcessor(const ProGe::NetlistBlock* progeBlock); virtual bool integrateCore(const ProGe::NetlistBlock& cores); virtual void printInfo(std::ostream& stream) const; virtual TCEString deviceFamily() const; virtual void setDeviceFamily(TCEString devFamily); virtual TCEString deviceName() const; virtual TCEString devicePackage() const; virtual TCEString deviceSpeedClass() const; virtual int targetClockFrequency() const; virtual TCEString pinTag() const; virtual bool chopTaggedSignals() const; virtual ProjectFileGenerator* projectFileGenerator() const; protected: virtual MemoryGenerator& imemInstance(MemInfo imem); virtual MemoryGenerator& dmemInstance( MemInfo dmem, TTAMachine::FunctionUnit& lsuArch, HDB::FUImplementation& lsuImplementation); private: void addMemoryPorts(const TCEString as_name, const TCEString data_width, const TCEString addr_width); void addAlmaifBlock(); void addAlmaifFiles(); void copyPlatformFile(const TCEString inputPath, std::vector<TCEString>& fileList) const; void instantiatePlatformFile(const TCEString inputPath, std::vector<TCEString>& fileList) const; int axiAddressWidth() const; bool verifyMemories() const; static const TCEString DMEM_NAME; static const TCEString PMEM_NAME; static const TCEString ALMAIF_MODULE; MemoryGenerator* imemGen_; std::map<TCEString, MemoryGenerator*> dmemGen_; std::map<TCEString, ProGe::NetlistPort*> almaif_ttacore_ports; ProGe::NetlistBlock* almaifBlock_; TCEString deviceFamily_; DefaultProjectFileGenerator* fileGen_; }; #endif
32.025641
78
0.731785
kanishkan
4029fe61bd9aaa38e13a6aacea0750c6aa697b2c
2,685
cpp
C++
src/CL_DataBuffer_stub.cpp
fccm/ocaml-clanlib
1929f1c11d4cc9fc19e7da22826238b4cce7a07d
[ "Zlib", "OLDAP-2.2.1" ]
1
2020-10-24T14:48:04.000Z
2020-10-24T14:48:04.000Z
src/CL_DataBuffer_stub.cpp
fccm/ocaml-clanlib
1929f1c11d4cc9fc19e7da22826238b4cce7a07d
[ "Zlib", "OLDAP-2.2.1" ]
null
null
null
src/CL_DataBuffer_stub.cpp
fccm/ocaml-clanlib
1929f1c11d4cc9fc19e7da22826238b4cce7a07d
[ "Zlib", "OLDAP-2.2.1" ]
null
null
null
/* ocaml-clanlib: OCaml bindings to the ClanLib SDK Copyright (C) 2013 Florent Monnier 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. */ #include <ClanLib/Core/System/databuffer.h> #include "cl_caml_incs.hpp" #include "cl_caml_conv.hpp" #include "CL_DataBuffer_stub.hpp" CAMLextern_C value caml_CL_DataBuffer_init(value unit) { CL_DataBuffer *buf = new CL_DataBuffer(); return Val_CL_DataBuffer(buf); } CAMLextern_C value caml_CL_DataBuffer_copy(value orig) { CL_DataBuffer *buf = new CL_DataBuffer(*CL_DataBuffer_val(orig)); return Val_CL_DataBuffer(buf); } CAMLextern_C value caml_CL_DataBuffer_of_string(value str) { CL_DataBuffer *buf = new CL_DataBuffer( String_val(str), caml_string_length(str)); return Val_CL_DataBuffer(buf); } /* TODO: CL_DataBuffer(int size, CL_MemoryPool *pool = 0); CL_DataBuffer(const void *data, int size, CL_MemoryPool *pool = 0); CL_DataBuffer(const CL_DataBuffer &data, int pos, int size = -1, CL_MemoryPool *pool = 0); */ CAMLextern_C value caml_CL_DataBuffer_delete(value buf) { delete CL_DataBuffer_val(buf); nullify_ptr(buf); return Val_unit; } CAMLextern_C value caml_CL_DataBuffer_get_size(value buf) { int size = CL_DataBuffer_val(buf)->get_size(); return Val_long(size); } CAMLextern_C value caml_CL_DataBuffer_get_capacity(value buf) { int cap = CL_DataBuffer_val(buf)->get_capacity(); return Val_long(cap); } CAMLextern_C value caml_CL_DataBuffer_set_size(value buf, value size) { CL_DataBuffer_val(buf)->set_size(Int_val(size)); return Val_unit; } CAMLextern_C value caml_CL_DataBuffer_set_capacity(value buf, value cap) { CL_DataBuffer_val(buf)->set_capacity(Int_val(cap)); return Val_unit; } CAMLextern_C value caml_CL_DataBuffer_get_i(value buf, value i) { const char c = (*CL_DataBuffer_val(buf))[ Int_val(i) ]; return Val_char(c); } CAMLextern_C value caml_CL_DataBuffer_set_i(value buf, value i, value c) { (*CL_DataBuffer_val(buf))[ Int_val(i) ] = Char_val(c); return Val_unit; } /* TODO: char *get_data(); const char *get_data(); char &operator[](int i); const char &operator[](int i); char &operator[](unsigned int i); const char &operator[](unsigned int i); bool is_null(); CL_DataBuffer &operator =(const CL_DataBuffer &copy); */ // vim: sw=4 sts=4 ts=4 et
24.189189
94
0.72365
fccm
402e91dbc88528fd74639a15bb0e5689aed78f82
3,491
cpp
C++
libcaf_core/src/response_promise.cpp
v2nero/actor-framework
c2f811809143d32c598471a20363238b0882a761
[ "BSL-1.0", "BSD-3-Clause" ]
1
2021-03-06T19:51:07.000Z
2021-03-06T19:51:07.000Z
libcaf_core/src/response_promise.cpp
Boubou818/actor-framework
da90ef78b26da5d225f039072e616da415c48494
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
libcaf_core/src/response_promise.cpp
Boubou818/actor-framework
da90ef78b26da5d225f039072e616da415c48494
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include <utility> #include <algorithm> #include "caf/response_promise.hpp" #include "caf/logger.hpp" #include "caf/local_actor.hpp" namespace caf { response_promise::response_promise() : self_(nullptr) { // nop } response_promise::response_promise(none_t) : response_promise() { // nop } response_promise::response_promise(strong_actor_ptr self, strong_actor_ptr source, forwarding_stack stages, message_id mid) : self_(std::move(self)), source_(std::move(source)), stages_(std::move(stages)), id_(mid) { // Form an invalid request promise when initialized from a response ID, since // we always drop messages in this case. if (mid.is_response()) { source_ = nullptr; stages_.clear(); } } response_promise::response_promise(strong_actor_ptr self, mailbox_element& src) : response_promise(std::move(self), std::move(src.sender), std::move(src.stages), src.mid) { // nop } void response_promise::deliver(error x) { deliver_impl(make_message(std::move(x))); } void response_promise::deliver(unit_t) { deliver_impl(make_message()); } bool response_promise::async() const { return id_.is_async(); } execution_unit* response_promise::context() { return self_ == nullptr ? nullptr : static_cast<local_actor*>(actor_cast<abstract_actor*>(self_)) ->context(); } void response_promise::deliver_impl(message msg) { CAF_LOG_TRACE(CAF_ARG(msg)); if (!stages_.empty()) { auto next = std::move(stages_.back()); stages_.pop_back(); next->enqueue(make_mailbox_element(std::move(source_), id_, std::move(stages_), std::move(msg)), context()); return; } if (source_) { source_->enqueue(std::move(self_), id_.response_id(), std::move(msg), context()); source_.reset(); return; } CAF_LOG_INFO_IF(self_ != nullptr, "response promise already satisfied"); CAF_LOG_INFO_IF(self_ == nullptr, "invalid response promise"); } } // namespace caf
35.262626
80
0.493841
v2nero
402efd6856e50ca629d5b72ec75b07bbe50e7ac7
1,948
hpp
C++
system/dummy_diag_publisher/include/dummy_diag_publisher/dummy_diag_publisher_node.hpp
meliketanrikulu/autoware.universe
04f2b53ae1d7b41846478641ad6ff478c3d5a247
[ "Apache-2.0" ]
58
2021-11-30T09:03:46.000Z
2022-03-31T15:25:17.000Z
system/dummy_diag_publisher/include/dummy_diag_publisher/dummy_diag_publisher_node.hpp
meliketanrikulu/autoware.universe
04f2b53ae1d7b41846478641ad6ff478c3d5a247
[ "Apache-2.0" ]
425
2021-11-30T02:24:44.000Z
2022-03-31T10:26:37.000Z
system/dummy_diag_publisher/include/dummy_diag_publisher/dummy_diag_publisher_node.hpp
meliketanrikulu/autoware.universe
04f2b53ae1d7b41846478641ad6ff478c3d5a247
[ "Apache-2.0" ]
69
2021-11-30T02:09:18.000Z
2022-03-31T15:38:29.000Z
// Copyright 2020 Tier IV, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef DUMMY_DIAG_PUBLISHER__DUMMY_DIAG_PUBLISHER_NODE_HPP_ #define DUMMY_DIAG_PUBLISHER__DUMMY_DIAG_PUBLISHER_NODE_HPP_ #include <diagnostic_updater/diagnostic_updater.hpp> #include <rclcpp/rclcpp.hpp> #include <string> #include <vector> struct DiagConfig { std::string name; std::string hardware_id; std::string msg_ok; std::string msg_warn; std::string msg_error; std::string msg_stale; }; class DummyDiagPublisherNode : public rclcpp::Node { public: explicit DummyDiagPublisherNode(const rclcpp::NodeOptions & node_options); private: enum Status { OK, WARN, ERROR, STALE, }; struct DummyDiagPublisherConfig { Status status; bool is_active; }; // Parameter double update_rate_; DiagConfig diag_config_; DummyDiagPublisherConfig config_; // Dynamic Reconfigure OnSetParametersCallbackHandle::SharedPtr set_param_res_; rcl_interfaces::msg::SetParametersResult paramCallback( const std::vector<rclcpp::Parameter> & parameters); // Diagnostic Updater // Set long period to reduce automatic update diagnostic_updater::Updater updater_{this, 1000.0 /* sec */}; void produceDiagnostics(diagnostic_updater::DiagnosticStatusWrapper & stat); // Timer void onTimer(); rclcpp::TimerBase::SharedPtr timer_; }; #endif // DUMMY_DIAG_PUBLISHER__DUMMY_DIAG_PUBLISHER_NODE_HPP_
25.973333
78
0.755647
meliketanrikulu
4035fef9cc227b62898e0aa7c51bdcd618626852
4,416
hpp
C++
src/libraries/core/fvMesh/fvMeshMapper/fvSurfaceMapper.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/fvMesh/fvMeshMapper/fvSurfaceMapper.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/fvMesh/fvMeshMapper/fvSurfaceMapper.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2011 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>. Class CML::fvSurfaceMapper Description FV surface mapper. SourceFiles fvSurfaceMapper.cpp \*---------------------------------------------------------------------------*/ #ifndef fvSurfaceMapper_H #define fvSurfaceMapper_H #include "morphFieldMapper.hpp" #include "fvMesh.hpp" #include "faceMapper.hpp" #include "HashSet.hpp" #include "mapPolyMesh.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace CML { // Forward declaration of classes /*---------------------------------------------------------------------------*\ Class fvSurfaceMapper Declaration \*---------------------------------------------------------------------------*/ class fvSurfaceMapper : public morphFieldMapper { // Private data //- Reference to mesh const fvMesh& mesh_; //- Reference to face mapper const faceMapper& faceMap_; // Demand-driven private data //- Direct addressing (only one for of addressing is used) mutable labelList* directAddrPtr_; //- Interpolated addressing (only one for of addressing is used) mutable labelListList* interpolationAddrPtr_; //- Interpolation weights mutable scalarListList* weightsPtr_; //- Inserted faces mutable labelList* insertedObjectLabelsPtr_; // Private Member Functions //- Disallow default bitwise copy construct fvSurfaceMapper(const fvSurfaceMapper&); //- Disallow default bitwise assignment void operator=(const fvSurfaceMapper&); //- Calculate addressing void calcAddressing() const; //- Clear out local storage void clearOut(); public: // Constructors //- Construct from components fvSurfaceMapper ( const fvMesh& mesh, const faceMapper& fMapper ); //- Destructor virtual ~fvSurfaceMapper(); // Member Functions //- Return size virtual label size() const { return mesh_.nInternalFaces(); } //- Return size of field before mapping virtual label sizeBeforeMapping() const { return faceMap_.internalSizeBeforeMapping(); } //- Is the mapping direct virtual bool direct() const { return faceMap_.direct(); } //- Has unmapped elements virtual bool hasUnmapped() const { return insertedObjects(); } //- Return direct addressing virtual const labelUList& directAddressing() const; //- Return interpolated addressing virtual const labelListList& addressing() const; //- Return interpolaion weights virtual const scalarListList& weights() const; //- Are there any inserted faces virtual bool insertedObjects() const { return faceMap_.insertedObjects(); } //- Return list of inserted faces virtual const labelList& insertedObjectLabels() const; //- Return flux flip map const labelHashSet& flipFaceFlux() const { return faceMap_.flipFaceFlux(); } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace CML // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
25.526012
79
0.532382
MrAwesomeRocks
4036c8a294efeb2a4193bc52a7f0d5a28ffa74ea
1,749
hpp
C++
sdk/boost_1_30_0/boost/type_traits/detail/cv_traits_impl.hpp
acidicMercury8/xray-1.0
65e85c0e31e82d612c793d980dc4b73fa186c76c
[ "Linux-OpenIB" ]
10
2021-05-04T06:40:27.000Z
2022-01-20T20:24:28.000Z
sdk/boost_1_30_0/boost/type_traits/detail/cv_traits_impl.hpp
acidicMercury8/xray-1.0
65e85c0e31e82d612c793d980dc4b73fa186c76c
[ "Linux-OpenIB" ]
null
null
null
sdk/boost_1_30_0/boost/type_traits/detail/cv_traits_impl.hpp
acidicMercury8/xray-1.0
65e85c0e31e82d612c793d980dc4b73fa186c76c
[ "Linux-OpenIB" ]
2
2020-05-17T10:01:14.000Z
2020-09-11T20:17:27.000Z
// (C) Copyright Dave Abrahams, Steve Cleary, Beman Dawes, Howard // Hinnant & John Maddock 2000. Permission to copy, use, modify, // sell and distribute this software is granted provided this // copyright notice appears in all copies. This software is provided // "as is" without express or implied warranty, and with no claim as // to its suitability for any purpose. // // See http://www.boost.org for most recent version including documentation. #ifndef BOOST_TT_DETAIL_CV_TRAITS_IMPL_HPP_INCLUDED #define BOOST_TT_DETAIL_CV_TRAITS_IMPL_HPP_INCLUDED #include "boost/config.hpp" #ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION namespace boost { namespace detail { // implementation helper: template <typename T> struct cv_traits_imp {}; template <typename T> struct cv_traits_imp<T*> { BOOST_STATIC_CONSTANT(bool, is_const = false); BOOST_STATIC_CONSTANT(bool, is_volatile = false); typedef T unqualified_type; }; template <typename T> struct cv_traits_imp<const T*> { BOOST_STATIC_CONSTANT(bool, is_const = true); BOOST_STATIC_CONSTANT(bool, is_volatile = false); typedef T unqualified_type; }; template <typename T> struct cv_traits_imp<volatile T*> { BOOST_STATIC_CONSTANT(bool, is_const = false); BOOST_STATIC_CONSTANT(bool, is_volatile = true); typedef T unqualified_type; }; template <typename T> struct cv_traits_imp<const volatile T*> { BOOST_STATIC_CONSTANT(bool, is_const = true); BOOST_STATIC_CONSTANT(bool, is_volatile = true); typedef T unqualified_type; }; } // namespace detail } // namespace boost #endif // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION #endif // BOOST_TT_DETAIL_CV_TRAITS_IMPL_HPP_INCLUDED
27.761905
77
0.740423
acidicMercury8
4037198d8d3c56b935e3d4812801ed4cddd9e74f
11,493
cpp
C++
rilc_test.cpp
cocktail828/rilc
09d469e26b527cef9b407e7e8d4186ac3726eef7
[ "MIT" ]
null
null
null
rilc_test.cpp
cocktail828/rilc
09d469e26b527cef9b407e7e8d4186ac3726eef7
[ "MIT" ]
null
null
null
rilc_test.cpp
cocktail828/rilc
09d469e26b527cef9b407e7e8d4186ac3726eef7
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <thread> #include <chrono> #include <future> #include <vector> #include <getopt.h> #include <unistd.h> #include <string.h> #include "rilc_api.h" #include "rilc_interface.h" #include "logger.h" std::mutex mutexSocilited; std::condition_variable condSocilited; void socilited_notify(RILResponse *arg) { condSocilited.notify_one(); LOGI << "RILC call user defined socilited_notify function" << ENDL; } void unsocilited_notify(RILResponse *arg) { LOGI << "RILC call user defined unsocilited_notify function" << ENDL; } static int sg_index = 0; /** * will call std::abort() if get an timeout */ #define RILC_TEST_ABORT_TIMEOUT(func, args...) \ do \ { \ LOGI << ">>>>>>>> RILC_TEST index: " << ++sg_index << ENDL; \ RILResponse resp; \ memset(&resp, 0, sizeof(RILResponse)); \ resp.responseNotify = socilited_notify; \ std::unique_lock<std::mutex> _lk(mutexSocilited); \ func(&resp, ##args); \ if (condSocilited.wait_for(_lk, std::chrono::seconds(60)) == std::cv_status::timeout) \ { \ LOGI << ">>>>>>>> RILC_TEST index: " << sg_index << " failed for timeout" << ENDL; \ LOGE << "OOPS!!! request timeout" << ENDL; \ LOGE << "check wether host can get response from device" << ENDL; \ std::abort(); \ } \ else \ { \ if (resp.responseShow) \ resp.responseShow(&resp); \ if (resp.responseFree) \ resp.responseFree(&resp); \ LOGI << ">>>>>>>> RILC_TEST index: " << sg_index << " pass" << ENDL; \ } \ _lk.unlock(); \ LOGI << ">>>>>>>> RILC_TEST index: " << sg_index << " finished" << ENDL << ENDL << ENDL; \ } while (0); int main(int argc, char **argv) { static const struct option long_options[] = { {"device", required_argument, NULL, 'd'}, {"mode", required_argument, NULL, 'm'}, {"platform", required_argument, NULL, 'p'}, {"level", required_argument, NULL, 'l'}, {NULL, 0, NULL, 0}}; const char *device = "/dev/ttyUSB4"; Severity s = Severity::DEBUG; /** * 0 Linux * 1 Android */ int platform = 0; /** * 0 abort if timeout * 1 abort if response report an error */ int test_mode = 0; int long_index = 0; int opt; while ((opt = getopt_long(argc, argv, "d:m:p:l:?h", long_options, &long_index)) != -1) { switch (opt) { case 'd': device = optarg; LOGI << "using device: " << device << ENDL; break; case 'm': test_mode = !!atoi(optarg); LOGI << "using test mode: " << test_mode << ENDL; break; case 'p': if (optarg && !strncasecmp(optarg, "linux", 4)) platform = 0; else if (optarg && !strncasecmp(optarg, "android", 4)) platform = 1; LOGI << "using platform: " << (platform ? "Android" : "Linux") << ENDL; break; case 'l': if (optarg && !strncasecmp(optarg, "debug", 4)) s = Severity::DEBUG; else if (optarg && !strncasecmp(optarg, "info", 4)) s = Severity::INFO; else if (optarg && !strncasecmp(optarg, "warn", 4)) s = Severity::WARNING; else if (optarg && !strncasecmp(optarg, "error", 4)) s = Severity::ERROR; else s = Severity::INFO; break; default: LOGI << "help message:" << ENDL; LOGI << " -d, --device ttydevice or socket" << ENDL; LOGI << " -m, --mode test mode(0 stop test if meet a timeout, 1 stop test if meet an error)" << ENDL; LOGI << " -p, --platform os platform(0 for Linux, 1 for Android)" << ENDL; LOGI << " -l, --level log level(debug, info, warning, error)" << ENDL; return 0; } } if (access(device, R_OK | W_OK)) { LOGE << "invalid device: " << device << ENDL; return 0; } /** * set log level Severity::INFO * for more detail set Severity::DEBUG */ Logger::Init("RILC", s, false); /** test on Android * Android only allow user radio connect socket '/dev/socket/rild' */ if (platform == 1) { setgid(1001); setuid(1001); LOGI << "try to switch user to radio: id 1001" << ENDL; LOGD << "after switch user UID\t= " << getuid() << ENDL; LOGD << "after switch user EUID\t= " << geteuid() << ENDL; LOGD << "after switch user GID\t= " << getgid() << ENDL; LOGD << "after switch user EGID\t= " << getegid() << ENDL; } /** test on Linux with RG500U * Android only allow user radio connect socket '/dev/socket/rild' */ if (device) RILC_init(device); else { if (platform == 1) RILC_init("/dev/socket/rild"); else RILC_init("/dev/ttyUSB4"); } RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_NEW_SMS, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_NEW_SMS_STATUS_REPORT, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_NEW_SMS_ON_SIM, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_ON_USSD, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_ON_USSD_REQUEST, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_NITZ_TIME_RECEIVED, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_SIGNAL_STRENGTH, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_DATA_CALL_LIST_CHANGED, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_SUPP_SVC_NOTIFICATION, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_STK_SESSION_END, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_STK_PROACTIVE_COMMAND, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_STK_EVENT_NOTIFY, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_STK_CALL_SETUP, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_SIM_SMS_STORAGE_FULL, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_SIM_REFRESH, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_CALL_RING, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_CDMA_NEW_SMS, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_NEW_BROADCAST_SMS, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_CDMA_RUIM_SMS_STORAGE_FULL, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_RESTRICTED_STATE_CHANGED, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_ENTER_EMERGENCY_CALLBACK_MODE, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_CDMA_CALL_WAITING, unsocilited_notify); // TOD; RILC_unsocilitedRegister(RIL_UNSOL_CDMA_OTA_PROVISION_STATUS, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_CDMA_INFO_REC, unsocilited_notify); // TOD; RILC_unsocilitedRegister(RIL_UNSOL_OEM_HOOK_RAW, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_RINGBACK_TONE, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_RESEND_INCALL_MUTE, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_CDMA_PRL_CHANGED, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_EXIT_EMERGENCY_CALLBACK_MODE, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_RIL_CONNECTED, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_VOICE_RADIO_TECH_CHANGED, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_CELL_INFO_LIST, unsocilited_notify); // TOD; RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_IMS_NETWORK_STATE_CHANGED, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_UICC_SUBSCRIPTION_STATUS_CHANGED, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_SRVCC_STATE_NOTIFY, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_HARDWARE_CONFIG_CHANGED, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_DC_RT_INFO_CHANGED, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_RADIO_CAPABILITY, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_ON_SS, unsocilited_notify); // TOD; RILC_unsocilitedRegister(RIL_UNSOL_STK_CC_ALPHA_NOTIFY, unsocilited_notify); RILC_unsocilitedRegister(RIL_UNSOL_LCEDATA_RECV, unsocilited_notify); RILC_TEST_ABORT_TIMEOUT(RILC_getIMEI); RILC_TEST_ABORT_TIMEOUT(RILC_getIMEISV); RILC_TEST_ABORT_TIMEOUT(RILC_getIMSI); RILC_TEST_ABORT_TIMEOUT(RILC_getVoiceRegistrationState); RILC_TEST_ABORT_TIMEOUT(RILC_getDataRegistrationState); RILC_TEST_ABORT_TIMEOUT(RILC_getOperator); RILC_TEST_ABORT_TIMEOUT(RILC_getNeighboringCids); RILC_TEST_ABORT_TIMEOUT(RILC_getSignalStrength); RILC_TEST_ABORT_TIMEOUT(RILC_getPreferredNetworkType); RILC_TEST_ABORT_TIMEOUT(RILC_setPreferredNetworkType, RADIO_TECHNOLOGY_LTE); RILC_TEST_ABORT_TIMEOUT(RILC_setupDataCall, RADIO_TECHNOLOGY_LTE, "0", "3gnet", "", "", SETUP_DATA_AUTH_NONE, PROTOCOL_IPV4); RILC_TEST_ABORT_TIMEOUT(RILC_getIccCardStatus); RILC_TEST_ABORT_TIMEOUT(RILC_getCurrentCalls); RILC_TEST_ABORT_TIMEOUT(RILC_getNetworkSelectionMode); RILC_TEST_ABORT_TIMEOUT(RILC_getDataCallList); RILC_TEST_ABORT_TIMEOUT(RILC_getBasebandVersion); RILC_TEST_ABORT_TIMEOUT(RILC_queryAvailableBandMode); RILC_uninit(); return 0; }
45.426877
127
0.595406
cocktail828
4038654c9fcdc2b790ca19c3b87d229ac0346f20
939
cpp
C++
sample03/utils.cpp
trumpsilver/Aladin
283233c0583db120eb2a881cddca20f474dc6a98
[ "MIT" ]
null
null
null
sample03/utils.cpp
trumpsilver/Aladin
283233c0583db120eb2a881cddca20f474dc6a98
[ "MIT" ]
null
null
null
sample03/utils.cpp
trumpsilver/Aladin
283233c0583db120eb2a881cddca20f474dc6a98
[ "MIT" ]
null
null
null
#include <d3dx9.h> #include "utils.h" #include "trace.h" LPDIRECT3DSURFACE9 CreateSurfaceFromFile(LPDIRECT3DDEVICE9 d3ddv, LPWSTR FilePath) { D3DXIMAGE_INFO info; HRESULT result = D3DXGetImageInfoFromFile(FilePath,&info); if (result!=D3D_OK) { trace(L"[ERROR] Failed to get image info '%s'",FilePath); return NULL; } LPDIRECT3DSURFACE9 surface; d3ddv->CreateOffscreenPlainSurface( info.Width, // width info.Height, // height D3DFMT_X8R8G8B8, // format D3DPOOL_DEFAULT, &surface, NULL); result = D3DXLoadSurfaceFromFile( surface, // surface NULL, // destination palette NULL, // destination rectangle FilePath, NULL, // source rectangle D3DX_DEFAULT, // filter image D3DCOLOR_XRGB(0,0,0), // transparency (0 = none) NULL); // reserved if (result!=D3D_OK) { trace(L"[ERROR] D3DXLoadSurfaceFromFile() failed"); return NULL; } return surface; }
20.866667
82
0.681576
trumpsilver
40392ee2adc672b6b7007720bda215e1dca4677c
3,619
cpp
C++
CanInterface/module.cpp
code2love/Can4Python
3899442bea7985bf790412bafc8048a550f59249
[ "BSD-2-Clause" ]
1
2020-03-18T22:29:35.000Z
2020-03-18T22:29:35.000Z
CanInterface/module.cpp
code2love/Can4Python
3899442bea7985bf790412bafc8048a550f59249
[ "BSD-2-Clause" ]
null
null
null
CanInterface/module.cpp
code2love/Can4Python
3899442bea7985bf790412bafc8048a550f59249
[ "BSD-2-Clause" ]
null
null
null
#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <Windows.h> #include <cmath> #include "CanInterface.h" using namespace pybind11::literals; namespace py = pybind11; class Can4Python : public CanInterface { public: Can4Python() : CanInterface() {} bool SendCanMessage(int devIndex, unsigned int messageId, std::vector<unsigned char> payload, int messageFlags) { unsigned char payloadArr[64]; for (int i = 0; i < payload.size(); i++) payloadArr[i] = payload.at(i); return CanInterface::SendCanMessage(devIndex, messageId, payloadArr, payload.size(), messageFlags); } bool SendCanMessageAsync(int devIndex, unsigned int messageId, std::vector<unsigned char> payload, int messageFlags) { unsigned char payloadArr[64]; for (int i = 0; i < payload.size(); i++) payloadArr[i] = payload.at(i); return CanInterface::SendCanMessageAsync(devIndex, messageId, payloadArr, payload.size(), messageFlags); } py::dict GetCanMessage(int devIndex) { unsigned int identifier; unsigned char payload[64]; int payloadLength; int messageFlags; unsigned long timestamp; if (CanInterface::GetCanMessage(devIndex, &identifier, payload, &payloadLength, &messageFlags, &timestamp)) { auto payloadArr = std::vector<unsigned char>(); for (int i = 0; i < payloadLength; i++) payloadArr.push_back(payload[i]); return py::dict("identifier"_a = identifier, "payload"_a = payloadArr, "messageFlags"_a = messageFlags, "timestamp"_a = timestamp); } return py::dict(); } }; PYBIND11_MODULE(Can4Python, mod) { py::class_<Can4Python, std::shared_ptr<Can4Python>> clsCan4Python(mod, "CanInterface"); py::enum_<Can4Python::IdentifierFlags>(clsCan4Python, "IdentifierFlags") .value("EXTENDED_29BIT", Can4Python::IdentifierFlags::EXTENDED_29BIT) .value("STANDARD_11BIT", Can4Python::IdentifierFlags::STANDARD_11BIT); py::enum_<Can4Python::MessageFlags>(clsCan4Python, "MessageFlags") .value("USE_BRS", Can4Python::MessageFlags::USE_BRS) .value("USE_EDL", Can4Python::MessageFlags::USE_EDL) .value("USE_EXT", Can4Python::MessageFlags::USE_EXT); clsCan4Python.def(py::init<>()); clsCan4Python.def("GetDeviceCount", &Can4Python::GetDeviceCount); clsCan4Python.def("EnableTransreceiver", &Can4Python::EnableTransreceiver); clsCan4Python.def("DisableTransreceiver", &Can4Python::DisableTransreceiver); clsCan4Python.def("OpenCan20", &Can4Python::OpenCan20); clsCan4Python.def("OpenCanFD", &Can4Python::OpenCanFD); clsCan4Python.def("CloseCan", &Can4Python::CloseCan); clsCan4Python.def("StartReceiving", &Can4Python::StartReceiving); clsCan4Python.def("StopReceiving", &Can4Python::StopReceiving); clsCan4Python.def("SendCanMessage", &Can4Python::SendCanMessage); clsCan4Python.def("SendCanMessageAsync", &Can4Python::SendCanMessageAsync); clsCan4Python.def("GetCanMessage", &Can4Python::GetCanMessage); clsCan4Python.def("AddReceiveHandler", (int (Can4Python::*)(int, unsigned int, int) ) & Can4Python::AddReceiveHandler, "devIndex"_a, "messageId"_a, "identifierFlags"_a); clsCan4Python.def("AddReceiveHandler", (int (Can4Python::*)(int, unsigned int, unsigned int, int)) & Can4Python::AddReceiveHandler, "devIndex"_a, "lowerMessageId"_a, "higherMessageId"_a, "identifierFlags"_a); clsCan4Python.def("AddReceiveHandler", (int (Can4Python::*)(int, int)) & Can4Python::AddReceiveHandler, "devIndex"_a, "identifierFlags"_a); clsCan4Python.def("RemoveReceiveHandler", &Can4Python::RemoveReceiveHandler, "devIndex"_a, "handlerId"_a = -1); #ifdef VERSION_INFO mod.attr("__version__") = VERSION_INFO; #else mod.attr("__version__") = "dev"; #endif }
40.662921
134
0.751036
code2love
403ac187da7e7c7c5fc71365257f91d6306c8305
356
cpp
C++
dataset/test/modification/1467_rename/27/transformation_1.cpp
Karina5005/Plagiarism
ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb
[ "MIT" ]
3
2022-02-15T00:29:39.000Z
2022-03-15T08:36:44.000Z
dataset/test/modification/1467_rename/27/transformation_1.cpp
Kira5005-code/Plagiarism
ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb
[ "MIT" ]
null
null
null
dataset/test/modification/1467_rename/27/transformation_1.cpp
Kira5005-code/Plagiarism
ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb
[ "MIT" ]
null
null
null
#include <cstdio> int main() { int pwg;scanf("%d", &pwg); while (pwg--) { int awr;scanf("%d", &awr); switch (awr) { case 1: printf("9");break; case 2: printf("98");break; default: printf("989");int zqi_ifn = 0;for (int ebe = 4;ebe <= awr;ebe++) {printf("%d", zqi_ifn);zqi_ifn = (zqi_ifn + 1) % 10;}break; } printf("\n"); } return 0; }
23.733333
136
0.55618
Karina5005
403b76428c6f36b0dfa3723efaa3cd6befc6fdbc
9,350
hpp
C++
vsl/Types.hpp
VegaLib/VSL
c110b1b8ce6aa7a88d2bc97a3e99385e638dfc6d
[ "MS-PL" ]
null
null
null
vsl/Types.hpp
VegaLib/VSL
c110b1b8ce6aa7a88d2bc97a3e99385e638dfc6d
[ "MS-PL" ]
null
null
null
vsl/Types.hpp
VegaLib/VSL
c110b1b8ce6aa7a88d2bc97a3e99385e638dfc6d
[ "MS-PL" ]
null
null
null
/* * Microsoft Public License (Ms-PL) - Copyright (c) 2020-2021 Sean Moss * This file is subject to the terms and conditions of the Microsoft Public License, the text of which can be found in * the 'LICENSE' file at the root of this repository, or online at <https://opensource.org/licenses/MS-PL>. */ #pragma once #include "./Config.hpp" #include <unordered_map> #include <vector> namespace vsl { // Enum of the base shader types enum class BaseType : uint32 { Void = 0, // Special type for errors and function returns Boolean = 1, // Boolean scalar/vector Signed = 2, // Signed integer scalar/vector Unsigned = 3, // Unsigned integer scalar/vector Float = 4, // Floating point scalar/vector/matrix Sampler = 5, // Vk combined image/sampler, glsl 'sampler*D' (no separate image and sampler objects) Image = 6, // Vk storage image, glsl `image*D` w/ layout ROBuffer = 7, // Vk readonly storage buffer, glsl `readonly buffer <name> { ... }` RWBuffer = 8, // Vk read/write storage buffer, glsl `buffer <name> { ... }` ROTexels = 9, // Vk uniform texel buffer, glsl `textureBuffer` RWTexels = 10, // Vk storage texel buffer, glsl `imageBuffer` w/ layout SPInput = 11, // Vk input attachment, glsl `[ ui]subpassInput` Uniform = 12, // Vk uniform buffer, glsl `uniform <name> { ... }` Struct = 13, // User-defined POD struct // Max value MAX = Struct }; // enum class BaseType struct ShaderType; // Describes a user-defined struct type struct StructType final { public: struct Member final { string name; uint32 arraySize; const ShaderType* type; }; // struct Member StructType(const string& name, const std::vector<Member>& members); StructType() : StructType("INVALID", {}) { } ~StructType() { } /* Fields */ inline const string& name() const { return name_; } inline const std::vector<Member>& members() const { return members_; } inline const std::vector<uint32>& offsets() const { return offsets_; } inline uint32 size() const { return size_; } inline uint32 alignment() const { return alignment_; } /* Member Access */ const Member* getMember(const string& name, uint32* offset = nullptr) const; inline bool hasMember(const string& name) const { return !!getMember(name, nullptr); } private: string name_; std::vector<Member> members_; std::vector<uint32> offsets_; uint32 size_; uint32 alignment_; }; // struct StructType // The different ranks (dimension counts) that texel-like objects can have enum class TexelRank : uint32 { E1D = 0, // Single 1D texture E2D = 1, // Single 2D texture E3D = 2, // Single 3D texture E1DArray = 3, // Array of 1D textures E2DArray = 4, // Array of 2D textures Cube = 5, // Single cubemap texture Buffer = 6, // The dims specific to a ROTexels object // Max value MAX = Buffer }; // enum class TexelRank string TexelRankGetSuffix(TexelRank rank); uint32 TexelRankGetComponentCount(TexelRank rank); // The base types for texel formats enum class TexelType : uint32 { Signed = 0, Unsigned = 1, Float = 2, UNorm = 3, SNorm = 4, MAX = SNorm }; // Describes a texel format struct TexelFormat final { public: TexelFormat() : type{}, size{ 0 }, count{ 0 } { } TexelFormat(TexelType type, uint32 size, uint32 count) : type{ type }, size{ size }, count{ count } { } /* Base Type Checks */ inline bool isSigned() const { return type == TexelType::Signed; } inline bool isUnsigned() const { return type == TexelType::Unsigned; } inline bool isFloat() const { return type == TexelType::Float; } inline bool isUNorm() const { return type == TexelType::UNorm; } inline bool isSNorm() const { return type == TexelType::SNorm; } inline bool isIntegerType() const { return isSigned() || isUnsigned(); } inline bool isFloatingType() const { return isFloat() || isUNorm() || isSNorm(); } inline bool isNormlizedType() const { return isUNorm() || isSNorm(); } /* Type Check */ bool isSame(const TexelFormat* format) const; /* Names */ string getVSLName() const; string getGLSLName() const; string getVSLPrefix() const; string getGLSLPrefix() const; /* Conversion */ const ShaderType* asDataType() const; public: TexelType type; uint32 size; uint32 count; }; // struct TexelFormat // Contains complete type information (minus array size) about an object, variable, or result struct ShaderType final { public: ShaderType() : baseType{ BaseType::Void }, texel{} { } ShaderType(BaseType numericType, uint32 size, uint32 components, uint32 columns) : baseType{ numericType }, texel{} { numeric = { size, { components, columns } }; } ShaderType(BaseType texelObjectType, TexelRank rank, const TexelFormat* format) : baseType{ texelObjectType }, texel{ rank, format } { } ShaderType(const BaseType bufferType, const ShaderType* structType) : baseType{ bufferType }, texel{} { buffer.structType = structType; } ShaderType(const StructType* structType) : baseType{ BaseType::Struct }, texel{} { userStruct.type = structType; } /* Base Type Checks */ inline bool isVoid() const { return baseType == BaseType::Void; } inline bool isBoolean() const { return baseType == BaseType::Boolean; } inline bool isSigned() const { return baseType == BaseType::Signed; } inline bool isUnsigned() const { return baseType == BaseType::Unsigned; } inline bool isFloat() const { return baseType == BaseType::Float; } inline bool isSampler() const { return baseType == BaseType::Sampler; } inline bool isImage() const { return baseType == BaseType::Image; } inline bool isROBuffer() const { return baseType == BaseType::ROBuffer; } inline bool isRWBuffer() const { return baseType == BaseType::RWBuffer; } inline bool isROTexels() const { return baseType == BaseType::ROTexels; } inline bool isRWTexels() const { return baseType == BaseType::RWTexels; } inline bool isSPInput() const { return baseType == BaseType::SPInput; } inline bool isUniform() const { return baseType == BaseType::Uniform; } inline bool isStruct() const { return baseType == BaseType::Struct; } /* Composite Type Checks */ inline bool isInteger() const { return isSigned() || isUnsigned(); } inline bool isNumericType() const { return isInteger() || isFloat(); } inline bool isScalar() const { return (isNumericType() || isBoolean()) && (numeric.dims[0] == 1) && (numeric.dims[1] == 1); } inline bool isVector() const { return (isNumericType() || isBoolean()) && (numeric.dims[0] != 1) && (numeric.dims[1] == 1); } inline bool isMatrix() const { return isNumericType() && (numeric.dims[0] != 1) && (numeric.dims[1] != 1); } inline bool isTexelType() const { return isSampler() || isImage() || isROTexels() || isRWTexels() || isSPInput(); } inline bool isBufferType() const { return isROBuffer() || isRWBuffer(); } inline bool hasStructType() const { return isUniform() || isBufferType() || isStruct(); } /* Casting */ bool isSame(const ShaderType* otherType) const; bool hasImplicitCast(const ShaderType* targetType) const; /* Names */ string getVSLName() const; string getGLSLName() const; /* Type-Specific Functions */ uint32 getBindingCount() const; /* Operators */ inline bool operator == (const ShaderType& r) const { return (this == &r) || isSame(&r); } inline bool operator != (const ShaderType& r) const { return (this != &r) && !isSame(&r); } public: BaseType baseType; union { struct NumericInfo { uint32 size; uint32 dims[2]; } numeric; struct TexelInfo { TexelRank rank; const TexelFormat* format; } texel; struct BufferInfo { const ShaderType* structType; } buffer; struct StructInfo { const StructType* type; } userStruct; }; }; // struct ShaderType // Contains a collection of types for a specific shader class TypeList final { public: using TypeMap = std::unordered_map<string, ShaderType>; using StructMap = std::unordered_map<string, StructType>; using FormatMap = std::unordered_map<string, TexelFormat>; TypeList() : types_{ }, structs_{ }, error_{ } { Initialize(); } ~TypeList() { } inline const string& lastError() const { return error_; } /* Types */ const ShaderType* addType(const string& name, const ShaderType& type); const ShaderType* getType(const string& name) const; const StructType* addStructType(const string& name, const StructType& type); const StructType* getStructType(const string& name) const; const ShaderType* parseOrGetType(const string& name); /* Access */ inline static const TypeMap& BuiltinTypes() { if (BuiltinTypes_.empty()) { Initialize(); } return BuiltinTypes_; } static const ShaderType* GetBuiltinType(const string& name); static const TexelFormat* GetTexelFormat(const string& format); static const ShaderType* GetNumericType(BaseType baseType, uint32 size, uint32 dim0, uint32 dim1); static const ShaderType* ParseGenericType(const string& baseType); private: static void Initialize(); private: TypeMap types_; // Types added by the shader, does not duplicate BuiltinTypes_ StructMap structs_; mutable string error_; static bool Initialized_; static TypeMap BuiltinTypes_; static TypeMap GenericTypes_; static FormatMap Formats_; VSL_NO_COPY(TypeList) VSL_NO_MOVE(TypeList) }; // class TypeList } // namespace vsl
31.694915
118
0.694118
VegaLib
403b95a9c060df7849f5de1ded3bd9053846e746
4,223
cpp
C++
MachoRuntimeSpy/utils.cpp
jmpews/rtspy
a2cfd5875a1a45935e5da53e8d5e4c51bf76abd7
[ "Apache-2.0" ]
30
2017-03-20T13:25:31.000Z
2021-04-25T10:22:45.000Z
MachoRuntimeSpy/utils.cpp
jmpews/rtspy
a2cfd5875a1a45935e5da53e8d5e4c51bf76abd7
[ "Apache-2.0" ]
null
null
null
MachoRuntimeSpy/utils.cpp
jmpews/rtspy
a2cfd5875a1a45935e5da53e8d5e4c51bf76abd7
[ "Apache-2.0" ]
9
2017-03-28T02:07:18.000Z
2020-05-04T09:44:31.000Z
#include "utils.hpp" #include "cli.hpp" #include <mach-o/dyld_images.h> bool readTaskMemory(task_t t, vm_address_t addr, void *buf, unsigned long len) { if(addr <= 0) Serror("memory read address < 0"); if(len <= 0) Serror("memory read length <0"); vm_size_t dataCnt = len; kern_return_t kr = vm_read_overwrite(t, addr, len, (vm_address_t)buf, (vm_size_t *)&dataCnt); if (kr) return false; if (len != dataCnt) { warnx("rt_read size return not match!"); return false; } return true; } char *readTaskString(task_t t, vm_address_t addr) { char x = '\0'; vm_address_t end; char *str = NULL; //string upper limit 0x1000 end = memorySearch(t, addr, addr + 0x1000, &x, 1); if (!end) { return NULL; } str = (char *)malloc(end - addr + 1); if (readTaskMemory(t, addr, str, end - addr + 1)) { return str; } return NULL; } task_t pid2task(unsigned int pid) { task_t t; kern_return_t ret = task_for_pid(mach_task_self(), pid, &t); if (ret != KERN_SUCCESS) { printf("Attach to: %d Failed: %d %s\n", pid, ret, mach_error_string(ret)); return 0; } return t; } //get dyld load address by task_info, TASK_DYLD_INFO vm_address_t getDyldLoadAddress(task_t task) { //http://stackoverflow.com/questions/4309117/determining-programmatically-what-modules-are-loaded-in-another-process-os-x kern_return_t kr; task_flavor_t flavor = TASK_DYLD_INFO; task_dyld_info_data_t infoData; mach_msg_type_number_t task_info_outCnt = TASK_DYLD_INFO_COUNT; kr = task_info(task, flavor, (task_info_t)&infoData, &task_info_outCnt ); if(kr){ Serror("getDyldLoadAddress:task_info error"); return 0; } struct dyld_all_image_infos *allImageInfos = (struct dyld_all_image_infos *)infoData.all_image_info_addr; allImageInfos = (struct dyld_all_image_infos *)malloc(sizeof(struct dyld_all_image_infos)); if(readTaskMemory(task, infoData.all_image_info_addr, allImageInfos, sizeof(struct dyld_all_image_infos))) { return (vm_address_t)(allImageInfos->dyldImageLoadAddress); } else { Serror("getDyldLoadAddress:readTaskMemory error"); return 0; } } vm_address_t memorySearch(task_t task, vm_address_t start, vm_address_t end, char *data, unsigned long len) { if(start <= 0) Serror("memory search address < 0"); if(start > end) Serror("memeory search end < start"); vm_address_t addr = start; char *buf = (char *)malloc(len); while (end > addr) { if (readTaskMemory(task, addr, buf, len)) if (!memcmp(buf, data, len)) { return addr; } addr += len; } return 0; // unsigned long search_block_size = 0x1000; // vm_address_t addr = start; // // char *buf = (char *)malloc(search_block_size + len); // unsigned long search_len; // search_len = search_block_size; // // while(end >= addr + len || (!end)) { // // if(readTaskMemory(task, addr, buf, search_len + len - 1)) { // if(len == 1) { // std::cout << "memorySearch: " << buf << std::endl; // } // for(char *p = buf; p < buf + search_len; p++){ // // if(!memcmp(p, data, len)) { // return addr + p - buf; // } // } // } else { // if(len == 1) { // sleep(-1); // std::cout << "memorySearch: error" << std::endl; // } // } // // addr += search_block_size; // } // // search_len = end - addr - (len - 1); // if(search_len >0 && readTaskMemory(task, addr, buf, search_len + len - 1)) { // for(char *p = buf; p < buf + search_len; p++){ // if(!memcmp(p, data, len)) { // return addr + p - buf; // } // } // } // return 0; }
29.950355
125
0.542505
jmpews
403bf13cd3d727bb040b68c6ed8860e673818d6d
5,322
cpp
C++
VEngine/src/VEngine/scene/Scene.cpp
Parsif/VEngine
a31bdb1479c4dabe6a5eb808008600e736164180
[ "MIT" ]
null
null
null
VEngine/src/VEngine/scene/Scene.cpp
Parsif/VEngine
a31bdb1479c4dabe6a5eb808008600e736164180
[ "MIT" ]
null
null
null
VEngine/src/VEngine/scene/Scene.cpp
Parsif/VEngine
a31bdb1479c4dabe6a5eb808008600e736164180
[ "MIT" ]
null
null
null
#include "precheader.h" #include "Scene.h" #include "renderer/ModelLoader.h" #include "renderer/Renderer.h" #include "renderer/MaterialLibrary.h" #include <glm/gtx/string_cast.hpp> namespace vengine { void Scene::init(Ref<Renderer> renderer) { m_renderer = renderer; create_camera(); } void Scene::on_update() { //Try to move setting params out from loop m_renderer->set_camera_params(m_active_camera); for (auto&& [view_entity, dir_light_component, transform_component] : m_registry.view<DirLightComponent, TransformComponent>().each()) { m_renderer->add_dir_light(dir_light_component, transform_component.translation); } for (auto&& [view_entity, point_light_component, transform_component] : m_registry.view<PointLightComponent, TransformComponent>().each()) { m_renderer->add_point_light(point_light_component, transform_component.translation); } for (auto&& [view_entity, sphere_area_light_component, transform_component] : m_registry.view<SphereAreaLightComponent, TransformComponent>().each()) { m_renderer->add_sphere_area_light(sphere_area_light_component, transform_component.translation); } for (auto&& [view_entity, tube_area_light_component, transform_component] : m_registry.view<TubeAreaLightComponent, TransformComponent>().each()) { m_renderer->add_tube_area_light(tube_area_light_component, transform_component.translation); } for (auto&& [view_entity, model_component, transform_component, materials_component] : m_registry.view<ModelComponent, TransformComponent, MaterialsComponent>().each()) { auto& mesh = ModelLoader::get_mesh(model_component.filepath); mesh.is_casting_shadow = true; mesh.transform = transform_component.get_transform(); mesh.materials = materials_component; m_renderer->add_drawable(mesh); } } void Scene::on_event(const Event& event) { m_active_camera.on_event(event); } [[nodiscard]] entt::entity Scene::create_empty_entity(const std::string& tag) { const auto entity = m_registry.create(); m_registry.emplace<TagComponent>(entity, tag); return entity; } void Scene::create_camera() { m_game_camera_entity = m_registry.create(); m_registry.emplace<TagComponent>(m_game_camera_entity, "Camera"); const Camera camera{ 45.0f, 0.1f, 500.f }; m_registry.emplace<CameraComponent>(m_game_camera_entity, camera); m_registry.emplace<TransformComponent>(m_game_camera_entity); } void Scene::create_model(const std::string& model_path) { const auto entity = m_registry.create(); m_registry.emplace<TagComponent>(entity, "Model entity"); m_registry.emplace<TransformComponent>(entity); m_registry.emplace<ModelComponent>(entity, model_path); m_registry.emplace<MaterialsComponent>(entity); } void Scene::destroy_entity(entt::entity entity) { m_registry.destroy(entity); } void Scene::set_game_camera_entity(entt::entity entity) { m_game_camera_entity = entity; } void Scene::clear() { m_registry.clear(); } void Scene::create_dir_light() { if (m_registry.view<DirLightComponent>().size() == Renderer::get_max_lights()) { LOG_WARNING("Too many lights") return; } const entt::entity entity = m_registry.create(); m_registry.emplace<TagComponent>(entity, "Directional light"); m_registry.emplace<TransformComponent>(entity); m_registry.emplace<DirLightComponent>(entity); } void Scene::create_point_light() { if (m_registry.view<PointLightComponent>().size() == Renderer::get_max_lights()) { LOG_WARNING("Too many lights") return; } const entt::entity entity = m_registry.create(); m_registry.emplace<TagComponent>(entity, "Point light"); m_registry.emplace<TransformComponent>(entity); m_registry.emplace<PointLightComponent>(entity); } void Scene::create_sphere_area_light() { if (m_registry.view<SphereAreaLightComponent>().size() == Renderer::get_max_lights()) { LOG_WARNING("Too many lights") return; } const entt::entity entity = m_registry.create(); m_registry.emplace<TagComponent>(entity, "Sphere area light"); m_registry.emplace<TransformComponent>(entity); m_registry.emplace<SphereAreaLightComponent>(entity); } void Scene::create_tube_area_light() { if(m_registry.view<TubeAreaLightComponent>().size() == Renderer::get_max_lights()) { LOG_WARNING("Too many lights") return; } const entt::entity entity = m_registry.create(); m_registry.emplace<TagComponent>(entity, "Tube area light"); m_registry.emplace<TransformComponent>(entity); m_registry.emplace<TubeAreaLightComponent>(entity); } void Scene::start_game() { if(m_registry.valid(m_game_camera_entity) && m_registry.has<CameraComponent>(m_game_camera_entity)) { m_is_gamemode_on = true; m_active_camera = m_registry.get<CameraComponent>(m_game_camera_entity).camera; m_active_camera.set_position(m_registry.get<TransformComponent>(m_game_camera_entity).translation); } else { LOG_ERROR("There is no camera in the scene") } } void Scene::stop_game() { m_is_gamemode_on = false; m_active_camera = m_editor_camera; } void Scene::set_environment_texture(const TextureGL& texture) const { m_renderer->set_scene_environment_map(texture); } void Scene::set_exposure(float exposure) const { m_renderer->set_exposure(exposure); } }
28.923913
151
0.753288
Parsif
403d1d9668f7539cd39f7d681a82ce208c989495
688
cc
C++
leetcode/Math/2_keys_keyboard.cc
LIZHICHAOUNICORN/Toolkits
db45dac4de14402a21be0c40ba8e87b4faeda1b6
[ "Apache-2.0" ]
null
null
null
leetcode/Math/2_keys_keyboard.cc
LIZHICHAOUNICORN/Toolkits
db45dac4de14402a21be0c40ba8e87b4faeda1b6
[ "Apache-2.0" ]
null
null
null
leetcode/Math/2_keys_keyboard.cc
LIZHICHAOUNICORN/Toolkits
db45dac4de14402a21be0c40ba8e87b4faeda1b6
[ "Apache-2.0" ]
null
null
null
#include <vector> #include "third_party/gflags/include/gflags.h" #include "third_party/glog/include/logging.h" using namespace std; // Problem: https://leetcode-cn.com/problems/2-keys-keyboard class Solution { public: int minSteps(int n) { int ret = 0; for (int i = 2; i * i < n; ++i) { while (n % i == 0) { n /= i; ret += i; } } if (n > 1) ret += n; return ret; } }; int main(int argc, char* argv[]) { google::InitGoogleLogging(argv[0]); gflags::ParseCommandLineFlags(&argc, &argv, false); Solution solu; for (int i = 3; i < 1000; ++i) { int ret = solu.minSteps(i); LOG(INFO) << "ret: " << ret; } return 0; }
19.657143
60
0.56686
LIZHICHAOUNICORN
403edaaa28d03cb446f8c7595ea664af9d30887e
126
cpp
C++
Computer_science/B06_Makefile/S1_Basics/S1_01_zZAux03.cpp
Polirecyliente/SGConocimiento
560b08984236d7a10f50c6b5e6fb28844193d81b
[ "CC-BY-4.0" ]
null
null
null
Computer_science/B06_Makefile/S1_Basics/S1_01_zZAux03.cpp
Polirecyliente/SGConocimiento
560b08984236d7a10f50c6b5e6fb28844193d81b
[ "CC-BY-4.0" ]
null
null
null
Computer_science/B06_Makefile/S1_Basics/S1_01_zZAux03.cpp
Polirecyliente/SGConocimiento
560b08984236d7a10f50c6b5e6fb28844193d81b
[ "CC-BY-4.0" ]
null
null
null
#include <iostream> using namespace std; void print_fun1() { cout << "In Section1_1AuxC, function print one" << endl; }
15.75
60
0.68254
Polirecyliente
404140631d8c24907572ed196bb6790b21d7964d
12,853
cpp
C++
src/main.cpp
sthoduka/VOCUS2
19da5f334ee59c36853a5989030ff63bc82b9f28
[ "MIT" ]
6
2018-03-21T03:33:26.000Z
2021-08-04T07:19:52.000Z
src/main.cpp
sthoduka/VOCUS2
19da5f334ee59c36853a5989030ff63bc82b9f28
[ "MIT" ]
null
null
null
src/main.cpp
sthoduka/VOCUS2
19da5f334ee59c36853a5989030ff63bc82b9f28
[ "MIT" ]
7
2017-12-01T11:01:19.000Z
2022-01-17T12:03:11.000Z
/***************************************************************************** * * main.cpp file for the saliency program VOCUS2. * A detailed description of the algorithm can be found in the paper: "Traditional Saliency Reloaded: A Good Old Model in New Shape", S. Frintrop, T. Werner, G. Martin Garcia, in Proceedings of the IEEE International Conference on Computer Vision and Pattern Recognition (CVPR), 2015. * Please cite this paper if you use our method. * * Implementation: Thomas Werner (wernert@cs.uni-bonn.de) * Design and supervision: Simone Frintrop (frintrop@iai.uni-bonn.de) * * Version 1.1 * * This code is published under the MIT License * (see file LICENSE.txt for details) * ******************************************************************************/ #include <iostream> #include <sstream> #include <unistd.h> #include <opencv2/highgui/highgui.hpp> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <sys/stat.h> #include "VOCUS2.h" using namespace std; using namespace cv; struct stat sb; int WEBCAM_MODE = -1; bool VIDEO_MODE = false; float MSR_THRESH = 0.75; // most salient region bool SHOW_OUTPUT = true; string WRITE_OUT = ""; string WRITE_PATH = ""; string OUTOUT = ""; bool WRITEPATHSET = false; bool CENTER_BIAS = false; float SIGMA, K; int MIN_SIZE, METHOD; vector<string> split_string(const string &s, char delim) { vector<string> elems; stringstream ss(s); string item; while (getline(ss, item, delim)) { elems.push_back(item); } return elems; } void print_usage(char* argv[]){ cout << "\nUsage: " << argv[0] << " [OPTIONS] <input-file(s)>" << endl << endl; cout << "===== SALIENCY =====" << endl << endl; cout << " -x <name>" << "\t\t" << "Config file (is loaded first, additional options have higher priority)" << endl << endl; cout << " -C <value>" << "\t\t" << "Used colorspace [default: 1]:" << endl; cout << "\t\t " << "0: LAB" << endl; cout << "\t\t " << "1: Opponent (CoDi)" << endl; cout << "\t\t " << "2: Opponent (Equal domains)\n" << endl; cout << " -f <value>" << "\t\t" << "Fusing operation (Feature maps) [default: 0]:" << endl; cout << " -F <value>" << "\t\t" << "Fusing operation (Conspicuity/Saliency maps) [default: 0]:" << endl; cout << "\t\t " << "0: Arithmetic mean" << endl; cout << "\t\t " << "1: Max" << endl; cout << "\t\t " << "2: Uniqueness weight\n" << endl; cout << " -p <value>" << "\t\t" << "Pyramidal structure [default: 2]:" << endl; cout << "\t\t " << "0: Two independant pyramids (Classic)" << endl; cout << "\t\t " << "1: Two pyramids derived from a base pyramid (CoDi-like)" << endl; cout << "\t\t " << "2: Surround pyramid derived from center pyramid (New)\n" << endl; cout << " -l <value>" << "\t\t" << "Start layer (included) [default: 0]" << endl << endl; cout << " -L <value>" << "\t\t" << "Stop layer (included) [default: 4]" << endl << endl; cout << " -S <value>" << "\t\t" << "No. of scales [default: 2]" << endl << endl; cout << " -c <value>" << "\t\t" << "Center sigma [default: 2]" << endl << endl; cout << " -s <value>" << "\t\t" << "Surround sigma [default: 10]" << endl << endl; //cout << " -r" << "\t\t" << "Use orientation [default: off] " << endl << endl; cout << " -e" << "\t\t" << "Use Combined Feature [default: off]" << endl << endl; cout << "===== MISC (NOT INCLUDED IN A CONFIG FILE) =====" << endl << endl; cout << " -v <id>" << "\t\t" << "Webcam source" << endl << endl; cout << " -V" << "\t\t" << "Video files" << endl << endl; cout << " -t <value>" << "\t\t" << "MSR threshold (percentage of fixation) [default: 0.75]" << endl << endl; cout << " -N" << "\t\t" << "No visualization" << endl << endl; cout << " -o <path>" << "\t\t" << "WRITE results to specified path [default: <input_path>/saliency/*]" << endl << endl; cout << " -w <path>" << "\t\t" << "WRITE all intermediate maps to an existing folder" << endl << endl; cout << " -b" << "\t\t" << "Add center bias to the saliency map\n" << endl << endl; } bool process_arguments(int argc, char* argv[], VOCUS2_Cfg& cfg, vector<char*>& files){ if(argc == 1) return false; int c; while((c = getopt(argc, argv, "bnreNhVC:x:f:F:v:l:o:L:S:c:s:t:p:w:G:")) != -1){ switch(c){ case 'h': return false; case 'C': cfg.c_space = ColorSpace(atoi(optarg)); break; case 'f': cfg.fuse_feature = FusionOperation(atoi(optarg)); break; case 'F': cfg.fuse_conspicuity = FusionOperation(atoi(optarg)); break; case 'v': WEBCAM_MODE = atoi(optarg) ; break; case 'l': cfg.start_layer = atoi(optarg); break; case 'L': cfg.stop_layer = atoi(optarg); break; case 'S': cfg.n_scales = atoi(optarg); break; case 'c': cfg.center_sigma = atof(optarg); break; case 's': cfg.surround_sigma = atof(optarg); break; case 'V': VIDEO_MODE = true; break; case 't': MSR_THRESH = atof(optarg); break; case 'N': SHOW_OUTPUT = false; break; case 'o': WRITEPATHSET = true; WRITE_PATH = string(optarg); break; case 'n': cfg.normalize = true; break; case 'r': cfg.orientation = true; break; case 'e': cfg.combined_features = true; break; case 'p': cfg.pyr_struct = PyrStructure(atoi(optarg)); case 'w': WRITE_OUT = string(optarg); break; case 'b': CENTER_BIAS = true; break; case 'x': break; default: return false; } } if(MSR_THRESH < 0 || MSR_THRESH > 1){ cerr << "MSR threshold must be in the range [0,1]" << endl; return false; } if(cfg.start_layer < 0){ cerr << "Start layer must be positive" << endl; return false; } if(cfg.start_layer > cfg.stop_layer){ cerr << "Start layer cannot be larger than stop layer" << endl; return false; } if(cfg.n_scales <= 0){ cerr << "Numbor of scales must be > 0" << endl; return false; } if(cfg.center_sigma <= 0){ cerr << "Center sigma must be positive" << endl; return false; } if(cfg.surround_sigma <= cfg.center_sigma){ cerr << "Surround sigma must be positive and largen than center sigma" << endl; return false; } for (int i = optind; i < argc; i++) files.push_back(argv[i]); if (files.size() == 0 && WEBCAM_MODE < 0) { return false; } if(files.size() == 0 && VIDEO_MODE){ return false; } if(WEBCAM_MODE >= 0 && VIDEO_MODE){ return false; } return true; } // if parameter x specified, load config file VOCUS2_Cfg create_base_config(int argc, char* argv[]){ VOCUS2_Cfg cfg; int c; while((c = getopt(argc, argv, "NbnrehVC:x:f:F:v:l:L:S:o:c:s:t:p:w:G:")) != -1){ if(c == 'x') cfg.load(optarg); } optind = 1; return cfg; } //get most salient region vector<Point> get_msr(Mat& salmap){ double ma; Point p_ma; minMaxLoc(salmap, nullptr, &ma, nullptr, &p_ma); vector<Point> msr; msr.push_back(p_ma); int pos = 0; float thresh = MSR_THRESH*ma; Mat considered = Mat::zeros(salmap.size(), CV_8U); considered.at<uchar>(p_ma) = 1; while(pos < (int)msr.size()){ int r = msr[pos].y; int c = msr[pos].x; for(int dr = -1; dr <= 1; dr++){ for(int dc = -1; dc <= 1; dc++){ if(dc == 0 && dr == 0) continue; if(considered.ptr<uchar>(r+dr)[c+dc] != 0) continue; if(r+dr < 0 || r+dr >= salmap.rows) continue; if(c+dc < 0 || c+dc >= salmap.cols) continue; if(salmap.ptr<float>(r+dr)[c+dc] >= thresh){ msr.push_back(Point(c+dc, r+dr)); considered.ptr<uchar>(r+dr)[c+dc] = 1; } } } pos++; } return msr; } int main(int argc, char* argv[]) { VOCUS2_Cfg cfg = create_base_config(argc, argv); vector<char*> files; // names of input images or video files bool correct = process_arguments(argc, argv, cfg, files); if(!correct){ print_usage(argv); return EXIT_FAILURE; } VOCUS2 vocus2(cfg); if(WEBCAM_MODE <= -1 && !VIDEO_MODE){ // if normal image double overall_time = 0; if(stat(WRITE_PATH.c_str(), &sb)!=0){ if(WRITEPATHSET){ std::cout << "Creating directory..." << std::endl; mkdir(WRITE_PATH.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); } } //test if data is image data if(files.size()>=1){ Mat img = imread(files[0]); if( !(img.channels()==3) ){ std::cout << "ABBORT: Inconsistent Image Data"<< img.channels() << std::endl; exit(-1); } } //compute saliency for(size_t i = 0; i < files.size(); i++){ cout << "Opening " << files[i] << " (" << i+1 << "/" << files.size() << "), "; Mat img = imread(files[i], 1); long long start = getTickCount(); Mat salmap; vocus2.process(img); if(CENTER_BIAS) salmap = vocus2.add_center_bias(0.00005); else salmap = vocus2.get_salmap(); long long stop = getTickCount(); double elapsed_time = (stop-start)/getTickFrequency(); cout << elapsed_time << "sec" << endl; overall_time += elapsed_time; //WRITE resulting saliency maps to path/directory string pathStr(files[i]); int found = 0; found = pathStr.find_last_of("/\\"); string path = pathStr.substr(0,found); string filename_plus = pathStr.substr(found+1); string filename = filename_plus.substr(0,filename_plus.find_last_of(".")); string WRITE_NAME = filename + "_saliency"; string WRITE_result_PATH; //if no path set, write to /saliency directory if(!WRITEPATHSET){ //get the folder, if possible if(found>=0){ string WRITE_DIR = "/saliency/"; if ( !(stat(WRITE_PATH.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode))){ mkdir((path+WRITE_DIR).c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); } WRITE_result_PATH = path + WRITE_DIR + WRITE_NAME + ".png"; } else{ //if images are in the source folder string WRITE_DIR = "saliency/"; if ( !(stat(WRITE_PATH.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode))){ mkdir((WRITE_DIR).c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); } WRITE_result_PATH = WRITE_DIR + WRITE_NAME + ".png"; } } else{ WRITE_result_PATH = WRITE_PATH+"/"+WRITE_NAME+".png"; } std::cout << "WRITE result to " << WRITE_result_PATH << std::endl << std::endl; imwrite(WRITE_result_PATH.c_str(), salmap*255.f); if(WRITE_OUT.compare("") != 0) vocus2.write_out(WRITE_OUT); vector<Point> msr = get_msr(salmap); Point2f center; float rad; minEnclosingCircle(msr, center, rad); if(rad >= 5 && rad <= max(img.cols, img.rows)){ circle(img, center, (int)rad, Scalar(0,0,255), 3); } if(SHOW_OUTPUT){ imshow("input", img); imshow("saliency normalized", salmap); waitKey(0); } img.release(); } cout << "Avg. runtime per image: " << overall_time/(double)files.size() << endl; } else if(WEBCAM_MODE >= 0 || !VIDEO_MODE){ // data from webcam double overall_time = 0; int n_frames = 0; VideoCapture vc(WEBCAM_MODE); if(!vc.isOpened()) return EXIT_FAILURE; Mat img; while(vc.read(img)){ n_frames++; long start = getTickCount(); Mat salmap; vocus2.process(img); if(CENTER_BIAS) salmap = vocus2.add_center_bias(0.00005); else salmap = vocus2.get_salmap(); long stop = getTickCount(); double elapsed_time = (stop-start)/getTickFrequency(); cout << "frame " << n_frames << ": " << elapsed_time << "sec" << endl; overall_time += elapsed_time; vector<Point> msr = get_msr(salmap); Point2f center; float rad; minEnclosingCircle(msr, center, rad); if(SHOW_OUTPUT){ imshow("input (ESC to exit)", img); imshow("saliency streched (ESC to exit)", salmap); int key_code = waitKey(30); if(key_code == 113 || key_code == 27) break; } img.release(); } vc.release(); cout << "Avg. runtime per frame: " << overall_time/(double)n_frames << endl; } else{ // Video data for(size_t i = 0; i < files.size(); i++){ // loop over video files double overall_time = 0; int n_frames = 0; VideoCapture vc(files[i]); if(!vc.isOpened()) return EXIT_FAILURE; Mat img; while(vc.read(img)){ n_frames++; long start = getTickCount(); Mat salmap; vocus2.process(img); if(!CENTER_BIAS) salmap = vocus2.get_salmap(); else salmap = vocus2.add_center_bias(0.5); long stop = getTickCount(); double elapsed_time = (stop-start)/getTickFrequency(); cout << "frame " << n_frames << ": " << elapsed_time << "sec" << endl; overall_time += elapsed_time; vector<Point> msr = get_msr(salmap); Point2f center; float rad; minEnclosingCircle(msr, center, rad); if(SHOW_OUTPUT){ imshow("input (ESC to exit)", img); imshow("saliency streched (ESC to exit)", salmap); int key_code = waitKey(30); if(key_code == 113 || key_code == 27) break; } img.release(); } vc.release(); cout << "Avg. runtime per frame: " << overall_time/(double)n_frames << endl; } } return EXIT_SUCCESS; }
27.522484
285
0.597993
sthoduka
40418b3b6842bf314c4fddc9277886581fc06913
5,112
cpp
C++
msg_re/parse_x3/src/main.cpp
Bram-Wel/routeros
21d721384c25edbca66a3d52c853edc9faa83cad
[ "BSD-3-Clause" ]
732
2018-10-07T14:51:37.000Z
2022-03-31T09:25:20.000Z
msg_re/parse_x3/src/main.cpp
Bram-Wel/routeros
21d721384c25edbca66a3d52c853edc9faa83cad
[ "BSD-3-Clause" ]
22
2018-10-09T06:49:35.000Z
2020-05-17T07:43:20.000Z
msg_re/parse_x3/src/main.cpp
Bram-Wel/routeros
21d721384c25edbca66a3d52c853edc9faa83cad
[ "BSD-3-Clause" ]
401
2018-10-07T16:28:58.000Z
2022-03-30T09:17:47.000Z
#include <fstream> #include <iostream> #include <boost/cstdint.hpp> #include <boost/scoped_array.hpp> #include <boost/program_options.hpp> namespace { const char s_version[] = "x3 parser version 1.0.0"; // at least need room for the header const boost::uint32_t s_minFileSize = 12; // this isn't actually a hard limit, but larger sizes are unexpected const boost::uint32_t s_maxFileSize = 100000; struct x3_header { // total length is the file size - 4 bytes (ie. itself) boost::uint32_t m_totalLength; // unused? boost::uint32_t m_reserved0; // unused? boost::uint32_t m_reserved1; }; struct x3_entry { boost::uint32_t m_length; boost::uint32_t m_type; }; bool parseCommandLine(int p_argCount, const char* p_argArray[], std::string& p_file) { boost::program_options::options_description description("options"); description.add_options() ("help,h", "A list of command line options") ("version,v", "Display version information") ("file,f", boost::program_options::value<std::string>(), "The file to parse"); boost::program_options::variables_map argv_map; try { boost::program_options::store( boost::program_options::parse_command_line( p_argCount, p_argArray, description), argv_map); } catch (const std::exception& e) { std::cerr << e.what() << std::endl; std::cout << description << std::endl; return false; } boost::program_options::notify(argv_map); if (argv_map.empty() || argv_map.count("help")) { std::cout << description << std::endl; return false; } if (argv_map.count("version")) { std::cout << "Version: " << ::s_version << std::endl; return false; } if (argv_map.count("file")) { p_file.assign(argv_map["file"].as<std::string>()); return true; } return false; } } int main(int p_argc, const char** p_argv) { std::string file; if (!parseCommandLine(p_argc, p_argv, file)) { return EXIT_FAILURE; } std::ifstream fileStream(file, std::ios::in | std::ios::binary | std::ios::ate); if (!fileStream.is_open()) { std::cerr << "Failed to open " << file << std::endl; return EXIT_FAILURE; } std::streampos fileSize = fileStream.tellg(); if (fileSize < s_minFileSize || fileSize > s_maxFileSize) { std::cerr << "Bad file size: " << fileSize << std::endl; fileStream.close(); return EXIT_FAILURE; } // read the file into an array boost::scoped_array<char> memblock(new char[fileSize]); fileStream.seekg(0, std::ios::beg); fileStream.read(memblock.get(), fileSize); fileStream.close(); const x3_header* head = reinterpret_cast<const x3_header*>(memblock.get()); if (head->m_totalLength != (static_cast<boost::uint32_t>(fileSize) - 4)) { std::cerr << "Invalid total size." << std::endl; return EXIT_FAILURE; } const char* memoryEnd = memblock.get() + fileSize; const char* memoryCurrent = memblock.get() + 12; for (const x3_entry* entry = reinterpret_cast<const x3_entry*>(memoryCurrent); (reinterpret_cast<const char*>(entry) + 12) < memoryEnd; memoryCurrent += entry->m_length + 4, entry = reinterpret_cast<const x3_entry*>(memoryCurrent)) { // the outter entry should always be of type 0x1e if (entry->m_type != 0x1e) { std::cerr << "Parsing error." << std::endl; return EXIT_FAILURE; } for (const x3_entry* inner_entry = reinterpret_cast<const x3_entry*>(memoryCurrent + 12); reinterpret_cast<const char*>(inner_entry) < (memoryCurrent + entry->m_length + 4); inner_entry = reinterpret_cast<const x3_entry*>(reinterpret_cast<const char*>(inner_entry) + inner_entry->m_length + 4)) { switch (inner_entry->m_type) { case 0x04: // the router number { const char* route = reinterpret_cast<const char*>(inner_entry) + inner_entry->m_length; std::cout << ","; for (boost::uint8_t i = 0; i < 4; i++) { if (route[i] != 0) { std::cout << route[i]; } } std::cout << std::endl; } break; case 0x07: // the binary name { std::string path(reinterpret_cast<const char*>(inner_entry) + 20, inner_entry->m_length - 16); std::cout << path; } break; default: break; } } } return EXIT_SUCCESS; }
31.170732
133
0.544405
Bram-Wel
4045ef2d3dc6f14adcf1e7a489ccfcb50f8ab5a7
1,603
hh
C++
include/sot/torque_control/utils/lin-estimator.hh
nim65s/sot-torque-control
0277baa065e6addf16df804676d47597cf1b4b06
[ "BSD-2-Clause" ]
6
2017-11-01T20:14:53.000Z
2020-04-03T04:51:07.000Z
include/sot/torque_control/utils/lin-estimator.hh
nim65s/sot-torque-control
0277baa065e6addf16df804676d47597cf1b4b06
[ "BSD-2-Clause" ]
52
2017-03-31T21:24:38.000Z
2021-11-03T08:27:46.000Z
include/sot/torque_control/utils/lin-estimator.hh
nim65s/sot-torque-control
0277baa065e6addf16df804676d47597cf1b4b06
[ "BSD-2-Clause" ]
14
2017-04-06T20:03:27.000Z
2020-07-28T14:20:42.000Z
/* Oscar Efrain RAMOS PONCE, LAAS-CNRS Date: 28/10/2014 Object to estimate a polynomial of first order that fits some data. */ #ifndef _LIN_ESTIMATOR_HH_ #define _LIN_ESTIMATOR_HH_ #include <sot/torque_control/utils/poly-estimator.hh> /** * Object to fit a first order polynomial to a given data. This can be used to * compute the velocities given the positions. */ class LinEstimator : public PolyEstimator { public: /** * Create a linear estimator on a window of length N * @param N is the window length. * @param dim is the dimension of the input elements (number of dofs). * @param dt is the control (sampling) time. */ LinEstimator(const unsigned int& N, const unsigned int& dim, const double& dt = 0.0); virtual void estimate(std::vector<double>& estimee, const std::vector<double>& el); virtual void estimateRecursive(std::vector<double>& estimee, const std::vector<double>& el, const double& time); void getEstimateDerivative(std::vector<double>& estimeeDerivative, const unsigned int order); private: virtual void fit(); virtual double getEsteeme(); int dim_; // size of the data // Sums for the recursive computation double sum_ti_; double sum_ti2_; std::vector<double> sum_xi_; std::vector<double> sum_tixi_; // coefficients of the polynomial c2*x^2 + c1*x + c0 std::vector<double> c0_; std::vector<double> c1_; // Rows of the pseudo-inverse (when assuming constant sample time) double* pinv0_; double* pinv1_; // Half of the maximum time (according to the size of the window and dt) double tmed_; }; #endif
28.625
114
0.716157
nim65s
4047ee09ebe17c6fbed2988abb3bf23a30aab4cc
2,213
cpp
C++
Lab 09/lab9.cpp
ndbeals/Operating-System-Labs
a691558b240fd54ce8272ee2b045cd4c4743804c
[ "MIT" ]
null
null
null
Lab 09/lab9.cpp
ndbeals/Operating-System-Labs
a691558b240fd54ce8272ee2b045cd4c4743804c
[ "MIT" ]
null
null
null
Lab 09/lab9.cpp
ndbeals/Operating-System-Labs
a691558b240fd54ce8272ee2b045cd4c4743804c
[ "MIT" ]
null
null
null
#include <iostream> #include <stdio.h> #include <string> #include <numeric> #include <algorithm> // supplied values int blockSize[] = {5,10,50,100}; int numBlocks = sizeof blockSize / sizeof blockSize[0]; int processSize[] = {11,6,34,5,25,60}; int numberOfProcesses = sizeof processSize / sizeof processSize[0]; // process struct struct Process { int pid; int blockNumberFF; int blockNumberNF; int size; }; int main() { // create an array to hold our processes Process* list[numberOfProcesses]; // populate array for(int i = 0; i < numberOfProcesses; i++) { list[i] = new Process{ i+1 , 0 , 0 , processSize[i] }; } // First First for(int pid = 0; pid < numberOfProcesses; pid++) { Process* proc = list[pid]; for(int block = 0; block < numBlocks; block++) { // if the process size is less than or equal to block size, assign it to this block if (proc->size <= blockSize[block] ) { proc->blockNumberFF = block + 1; // subtract size from remaining blockSize[block] -= proc->size; //exit loop break; } } } int blockSize[] = {5,10,50,100}; // Best Fit int lastblock = 0; for(int pid = 0; pid < numberOfProcesses; pid++) { for(int block = lastblock; block < numBlocks; block++) { Process* proc = list[pid]; // if the process size is less than or equal to block size, assign it to this block if (proc->size <= blockSize[block] && proc->blockNumberNF < 1 ) { proc->blockNumberNF = block + 1; // subtract size from remaining blockSize[block] -= proc->size; lastblock=block; } } } // print processes printf("First Fit:\nPID Process Size Block no.\n"); for(int pid = 0; pid < numberOfProcesses; pid++) { Process* proc = list[pid]; printf(" %d %2d %d\n",proc->pid,proc->size,proc->blockNumberFF); } // print processes printf("Next Fit:\nPID Process Size Block no.\n"); for(int pid = 0; pid < numberOfProcesses; pid++) { Process* proc = list[pid]; if (proc->blockNumberNF==0) { printf(" %d %2d %s\n",proc->pid,proc->size,"Not Allocated"); } else { printf(" %d %2d %d\n",proc->pid,proc->size,proc->blockNumberNF); } } }
22.581633
86
0.617714
ndbeals
4048742113c630cd43b4c35c76e0e91c1a86eadf
18,177
cxx
C++
pandatool/src/palettizer/txaLine.cxx
kestred/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
3
2018-03-09T12:07:29.000Z
2021-02-25T06:50:25.000Z
pandatool/src/palettizer/txaLine.cxx
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
pandatool/src/palettizer/txaLine.cxx
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
// Filename: txaLine.cxx // Created by: drose (30Nov00) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #include "txaLine.h" #include "pal_string_utils.h" #include "eggFile.h" #include "palettizer.h" #include "textureImage.h" #include "sourceTextureImage.h" #include "paletteGroup.h" #include "pnotify.h" #include "pnmFileType.h" //////////////////////////////////////////////////////////////////// // Function: TxaLine::Constructor // Access: Public // Description: //////////////////////////////////////////////////////////////////// TxaLine:: TxaLine() { _size_type = ST_none; _scale = 0.0; _x_size = 0; _y_size = 0; _aniso_degree = 0; _num_channels = 0; _format = EggTexture::F_unspecified; _force_format = false; _generic_format = false; _keep_format = false; _alpha_mode = EggRenderMode::AM_unspecified; _wrap_u = EggTexture::WM_unspecified; _wrap_v = EggTexture::WM_unspecified; _quality_level = EggTexture::QL_unspecified; _got_margin = false; _margin = 0; _got_coverage_threshold = false; _coverage_threshold = 0.0; _color_type = (PNMFileType *)NULL; _alpha_type = (PNMFileType *)NULL; } //////////////////////////////////////////////////////////////////// // Function: TxaLine::parse // Access: Public // Description: Accepts a string that defines a line of the .txa file // and parses it into its constinuent parts. Returns // true if successful, false on error. //////////////////////////////////////////////////////////////////// bool TxaLine:: parse(const string &line) { size_t colon = line.find(':'); if (colon == string::npos) { nout << "Colon required.\n"; return false; } // Chop up the first part of the string (preceding the colon) into // its individual words. These are patterns to match. vector_string words; extract_words(line.substr(0, colon), words); vector_string::iterator wi; for (wi = words.begin(); wi != words.end(); ++wi) { string word = (*wi); // If the pattern ends in the string ".egg", and only if it ends // in this string, it is deemed an egg pattern and will only be // tested against egg files. If it ends in anything else, it is // deemed a texture pattern and will only be tested against // textures. if (word.length() > 4 && word.substr(word.length() - 4) == ".egg") { GlobPattern pattern(word); pattern.set_case_sensitive(false); _egg_patterns.push_back(pattern); } else { // However, the filename extension, if any, is stripped off // because the texture key names nowadays don't include them. size_t dot = word.rfind('.'); if (dot != string::npos) { word = word.substr(0, dot); } GlobPattern pattern(word); pattern.set_case_sensitive(false); _texture_patterns.push_back(pattern); } } if (_egg_patterns.empty() && _texture_patterns.empty()) { nout << "No texture or egg filenames given.\n"; return false; } // Now chop up the rest of the string (following the colon) into its // individual words. These are keywords and size indications. words.clear(); extract_words(line.substr(colon + 1), words); wi = words.begin(); while (wi != words.end()) { const string &word = *wi; nassertr(!word.empty(), false); if (isdigit(word[0])) { // This is either a new size or a scale percentage. if (_size_type != ST_none) { nout << "Invalid repeated size request: " << word << "\n"; return false; } if (word[word.length() - 1] == '%') { // It's a scale percentage! _size_type = ST_scale; string tail; _scale = string_to_double(word, tail); if (!(tail == "%")) { // This is an invalid number. return false; } ++wi; } else { // Collect a number of consecutive numeric fields. pvector<int> numbers; while (wi != words.end() && isdigit((*wi)[0])) { const string &word = *wi; int num; if (!string_to_int(word, num)) { nout << "Invalid size: " << word << "\n"; return false; } numbers.push_back(num); ++wi; } if (numbers.size() < 2) { nout << "At least two size numbers must be given, or a percent sign used to indicate scaling.\n"; return false; } else if (numbers.size() == 2) { _size_type = ST_explicit_2; _x_size = numbers[0]; _y_size = numbers[1]; } else if (numbers.size() == 3) { _size_type = ST_explicit_3; _x_size = numbers[0]; _y_size = numbers[1]; _num_channels = numbers[2]; } else { nout << "Too many size numbers given.\n"; return false; } } } else { // The word does not begin with a digit; therefore it's either a // keyword or an image file type request. if (word == "omit") { _keywords.push_back(KW_omit); } else if (word == "nearest") { _keywords.push_back(KW_nearest); } else if (word == "linear") { _keywords.push_back(KW_linear); } else if (word == "mipmap") { _keywords.push_back(KW_mipmap); } else if (word == "cont") { _keywords.push_back(KW_cont); } else if (word == "margin") { ++wi; if (wi == words.end()) { nout << "Argument required for 'margin'.\n"; return false; } const string &arg = (*wi); if (!string_to_int(arg, _margin)) { nout << "Not an integer: " << arg << "\n"; return false; } if (_margin < 0) { nout << "Invalid margin: " << _margin << "\n"; return false; } _got_margin = true; } else if (word == "aniso") { ++wi; if (wi == words.end()) { nout << "Integer argument required for 'aniso'.\n"; return false; } const string &arg = (*wi); if (!string_to_int(arg, _aniso_degree)) { nout << "Not an integer: " << arg << "\n"; return false; } if ((_aniso_degree < 2) || (_aniso_degree > 16)) { // make it an error to specific degree 0 or 1, which means no anisotropy so it's probably an input mistake nout << "Invalid anistropic degree (range is 2-16): " << _aniso_degree << "\n"; return false; } _keywords.push_back(KW_anisotropic); } else if (word == "coverage") { ++wi; if (wi == words.end()) { nout << "Argument required for 'coverage'.\n"; return false; } const string &arg = (*wi); if (!string_to_double(arg, _coverage_threshold)) { nout << "Not a number: " << arg << "\n"; return false; } if (_coverage_threshold <= 0.0) { nout << "Invalid coverage threshold: " << _coverage_threshold << "\n"; return false; } _got_coverage_threshold = true; } else if (word.substr(0, 6) == "force-") { // Force a particular format, despite the number of channels // in the image. string format_name = word.substr(6); EggTexture::Format format = EggTexture::string_format(format_name); if (format != EggTexture::F_unspecified) { _format = format; _force_format = true; } else { nout << "Unknown image format: " << format_name << "\n"; return false; } } else if (word == "generic") { // Genericize the image format by replacing bitcount-specific // formats with their generic equivalents, e.g. rgba8 becomes // rgba. _generic_format = true; } else if (word == "keep-format") { // Keep whatever image format was specified. _keep_format = true; } else { // Maybe it's a group name. PaletteGroup *group = pal->test_palette_group(word); if (group != (PaletteGroup *)NULL) { _palette_groups.insert(group); } else { // Maybe it's a format name. This suggests an image format, // but may be overridden to reflect the number of channels in // the image. EggTexture::Format format = EggTexture::string_format(word); if (format != EggTexture::F_unspecified) { if (!_force_format) { _format = format; } } else { // Maybe it's an alpha mode. EggRenderMode::AlphaMode am = EggRenderMode::string_alpha_mode(word); if (am != EggRenderMode::AM_unspecified) { _alpha_mode = am; } else { // Maybe it's a quality level. EggTexture::QualityLevel ql = EggTexture::string_quality_level(word); if (ql != EggTexture::QL_unspecified) { _quality_level = ql; } else if (word.length() > 2 && word[word.length() - 2] == '_' && strchr("uv", word[word.length() - 1]) != NULL) { // It must be a wrap mode for u or v. string prefix = word.substr(0, word.length() - 2); EggTexture::WrapMode wm = EggTexture::string_wrap_mode(prefix); if (wm == EggTexture::WM_unspecified) { return false; } switch (word[word.length() - 1]) { case 'u': _wrap_u = wm; break; case 'v': _wrap_v = wm; break; } } else { // Maybe it's an image file request. if (!parse_image_type_request(word, _color_type, _alpha_type)) { return false; } } } } } } ++wi; } } return true; } //////////////////////////////////////////////////////////////////// // Function: TxaLine::match_egg // Access: Public // Description: Compares the patterns on the line to the indicated // EggFile. If they match, updates the egg with the // appropriate information. Returns true if a match is // detected and the search for another line should stop, // or false if a match is not detected (or if the // keyword "cont" is present, which means the search // should continue regardless). //////////////////////////////////////////////////////////////////// bool TxaLine:: match_egg(EggFile *egg_file) const { string name = egg_file->get_name(); bool matched_any = false; Patterns::const_iterator pi; for (pi = _egg_patterns.begin(); pi != _egg_patterns.end() && !matched_any; ++pi) { matched_any = (*pi).matches(name); } if (!matched_any) { // No match this line; continue. return false; } bool got_cont = false; Keywords::const_iterator ki; for (ki = _keywords.begin(); ki != _keywords.end(); ++ki) { switch (*ki) { case KW_omit: break; case KW_nearest: case KW_linear: case KW_mipmap: case KW_anisotropic: // These mean nothing to an egg file. break; case KW_cont: got_cont = true; break; } } egg_file->match_txa_groups(_palette_groups); if (got_cont) { // If we have the "cont" keyword, we should keep scanning for // another line, even though we matched this one. return false; } // Otherwise, in the normal case, a match ends the search for // matches. egg_file->clear_surprise(); return true; } //////////////////////////////////////////////////////////////////// // Function: TxaLine::match_texture // Access: Public // Description: Compares the patterns on the line to the indicated // TextureImage. If they match, updates the texture // with the appropriate information. Returns true if a // match is detected and the search for another line // should stop, or false if a match is not detected (or // if the keyword "cont" is present, which means the // search should continue regardless). //////////////////////////////////////////////////////////////////// bool TxaLine:: match_texture(TextureImage *texture) const { string name = texture->get_name(); bool matched_any = false; Patterns::const_iterator pi; for (pi = _texture_patterns.begin(); pi != _texture_patterns.end() && !matched_any; ++pi) { matched_any = (*pi).matches(name); } if (!matched_any) { // No match this line; continue. return false; } SourceTextureImage *source = texture->get_preferred_source(); TextureRequest &request = texture->_request; if (!request._got_size) { switch (_size_type) { case ST_none: break; case ST_scale: if (source != (SourceTextureImage *)NULL && source->get_size()) { request._got_size = true; request._x_size = max(1, (int)(source->get_x_size() * _scale / 100.0)); request._y_size = max(1, (int)(source->get_y_size() * _scale / 100.0)); } break; case ST_explicit_3: request._got_num_channels = true; request._num_channels = _num_channels; // fall through case ST_explicit_2: request._got_size = true; request._x_size = _x_size; request._y_size = _y_size; break; } } if (_got_margin) { request._margin = _margin; } if (_got_coverage_threshold) { request._coverage_threshold = _coverage_threshold; } if (_color_type != (PNMFileType *)NULL) { request._properties._color_type = _color_type; request._properties._alpha_type = _alpha_type; } if (_quality_level != EggTexture::QL_unspecified) { request._properties._quality_level = _quality_level; } if (_format != EggTexture::F_unspecified) { request._format = _format; request._force_format = _force_format; request._generic_format = false; } if (_generic_format) { request._generic_format = true; } if (_keep_format) { request._keep_format = true; } if (_alpha_mode != EggRenderMode::AM_unspecified) { request._alpha_mode = _alpha_mode; } if (_wrap_u != EggTexture::WM_unspecified) { request._wrap_u = _wrap_u; } if (_wrap_v != EggTexture::WM_unspecified) { request._wrap_v = _wrap_v; } bool got_cont = false; Keywords::const_iterator ki; for (ki = _keywords.begin(); ki != _keywords.end(); ++ki) { switch (*ki) { case KW_omit: request._omit = true; break; case KW_nearest: request._minfilter = EggTexture::FT_nearest; request._magfilter = EggTexture::FT_nearest; break; case KW_linear: request._minfilter = EggTexture::FT_linear; request._magfilter = EggTexture::FT_linear; break; case KW_mipmap: request._minfilter = EggTexture::FT_linear_mipmap_linear; request._magfilter = EggTexture::FT_linear_mipmap_linear; break; case KW_anisotropic: request._anisotropic_degree = _aniso_degree; break; case KW_cont: got_cont = true; break; } } texture->_explicitly_assigned_groups.make_union (texture->_explicitly_assigned_groups, _palette_groups); texture->_explicitly_assigned_groups.remove_null(); if (got_cont) { // If we have the "cont" keyword, we should keep scanning for // another line, even though we matched this one. return false; } // Otherwise, in the normal case, a match ends the search for // matches. texture->_is_surprise = false; return true; } //////////////////////////////////////////////////////////////////// // Function: TxaLine::output // Access: Public // Description: //////////////////////////////////////////////////////////////////// void TxaLine:: output(ostream &out) const { Patterns::const_iterator pi; for (pi = _texture_patterns.begin(); pi != _texture_patterns.end(); ++pi) { out << (*pi) << " "; } for (pi = _egg_patterns.begin(); pi != _egg_patterns.end(); ++pi) { out << (*pi) << " "; } out << ":"; switch (_size_type) { case ST_none: break; case ST_scale: out << " " << _scale << "%"; break; case ST_explicit_2: out << " " << _x_size << " " << _y_size; break; case ST_explicit_3: out << " " << _x_size << " " << _y_size << " " << _num_channels; break; } if (_got_margin) { out << " margin " << _margin; } if (_got_coverage_threshold) { out << " coverage " << _coverage_threshold; } Keywords::const_iterator ki; for (ki = _keywords.begin(); ki != _keywords.end(); ++ki) { switch (*ki) { case KW_omit: out << " omit"; break; case KW_nearest: out << " nearest"; break; case KW_linear: out << " linear"; break; case KW_mipmap: out << " mipmap"; break; case KW_cont: out << " cont"; break; case KW_anisotropic: out << " aniso " << _aniso_degree; break; } } PaletteGroups::const_iterator gi; for (gi = _palette_groups.begin(); gi != _palette_groups.end(); ++gi) { out << " " << (*gi)->get_name(); } if (_format != EggTexture::F_unspecified) { out << " " << _format; if (_force_format) { out << " (forced)"; } } if (_color_type != (PNMFileType *)NULL) { out << " " << _color_type->get_suggested_extension(); if (_alpha_type != (PNMFileType *)NULL) { out << "," << _alpha_type->get_suggested_extension(); } } }
28.898251
116
0.550641
kestred
4049ab855718aaf0cb3883e3cb1477f844a019cd
2,893
cpp
C++
src/mame/video/exterm.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/mame/video/exterm.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/mame/video/exterm.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:Alex Pasadyn,Zsolt Vasvari,Aaron Giles /*************************************************************************** Gottlieb Exterminator hardware ***************************************************************************/ #include "emu.h" #include "includes/exterm.h" /************************************* * * Palette setup * *************************************/ void exterm_state::exterm_palette(palette_device &palette) const { // initialize 555 RGB lookup for (int i = 0; i < 32768; i++) palette.set_pen_color(i + 0x800, pal5bit(i >> 10), pal5bit(i >> 5), pal5bit(i >> 0)); } /************************************* * * Master shift register * *************************************/ TMS340X0_TO_SHIFTREG_CB_MEMBER(exterm_state::to_shiftreg_master) { memcpy(shiftreg, &m_master_videoram[address >> 4], 256 * sizeof(uint16_t)); } TMS340X0_FROM_SHIFTREG_CB_MEMBER(exterm_state::from_shiftreg_master) { memcpy(&m_master_videoram[address >> 4], shiftreg, 256 * sizeof(uint16_t)); } TMS340X0_TO_SHIFTREG_CB_MEMBER(exterm_state::to_shiftreg_slave) { memcpy(shiftreg, &m_slave_videoram[address >> 4], 256 * 2 * sizeof(uint8_t)); } TMS340X0_FROM_SHIFTREG_CB_MEMBER(exterm_state::from_shiftreg_slave) { memcpy(&m_slave_videoram[address >> 4], shiftreg, 256 * 2 * sizeof(uint8_t)); } /************************************* * * Main video refresh * *************************************/ TMS340X0_SCANLINE_IND16_CB_MEMBER(exterm_state::scanline_update) { uint16_t *const bgsrc = &m_master_videoram[(params->rowaddr << 8) & 0xff00]; uint16_t *const dest = &bitmap.pix(scanline); tms340x0_device::display_params fgparams; int coladdr = params->coladdr; int fgcoladdr = 0; /* get parameters for the slave CPU */ m_slave->get_display_params(&fgparams); /* compute info about the slave vram */ uint16_t *fgsrc = nullptr; if (fgparams.enabled && scanline >= fgparams.veblnk && scanline < fgparams.vsblnk && fgparams.heblnk < fgparams.hsblnk) { fgsrc = &m_slave_videoram[((fgparams.rowaddr << 8) + (fgparams.yoffset << 7)) & 0xff80]; fgcoladdr = (fgparams.coladdr >> 1); } /* copy the non-blanked portions of this scanline */ for (int x = params->heblnk; x < params->hsblnk; x += 2) { uint16_t bgdata, fgdata = 0; if (fgsrc != nullptr) fgdata = fgsrc[fgcoladdr++ & 0x7f]; bgdata = bgsrc[coladdr++ & 0xff]; if ((bgdata & 0xe000) == 0xe000) dest[x + 0] = bgdata & 0x7ff; else if ((fgdata & 0x00ff) != 0) dest[x + 0] = fgdata & 0x00ff; else dest[x + 0] = (bgdata & 0x8000) ? (bgdata & 0x7ff) : (bgdata + 0x800); bgdata = bgsrc[coladdr++ & 0xff]; if ((bgdata & 0xe000) == 0xe000) dest[x + 1] = bgdata & 0x7ff; else if ((fgdata & 0xff00) != 0) dest[x + 1] = fgdata >> 8; else dest[x + 1] = (bgdata & 0x8000) ? (bgdata & 0x7ff) : (bgdata + 0x800); } }
26.541284
120
0.58728
Robbbert