hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
47420fe837713722b30bd054801315dea2aff39d
3,659
cpp
C++
source/ff.dx12/source/queue.cpp
spadapet/ff_game_library
f1bf00f90adde66c2c2aa35b109fe61b8d2c6352
[ "MIT" ]
null
null
null
source/ff.dx12/source/queue.cpp
spadapet/ff_game_library
f1bf00f90adde66c2c2aa35b109fe61b8d2c6352
[ "MIT" ]
null
null
null
source/ff.dx12/source/queue.cpp
spadapet/ff_game_library
f1bf00f90adde66c2c2aa35b109fe61b8d2c6352
[ "MIT" ]
null
null
null
#include "pch.h" #include "access.h" #include "device_reset_priority.h" #include "fence.h" #include "globals.h" #include "queue.h" ff::dx12::queue::queue(D3D12_COMMAND_LIST_TYPE type) : type(type) { this->reset(); ff::dx12::add_device_child(this, ff::dx12::device_reset_priority::queue); } ff::dx12::queue::~queue() { ff::dx12::remove_device_child(this); } ff::dx12::queue::operator bool() const { return this->command_queue != nullptr; } void ff::dx12::queue::wait_for_idle() { ff::dx12::fence fence(this); fence.signal(this).wait(nullptr); } ff::dx12::commands ff::dx12::queue::new_commands(ID3D12PipelineStateX* initial_state) { Microsoft::WRL::ComPtr<ID3D12GraphicsCommandListX> list; Microsoft::WRL::ComPtr<ID3D12CommandAllocatorX> allocator; std::unique_ptr<ff::dx12::fence> fence; { std::scoped_lock lock(this->mutex); if (this->allocators.empty() || !this->allocators.front().first.complete()) { ff::dx12::device()->CreateCommandAllocator(this->type, IID_PPV_ARGS(&allocator)); } else { allocator = std::move(this->allocators.front().second); this->allocators.pop_front(); } if (this->lists.empty()) { ff::dx12::device()->CreateCommandList1(0, this->type, D3D12_COMMAND_LIST_FLAG_NONE, IID_PPV_ARGS(&list)); } else { list = std::move(this->lists.front()); this->lists.pop_front(); } if (this->fences.empty()) { fence = std::make_unique<ff::dx12::fence>(this); } else { fence = std::move(this->fences.front()); this->fences.pop_front(); } } allocator->Reset(); return ff::dx12::commands(*this, list.Get(), allocator.Get(), std::move(fence), initial_state); } void ff::dx12::queue::execute(ff::dx12::commands& commands) { ff::dx12::commands* p = &commands; this->execute(&p, 1); } void ff::dx12::queue::execute(ff::dx12::commands** commands, size_t count) { ff::stack_vector<ID3D12CommandList*, 16> lists; ff::dx12::fence_values fence_values; ff::dx12::fence_values wait_before_execute; if (count) { lists.reserve(count); fence_values.reserve(count); for (size_t i = 0; i < count; i++) { ff::dx12::commands& cur = *commands[i]; if (cur) { std::scoped_lock lock(this->mutex); this->allocators.push_back(std::make_pair(cur.next_fence_value(), ff::dx12::get_command_allocator(cur))); this->lists.push_front(ff::dx12::get_command_list(cur)); this->fences.push_front(std::move(ff::dx12::move_fence(cur))); lists.push_back(this->lists.front().Get()); fence_values.add(this->fences.front()->next_value()); } wait_before_execute.add(cur.wait_before_execute()); cur.close(); } wait_before_execute.wait(this); if (!lists.empty()) { this->command_queue->ExecuteCommandLists(static_cast<UINT>(lists.size()), lists.data()); fence_values.signal(this); } } } void ff::dx12::queue::before_reset() { this->allocators.clear(); this->lists.clear(); this->fences.clear(); this->command_queue.Reset(); } bool ff::dx12::queue::reset() { const D3D12_COMMAND_QUEUE_DESC command_queue_desc{ this->type }; return SUCCEEDED(ff::dx12::device()->CreateCommandQueue(&command_queue_desc, IID_PPV_ARGS(&this->command_queue))); }
27.511278
121
0.596338
spadapet
47477c973bc9e3b331ff840cd45038d5bfa7a81a
1,178
cpp
C++
src/LightBulbApp/TrainingPlans/Preferences/PredefinedPreferenceGroups/Evolution/RateDifferenceConditionPreferenceGroup.cpp
domin1101/ANNHelper
50acb5746d6dad6777532e4c7da4983a7683efe0
[ "Zlib" ]
5
2016-02-04T06:14:42.000Z
2017-02-06T02:21:43.000Z
src/LightBulbApp/TrainingPlans/Preferences/PredefinedPreferenceGroups/Evolution/RateDifferenceConditionPreferenceGroup.cpp
domin1101/ANNHelper
50acb5746d6dad6777532e4c7da4983a7683efe0
[ "Zlib" ]
41
2015-04-15T21:05:45.000Z
2015-07-09T12:59:02.000Z
src/LightBulbApp/TrainingPlans/Preferences/PredefinedPreferenceGroups/Evolution/RateDifferenceConditionPreferenceGroup.cpp
domin1101/LightBulb
50acb5746d6dad6777532e4c7da4983a7683efe0
[ "Zlib" ]
null
null
null
// Includes #include "LightBulbApp/TrainingPlans/Preferences/PredefinedPreferenceGroups/Evolution/RateDifferenceConditionPreferenceGroup.hpp" #include "LightBulbApp/TrainingPlans/Preferences/IntegerPreference.hpp" #include "LightBulbApp/TrainingPlans/Preferences/DoublePreference.hpp" #include "LightBulb/Learning/Evolution/RateDifferenceCondition.hpp" namespace LightBulb { #define PREFERENCE_DIFFERENCE "Difference" #define PREFERENCE_ITERATIONS "Iterations" RateDifferenceConditionPreferenceGroup::RateDifferenceConditionPreferenceGroup(const std::string& name) :PreferenceGroup(name) { addPreference(new DoublePreference(PREFERENCE_DIFFERENCE, 0.00001, 0, 1)); addPreference(new IntegerPreference(PREFERENCE_ITERATIONS, 10, 0, 100)); } RateDifferenceCondition* RateDifferenceConditionPreferenceGroup::create() const { double difference = getDoublePreference(PREFERENCE_DIFFERENCE); int iterations = getIntegerPreference(PREFERENCE_ITERATIONS); return new RateDifferenceCondition(difference, iterations); } AbstractCloneable* RateDifferenceConditionPreferenceGroup::clone() const { return new RateDifferenceConditionPreferenceGroup(*this); } }
36.8125
129
0.837861
domin1101
474785b19cfc9676eb90451dfbd807f1f5548fe3
11,465
cpp
C++
unittests/conversation.cpp
traviscross/libzina
6583baa68549a7d90bf6f9af5836361e41b3cef5
[ "Apache-2.0" ]
21
2016-04-03T00:05:34.000Z
2020-05-19T23:08:37.000Z
unittests/conversation.cpp
traviscross/libzina
6583baa68549a7d90bf6f9af5836361e41b3cef5
[ "Apache-2.0" ]
null
null
null
unittests/conversation.cpp
traviscross/libzina
6583baa68549a7d90bf6f9af5836361e41b3cef5
[ "Apache-2.0" ]
4
2018-01-15T07:17:27.000Z
2021-01-10T02:01:37.000Z
/* Copyright 2016 Silent Circle, LLC 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 <malloc.h> #include "gtest/gtest.h" #include "../ratchet/state/ZinaConversation.h" #include "../storage/sqlite/SQLiteStoreConv.h" #include "../ratchet/crypto/EcCurve.h" #include "../logging/ZinaLogging.h" using namespace zina; using namespace std; static std::string aliceName("alice@wonderland.org"); static std::string bobName("bob@milkyway.com"); static std::string aliceDev("aliceDevId"); static std::string bobDev("BobDevId"); static const uint8_t keyInData[] = {0,1,2,3,4,5,6,7,8,9,19,18,17,16,15,14,13,12,11,10,20,21,22,23,24,25,26,27,28,20,31,30}; /** * @brief Storage test fixture class that supports memory leak checking. * * NOTE: when using this class as a base class for a test fixture, * the derived class should not create any local member variables, as * they can cause memory leaks to be improperly reported. */ class StoreTestFixture: public ::testing::Test { public: StoreTestFixture( ) { // initialization code here } // code here will execute just before the test ensues void SetUp() { // capture the memory state at the beginning of the test struct mallinfo minfo = mallinfo(); beginMemoryState = minfo.uordblks; LOGGER_INSTANCE setLogLevel(WARNING); store = SQLiteStoreConv::getStore(); store->setKey(std::string((const char*)keyInData, 32)); store->openStore(std::string()); } void TearDown( ) { // code here will be called just after the test completes // ok to through exceptions from here if need be SQLiteStoreConv::closeStore(); // only check for memory leaks if the test did not end in a failure // NOTE: the logging via LOGGER statements may give wronge results. Thus either switch of // logging (LOGGER_INSTANCE setLogLevel(NONE);) during tests (after debugging :-) ) or make // sure that no errors etc are logged. The memory info may be wrong if the LOGGER really // prints out some data. if (!HasFailure()) { // Gets information about the currently running test. // Do NOT delete the returned object - it's managed by the UnitTest class. const ::testing::TestInfo* const test_info = ::testing::UnitTest::GetInstance()->current_test_info(); // if there are differences between the memory state at beginning and end, then there are memory leaks struct mallinfo minfo = mallinfo(); if ( beginMemoryState != minfo.uordblks ) { FAIL() << "Memory Leak(s) detected in " << test_info->name() << ", test case: " << test_info->test_case_name() << ", memory before: " << beginMemoryState << ", after: " << minfo.uordblks << ", difference: " << minfo.uordblks - beginMemoryState << endl; } } } ~StoreTestFixture( ) { // cleanup any pending stuff, but no exceptions allowed LOGGER_INSTANCE setLogLevel(VERBOSE); } // put in any custom data members that you need SQLiteStoreConv* store; int beginMemoryState; }; TEST_F(StoreTestFixture, BasicEmpty) { // localUser, remote user, remote dev id ZinaConversation conv(aliceName, bobName, bobDev); conv.storeConversation(*store); ASSERT_FALSE(SQL_FAIL(store->getSqlCode())) << store->getLastError(); auto conv1 = ZinaConversation::loadConversation(aliceName, bobName, bobDev, *store); ASSERT_TRUE(conv1 != NULL); ASSERT_TRUE(conv1->getRK().empty()); } TEST_F(StoreTestFixture, TestDHR) { // localUser, remote user, remote dev id ZinaConversation conv(aliceName, bobName, bobDev); conv.setRatchetFlag(true); conv.setDHRr(PublicKeyUnique(new Ec255PublicKey(keyInData))); PublicKeyUnique pubKey = PublicKeyUnique(new Ec255PublicKey(conv.getDHRr().getPublicKeyPointer())); conv.setDHRs(EcCurve::generateKeyPair(EcCurveTypes::Curve25519)); KeyPairUnique keyPair(new DhKeyPair(conv.getDHRs().getPublicKey(), conv.getDHRs().getPrivateKey())); conv.storeConversation(*store); auto conv1 = ZinaConversation::loadConversation(aliceName, bobName, bobDev, *store); ASSERT_TRUE(conv1 != NULL); ASSERT_TRUE(conv1->getRatchetFlag()); const DhKeyPair& keyPair1 = conv1->getDHRs(); ASSERT_TRUE(conv1->hasDHRs()); ASSERT_TRUE(keyPair->getPublicKey() == keyPair1.getPublicKey()); const DhPublicKey& pubKey1 = conv1->getDHRr(); ASSERT_TRUE(conv1->hasDHRr()); ASSERT_TRUE(*pubKey == pubKey1); } TEST_F(StoreTestFixture, TestDHI) { // localUser, remote user, remote dev id ZinaConversation conv(aliceName, bobName, bobDev); conv.setRatchetFlag(true); conv.setDHIr(PublicKeyUnique(new Ec255PublicKey(keyInData))); PublicKeyUnique pubKey = PublicKeyUnique(new Ec255PublicKey(conv.getDHIr().getPublicKeyPointer())); conv.setDHIs(EcCurve::generateKeyPair(EcCurveTypes::Curve25519)); KeyPairUnique keyPair(new DhKeyPair(conv.getDHIs().getPublicKey(), conv.getDHIs().getPrivateKey())); conv.storeConversation(*store); auto conv1 = ZinaConversation::loadConversation(aliceName, bobName, bobDev,*store); ASSERT_TRUE(conv1 != NULL); ASSERT_TRUE(conv1->getRatchetFlag()); const DhKeyPair& keyPair1 = conv1->getDHIs(); ASSERT_TRUE(conv1->hasDHIs()); ASSERT_TRUE(keyPair->getPublicKey() == keyPair1.getPublicKey()); const DhPublicKey& pubKey1 = conv1->getDHIr(); ASSERT_TRUE(conv1->hasDHIr()); ASSERT_TRUE(*pubKey == pubKey1); } TEST_F(StoreTestFixture, TestA0) { // localUser, remote user, remote dev id ZinaConversation conv(aliceName, bobName, bobDev); conv.setRatchetFlag(true); conv.setA0(EcCurve::generateKeyPair(EcCurveTypes::Curve25519)); KeyPairUnique keyPair(new DhKeyPair(conv.getA0().getPublicKey(), conv.getA0().getPrivateKey())); conv.storeConversation(*store); auto conv1 = ZinaConversation::loadConversation(aliceName, bobName, bobDev, *store); ASSERT_TRUE(conv1 != NULL); ASSERT_TRUE(conv1->getRatchetFlag()); const DhKeyPair& keyPair1 = conv1->getA0(); ASSERT_TRUE(conv1->hasA0()); ASSERT_TRUE(keyPair->getPublicKey() == keyPair1.getPublicKey()); } TEST_F(StoreTestFixture, SimpleFields) { string RK("RootKey"); string CKs("ChainKeyS 1"); string CKr("ChainKeyR 1"); // localUser, remote user, remote dev id ZinaConversation conv(aliceName, bobName, bobDev); conv.setRK(RK); conv.setCKr(CKr); conv.setCKs(CKs); conv.setNr(3); conv.setNs(7); conv.setPNs(11); conv.setPreKeyId(13); string tst("test"); conv.setDeviceName(tst); conv.storeConversation(*store); auto conv1 = ZinaConversation::loadConversation(aliceName, bobName, bobDev, *store); ASSERT_EQ(RK, conv1->getRK()); ASSERT_EQ(CKr, conv1->getCKr()); ASSERT_EQ(CKs, conv1->getCKs()); ASSERT_EQ(3, conv1->getNr()); ASSERT_EQ(7, conv1->getNs()); ASSERT_EQ(11, conv1->getPNs()); ASSERT_EQ(13, conv1->getPreKeyId()); ASSERT_TRUE(tst == conv1->getDeviceName()); } TEST_F(StoreTestFixture, SecondaryRatchet) { string RK("RootKey"); string CKs("ChainKeyS 1"); string CKr("ChainKeyR 1"); // localUser, remote user, remote dev id ZinaConversation conv(aliceName, bobName, bobDev); conv.setRK(RK); conv.setCKr(CKr); conv.setCKs(CKs); conv.saveSecondaryAddress(aliceDev, 4711); conv.setNr(3); conv.setNs(7); conv.setPNs(11); conv.setPreKeyId(13); string tst("test"); conv.setDeviceName(tst); conv.storeConversation(*store); auto conv1 = ZinaConversation::loadConversation(aliceName, bobName, bobDev, *store); string devId = conv1->lookupSecondaryDevId(4711); ASSERT_EQ(aliceDev, devId); ASSERT_EQ(RK, conv1->getRK()); ASSERT_EQ(CKr, conv1->getCKr()); ASSERT_EQ(CKs, conv1->getCKs()); ASSERT_EQ(3, conv1->getNr()); ASSERT_EQ(7, conv1->getNs()); ASSERT_EQ(11, conv1->getPNs()); ASSERT_EQ(13, conv1->getPreKeyId()); ASSERT_TRUE(tst == conv1->getDeviceName()); } ///** // * A base GTest (GoogleTest) text fixture class that supports memory leak checking. // * // * NOTE: when using this class as a base class for a test fixture, // * the derived class should not create any local member variables, as // * they can cause memory leaks to be improperly reported. // */ // //class BaseTestFixture : public ::testing::Test //{ //public: // virtual void SetUp() // { // // capture the memory state at the beginning of the test // struct mallinfo minfo = mallinfo(); // beginMemoryState = minfo.uordblks; // } // // virtual void TearDown() // { // // only check for memory leaks if the test did not end in a failure // if (!HasFailure()) // { // // Gets information about the currently running test. // // Do NOT delete the returned object - it's managed by the UnitTest class. // const ::testing::TestInfo* const test_info = ::testing::UnitTest::GetInstance()->current_test_info(); // // // if there are differences between the memory state at beginning and end, then there are memory leaks // struct mallinfo minfo = mallinfo(); // if ( beginMemoryState != minfo.uordblks ) // { // FAIL() << "Memory Leak(s) Detected in " << test_info->name() << ", test case: " << test_info->test_case_name() << endl; // } // } // } // //private: // // memory state at the beginning of the test fixture set up // int beginMemoryState; //}; // ////---------------------------------------------------------------- //// check that allocating nothing doesn't throw a false positive ////---------------------------------------------------------------- //TEST_F(BaseTestFixture, BaseTestFixtureTest) //{ // // should always pass an empty test //} // ////---------------------------------------------------------------- //// check that malloc()ing something is detected ////---------------------------------------------------------------- //TEST_F(BaseTestFixture, BaseTestFixtureMallocTest) //{ // // should always fail // void* p = malloc(10); //} // ////---------------------------------------------------------------- //// check that new()ing something is detected ////---------------------------------------------------------------- //TEST_F(BaseTestFixture, BaseTestFixtureNewFailTest) //{ // // should always fail // int* array = new int[10]; //} // ////---------------------------------------------------------------- //// ////---------------------------------------------------------------- //TEST_F(BaseTestFixture, BaseTestFixtureNewTest) //{ // void* p = malloc(10); // free( p ); //}
34.637462
137
0.632883
traviscross
474f455e0b90a74010298dbffc9363c798ebd1cd
17,913
cpp
C++
shaderapivulkan/src/TF2Vulkan/meshes/VulkanMesh.cpp
melvyn2/TF2Vulkan
a8cd1c49ecfe9d4dc31af0a50ba7690c61c255c4
[ "MIT" ]
null
null
null
shaderapivulkan/src/TF2Vulkan/meshes/VulkanMesh.cpp
melvyn2/TF2Vulkan
a8cd1c49ecfe9d4dc31af0a50ba7690c61c255c4
[ "MIT" ]
null
null
null
shaderapivulkan/src/TF2Vulkan/meshes/VulkanMesh.cpp
melvyn2/TF2Vulkan
a8cd1c49ecfe9d4dc31af0a50ba7690c61c255c4
[ "MIT" ]
null
null
null
#include "TF2Vulkan/IShaderAPI/IShaderAPI_StateManagerDynamic.h" #include "interface/IMaterialInternal.h" #include "interface/internal/IBufferPoolInternal.h" #include "interface/internal/IShaderDeviceInternal.h" #include "interface/internal/IStateManagerStatic.h" #include "TF2Vulkan/VulkanFactories.h" #include "VulkanMesh.h" #include <TF2Vulkan/Util/FourCC.h> #include "TF2Vulkan/Util/Misc.h" #include <TF2Vulkan/Util/std_variant.h> using namespace TF2Vulkan; static std::atomic<uint32_t> s_VulkanGPUBufferIndex = 0; void VulkanGPUBuffer::AssertCheckHeap() { ENSURE(_CrtCheckMemory()); } static void ValidateVertexFormat(VertexFormat meshFormat, VertexFormat materialFormat) { if (!materialFormat.IsCompressed()) assert(!meshFormat.IsCompressed()); const auto CheckFlag = [&](VertexFormatFlags flag) { if (meshFormat.m_Flags & flag) { assert(materialFormat.m_Flags & flag); } }; CheckFlag(VertexFormatFlags::Position); CheckFlag(VertexFormatFlags::Normal); CheckFlag(VertexFormatFlags::Color); CheckFlag(VertexFormatFlags::Specular); CheckFlag(VertexFormatFlags::TangentS); CheckFlag(VertexFormatFlags::TangentT); CheckFlag(VertexFormatFlags::Wrinkle); // Questionable checks #if false CheckFlag(VertexFormatFlags::BoneIndex); #endif } int VulkanMesh::GetRoomRemaining() const { auto lock = ScopeThreadLock(); LOG_FUNC_ANYTHREAD(); const auto vtxRoom = m_VertexBuffer->GetRoomRemaining(); const auto idxRoom = m_IndexBuffer->GetRoomRemaining(); assert(vtxRoom == idxRoom); return Util::algorithm::min(vtxRoom, idxRoom); } VertexFormat VulkanMesh::GetColorMeshFormat() const { LOG_FUNC_ANYTHREAD(); return m_ColorMesh ? VertexFormat(m_ColorMesh->GetVertexFormat()) : VertexFormat{}; } void VulkanMesh::OverrideVertexBuffer(IMesh* src) { auto lock = ScopeThreadLock(); LOG_FUNC_ANYTHREAD(); if (src) { if (!m_OriginalVertexBuffer) m_OriginalVertexBuffer = m_VertexBuffer; m_VertexBuffer = assert_cast<VulkanMesh*>(src)->m_VertexBuffer; } else { if (m_OriginalVertexBuffer) m_VertexBuffer = std::move(m_OriginalVertexBuffer); } } void VulkanMesh::OverrideIndexBuffer(IMesh* src) { auto lock = ScopeThreadLock(); LOG_FUNC_ANYTHREAD(); if (src) { if (!m_OriginalIndexBuffer) m_OriginalIndexBuffer = m_IndexBuffer; m_IndexBuffer = assert_cast<VulkanMesh*>(src)->m_IndexBuffer; } else { if (m_OriginalIndexBuffer) m_IndexBuffer = std::move(m_OriginalIndexBuffer); } } void VulkanGPUBuffer::UpdateDynamicBuffer() { auto lock = ScopeThreadLock(); LOG_FUNC_ANYTHREAD(); if (IsDynamic()) { if (Util::IsMainThread()) { TF2VULKAN_PIX_MARKER("UpdateDynamicBuffer %s [dynamic]: %zu bytes", vk::to_string(m_Usage).c_str(), m_CPUBuffer.size()); } // Just memcpy into the dynamic buffer //if (updateSize > 0 || !std::holds_alternative<BufferPoolEntry>(m_Buffer)) m_Buffer = g_ShaderDevice.GetBufferPool(m_Usage).Create(m_CPUBuffer.size(), m_CPUBuffer.data()); } } void* VulkanGPUBuffer::GetBuffer(size_t size, bool truncate) { AssertHasLock(); LOG_FUNC_ANYTHREAD(); if (Util::IsMainThread()) { TF2VULKAN_PIX_MARKER("GetBuffer(size = %zu, truncate = %s) %s [%s]", m_CPUBuffer.size(), truncate ? "true" : "false", vk::to_string(m_Usage).c_str(), IsDynamic() ? "dynamic" : "static"); } if (truncate || m_CPUBuffer.size() < size) m_CPUBuffer.resize(size); return m_CPUBuffer.data(); } void VulkanGPUBuffer::CommitModifications(size_t updateBegin, size_t updateSize) { AssertHasLock(); LOG_FUNC_ANYTHREAD(); if (!IsDynamic()) { if (Util::IsMainThread()) { TF2VULKAN_PIX_MARKER("CommitModifications %s [static]: %zu bytes @ offset %zu", vk::to_string(m_Usage).c_str(), updateBegin, updateSize); } assert(std::holds_alternative<std::monostate>(m_Buffer) || std::holds_alternative<vma::AllocatedBuffer>(m_Buffer)); auto entry = g_ShaderDevice .GetBufferPool(vk::BufferUsageFlagBits::eTransferSrc) .Create(updateSize, Util::OffsetPtr(m_CPUBuffer.data(), updateBegin)); const auto& realPool = static_cast<const IBufferPoolInternal&>(entry.GetPool()); const auto entryInfo = realPool.GetBufferInfo(entry); auto& cmdBuf = g_ShaderDevice.GetPrimaryCmdBuf(); auto& dstBuf = Util::get_or_emplace<vma::AllocatedBuffer>(m_Buffer); if (!dstBuf || dstBuf.size() < m_CPUBuffer.size()) { if (dstBuf) cmdBuf.AddResource(std::move(dstBuf)); char dbgName[128]; sprintf_s(dbgName, "VulkanGPUBuffer #%u [static] [%zu, %zu)", ++s_VulkanGPUBufferIndex, updateBegin, updateBegin + updateSize); dstBuf = Factories::BufferFactory{} .SetSize(m_CPUBuffer.size()) .SetUsage(m_Usage | vk::BufferUsageFlagBits::eTransferDst) .SetMemoryType(vma::MemoryType::eGpuOnly) .SetDebugName(dbgName) .Create(); } const auto region = vk::BufferCopy{} .setSize(updateSize) .setSrcOffset(entry.GetOffset()) .setDstOffset(updateBegin); if (auto [transfer, lock] = g_ShaderDevice.GetTransferQueue().locked(); transfer) { auto transferCmdBuf = transfer->CreateCmdBufferAndBegin(); transferCmdBuf->copyBuffer(entryInfo.m_Buffer, dstBuf.GetBuffer(), region); transferCmdBuf->Submit(); } else { cmdBuf.TryEndRenderPass(); cmdBuf.copyBuffer(entryInfo.m_Buffer, dstBuf.GetBuffer(), region); } } } VulkanMesh::VulkanMesh(const VertexFormat& fmt, bool isDynamic) : m_VertexBuffer(std::make_shared<VulkanVertexBuffer>(fmt, isDynamic)), m_IndexBuffer(std::make_shared<VulkanIndexBuffer>(isDynamic)) { } VulkanMesh::VulkanMesh(const VertexFormat& fmt) : VulkanMesh(fmt, false) { } void VulkanMesh::Draw(int firstIndex, int indexCount) { auto lock = ScopeThreadLock(); LOG_FUNC(); if (!g_ShaderDevice.IsPrimaryCmdBufReady()) { Warning(TF2VULKAN_PREFIX "Skipping mesh draw, shader device not ready yet\n"); return; } if (firstIndex == -1) { // "Start at true zero"? firstIndex = 0; } assert(firstIndex >= 0); // Catch other weird values assert(indexCount >= 0); if (indexCount == 0) { // Apparently, 0 means "draw everything" indexCount = IndexCount(); if (indexCount <= 0) return; // Nothing to draw } assert((firstIndex + indexCount) <= IndexCount()); ActiveMeshScope meshScope(ActiveMeshData{ this, firstIndex, indexCount }); auto& dynState = g_StateManagerDynamic.GetDynamicState(); auto internalMaterial = assert_cast<IMaterialInternal*>(dynState.m_BoundMaterial); #ifdef _DEBUG [[maybe_unused]] auto matName = internalMaterial->GetName(); [[maybe_unused]] auto shader = internalMaterial->GetShader(); [[maybe_unused]] auto shaderName = internalMaterial->GetShaderName(); #endif internalMaterial->DrawMesh(VertexFormat(GetVertexFormat()).GetCompressionType()); } void VulkanMesh::DrawInternal(IVulkanCommandBuffer& cmdBuf, int firstIndex, int indexCount) { auto lock = ScopeThreadLock(); LOG_FUNC(); if (!VertexCount()) { assert(!indexCount == !VertexCount()); Warning(TF2VULKAN_PREFIX "No vertices\n"); TF2VULKAN_PIX_MARKER("No vertices"); return; } vk::Buffer indexBuffer, vertexBuffer, vertexBufferColor; size_t indexBufferOffset, vertexBufferOffset, vertexBufferColorOffset = 0; // intentionally only last one assigned m_IndexBuffer->GetGPUBuffer(indexBuffer, indexBufferOffset); cmdBuf.bindIndexBuffer(indexBuffer, indexBufferOffset, vk::IndexType::eUint16); m_VertexBuffer->GetGPUBuffer(vertexBuffer, vertexBufferOffset); if (m_ColorMesh) { auto colorMeshInternal = assert_cast<IMeshInternal*>(m_ColorMesh); auto& colorVB = colorMeshInternal->GetVertexBuffer(); colorVB.GetGPUBuffer(vertexBufferColor, vertexBufferColorOffset); vertexBufferColorOffset += m_ColorMeshVertexOffset; } // Bind vertex buffers { const vk::Buffer vtxBufs[] = { g_ShaderDevice.GetDummyVertexBuffer(), vertexBuffer, vertexBufferColor, }; const vk::DeviceSize offsets[] = { 0, vertexBufferOffset, Util::SafeConvert<vk::DeviceSize>(vertexBufferColorOffset) }; const uint32_t vbCount = m_ColorMesh ? 3 : 2; static_assert(std::size(vtxBufs) == std::size(offsets)); cmdBuf.bindVertexBuffers(0, vk::ArrayProxy(vbCount, vtxBufs), vk::ArrayProxy(vbCount, offsets)); } cmdBuf.drawIndexed(Util::SafeConvert<uint32_t>(indexCount), 1, Util::SafeConvert<uint32_t>(firstIndex)); MarkAsDrawn(); } void VulkanMesh::SetColorMesh(IMesh* colorMesh, int vertexOffset) { auto lock = ScopeThreadLock(); LOG_FUNC_ANYTHREAD(); m_ColorMesh = colorMesh; m_ColorMeshVertexOffset = vertexOffset; } void VulkanMesh::Draw(CPrimList* lists, int listCount) { auto lock = ScopeThreadLock(); LOG_FUNC(); // TODO: Indirect rendering? //assert(listCount == 1); for (int i = 0; i < listCount; i++) Draw(lists[i].m_FirstIndex, lists[i].m_NumIndices); } void VulkanMesh::CopyToMeshBuilder(int startVert, int vertCount, int startIndex, int indexCount, int indexOffset, CMeshBuilder& builder) { NOT_IMPLEMENTED_FUNC(); } void VulkanMesh::SetFlexMesh(IMesh* mesh, int vertexOffset) { LOG_FUNC(); if (mesh || vertexOffset) NOT_IMPLEMENTED_FUNC_NOBREAK(); // TODO: This goes into vPosFlex and vNormalFlex } VulkanIndexBuffer::VulkanIndexBuffer(bool isDynamic) : VulkanGPUBuffer(isDynamic, vk::BufferUsageFlagBits::eIndexBuffer) { } void VulkanIndexBuffer::ModifyBegin(uint32_t firstIndex, uint32_t indexCount, IndexDesc_t& desc, bool read, bool write, bool truncate) { LOG_FUNC_ANYTHREAD(); desc = {}; desc.m_nIndexSize = sizeof(IndexFormatType) >> 1; // Why? desc.m_nFirstIndex = 0; desc.m_nOffset = 0; if (indexCount <= 0) { // Not thread safe at this point, but we don't want to unnecessarily // lock if indexCount is zero and we're just returning a pointer to // dummy data. assert(!m_ModifyIndexData); desc.m_pIndices = reinterpret_cast<IndexFormatType*>(&IShaderAPI_MeshManager::s_FallbackMeshData); return; } BeginThreadLock(); assert(!m_ModifyIndexData); // Once more after the lock, just to be sure const auto indexDataSize = indexCount * IndexElementSize(); const auto& modifyData = m_ModifyIndexData.emplace<ModifyData>({ firstIndex, indexCount }); desc.m_pIndices = reinterpret_cast<IndexFormatType*>(Util::OffsetPtr(GetBuffer(indexDataSize, truncate), firstIndex * IndexElementSize())); assert(desc.m_pIndices); } void VulkanIndexBuffer::ModifyBegin(bool readOnly, int firstIndex, int indexCount, IndexDesc_t& desc) { LOG_FUNC_ANYTHREAD(); const bool shouldAllowRead = true; const bool shouldAllowWrite = !readOnly; return ModifyBegin(firstIndex, indexCount, desc, shouldAllowRead, shouldAllowWrite, false); } void VulkanIndexBuffer::ModifyEnd(IndexDesc_t& desc) { LOG_FUNC_ANYTHREAD(); AssertCheckHeap(); if (!m_ModifyIndexData) return; const auto& modify = m_ModifyIndexData.value(); assert(IsDynamic() || modify.m_Count > 0); CommitModifications(modify.m_Offset * IndexElementSize(), modify.m_Count * IndexElementSize()); ValidateData(m_IndexCount, 0, desc); m_ModifyIndexData.reset(); EndThreadLock(); } void VulkanIndexBuffer::ValidateData(int indexCount, const IndexDesc_t& desc) { LOG_FUNC_ANYTHREAD(); return ValidateData(Util::SafeConvert<uint32_t>(indexCount), 0, desc); } void VulkanIndexBuffer::ValidateData(uint32_t indexCount, uint32_t firstIndex, const IndexDesc_t& desc) { LOG_FUNC_ANYTHREAD(); // TODO } VulkanGPUBuffer::VulkanGPUBuffer(bool isDynamic, vk::BufferUsageFlags usage) : m_IsDynamic(isDynamic), m_Usage(usage) { } void VulkanGPUBuffer::GetGPUBuffer(vk::Buffer& buffer, size_t& offset) { auto lock = ScopeThreadLock(); if (IsDynamic()) UpdateDynamicBuffer(); if (auto foundBuf = std::get_if<vma::AllocatedBuffer>(&m_Buffer)) { buffer = foundBuf->GetBuffer(); offset = 0; } else if (auto foundBuf = std::get_if<BufferPoolEntry>(&m_Buffer)) { offset = foundBuf->GetOffset(); buffer = static_cast<const IBufferPoolInternal&>(foundBuf->GetPool()).GetBuffer(offset); } else { const auto& realPool = static_cast<const IBufferPoolInternal&>(g_ShaderDevice.GetBufferPool(m_Usage)); buffer = realPool.GetBufferInfo(0).m_Buffer; offset = 0; } } VulkanVertexBuffer::VulkanVertexBuffer(const VertexFormat& format, bool isDynamic) : VulkanGPUBuffer(isDynamic, vk::BufferUsageFlagBits::eVertexBuffer), m_Format(format) { } void VulkanVertexBuffer::Unlock(int vertexCount, VertexDesc_t& desc) { LOG_FUNC_ANYTHREAD(); if (!m_ModifyVertexData) return; auto& modify = m_ModifyVertexData.value(); [[maybe_unused]] const auto oldModifySize = modify.m_Size; [[maybe_unused]] const auto oldVertexCount = m_VertexCount; Util::SafeConvert(vertexCount, m_VertexCount); modify.m_Size = m_VertexCount * Util::SafeConvert<uint32_t>(desc.m_ActualVertexSize); ModifyEnd(desc); } void VulkanIndexBuffer::Unlock(int indexCount, IndexDesc_t& desc) { LOG_FUNC_ANYTHREAD(); AssertCheckHeap(); if (!m_ModifyIndexData) return; auto& modify = m_ModifyIndexData.value(); [[maybe_unused]] const auto oldModifyCount = modify.m_Count; [[maybe_unused]] const auto oldIndexCount = m_IndexCount; Util::SafeConvert(indexCount, m_IndexCount); Util::SafeConvert(m_IndexCount, modify.m_Count); ModifyEnd(desc); } void VulkanVertexBuffer::ModifyEnd(VertexDesc_t& desc) { LOG_FUNC_ANYTHREAD(); if (!m_ModifyVertexData) return; const auto& modify = m_ModifyVertexData.value(); CommitModifications(modify.m_Offset, modify.m_Size); m_VertexCount = Util::algorithm::max(m_VertexCount, (modify.m_Size + modify.m_Offset) / desc.m_ActualVertexSize); ValidateData(modify.m_Size / desc.m_ActualVertexSize, desc); m_ModifyVertexData.reset(); EndThreadLock(); } void VulkanVertexBuffer::ModifyBegin(uint32_t firstVertex, uint32_t vertexCount, VertexDesc_t& desc, bool read, bool write, bool truncate) { LOG_FUNC_ANYTHREAD(); desc = {}; if (vertexCount <= 0) { // Not thread safe yet, but avoid unnecessary locks if just returning dummy data. assert(!m_ModifyVertexData); g_MeshManager.SetDummyDataPointers(desc); return; } BeginThreadLock(); assert(!m_ModifyVertexData); // Once more, after the lock AssertCheckHeap(); assert(!m_Format.IsUnknownFormat()); VertexFormat::Element vtxElems[VERTEX_ELEMENT_NUMELEMENTS]; size_t totalVtxSize; desc.m_NumBoneWeights = m_Format.m_BoneWeightCount; const auto vtxElemsCount = m_Format.GetVertexElements(vtxElems, std::size(vtxElems), &totalVtxSize); assert(!m_ModifyVertexData); const auto& modify = m_ModifyVertexData.emplace<ModifyData>({ firstVertex * totalVtxSize, vertexCount * totalVtxSize }); assert(modify.m_Size > 0); g_MeshManager.ComputeVertexDescription(GetBuffer(modify.m_Offset + modify.m_Size, truncate), m_Format, desc); //ValidateData(vertexCount, firstVertex, desc); } template<typename T, size_t count, size_t alignment, typename = std::enable_if_t<std::is_floating_point_v<T>>> static void ValidateType(const Shaders::vector<T, count, alignment>& v) { for (size_t i = 0; i < count; i++) { if (!std::isfinite(v[i])) DebuggerBreakIfDebugging(); } } template<typename T> static void ValidateType(const void* base, int elementIndex, int elementSize) { if (elementSize <= 0) return; const T& typed = *reinterpret_cast<const T*>(reinterpret_cast<const std::byte*>(base) + elementSize * elementIndex); ValidateType(typed); } void VulkanVertexBuffer::ValidateData(uint32_t vertexCount, uint32_t firstVertex, const VertexDesc_t& desc) { LOG_FUNC_ANYTHREAD(); const uint32_t endVertex = firstVertex + vertexCount; for (uint32_t i = firstVertex; i < endVertex; i++) { ValidateType<Shaders::float3>(desc.m_pPosition, i, desc.m_VertexSize_Position); if (desc.m_CompressionType == VERTEX_COMPRESSION_NONE) ValidateType<Shaders::float3>(desc.m_pNormal, i, desc.m_VertexSize_Normal); } } VulkanDynamicMesh::VulkanDynamicMesh(const VertexFormat& fmt) : VulkanMesh(fmt, true) { } void VulkanDynamicMesh::LockMesh(int vertexCount, int indexCount, MeshDesc_t& desc) { LOG_FUNC_ANYTHREAD(); if (m_HasDrawn) { m_FirstUndrawnIndex = 0; m_FirstUndrawnVertex = 0; m_TotalIndices = 0; m_TotalVertices = 0; m_HasDrawn = false; } return VulkanMesh::LockMesh(vertexCount, indexCount, desc); } void VulkanDynamicMesh::UnlockMesh(int vertexCount, int indexCount, MeshDesc_t& desc) { LOG_FUNC_ANYTHREAD(); m_TotalVertices += Util::SafeConvert<uint32_t>(vertexCount); m_TotalIndices += Util::SafeConvert<uint32_t>(indexCount); return BaseClass::UnlockMesh(vertexCount, indexCount, desc); } void VulkanDynamicMesh::Draw(int firstIndex, int indexCount) { LOG_FUNC_ANYTHREAD(); MarkAsDrawn(); const bool isPointsOrInstQuads = GetPrimitiveType() == MATERIAL_POINTS || GetPrimitiveType() == MATERIAL_INSTANCED_QUADS; const bool ibOverride = HasIndexBufferOverride(); const bool vbOverride = HasVertexBufferOverride(); if (ibOverride || vbOverride || (m_TotalVertices > 0 && (m_TotalIndices > 0 || isPointsOrInstQuads))) { const uint32_t firstVertex = vbOverride ? 0 : m_FirstUndrawnVertex; //const uint32_t firstIndex = m_IndexOverride ? 0 : m_FirstUndrawnIndex; const uint32_t realIndexCount = ibOverride ? firstVertex : 0; const uint32_t baseIndex = ibOverride ? 0 : m_FirstUndrawnIndex; if (firstIndex == -1 && indexCount == 0) { // Draw the entire mesh if (ibOverride) { indexCount = IndexCount(); } else { if (isPointsOrInstQuads) Util::SafeConvert(m_TotalVertices, indexCount); else Util::SafeConvert(m_TotalIndices, indexCount); } assert(indexCount > 0); } else { assert(firstIndex >= 0); firstIndex += baseIndex; } BaseClass::Draw(firstIndex, indexCount); } else { const auto idxCount = IndexCount(); const auto vtxCount = VertexCount(); if (idxCount > 0 && vtxCount > 0) Warning(TF2VULKAN_PREFIX "Skipping draw (%i indices and %i vertices)\n", idxCount, vtxCount); } } void VulkanDynamicMesh::MarkAsDrawn() { LOG_FUNC_ANYTHREAD(); m_HasDrawn = true; }
26.498521
140
0.74566
melvyn2
47535de4a05f42be5091ec3b3c518135ce8e4508
2,109
cpp
C++
shared/Heap/Heap.cpp
alicialink/system-squeeze
f0a82546389d5feae48668352e0b1dcd83100674
[ "MIT" ]
null
null
null
shared/Heap/Heap.cpp
alicialink/system-squeeze
f0a82546389d5feae48668352e0b1dcd83100674
[ "MIT" ]
null
null
null
shared/Heap/Heap.cpp
alicialink/system-squeeze
f0a82546389d5feae48668352e0b1dcd83100674
[ "MIT" ]
null
null
null
#include "Heap.h" #include <stdlib.h> int h_parent(int i) { return (int)((i - 1) / 2); } int h_child_left(int i) { return (2 * i) + 1; } int h_child_right(int i) { return (2 * i) + 2; } bool h_create(Heap **h) { Heap *newHeap = (Heap *)malloc(sizeof(Heap)); if (newHeap == NULL) { return false; } else { newHeap->tree = NULL; newHeap->size = 0; *h = newHeap; return true; } } bool h_insert(Heap *h, int data) { int *temp = (int *)realloc(h->tree, sizeof(int) * (h->size + 1)); if (temp == NULL) { return false; } h->tree = temp; h->size++; h->tree[h->size - 1] = data; int child = h->size - 1; int parent = h_parent(child); while (child > 0 && h->tree[child] > h->tree[parent]) { int swap = h->tree[parent]; h->tree[parent] = h->tree[child]; h->tree[child] = swap; child = parent; parent = h_parent(child); } return true; } bool h_remove(Heap *h, int *data) { if (h->tree == NULL) { return false; } if (h->size == 1) { *data = h->tree[0]; free(h->tree); h->tree = NULL; } else { *data = h->tree[0]; int oldEnd = h->tree[h->size - 1]; int *temp = (int *)realloc(h->tree, sizeof(int) * (h->size - 1)); if (temp == NULL) { return false; } h->size--; h->tree[0] = oldEnd; int parent = 0; int left = 0; int right = 0; int maximum = 0; while (true) { left = h_child_left(parent); right = h_child_right(parent); if (left < h->size && (h->tree[left] > h->tree[parent])) { maximum = left; } else { maximum = parent; } if (right < h->size && (h->tree[right] > h->tree[maximum])) { maximum = right; } if (maximum == parent) { break; } else { int swap = h->tree[maximum]; h->tree[maximum] = h->tree[parent]; h->tree[parent] = swap; parent = maximum; } } } return true; } void h_erase(Heap *h) { if (h != NULL) { if (h->tree != NULL) { free(h->tree); } free(h); } }
15.857143
69
0.495021
alicialink
4755c138300bb384230b1feed1c8d051175c5b97
5,366
cpp
C++
libcaf_core/src/response_promise.cpp
Hamdor/actor-framework
ce63edffa2b7acb698cfaea571142029d38e9ef0
[ "BSD-3-Clause" ]
2,517
2015-01-04T22:19:43.000Z
2022-03-31T12:20:48.000Z
libcaf_core/src/response_promise.cpp
Hamdor/actor-framework
ce63edffa2b7acb698cfaea571142029d38e9ef0
[ "BSD-3-Clause" ]
894
2015-01-07T14:21:21.000Z
2022-03-30T06:37:18.000Z
libcaf_core/src/response_promise.cpp
Hamdor/actor-framework
ce63edffa2b7acb698cfaea571142029d38e9ef0
[ "BSD-3-Clause" ]
570
2015-01-21T18:59:33.000Z
2022-03-31T19:00:02.000Z
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #include <algorithm> #include <utility> #include "caf/response_promise.hpp" #include "caf/detail/profiled_send.hpp" #include "caf/local_actor.hpp" #include "caf/logger.hpp" #include "caf/no_stages.hpp" namespace caf { namespace { bool requires_response(message_id mid) { return !mid.is_response() && !mid.is_answered(); } bool requires_response(const mailbox_element& src) { return requires_response(src.mid); } bool has_response_receiver(const mailbox_element& src) { return src.sender || !src.stages.empty(); } } // namespace // -- constructors, destructors, and assignment operators ---------------------- response_promise::response_promise(local_actor* self, strong_actor_ptr source, forwarding_stack stages, message_id mid) { CAF_ASSERT(self != nullptr); // Form an invalid request promise when initialized from a response ID, since // we always drop messages in this case. Also don't create promises for // anonymous messages since there's nowhere to send the message to anyway. if (requires_response(mid)) { state_ = make_counted<state>(); state_->self = self; state_->source.swap(source); state_->stages.swap(stages); state_->id = mid; } } response_promise::response_promise(local_actor* self, mailbox_element& src) : response_promise(self, std::move(src.sender), std::move(src.stages), src.mid) { // nop } // -- properties --------------------------------------------------------------- bool response_promise::async() const noexcept { return id().is_async(); } bool response_promise::pending() const noexcept { return state_ != nullptr && state_->self != nullptr; } strong_actor_ptr response_promise::source() const noexcept { if (state_) return state_->source; else return nullptr; } response_promise::forwarding_stack response_promise::stages() const { if (state_) return state_->stages; else return {}; } strong_actor_ptr response_promise::next() const noexcept { if (state_) return state_->stages.empty() ? state_->source : state_->stages[0]; else return nullptr; } message_id response_promise::id() const noexcept { if (state_) return state_->id; else return make_message_id(); } // -- delivery ----------------------------------------------------------------- void response_promise::deliver(message msg) { CAF_LOG_TRACE(CAF_ARG(msg)); if (pending()) { state_->deliver_impl(std::move(msg)); state_.reset(); } } void response_promise::deliver(error x) { CAF_LOG_TRACE(CAF_ARG(x)); if (pending()) { state_->deliver_impl(make_message(std::move(x))); state_.reset(); } } void response_promise::deliver() { CAF_LOG_TRACE(CAF_ARG("")); if (pending()) { state_->deliver_impl(make_message()); state_.reset(); } } void response_promise::respond_to(local_actor* self, mailbox_element* request, message& response) { if (request && requires_response(*request) && has_response_receiver(*request)) { state tmp; tmp.self = self; tmp.source.swap(request->sender); tmp.stages.swap(request->stages); tmp.id = request->mid; tmp.deliver_impl(std::move(response)); request->mid.mark_as_answered(); } } void response_promise::respond_to(local_actor* self, mailbox_element* request, error& response) { if (request && requires_response(*request) && has_response_receiver(*request)) { state tmp; tmp.self = self; tmp.source.swap(request->sender); tmp.stages.swap(request->stages); tmp.id = request->mid; tmp.deliver_impl(make_message(std::move(response))); request->mid.mark_as_answered(); } } // -- state -------------------------------------------------------------------- response_promise::state::~state() { if (self) { CAF_LOG_DEBUG("broken promise!"); deliver_impl(make_message(make_error(sec::broken_promise))); } } void response_promise::state::cancel() { self = nullptr; } void response_promise::state::deliver_impl(message msg) { CAF_LOG_TRACE(CAF_ARG(msg)); if (msg.empty() && id.is_async()) { CAF_LOG_DEBUG("drop response: empty response to asynchronous input"); } else if (!stages.empty()) { auto next = std::move(stages.back()); stages.pop_back(); detail::profiled_send(self, std::move(source), next, id, std::move(stages), self->context(), std::move(msg)); } else if (source != nullptr) { detail::profiled_send(self, self->ctrl(), source, id.response_id(), forwarding_stack{}, self->context(), std::move(msg)); } cancel(); } void response_promise::state::delegate_impl(abstract_actor* receiver, message msg) { CAF_LOG_TRACE(CAF_ARG(msg)); if (receiver != nullptr) { detail::profiled_send(self, std::move(source), receiver, id, std::move(stages), self->context(), std::move(msg)); } else { CAF_LOG_DEBUG("drop response: invalid delegation target"); } cancel(); } } // namespace caf
28.242105
80
0.636974
Hamdor
4755cc6261ec0a76d98fa0fc10100bb7156beec2
3,766
cpp
C++
VrpnNet/AnalogOutputRemote.cpp
vrpn/VrpnNet
b75e5dd846f11b564f6e5ae06317b8781c40142f
[ "MIT" ]
11
2015-04-13T17:53:29.000Z
2021-06-01T17:33:49.000Z
VrpnNet/AnalogOutputRemote.cpp
vrpn/VrpnNet
b75e5dd846f11b564f6e5ae06317b8781c40142f
[ "MIT" ]
7
2015-04-13T17:45:44.000Z
2016-09-18T23:42:52.000Z
VrpnNet/AnalogOutputRemote.cpp
vancegroup/VrpnNet
9767f94c573529f2b4859df1cebb96381b7750a9
[ "MIT" ]
4
2015-05-20T19:20:29.000Z
2016-03-20T13:57:28.000Z
// AnalogOutputRemote.cpp: Implementation for Vrpn.AnalogOutputRemote // // Copyright (c) 2008-2009 Chris VanderKnyff // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include "stdafx.h" #include "AnalogOutputRemote.h" using namespace System; using namespace System::Runtime::InteropServices; using namespace Vrpn; AnalogOutputRemote::AnalogOutputRemote(String ^name) { Initialize(name, 0); } AnalogOutputRemote::AnalogOutputRemote(String ^name, Connection ^c) { Initialize(name, c->ToPointer()); } AnalogOutputRemote::~AnalogOutputRemote() { this->!AnalogOutputRemote(); } AnalogOutputRemote::!AnalogOutputRemote() { delete m_analogOut; m_disposed = true; } void AnalogOutputRemote::Initialize(String ^name, vrpn_Connection *lpConn) { IntPtr hAnsiName = Marshal::StringToHGlobalAnsi(name); const char *ansiName = static_cast<const char *>(hAnsiName.ToPointer()); m_analogOut = new ::vrpn_Analog_Output_Remote(ansiName, lpConn); Marshal::FreeHGlobal(hAnsiName); m_disposed = false; } void AnalogOutputRemote::Update() { CHECK_DISPOSAL_STATUS(); m_analogOut->mainloop(); } void AnalogOutputRemote::MuteWarnings::set(Boolean shutUp) { CHECK_DISPOSAL_STATUS(); m_analogOut->shutup = shutUp; } Boolean AnalogOutputRemote::MuteWarnings::get() { CHECK_DISPOSAL_STATUS(); return m_analogOut->shutup; } Connection^ AnalogOutputRemote::GetConnection() { CHECK_DISPOSAL_STATUS(); return Connection::FromPointer(m_analogOut->connectionPtr()); } Boolean AnalogOutputRemote::RequestChannelChange(Int64 channel, Double value) { CHECK_DISPOSAL_STATUS(); return RequestChannelChange(channel, value, ServiceClass::Reliable); } Boolean AnalogOutputRemote::RequestChannelChange(Int64 channel, Double value, ServiceClass sc) { CHECK_DISPOSAL_STATUS(); if (channel > 0xFFFFFFFFUL) throw gcnew ArgumentOutOfRangeException("channel", "Value must fit in a vrpn_uint32 type"); return m_analogOut->request_change_channel_value( static_cast<unsigned int>(channel), value, static_cast<unsigned int>(sc)); } Boolean AnalogOutputRemote::RequestChannelChange(array<Double> ^channels) { CHECK_DISPOSAL_STATUS(); return RequestChannelChange(channels, ServiceClass::Reliable); } Boolean AnalogOutputRemote::RequestChannelChange(array<Double> ^channels, ServiceClass sc) { CHECK_DISPOSAL_STATUS(); if (channels->LongLength > 0xFFFFFFFFUL) throw gcnew ArgumentException( "VRPN AnalogOutput class supports only 2^32-1 channels", "channels"); pin_ptr<Double> pChannels = &channels[0]; return m_analogOut->request_change_channels(channels->Length, pChannels, static_cast<unsigned int>(sc)); }
31.123967
95
0.754116
vrpn
47587fb719b576a9f4a953f4233de13d93ae190f
21,327
cpp
C++
Modules/PhotoacousticsAlgorithms/Algorithms/mitkPhotoacousticBeamformingFilter.cpp
ZP-Hust/MITK
ca11353183c5ed4bc30f938eae8bde43a0689bf6
[ "BSD-3-Clause" ]
null
null
null
Modules/PhotoacousticsAlgorithms/Algorithms/mitkPhotoacousticBeamformingFilter.cpp
ZP-Hust/MITK
ca11353183c5ed4bc30f938eae8bde43a0689bf6
[ "BSD-3-Clause" ]
null
null
null
Modules/PhotoacousticsAlgorithms/Algorithms/mitkPhotoacousticBeamformingFilter.cpp
ZP-Hust/MITK
ca11353183c5ed4bc30f938eae8bde43a0689bf6
[ "BSD-3-Clause" ]
1
2019-01-09T08:20:18.000Z
2019-01-09T08:20:18.000Z
/*=================================================================== mitkPhotoacousticBeamformingFilter The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #define _USE_MATH_DEFINES #include "mitkPhotoacousticBeamformingFilter.h" #include "mitkProperties.h" #include "mitkImageReadAccessor.h" #include <algorithm> #include <itkImageIOBase.h> #include <chrono> #include <cmath> #include <thread> #include <itkImageIOBase.h> #include "mitkImageCast.h" #include <mitkPhotoacousticOCLBeamformer.h> mitk::BeamformingFilter::BeamformingFilter() : m_OutputData(nullptr), m_InputData(nullptr) { this->SetNumberOfIndexedInputs(1); this->SetNumberOfRequiredInputs(1); m_ProgressHandle = [](int, std::string) {}; } void mitk::BeamformingFilter::SetProgressHandle(std::function<void(int, std::string)> progressHandle) { m_ProgressHandle = progressHandle; } mitk::BeamformingFilter::~BeamformingFilter() { } void mitk::BeamformingFilter::GenerateInputRequestedRegion() { Superclass::GenerateInputRequestedRegion(); mitk::Image* output = this->GetOutput(); mitk::Image* input = const_cast<mitk::Image *> (this->GetInput()); if (!output->IsInitialized()) { return; } input->SetRequestedRegionToLargestPossibleRegion(); //GenerateTimeInInputRegion(output, input); } void mitk::BeamformingFilter::GenerateOutputInformation() { mitk::Image::ConstPointer input = this->GetInput(); mitk::Image::Pointer output = this->GetOutput(); if ((output->IsInitialized()) && (this->GetMTime() <= m_TimeOfHeaderInitialization.GetMTime())) return; itkDebugMacro(<< "GenerateOutputInformation()"); unsigned int dim[] = { m_Conf.ReconstructionLines, m_Conf.SamplesPerLine, input->GetDimension(2) }; output->Initialize(mitk::MakeScalarPixelType<float>(), 3, dim); mitk::Vector3D spacing; spacing[0] = m_Conf.Pitch * m_Conf.TransducerElements * 1000 / m_Conf.ReconstructionLines; spacing[1] = m_Conf.RecordTime / 2 * m_Conf.SpeedOfSound * 1000 / m_Conf.SamplesPerLine; spacing[2] = 1; output->GetGeometry()->SetSpacing(spacing); output->GetGeometry()->Modified(); output->SetPropertyList(input->GetPropertyList()->Clone()); m_TimeOfHeaderInitialization.Modified(); } void mitk::BeamformingFilter::GenerateData() { GenerateOutputInformation(); mitk::Image::Pointer input = this->GetInput(); mitk::Image::Pointer output = this->GetOutput(); if (!output->IsInitialized()) return; float inputDim[2] = { (float)input->GetDimension(0), (float)input->GetDimension(1) }; float outputDim[2] = { (float)output->GetDimension(0), (float)output->GetDimension(1) }; unsigned short chunkSize = 2; // TODO: make this slightly less arbitrary unsigned int oclOutputDim[3] = { output->GetDimension(0), output->GetDimension(1), output->GetDimension(2) }; unsigned int oclOutputDimChunk[3] = { output->GetDimension(0), output->GetDimension(1), chunkSize}; unsigned int oclInputDimChunk[3] = { input->GetDimension(0), input->GetDimension(1), chunkSize}; unsigned int oclOutputDimLastChunk[3] = { output->GetDimension(0), output->GetDimension(1), input->GetDimension(2) % chunkSize }; unsigned int oclInputDimLastChunk[3] = { input->GetDimension(0), input->GetDimension(1), input->GetDimension(2) % chunkSize }; const int apodArraySize = m_Conf.TransducerElements * 4; // set the resolution of the apodization array float* ApodWindow; // calculate the appropiate apodization window switch (m_Conf.Apod) { case beamformingSettings::Apodization::Hann: ApodWindow = VonHannFunction(apodArraySize); break; case beamformingSettings::Apodization::Hamm: ApodWindow = HammFunction(apodArraySize); break; case beamformingSettings::Apodization::Box: ApodWindow = BoxFunction(apodArraySize); break; default: ApodWindow = BoxFunction(apodArraySize); break; } int progInterval = output->GetDimension(2) / 20 > 1 ? output->GetDimension(2) / 20 : 1; // the interval at which we update the gui progress bar auto begin = std::chrono::high_resolution_clock::now(); // debbuging the performance... if (!m_Conf.UseGPU) { for (unsigned int i = 0; i < output->GetDimension(2); ++i) // seperate Slices should get Beamforming seperately applied { mitk::ImageReadAccessor inputReadAccessor(input, input->GetSliceData(i)); m_OutputData = new float[m_Conf.ReconstructionLines*m_Conf.SamplesPerLine]; m_InputDataPuffer = new float[input->GetDimension(0)*input->GetDimension(1)]; // first, we convert any data to float, which we use by default if (input->GetPixelType().GetTypeAsString() == "scalar (float)" || input->GetPixelType().GetTypeAsString() == " (float)") { m_InputData = (float*)inputReadAccessor.GetData(); } else { MITK_INFO << "Pixel type is not float, abort"; return; } // fill the image with zeros for (int l = 0; l < outputDim[0]; ++l) { for (int s = 0; s < outputDim[1]; ++s) { m_OutputData[l*(short)outputDim[1] + s] = 0; } } std::thread *threads = new std::thread[(short)outputDim[0]]; // every line will be beamformed in a seperate thread if (m_Conf.Algorithm == beamformingSettings::BeamformingAlgorithm::DAS) { if (m_Conf.DelayCalculationMethod == beamformingSettings::DelayCalc::QuadApprox) { for (short line = 0; line < outputDim[0]; ++line) { threads[line] = std::thread(&BeamformingFilter::DASQuadraticLine, this, m_InputData, m_OutputData, inputDim, outputDim, line, ApodWindow, apodArraySize); } } else if (m_Conf.DelayCalculationMethod == beamformingSettings::DelayCalc::Spherical) { for (short line = 0; line < outputDim[0]; ++line) { threads[line] = std::thread(&BeamformingFilter::DASSphericalLine, this, m_InputData, m_OutputData, inputDim, outputDim, line, ApodWindow, apodArraySize); } } } else if (m_Conf.Algorithm == beamformingSettings::BeamformingAlgorithm::DMAS) { if (m_Conf.DelayCalculationMethod == beamformingSettings::DelayCalc::QuadApprox) { for (short line = 0; line < outputDim[0]; ++line) { threads[line] = std::thread(&BeamformingFilter::DMASQuadraticLine, this, m_InputData, m_OutputData, inputDim, outputDim, line, ApodWindow, apodArraySize); } } else if (m_Conf.DelayCalculationMethod == beamformingSettings::DelayCalc::Spherical) { for (short line = 0; line < outputDim[0]; ++line) { threads[line] = std::thread(&BeamformingFilter::DMASSphericalLine, this, m_InputData, m_OutputData, inputDim, outputDim, line, ApodWindow, apodArraySize); } } } // wait for all lines to finish for (short line = 0; line < outputDim[0]; ++line) { threads[line].join(); } output->SetSlice(m_OutputData, i); if (i % progInterval == 0) m_ProgressHandle((int)((i + 1) / (float)output->GetDimension(2) * 100), "performing reconstruction"); delete[] m_OutputData; delete[] m_InputDataPuffer; m_OutputData = nullptr; m_InputData = nullptr; } } else { mitk::PhotoacousticOCLBeamformer::Pointer m_oclFilter = mitk::PhotoacousticOCLBeamformer::New(); try { if (m_Conf.Algorithm == beamformingSettings::BeamformingAlgorithm::DAS) { if (m_Conf.DelayCalculationMethod == beamformingSettings::DelayCalc::QuadApprox) m_oclFilter->SetAlgorithm(PhotoacousticOCLBeamformer::BeamformingAlgorithm::DASQuad, true); else if (m_Conf.DelayCalculationMethod == beamformingSettings::DelayCalc::Spherical) m_oclFilter->SetAlgorithm(PhotoacousticOCLBeamformer::BeamformingAlgorithm::DASSphe, true); } else if (m_Conf.Algorithm == beamformingSettings::BeamformingAlgorithm::DMAS) { if (m_Conf.DelayCalculationMethod == beamformingSettings::DelayCalc::QuadApprox) m_oclFilter->SetAlgorithm(PhotoacousticOCLBeamformer::BeamformingAlgorithm::DMASQuad, true); else if (m_Conf.DelayCalculationMethod == beamformingSettings::DelayCalc::Spherical) m_oclFilter->SetAlgorithm(PhotoacousticOCLBeamformer::BeamformingAlgorithm::DMASSphe, true); } m_oclFilter->SetApodisation(ApodWindow, apodArraySize); m_oclFilter->SetOutputDim(oclOutputDimChunk); m_oclFilter->SetBeamformingParameters(m_Conf.SpeedOfSound, m_Conf.TimeSpacing, m_Conf.Pitch, m_Conf.Angle, m_Conf.Photoacoustic, m_Conf.TransducerElements); if (chunkSize < oclOutputDim[2]) { bool skip = false; for (unsigned int i = 0; !skip && i < ceil((float)oclOutputDim[2] / (float)chunkSize); ++i) { m_ProgressHandle(100 * ((float)(i * chunkSize) / (float)oclOutputDim[2]), "performing reconstruction"); mitk::Image::Pointer chunk = mitk::Image::New(); if ((int)((oclOutputDim[2]) - (i * chunkSize)) == (int)(1 + chunkSize)) { // A 3d image of 3rd dimension == 1 can not be processed by openCL, make sure that this case never arises oclInputDimLastChunk[2] = input->GetDimension(2) % chunkSize + chunkSize; oclOutputDimLastChunk[2] = input->GetDimension(2) % chunkSize + chunkSize; chunk->Initialize(input->GetPixelType(), 3, oclInputDimLastChunk); m_oclFilter->SetOutputDim(oclOutputDimLastChunk); skip = true; //skip the last chunk } else if ((oclOutputDim[2]) - (i * chunkSize) >= chunkSize) chunk->Initialize(input->GetPixelType(), 3, oclInputDimChunk); else { chunk->Initialize(input->GetPixelType(), 3, oclInputDimLastChunk); m_oclFilter->SetOutputDim(oclOutputDimLastChunk); } chunk->SetSpacing(input->GetGeometry()->GetSpacing()); mitk::ImageReadAccessor ChunkMove(input); chunk->SetImportVolume((void*)&(((float*)const_cast<void*>(ChunkMove.GetData()))[i * chunkSize * input->GetDimension(0) * input->GetDimension(1)]), 0, 0, mitk::Image::ReferenceMemory); m_oclFilter->SetInput(chunk); m_oclFilter->Update(); auto out = m_oclFilter->GetOutput(); for (unsigned int s = i * chunkSize; s < oclOutputDim[2]; ++s) // TODO: make the bounds here smaller... { mitk::ImageReadAccessor copy(out, out->GetSliceData(s - i * chunkSize)); output->SetImportSlice(const_cast<void*>(copy.GetData()), s, 0, 0, mitk::Image::ReferenceMemory); } } } else { m_ProgressHandle(50, "performing reconstruction"); m_oclFilter->SetOutputDim(oclOutputDim); m_oclFilter->SetInput(input); m_oclFilter->Update(); auto out = m_oclFilter->GetOutput(); mitk::ImageReadAccessor copy(out); output->SetImportVolume(const_cast<void*>(copy.GetData()), 0, 0, mitk::Image::ReferenceMemory); } } catch (mitk::Exception &e) { std::string errorMessage = "Caught unexpected exception "; errorMessage.append(e.what()); MITK_ERROR << errorMessage; } } m_TimeOfHeaderInitialization.Modified(); auto end = std::chrono::high_resolution_clock::now(); MITK_INFO << "Beamforming of " << output->GetDimension(2) << " Images completed in " << ((float)std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count()) / 1000000 << "ms" << std::endl; } void mitk::BeamformingFilter::Configure(beamformingSettings settings) { m_Conf = settings; } float* mitk::BeamformingFilter::VonHannFunction(int samples) { float* ApodWindow = new float[samples]; for (int n = 0; n < samples; ++n) { ApodWindow[n] = (1 - cos(2 * M_PI * n / (samples - 1))) / 2; } return ApodWindow; } float* mitk::BeamformingFilter::HammFunction(int samples) { float* ApodWindow = new float[samples]; for (int n = 0; n < samples; ++n) { ApodWindow[n] = 0.54 - 0.46*cos(2 * M_PI*n / (samples - 1)); } return ApodWindow; } float* mitk::BeamformingFilter::BoxFunction(int samples) { float* ApodWindow = new float[samples]; for (int n = 0; n < samples; ++n) { ApodWindow[n] = 1; } return ApodWindow; } void mitk::BeamformingFilter::DASQuadraticLine(float* input, float* output, float inputDim[2], float outputDim[2], const short& line, float* apodisation, const short& apodArraySize) { float& inputS = inputDim[1]; float& inputL = inputDim[0]; float& outputS = outputDim[1]; float& outputL = outputDim[0]; short AddSample = 0; short maxLine = 0; short minLine = 0; float delayMultiplicator = 0; float l_i = 0; float s_i = 0; float part = 0.07 * inputL; float tan_phi = std::tan(m_Conf.Angle / 360 * 2 * M_PI); float part_multiplicator = tan_phi * m_Conf.TimeSpacing * m_Conf.SpeedOfSound / m_Conf.Pitch * m_Conf.ReconstructionLines / m_Conf.TransducerElements; float apod_mult = 1; short usedLines = (maxLine - minLine); //quadratic delay l_i = line / outputL * inputL; for (short sample = 0; sample < outputS; ++sample) { s_i = (float)sample / outputS * inputS / 2; part = part_multiplicator*s_i; if (part < 1) part = 1; maxLine = (short)std::min((l_i + part) + 1, inputL); minLine = (short)std::max((l_i - part), 0.0f); usedLines = (maxLine - minLine); apod_mult = apodArraySize / (maxLine - minLine); delayMultiplicator = pow((1 / (m_Conf.TimeSpacing*m_Conf.SpeedOfSound) * (m_Conf.Pitch*m_Conf.TransducerElements) / inputL), 2) / s_i / 2; for (short l_s = minLine; l_s < maxLine; ++l_s) { AddSample = delayMultiplicator * pow((l_s - l_i), 2) + s_i + (1 - m_Conf.Photoacoustic)*s_i; if (AddSample < inputS && AddSample >= 0) output[sample*(short)outputL + line] += input[l_s + AddSample*(short)inputL] * apodisation[(short)((l_s - minLine)*apod_mult)]; else --usedLines; } output[sample*(short)outputL + line] = output[sample*(short)outputL + line] / usedLines; } } void mitk::BeamformingFilter::DASSphericalLine(float* input, float* output, float inputDim[2], float outputDim[2], const short& line, float* apodisation, const short& apodArraySize) { float& inputS = inputDim[1]; float& inputL = inputDim[0]; float& outputS = outputDim[1]; float& outputL = outputDim[0]; short AddSample = 0; short maxLine = 0; short minLine = 0; float l_i = 0; float s_i = 0; float part = 0.07 * inputL; float tan_phi = std::tan(m_Conf.Angle / 360 * 2 * M_PI); float part_multiplicator = tan_phi * m_Conf.TimeSpacing * m_Conf.SpeedOfSound / m_Conf.Pitch * m_Conf.ReconstructionLines / m_Conf.TransducerElements; float apod_mult = 1; short usedLines = (maxLine - minLine); //exact delay l_i = (float)line / outputL * inputL; for (short sample = 0; sample < outputS; ++sample) { s_i = (float)sample / outputS * inputS / 2; part = part_multiplicator*s_i; if (part < 1) part = 1; maxLine = (short)std::min((l_i + part) + 1, inputL); minLine = (short)std::max((l_i - part), 0.0f); usedLines = (maxLine - minLine); apod_mult = apodArraySize / (maxLine - minLine); for (short l_s = minLine; l_s < maxLine; ++l_s) { AddSample = (int)sqrt( pow(s_i, 2) + pow((1 / (m_Conf.TimeSpacing*m_Conf.SpeedOfSound) * ((l_s - l_i)*m_Conf.Pitch*m_Conf.TransducerElements) / inputL), 2) ) + (1 - m_Conf.Photoacoustic)*s_i; if (AddSample < inputS && AddSample >= 0) output[sample*(short)outputL + line] += input[l_s + AddSample*(short)inputL] * apodisation[(short)((l_s - minLine)*apod_mult)]; else --usedLines; } output[sample*(short)outputL + line] = output[sample*(short)outputL + line] / usedLines; } } void mitk::BeamformingFilter::DMASQuadraticLine(float* input, float* output, float inputDim[2], float outputDim[2], const short& line, float* apodisation, const short& apodArraySize) { float& inputS = inputDim[1]; float& inputL = inputDim[0]; float& outputS = outputDim[1]; float& outputL = outputDim[0]; short maxLine = 0; short minLine = 0; float delayMultiplicator = 0; float l_i = 0; float s_i = 0; float part = 0.07 * inputL; float tan_phi = std::tan(m_Conf.Angle / 360 * 2 * M_PI); float part_multiplicator = tan_phi * m_Conf.TimeSpacing * m_Conf.SpeedOfSound / m_Conf.Pitch * m_Conf.ReconstructionLines / m_Conf.TransducerElements; float apod_mult = 1; float mult = 0; short usedLines = (maxLine - minLine); //quadratic delay l_i = line / outputL * inputL; for (short sample = 0; sample < outputS; ++sample) { s_i = sample / outputS * inputS / 2; part = part_multiplicator*s_i; if (part < 1) part = 1; maxLine = (short)std::min((l_i + part) + 1, inputL); minLine = (short)std::max((l_i - part), 0.0f); usedLines = (maxLine - minLine); apod_mult = apodArraySize / (maxLine - minLine); delayMultiplicator = pow((1 / (m_Conf.TimeSpacing*m_Conf.SpeedOfSound) * (m_Conf.Pitch*m_Conf.TransducerElements) / inputL), 2) / s_i / 2; //calculate the AddSamples beforehand to save some time short* AddSample = new short[maxLine - minLine]; for (short l_s = 0; l_s < maxLine - minLine; ++l_s) { AddSample[l_s] = (short)(delayMultiplicator * pow((minLine + l_s - l_i), 2) + s_i) + (1 - m_Conf.Photoacoustic)*s_i; } for (short l_s1 = minLine; l_s1 < maxLine - 1; ++l_s1) { if (AddSample[l_s1 - minLine] < (short)inputS && AddSample[l_s1 - minLine] >= 0) { for (short l_s2 = l_s1 + 1; l_s2 < maxLine; ++l_s2) { if (AddSample[l_s2 - minLine] < inputS && AddSample[l_s2 - minLine] >= 0) { mult = input[l_s2 + AddSample[l_s2 - minLine] * (short)inputL] * apodisation[(short)((l_s2 - minLine)*apod_mult)] * input[l_s1 + AddSample[l_s1 - minLine] * (short)inputL] * apodisation[(short)((l_s1 - minLine)*apod_mult)]; output[sample*(short)outputL + line] += sqrt(abs(mult)) * ((mult > 0) - (mult < 0)); } } } else --usedLines; } output[sample*(short)outputL + line] = 10 * output[sample*(short)outputL + line] / (pow(usedLines, 2) - (usedLines - 1)); delete[] AddSample; } } void mitk::BeamformingFilter::DMASSphericalLine(float* input, float* output, float inputDim[2], float outputDim[2], const short& line, float* apodisation, const short& apodArraySize) { float& inputS = inputDim[1]; float& inputL = inputDim[0]; float& outputS = outputDim[1]; float& outputL = outputDim[0]; short maxLine = 0; short minLine = 0; float l_i = 0; float s_i = 0; float part = 0.07 * inputL; float tan_phi = std::tan(m_Conf.Angle / 360 * 2 * M_PI); float part_multiplicator = tan_phi * m_Conf.TimeSpacing * m_Conf.SpeedOfSound / m_Conf.Pitch * m_Conf.ReconstructionLines / m_Conf.TransducerElements; float apod_mult = 1; float mult = 0; short usedLines = (maxLine - minLine); //exact delay l_i = line / outputL * inputL; for (short sample = 0; sample < outputS; ++sample) { s_i = sample / outputS * inputS / 2; part = part_multiplicator*s_i; if (part < 1) part = 1; maxLine = (short)std::min((l_i + part) + 1, inputL); minLine = (short)std::max((l_i - part), 0.0f); usedLines = (maxLine - minLine); apod_mult = apodArraySize / (maxLine - minLine); //calculate the AddSamples beforehand to save some time short* AddSample = new short[maxLine - minLine]; for (short l_s = 0; l_s < maxLine - minLine; ++l_s) { AddSample[l_s] = (short)sqrt( pow(s_i, 2) + pow((1 / (m_Conf.TimeSpacing*m_Conf.SpeedOfSound) * ((minLine + l_s - l_i)*m_Conf.Pitch*m_Conf.TransducerElements) / inputL), 2) ) + (1 - m_Conf.Photoacoustic)*s_i; } for (short l_s1 = minLine; l_s1 < maxLine - 1; ++l_s1) { if (AddSample[l_s1 - minLine] < inputS && AddSample[l_s1 - minLine] >= 0) { for (short l_s2 = l_s1 + 1; l_s2 < maxLine; ++l_s2) { if (AddSample[l_s2 - minLine] < inputS && AddSample[l_s2 - minLine] >= 0) { mult = input[l_s2 + AddSample[l_s2 - minLine] * (short)inputL] * apodisation[(int)((l_s2 - minLine)*apod_mult)] * input[l_s1 + AddSample[l_s1 - minLine] * (short)inputL] * apodisation[(int)((l_s1 - minLine)*apod_mult)]; output[sample*(short)outputL + line] += sqrt(abs(mult)) * ((mult > 0) - (mult < 0)); } } } else --usedLines; } output[sample*(short)outputL + line] = 10 * output[sample*(short)outputL + line] / (pow(usedLines, 2) - (usedLines - 1)); delete[] AddSample; } }
35.077303
235
0.648099
ZP-Hust
4758a5d70b1bf5667b99161e9cefcf234ba15c33
3,732
cpp
C++
firmware-latest/communication/src/events.cpp
adeeshag/particle_project
0c2ab278cf902f97d2422c44c008978be58fe6b7
[ "Unlicense" ]
null
null
null
firmware-latest/communication/src/events.cpp
adeeshag/particle_project
0c2ab278cf902f97d2422c44c008978be58fe6b7
[ "Unlicense" ]
null
null
null
firmware-latest/communication/src/events.cpp
adeeshag/particle_project
0c2ab278cf902f97d2422c44c008978be58fe6b7
[ "Unlicense" ]
null
null
null
/** ****************************************************************************** * @file events.cpp * @authors Zachary Crockett * @version V1.0.0 * @date 26-Feb-2014 * @brief Internal CoAP event message creation ****************************************************************************** Copyright (c) 2014-2015 Particle Industries, Inc. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, see <http://www.gnu.org/licenses/>. ****************************************************************************** */ #include "events.h" #include <string.h> size_t event(uint8_t buf[], uint16_t message_id, const char *event_name, const char *data, int ttl, EventType::Enum event_type) { uint8_t *p = buf; *p++ = 0x50; // non-confirmable, no token *p++ = 0x02; // code 0.02 POST request *p++ = message_id >> 8; *p++ = message_id & 0xff; *p++ = 0xb1; // one-byte Uri-Path option *p++ = event_type; size_t name_data_len = strnlen(event_name, 63); p += event_name_uri_path(p, event_name, name_data_len); if (60 != ttl) { *p++ = 0x33; *p++ = (ttl >> 16) & 0xff; *p++ = (ttl >> 8) & 0xff; *p++ = ttl & 0xff; } if (NULL != data) { name_data_len = strnlen(data, 255); *p++ = 0xff; memcpy(p, data, name_data_len); p += name_data_len; } return p - buf; } // Private, used by two subscription variants below uint8_t *subscription_prelude(uint8_t buf[], uint16_t message_id, const char *event_name) { uint8_t *p = buf; *p++ = 0x40; // confirmable, no token *p++ = 0x01; // code 0.01 GET request *p++ = message_id >> 8; *p++ = message_id & 0xff; *p++ = 0xb1; // one-byte Uri-Path option *p++ = 'e'; if (NULL != event_name) { size_t len = strnlen(event_name, 63); p += event_name_uri_path(p, event_name, len); } return p; } size_t subscription(uint8_t buf[], uint16_t message_id, const char *event_name, const char *device_id) { uint8_t *p = subscription_prelude(buf, message_id, event_name); if (NULL != device_id) { size_t len = strnlen(device_id, 63); *p++ = 0xff; memcpy(p, device_id, len); p += len; } return p - buf; } size_t subscription(uint8_t buf[], uint16_t message_id, const char *event_name, SubscriptionScope::Enum scope) { uint8_t *p = subscription_prelude(buf, message_id, event_name); switch (scope) { case SubscriptionScope::MY_DEVICES: *p++ = 0x41; // one-byte Uri-Query option *p++ = 'u'; break; case SubscriptionScope::FIREHOSE: default: // unfiltered firehose is not allowed if (NULL == event_name || 0 == *event_name) { return -1; } } return p - buf; } size_t event_name_uri_path(uint8_t buf[], const char *name, size_t name_len) { if (0 == name_len) { return 0; } else if (name_len < 13) { buf[0] = name_len; memcpy(buf + 1, name, name_len); return name_len + 1; } else { buf[0] = 0x0d; buf[1] = name_len - 13; memcpy(buf + 2, name, name_len); return name_len + 2; } }
26.097902
80
0.583333
adeeshag
e6e577deb83d81b726fe574676492d8bb7430f7a
2,263
cpp
C++
code/87.cpp
Nightwish-cn/my_leetcode
40f206e346f3f734fb28f52b9cde0e0041436973
[ "MIT" ]
23
2020-03-30T05:44:56.000Z
2021-09-04T16:00:57.000Z
code/87.cpp
Nightwish-cn/my_leetcode
40f206e346f3f734fb28f52b9cde0e0041436973
[ "MIT" ]
1
2020-05-10T15:04:05.000Z
2020-06-14T01:21:44.000Z
code/87.cpp
Nightwish-cn/my_leetcode
40f206e346f3f734fb28f52b9cde0e0041436973
[ "MIT" ]
6
2020-03-30T05:45:04.000Z
2020-08-13T10:01:39.000Z
#include <bits/stdc++.h> #define INF 2000000000 using namespace std; typedef long long ll; int read(){ int f = 1, x = 0; char c = getchar(); while(c < '0' || c > '9'){if(c == '-') f = -f; c = getchar();} while(c >= '0' && c <= '9')x = x * 10 + c - '0', c = getchar(); return f * x; } struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; bool isLeaf(TreeNode* root) { return root->left == NULL && root->right == NULL; } class Solution { public: bool dfs(string& s1, string& s2, int l1, int r1, int l2, int r2, bool flag){ if (r1 - l1 == 1) return s1[l1] == s2[l2]; int vec[26] = {0}, cnt = 0; for (int i = 1; i < r1 - l1; ++i){ if (vec[s1[l1 + i - 1]] == 0) ++cnt; else if (vec[s1[l1 + i - 1]] == -1) --cnt; ++vec[s1[l1 + i - 1]]; if (flag) { if (vec[s2[l2 + i - 1]] == 1) --cnt; else if (vec[s2[l2 + i - 1]] == 0) ++cnt; --vec[s2[l2 + i - 1]]; if (cnt == 0 && (dfs(s1, s2, l1, l1 + i, l2, l2 + i, true) || dfs(s1, s2, l1, l1 + i, l2, l2 + i, false)) && (dfs(s1, s2, l1 + i, r1, l2 + i, r2, true) || dfs(s1, s2, l1 + i, r1, l2 + i, r2, false))) return true; }else { if (vec[s2[r2 - i]] == 1) --cnt; else if (vec[s2[r2 - i]] == 0) ++cnt; --vec[s2[r2 - i]]; if (cnt == 0 && (dfs(s1, s2, l1, l1 + i, r2 - i, r2, true) || dfs(s1, s2, l1, l1 + i, r2 - i, r2, false)) && (dfs(s1, s2, l1 + i, r1, l2, r2 - i, true) || dfs(s1, s2, l1 + i, r1, l2, r2 - i, false))) return true; } } return false; } bool isScramble(string s1, string s2) { for (int i = 0; i < s1.length(); ++i) s1[i] -= 'a'; for (int i = 0; i < s2.length(); ++i) s2[i] -= 'a'; return dfs(s1, s2, 0, s1.length(), 0, s2.length(), true) || dfs(s1, s2, 0, s1.length(), 0, s2.length(), false); } }; Solution sol; void init(){ } void solve(){ // sol.convert(); } int main(){ init(); solve(); return 0; }
31
124
0.418913
Nightwish-cn
e6e6e861d6ae33a6ed1e82d6202e984019b0062d
3,033
cpp
C++
test/module/shared_model/builders/common_objects/signature_builder_test.cpp
coderintherye/iroha
68509282851130c9818f21acef1ef28e53622315
[ "Apache-2.0" ]
null
null
null
test/module/shared_model/builders/common_objects/signature_builder_test.cpp
coderintherye/iroha
68509282851130c9818f21acef1ef28e53622315
[ "Apache-2.0" ]
null
null
null
test/module/shared_model/builders/common_objects/signature_builder_test.cpp
coderintherye/iroha
68509282851130c9818f21acef1ef28e53622315
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. 2018 All Rights Reserved. * http://soramitsu.co.jp * * 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 <gtest/gtest.h> #include "builders_test_fixture.hpp" #include "module/shared_model/builders/common_objects/signature_builder.hpp" #include "module/shared_model/builders/protobuf/common_objects/proto_signature_builder.hpp" #include "validators/field_validator.hpp" // TODO: 14.02.2018 nickaleks mock builder implementation IR-970 // TODO: 14.02.2018 nickaleks mock field validator IR-971 /** * @given field values which pass stateless validation * @when PeerBuilder is invoked * @then Peer object is successfully constructed and has valid fields */ TEST(PeerBuilderTest, StatelessValidAddressCreation) { shared_model::builder::SignatureBuilder< shared_model::proto::SignatureBuilder, shared_model::validation::FieldValidator> builder; shared_model::interface::types::PubkeyType expected_key(std::string(32, '1')); shared_model::interface::Signature::SignedType expected_signed( "signed object"); auto signature = builder.publicKey(expected_key).signedData(expected_signed).build(); signature.match( [&](shared_model::builder::BuilderResult< shared_model::interface::Signature>::ValueType &v) { EXPECT_EQ(v.value->publicKey(), expected_key); EXPECT_EQ(v.value->signedData(), expected_signed); }, [](shared_model::builder::BuilderResult< shared_model::interface::Signature>::ErrorType &e) { FAIL() << *e.error; }); } /** * @given field values which pass stateless validation * @when SignatureBuilder is invoked twice * @then Two identical (==) Signature objects are constructed */ TEST(SignatureBuilderTest, SeveralObjectsFromOneBuilder) { shared_model::builder::SignatureBuilder< shared_model::proto::SignatureBuilder, shared_model::validation::FieldValidator> builder; shared_model::interface::types::PubkeyType expected_key(std::string(32, '1')); shared_model::interface::Signature::SignedType expected_signed( "signed object"); auto state = builder.publicKey(expected_key).signedData(expected_signed); auto signature = state.build(); auto signature2 = state.build(); testResultObjects(signature, signature2, [](auto &a, auto &b) { // pointer points to different objects ASSERT_TRUE(a != b); EXPECT_EQ(a->publicKey(), b->publicKey()); EXPECT_EQ(a->signedData(), b->signedData()); }); }
35.682353
91
0.726014
coderintherye
e6eda95147638c5a9ab2e6f5107109c2dc181850
16,857
cpp
C++
src/modrin_motor_plugins/epos2.cpp
ein57ein/modrin
7ec843439ffb19fb9fb68ca416f78770b5c72228
[ "BSD-3-Clause" ]
null
null
null
src/modrin_motor_plugins/epos2.cpp
ein57ein/modrin
7ec843439ffb19fb9fb68ca416f78770b5c72228
[ "BSD-3-Clause" ]
null
null
null
src/modrin_motor_plugins/epos2.cpp
ein57ein/modrin
7ec843439ffb19fb9fb68ca416f78770b5c72228
[ "BSD-3-Clause" ]
null
null
null
#include <pluginlib/class_list_macros.h> #include <modrin_motor_plugins/epos2.hpp> PLUGINLIB_EXPORT_CLASS(modrin_motor_plugins::Epos2, modrin::Motor) namespace modrin_motor_plugins { Epos2::Epos2():devhandle(0), lastEpos2ErrorCode(0) { ROS_DEBUG("created an instance of epos2-plugin for modrin"); } Epos2::~Epos2() { if ( devhandle != 0 ) closeEpos2(); } bool Epos2::onInit() { if ( ros::param::has(full_namespace + "/node_nr") ) { int temp; ros::param::get(full_namespace + "/node_nr", temp); epos_node_nr.push_back(temp); } else { ROS_ERROR("[%s] couldn't read an Epos2 node_nr from the parameter-server at \"%s\"", name.c_str(), (full_namespace + "/node_nr").c_str() ); return false; } eposCanClient = ros::param::has(full_namespace + "/can_connected_with"); if ( eposCanClient ) { std::string can_connected_with; ros::param::get(full_namespace + "/can_connected_with", can_connected_with); //size_t x = srv_name.find_last_of("/"); //srv_name = srv_name.substr(0, x+1) + can_connected_with; srv_name = ros::this_node::getName() + "/" + can_connected_with; epos2_can = roshandle.serviceClient<modrin::epos2_can>( srv_name ); } else { //establishCommmunication(); srv_name = full_namespace; epos2_can_srv = roshandle.advertiseService(srv_name.c_str(), &Epos2::canSrv, this); ROS_DEBUG("[%s] create srv: %s", name.c_str(), srv_name.c_str()); } controllTimer = roshandle.createTimer(ros::Rate(0.2), &Epos2::periopdicControllCallback, this); return initEpos2(1000); } void Epos2::periopdicControllCallback(const ros::TimerEvent& event) { switch ( getState() ) { case not_init: initEpos2(); break; case fault: if (!eposCanClient) resetAndClearFaultOnAllDevices(); break; } } bool Epos2::initEpos2(int timeout) { if (eposCanClient) { modrin::epos2_can temp; temp.request.node_nr = epos_node_nr[0]; ros::service::waitForService(srv_name, timeout); ROS_DEBUG("call srv: %s", srv_name.c_str() ); if (epos2_can.call(temp)) { devhandle = (void*) temp.response.devhandle; ROS_INFO("[%s] receive an epos2 device-handle: %#lx", name.c_str(), (unsigned long int) devhandle); } else { devhandle = 0; } } else { establishCommmunication(); } if (devhandle == 0) { if (eposCanClient) { ROS_WARN("[%s] couldn't receive an epos2 device-handle", name.c_str()); } else { ROS_ERROR("[%s] couldn't receive an epos2 device-handle", name.c_str()); } return false; } else { //set parameter if (eposCanClient) {setParameter();} ROS_INFO("[%s] Epos2 with node_nr %i successfully started in ns \"%s\"", name.c_str(), epos_node_nr[0], full_namespace.c_str() ); return true; } } bool Epos2::establishCommmunication() { std::string port; char *protocol, *port_type; int baudrate, timeout; ros::param::get(full_namespace + "/port", port); ros::param::param<int>(full_namespace + "/timeout", timeout, 750); if ( port.substr(0,3).compare("USB") == 0 ) { ros::param::param<int>(full_namespace + "/baudrate", baudrate, 1000000); protocol = (char*)"MAXON SERIAL V2"; port_type = (char*)"USB"; } else if ( port.substr(0,8).compare("/dev/tty") == 0 ) { ros::param::param<int>(full_namespace + "/baudrate", baudrate, 115200); protocol = (char*)"MAXON_RS232"; port_type = (char*)"RS232"; } else { ROS_ERROR("[%s] \"%s\" isn't a valid portname for the Epos2. Allowed are USB* or /dev/tty*", name.c_str(), port.c_str()); return false; } unsigned int errorCode=0; devhandle = VCS_OpenDevice((char*)"EPOS2", protocol, port_type, (char*) port.c_str(), &lastEpos2ErrorCode); if (devhandle == 0) { printEpos2Error(); return false; } else { if ( VCS_SetProtocolStackSettings(devhandle, baudrate, timeout, &lastEpos2ErrorCode) ) { ROS_INFO("[%s] open EPOS2-Device on port %s (baudrate: %i; timeout: %i). device-handle: %#lx", name.c_str(), port.c_str(), baudrate, timeout, (unsigned long int) devhandle); return true; } else { printEpos2Error(); return false; } } } bool Epos2::canSrv(modrin::epos2_can::Request &req, modrin::epos2_can::Response &res) { ROS_INFO("[%s] Epos2 with node_nr %i call the canSrv", name.c_str(), req.node_nr); res.devhandle = (unsigned long int) devhandle; if (devhandle == 0) { return false; } else { epos_node_nr.push_back(req.node_nr); resetAndClearFaultOnAllDevices(); setParameter(); return true; } } bool Epos2::setEnable() { state temp = getState(); if ( temp == enabled ) return true; if ( temp != disabled ) return false; if ( VCS_SetEnableState(devhandle, epos_node_nr[0], &lastEpos2ErrorCode) ) { return true; } else { printEpos2Error(); return false; } } bool Epos2::setDisable() { state temp = getState(); if ( temp == disabled ) return true; if ( temp == not_init ) return false; if ( VCS_SetDisableState(devhandle, epos_node_nr[0], &lastEpos2ErrorCode) ) { return true; } else { printEpos2Error(); return false; } } bool Epos2::setQuickStop() { if ( VCS_SetQuickStopState(devhandle, epos_node_nr[0], &lastEpos2ErrorCode) ) { return true; } else { printEpos2Error(); return false; } } modrin::Motor::state Epos2::getState() { unsigned short tempState=0; if ( VCS_GetState(devhandle, epos_node_nr[0], &tempState, &lastEpos2ErrorCode) ) { switch (tempState) { case ST_ENABLED: return enabled; break; case ST_DISABLED: return disabled; break; case ST_QUICKSTOP: return disabled; break; case ST_FAULT: default: return fault; break; } } else { if ( devhandle != 0 ) { printEpos2Error(); closeEpos2(); } return not_init; } } void Epos2::closeEpos2() { setDisable(); if ( !VCS_CloseDevice(devhandle, &lastEpos2ErrorCode) ) printEpos2Error(); devhandle = 0; } //set parameters first (notation and dimension) bool Epos2::setRPM(double rpm) {return false;} double Epos2::getMaxRPM() { return 0.0; } void Epos2::resetAndClearFaultOnAllDevices() { std::vector<int>::iterator it; for (it = epos_node_nr.begin(); it < epos_node_nr.end(); it++) { if ( !VCS_SetDisableState(devhandle, *it, &lastEpos2ErrorCode) ) printEpos2Error(); } for (it = epos_node_nr.begin(); it < epos_node_nr.end(); it++) { if ( !VCS_ResetDevice(devhandle, *it, &lastEpos2ErrorCode) ) printEpos2Error(); } for (it = epos_node_nr.begin(); it < epos_node_nr.end(); it++) { if ( !VCS_ClearFault(devhandle, *it, &lastEpos2ErrorCode) ) printEpos2Error(); } for (it = epos_node_nr.begin(); it < epos_node_nr.end(); it++) { if ( !VCS_SetEnableState(devhandle, *it, &lastEpos2ErrorCode) ) printEpos2Error(); } } void Epos2::printEpos2Error() { unsigned short maxStr=255; //max stringsize char errorText[maxStr]; //errorstring if ( VCS_GetErrorInfo(lastEpos2ErrorCode, errorText, maxStr) ) { ROS_ERROR("[%s] %s (errorCode: %#x)", name.c_str(), errorText, lastEpos2ErrorCode); } else { ROS_FATAL("[%s] Unable to resolve an errorText for the Epos2-ErrorCode %#x", name.c_str(), lastEpos2ErrorCode); } } bool Epos2::setParameter() { if ( !setDisable() ) return false; if ( !setDimensionAndNotation() ) return false; if ( !checkSpin() ) return false; if ( !checkMotorParameter() ) return false; if ( !VCS_Store(devhandle, epos_node_nr[0], &lastEpos2ErrorCode) ) { printEpos2Error(); } if ( !setEnable() ) return false; return true; } bool Epos2::checkMotorParameter() { short unsigned motor_type; if ( !VCS_GetMotorType(devhandle, epos_node_nr[0], &motor_type, &lastEpos2ErrorCode) ) { printEpos2Error(); } //ros::param::has(full_namespace + "/motor_type") if ( ros::param::get(full_namespace + "/motor_type", (int&) motor_type) ) { if ( !VCS_SetMotorType(devhandle, epos_node_nr[0], motor_type, &lastEpos2ErrorCode) ) { printEpos2Error(); } } short unsigned nominal_current = 0, max_current = 0, thermal_time_constant = 0; unsigned char number_of_pole_pairs = 1; std::string motor_str; if ( motor_type == MT_DC_MOTOR ) { motor_str = "brushed DC motor"; if ( !VCS_GetDcMotorParameter(devhandle, epos_node_nr[0], &nominal_current, &max_current, &thermal_time_constant, &lastEpos2ErrorCode) ) { printEpos2Error(); } } else { motor_str = (motor_type == MT_EC_SINUS_COMMUTATED_MOTOR) ? "EC motor sinus commutated" : "EC motor block commutated"; if ( !VCS_GetEcMotorParameter(devhandle, epos_node_nr[0], &nominal_current, &max_current, &thermal_time_constant, &number_of_pole_pairs, &lastEpos2ErrorCode) ) { printEpos2Error(); } } thermal_time_constant = 100 * thermal_time_constant; bool something_changed = false, successfully_set = true; if ( ros::param::get(full_namespace + "/motor_nominal_current", (int&) nominal_current) ) { something_changed = true; } if ( ros::param::get(full_namespace + "/motor_max_output_current", (int&) max_current) ) { something_changed = true; } if ( ros::param::get(full_namespace + "/motor_thermal_time_constant", (int&) thermal_time_constant) ) { something_changed = true; } std::ostringstream pole_pair_str; pole_pair_str.str(""); if ( motor_type == MT_DC_MOTOR ) { if (something_changed) { if ( !VCS_SetDcMotorParameter(devhandle, epos_node_nr[0], nominal_current, max_current, (short unsigned) (thermal_time_constant / 100.0), &lastEpos2ErrorCode) ) { printEpos2Error(); successfully_set = false; } } } else { if ( ros::param::get(full_namespace + "/motor_pole_pair_number", (int&) number_of_pole_pairs) ) { something_changed = true; } pole_pair_str << number_of_pole_pairs << " pole pairs, "; if (something_changed) { if ( !VCS_SetEcMotorParameter(devhandle, epos_node_nr[0], nominal_current, max_current, (short unsigned) (thermal_time_constant / 100.0), number_of_pole_pairs, &lastEpos2ErrorCode) ) { printEpos2Error(); successfully_set = false; } } } unsigned int bytes = 0; int max_rpm; if ( !VCS_GetObject(devhandle, epos_node_nr[0], 0x6410, 0x04, &max_rpm, 4, &bytes, &lastEpos2ErrorCode) ) { printEpos2Error(); } if ( ros::param::get(full_namespace + "/motor_max_rpm", max_rpm) ) { if ( !VCS_SetObject(devhandle, epos_node_nr[0], 0x6410, 0x04, &max_rpm, 4, &bytes, &lastEpos2ErrorCode) ) { printEpos2Error(); } } if (successfully_set) { ROS_INFO("[%s] current motor parameter: %s, %.3fA nominal current, %.3fA peak current, max %i rpm, %sthermal time constant winding = %.1fs", name.c_str(), motor_str.c_str(), nominal_current/1000.0, max_current/1000.0, max_rpm, pole_pair_str.str().c_str(), thermal_time_constant/1000.0); return true; } else { return false; } } bool Epos2::setDimensionAndNotation() { object_data data_temp[]={ //{VN_STANDARD, int8, 0x6089, 0}, {0xac, uint8, 0x608a, 0}, //Position [steps] {VN_MILLI, int8, 0x608b, 0}, //{VD_RPM, uint8, 0x608c, 0}, //Velocity [1e-3 rev/min] //{VN_STANDARD, int8, 0x608d, 0}, {VD_RPM, uint8, 0x608e, 0} //Acceleration [rev/(min * s)] }; std::vector<object_data> data; for (int i=0; i < sizeof(data_temp) / sizeof(object_data); i ++) { data.push_back(data_temp[i]); } return setObject(&data); } bool Epos2::checkSpin() { object_data data_temp = {0, uint16, 0x2008, 0}; std::vector<object_data> data; data.push_back(data_temp); if ( !getObject(&data) ) { return false; } bool temp; //true = 1; false = 0 if ( ros::param::get(full_namespace + "/motor_reverse", temp) ) { if ( temp xor (data[0].value >> 8) & 1 ) { data[0].value = (data[0].value & 0xfeff) + temp * 0x100; setObject(&data); } } ROS_INFO("[%s] Miscellaneous Configuration Word: %#x", name.c_str(), data[0].value ); return true; } bool Epos2::checkGearParameter() { object_data data_temp[]={ {1, uint32, 0x2230, 0x01}, //Gear Ratio Numerator {1, uint16, 0x2230, 0x02}, //Gear Ratio Denominator {1000, uint32, 0x2230, 0x03} //Gear Maximal Speed }; std::vector<object_data> data; for (int i=0; i < sizeof(data_temp) / sizeof(object_data); i ++) { data.push_back(data_temp[i]); } if ( !getObject(&data) ) { return false; } } bool Epos2::getObject(std::vector<object_data> *data) { bool no_error = true; uint32_t bytes; for (std::vector<object_data>::iterator it=data->begin(); it < data->end(); it++) { if ( it->type == int8 ) { int8_t value; if ( !VCS_GetObject(devhandle, epos_node_nr[0], it->index, it->sub_index, &value, 1, &bytes, &lastEpos2ErrorCode) ) { printEpos2Error(); no_error = false; } else { it->value = value; } } else if ( it->type == uint8 ) { uint8_t value; if ( !VCS_GetObject(devhandle, epos_node_nr[0], it->index, it->sub_index, &value, 1, &bytes, &lastEpos2ErrorCode) ) { printEpos2Error(); no_error = false; } else { it->value = value; } } else if ( it->type == uint16 ) { uint16_t value; if ( !VCS_GetObject(devhandle, epos_node_nr[0], it->index, it->sub_index, &value, 2, &bytes, &lastEpos2ErrorCode) ) { printEpos2Error(); no_error = false; } else { it->value = value; } } else if ( it->type == uint32 ) { uint32_t value; if ( !VCS_GetObject(devhandle, epos_node_nr[0], it->index, it->sub_index, &value, 4, &bytes, &lastEpos2ErrorCode) ) { printEpos2Error(); no_error = false; } else { it->value = value; } } } return no_error; } bool Epos2::setObject(std::vector<object_data> *data) { bool no_error = true; uint32_t bytes; for (std::vector<object_data>::iterator it=data->begin(); it < data->end(); it++) { if ( it->type == int8 ) { int8_t value = it->value; if ( !VCS_SetObject(devhandle, epos_node_nr[0], it->index, it->sub_index, &value, 1, &bytes, &lastEpos2ErrorCode) ) { printEpos2Error(); no_error = false; } } else if ( it->type == uint8 ) { uint8_t value = it->value; if ( !VCS_SetObject(devhandle, epos_node_nr[0], it->index, it->sub_index, &value, 1, &bytes, &lastEpos2ErrorCode) ) { printEpos2Error(); no_error = false; } } else if ( it->type == uint16 ) { uint16_t value = it->value; if ( !VCS_SetObject(devhandle, epos_node_nr[0], it->index, it->sub_index, &value, 2, &bytes, &lastEpos2ErrorCode) ) { printEpos2Error(); no_error = false; } } else if ( it->type == uint32 ) { uint32_t value = it->value; if ( !VCS_SetObject(devhandle, epos_node_nr[0], it->index, it->sub_index, &value, 4, &bytes, &lastEpos2ErrorCode) ) { printEpos2Error(); no_error = false; } } } return no_error; } }
34.543033
295
0.576556
ein57ein
e6f237ff9f91f4470cdb7e401b1e5960c0564716
2,454
hh
C++
nipXray/include/NXChamberParameterisation.hh
maxwell-herrmann/geant4-simple-examples
0052d40fdc05baef05b4a6873c03d0d54885ad40
[ "BSD-2-Clause" ]
9
2015-04-27T11:54:19.000Z
2022-01-30T23:42:00.000Z
nipXray/include/NXChamberParameterisation.hh
maxwell-herrmann/geant4-simple-examples
0052d40fdc05baef05b4a6873c03d0d54885ad40
[ "BSD-2-Clause" ]
null
null
null
nipXray/include/NXChamberParameterisation.hh
maxwell-herrmann/geant4-simple-examples
0052d40fdc05baef05b4a6873c03d0d54885ad40
[ "BSD-2-Clause" ]
3
2019-12-18T21:11:57.000Z
2020-05-28T17:30:03.000Z
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... #ifndef NXChamberParameterisation_H #define NXChamberParameterisation_H 1 #include "globals.hh" #include "G4VPVParameterisation.hh" #include "G4NistManager.hh" class G4VPhysicalVolume; class G4Box; // Dummy declarations to get rid of warnings ... class G4Trd; class G4Trap; class G4Cons; class G4Orb; class G4Sphere; class G4Torus; class G4Para; class G4Hype; class G4Tubs; class G4Polycone; class G4Polyhedra; //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... class NXChamberParameterisation : public G4VPVParameterisation { public: NXChamberParameterisation( G4double startZ ); virtual ~NXChamberParameterisation(); void ComputeTransformation (const G4int copyNo, G4VPhysicalVolume* physVol) const; void ComputeDimensions (G4Box & trackerLayer, const G4int copyNo, const G4VPhysicalVolume* physVol) const; G4Material* ComputeMaterial(const G4int repNo,G4VPhysicalVolume *currentVol, const G4VTouchable *parentTouch=0); private: // Dummy declarations to get rid of warnings ... void ComputeDimensions (G4Trd&,const G4int,const G4VPhysicalVolume*) const {} void ComputeDimensions (G4Trap&,const G4int,const G4VPhysicalVolume*) const {} void ComputeDimensions (G4Cons&,const G4int,const G4VPhysicalVolume*) const {} void ComputeDimensions (G4Sphere&,const G4int,const G4VPhysicalVolume*) const {} void ComputeDimensions (G4Orb&,const G4int,const G4VPhysicalVolume*) const {} void ComputeDimensions (G4Torus&,const G4int,const G4VPhysicalVolume*) const {} void ComputeDimensions (G4Para&,const G4int,const G4VPhysicalVolume*) const {} void ComputeDimensions (G4Hype&,const G4int,const G4VPhysicalVolume*) const {} void ComputeDimensions (G4Tubs&,const G4int,const G4VPhysicalVolume*) const {} void ComputeDimensions (G4Polycone&,const G4int,const G4VPhysicalVolume*) const {} void ComputeDimensions (G4Polyhedra&,const G4int,const G4VPhysicalVolume*) const {} private: G4double fStartZ; G4Material* Fe; G4Material* Vacuum; }; //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... #endif
34.083333
91
0.696007
maxwell-herrmann
e6f5d5e5ce376f277c99c3f9d56ee7f31d62a478
33,983
hpp
C++
src/lang/dzm_prc.hpp
arogan-group/DZMLang
4ef827de34a07fb4f2dde817c297841c25382231
[ "Apache-2.0" ]
1
2016-09-23T14:29:44.000Z
2016-09-23T14:29:44.000Z
src/lang/dzm_prc.hpp
arogan-group/DZMLang
4ef827de34a07fb4f2dde817c297841c25382231
[ "Apache-2.0" ]
null
null
null
src/lang/dzm_prc.hpp
arogan-group/DZMLang
4ef827de34a07fb4f2dde817c297841c25382231
[ "Apache-2.0" ]
null
null
null
/* Copyright 2016 Dominik Madarasz Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #if !defined(DZM_PRC_H) #include <ctime> #include <cmath> #ifndef WIN32 #include <pthread.h> #endif #define def_proc(Name) static inline OBJECT * Name##_proc(OBJECT *Args) #define add_procedure(Name, Call) \ define_variable(make_symbol((u8 *)Name), \ make_procedure(Call), \ Env); #define check_args(o) \ if(is_nil(pair_get_a(Args))) \ LOG(LOG_WARN, o " " "is missing required arguments") #include "prc/prc_net.hpp" #include "prc/prc_thd.hpp" def_proc(inc) { OBJECT *Arg0 = pair_get_a(Args); OBJECT *Obj = Arg0; if(is_realnum(Arg0)) { Obj = make_realnum(Arg0->uData.MDL_REALNUM.Value + 1.0); } else if(is_fixnum(Arg0)) { Obj = make_fixnum(Arg0->uData.MDL_FIXNUM.Value + 1); } else if(is_character(Arg0)) { Obj = make_character(Arg0->uData.MDL_CHARACTER.Value + 1); } else if(is_string(Arg0)) { Obj = make_string(Arg0->uData.MDL_STRING.Value + 1); } return(Obj); } def_proc(dec) { OBJECT *Arg0 = pair_get_a(Args); OBJECT *Obj = Arg0; if(is_realnum(Arg0)) { Obj = make_realnum(Arg0->uData.MDL_REALNUM.Value - 1.0); } else if(is_fixnum(Arg0)) { Obj = make_fixnum(Arg0->uData.MDL_FIXNUM.Value - 1); } else if(is_character(Arg0)) { Obj = make_character(Arg0->uData.MDL_CHARACTER.Value - 1); } else if(is_string(Arg0)) { Obj = make_string(Arg0->uData.MDL_STRING.Value - 1); } return(Obj); } // NOTE(zaklaus): Arithmetic operators static inline OBJECT * add_proc(OBJECT *Args) { real64 Result = 0; b32 Real = 0; while(!is_nil(Args)) { if(is_fixnum(pair_get_a(Args))) Result += (pair_get_a(Args))->uData.MDL_FIXNUM.Value; else { Real = 1; Result += (pair_get_a(Args))->uData.MDL_REALNUM.Value; } Args = pair_get_b(Args); } if(!Real) return(make_fixnum((s64)Result)); else return(make_realnum(Result)); } static inline OBJECT * sub_proc(OBJECT *Args) { r64 Result = 0; b32 Real = 0; if(!is_nil(Args)) { if(is_fixnum(pair_get_a(Args))) Result = (r64)(pair_get_a(Args))->uData.MDL_FIXNUM.Value; else { Real = 1; Result = (pair_get_a(Args))->uData.MDL_REALNUM.Value; } Args = pair_get_b(Args); } b32 IsAlone = 1; while(!is_nil(Args)) { Result -= (pair_get_a(Args))->uData.MDL_FIXNUM.Value; Args = pair_get_b(Args); IsAlone = 0; } if(IsAlone) { Result = -Result; } if(!Real) return(make_fixnum((s64)Result)); else return(make_realnum(Result)); } static inline OBJECT * div_proc(OBJECT *Args) { r64 Result = 0; b32 Real = 1; if(!is_nil(Args)) { if(is_fixnum(pair_get_a(Args))) Result = (r64)(pair_get_a(Args))->uData.MDL_FIXNUM.Value; else { Result = (r64)(pair_get_a(Args))->uData.MDL_REALNUM.Value; } Args = pair_get_b(Args); } while(!is_nil(Args)) { if((pair_get_a(Args))->uData.MDL_FIXNUM.Value == 0) { LOG(ERR_WARN, "Division by zero"); return(Nil); InvalidCodePath; } if(is_fixnum(pair_get_a(Args))) Result = (r64)Result / (r64)(pair_get_a(Args))->uData.MDL_FIXNUM.Value; else { Result /= (r64)(pair_get_a(Args))->uData.MDL_REALNUM.Value; } Args = pair_get_b(Args); } if(!Real) return(make_fixnum((s64)Result)); else return(make_realnum(Result)); } static inline OBJECT * div_full_proc(OBJECT *Args) { r64 Result = 0; b32 Real = 0; if (!is_nil(Args)) { if (is_fixnum(pair_get_a(Args))) Result = (r64)(pair_get_a(Args))->uData.MDL_FIXNUM.Value; else { Result = (r64)(pair_get_a(Args))->uData.MDL_REALNUM.Value; } Args = pair_get_b(Args); } while (!is_nil(Args)) { if ((pair_get_a(Args))->uData.MDL_FIXNUM.Value == 0) { LOG(ERR_WARN, "Division by zero"); return(Nil); InvalidCodePath; } if (is_fixnum(pair_get_a(Args))) Result = (r64)Result / (r64)(pair_get_a(Args))->uData.MDL_FIXNUM.Value; else { Result /= (r64)(pair_get_a(Args))->uData.MDL_REALNUM.Value; } Args = pair_get_b(Args); } if (!Real) return(make_fixnum((s64)Result)); else return(make_realnum(Result)); } static inline OBJECT * mod_proc(OBJECT *Args) { s64 Result = 0; if(is_realnum(pair_get_a(Args))) { r64 Value = pair_get_a(Args)->uData.MDL_REALNUM.Value; if(trunc(Value) != Value) Value = -1; pair_set_a(Args, make_fixnum(Value)); } if(!is_nil(Args)) { Result = (pair_get_a(Args))->uData.MDL_FIXNUM.Value; Args = pair_get_b(Args); } while(!is_nil(Args)) { if((pair_get_a(Args))->uData.MDL_FIXNUM.Value == 0) { LOG(ERR_WARN, "Division by zero"); return(Nil); InvalidCodePath; } Result %= (pair_get_a(Args))->uData.MDL_FIXNUM.Value; Args = pair_get_b(Args); } return(make_fixnum(Result)); } static inline OBJECT * mul_proc(OBJECT *Args) { r64 Result = 1; b32 Real = 0; while(!is_nil(Args)) { if(is_fixnum(pair_get_a(Args))) Result *= (pair_get_a(Args))->uData.MDL_FIXNUM.Value; else { Real = 1; Result *= (pair_get_a(Args))->uData.MDL_REALNUM.Value; } Args = pair_get_b(Args); } if(!Real) return(make_fixnum((s64)Result)); else return(make_realnum(Result)); } // NOTE(zaklaus): Existence checks def_proc(is_nil) { return(is_nil(pair_get_a(Args)) ? True : False); } def_proc(is_boolean) { return(is_boolean(pair_get_a(Args)) ? True : False); } def_proc(is_symbol) { return(is_symbol(pair_get_a(Args)) ? True : False); } def_proc(is_integer) { return(is_fixnum(pair_get_a(Args)) ? True : False); } def_proc(is_real) { return(is_realnum(pair_get_a(Args)) ? True : False); } def_proc(is_char) { return(is_character(pair_get_a(Args)) ? True : False); } def_proc(is_string) { return(is_string(pair_get_a(Args)) ? True : False); } def_proc(is_pair) { return(is_pair(pair_get_a(Args)) ? True : False); } def_proc(is_compound) { return(is_compound(pair_get_a(Args)) ? True : False); } def_proc(is_procedure) { return((is_procedure(pair_get_a(Args))) ? True : False); } // NOTE(zaklaus): Type conversions def_proc(char_to_integer) { return(make_fixnum((pair_get_a(Args))->uData.MDL_CHARACTER.Value)); } def_proc(integer_to_char) { return(make_character((u8)(pair_get_a(Args))->uData.MDL_FIXNUM.Value)); } def_proc(string_to_char) { return(make_character(*((pair_get_a(Args))->uData.MDL_STRING.Value))); } def_proc(char_to_symbol) { TEMP_MEMORY Mem = begin_temp(&StringArena); char *Buffer = (char *)push_size(&StringArena, 2, default_arena_params()); sprintf(Buffer, "%c", pair_get_a(Args)->uData.MDL_CHARACTER.Value); end_temp(Mem); return(make_symbol((u8 *)Buffer)); } def_proc(char_to_string) { TEMP_MEMORY Mem = begin_temp(&StringArena); char *Buffer = (char *)push_size(&StringArena, 2, default_arena_params()); sprintf(Buffer, "%c", pair_get_a(Args)->uData.MDL_CHARACTER.Value); end_temp(Mem); return(make_string((u8 *)Buffer)); } def_proc(number_to_string) { TEMP_MEMORY Mem = begin_temp(&StringArena); char *Buffer = (char *)push_size(&StringArena, 66, default_arena_params()); if(is_fixnum(pair_get_a(Args))) sprintf(Buffer, "%" PRId64, (pair_get_a(Args))->uData.MDL_FIXNUM.Value); else sprintf(Buffer, "%lf", (double)((pair_get_a(Args))->uData.MDL_REALNUM.Value)); end_temp(Mem); return(make_string((u8 *)Buffer)); } def_proc(string_to_number) { char * String = (char *)((pair_get_a(Args))->uData.MDL_STRING.Value); char * EndPtr = 0; s64 Number = strtoull(String, &EndPtr, 10); return(make_fixnum(Number)); } def_proc(symbol_to_string) { return(make_string((pair_get_a(Args))->uData.MDL_SYMBOL.Value)); } def_proc(string_to_symbol) { return(make_symbol((pair_get_a(Args))->uData.MDL_STRING.Value)); } def_proc(is_number_equal) { OBJECT *R = False; if(pair_get_a(Args)->Type == MDL_FIXNUM) { s64 Value = (pair_get_a(Args))->uData.MDL_FIXNUM.Value; while(!is_nil(Args = pair_get_b(Args))) { if(is_fixnum(pair_get_a(Args))) { R = (Value == pair_get_a(Args)->uData.MDL_FIXNUM.Value) ? True : False; } if(is_realnum(pair_get_a(Args))) { R = ((r64)Value == pair_get_a(Args)->uData.MDL_REALNUM.Value) ? True : False; } } } else if(pair_get_a(Args)->Type == MDL_REALNUM) { r64 Value = (pair_get_a(Args))->uData.MDL_REALNUM.Value; while(!is_nil(Args = pair_get_b(Args))) { if(is_fixnum(pair_get_a(Args))) { R = (Value == (r64)pair_get_a(Args)->uData.MDL_FIXNUM.Value) ? True : False; } if(is_realnum(pair_get_a(Args))) { R = (Value == pair_get_a(Args)->uData.MDL_REALNUM.Value) ? True : False; } if(R == False) return(R); } } return(R); } def_proc(is_greater_than_or_equal) { OBJECT* R = 0; if(pair_get_a(Args)->Type == MDL_FIXNUM) { s64 Value = (pair_get_a(Args))->uData.MDL_FIXNUM.Value; while(!is_nil(Args = pair_get_b(Args))) { if(is_fixnum(pair_get_a(Args))) { R = (Value >= pair_get_a(Args)->uData.MDL_FIXNUM.Value) ? True : False; } if(is_realnum(pair_get_a(Args))) { R = ((r64)Value >= pair_get_a(Args)->uData.MDL_REALNUM.Value) ? True : False; } if(R == False) return(R); } } else if(pair_get_a(Args)->Type == MDL_REALNUM) { r64 Value = (pair_get_a(Args))->uData.MDL_REALNUM.Value; while(!is_nil(Args = pair_get_b(Args))) { if(is_fixnum(pair_get_a(Args))) { R = (Value >= (r64)pair_get_a(Args)->uData.MDL_FIXNUM.Value) ? True : False; } if(is_realnum(pair_get_a(Args))) { R = (Value >= pair_get_a(Args)->uData.MDL_REALNUM.Value) ? True : False; } if(R == False) return(R); } } return(R); } def_proc(is_greater_than) { OBJECT* R = 0; if(pair_get_a(Args)->Type == MDL_FIXNUM) { s64 Value = (pair_get_a(Args))->uData.MDL_FIXNUM.Value; while(!is_nil(Args = pair_get_b(Args))) { if(is_fixnum(pair_get_a(Args))) { R = (Value > pair_get_a(Args)->uData.MDL_FIXNUM.Value) ? True : False; } if(is_realnum(pair_get_a(Args))) { R = ((r64)Value > pair_get_a(Args)->uData.MDL_REALNUM.Value) ? True : False; } if(R == False) return(R); } } else if(pair_get_a(Args)->Type == MDL_REALNUM) { r64 Value = (pair_get_a(Args))->uData.MDL_REALNUM.Value; while(!is_nil(Args = pair_get_b(Args))) { if(is_fixnum(pair_get_a(Args))) { R = (Value > (r64)pair_get_a(Args)->uData.MDL_FIXNUM.Value) ? True : False; } if(is_realnum(pair_get_a(Args))) { R = (Value > pair_get_a(Args)->uData.MDL_REALNUM.Value) ? True : False; } if(R == False) return(R); } } return(R); } def_proc(is_less_than) { OBJECT* R = 0; if(pair_get_a(Args)->Type == MDL_FIXNUM) { s64 Value = (pair_get_a(Args))->uData.MDL_FIXNUM.Value; while(!is_nil(Args = pair_get_b(Args))) { if(is_fixnum(pair_get_a(Args))) { R = (Value < pair_get_a(Args)->uData.MDL_FIXNUM.Value) ? True : False; } if(is_realnum(pair_get_a(Args))) { R = ((r64)Value < pair_get_a(Args)->uData.MDL_REALNUM.Value) ? True : False; } if(R == False) return(R); } } else if(pair_get_a(Args)->Type == MDL_REALNUM) { r64 Value = (pair_get_a(Args))->uData.MDL_REALNUM.Value; while(!is_nil(Args = pair_get_b(Args))) { if(is_fixnum(pair_get_a(Args))) { R = (Value < (r64)pair_get_a(Args)->uData.MDL_FIXNUM.Value) ? True : False; } if(is_realnum(pair_get_a(Args))) { R = (Value < pair_get_a(Args)->uData.MDL_REALNUM.Value) ? True : False; } if(R == False) return(R); } } return(R); } def_proc(is_less_than_or_equal) { OBJECT* R = 0; if(pair_get_a(Args)->Type == MDL_FIXNUM) { s64 Value = (pair_get_a(Args))->uData.MDL_FIXNUM.Value; while(!is_nil(Args = pair_get_b(Args))) { if(is_fixnum(pair_get_a(Args))) { R = (Value <= pair_get_a(Args)->uData.MDL_FIXNUM.Value) ? True : False; } if(is_realnum(pair_get_a(Args))) { R = ((r64)Value <= pair_get_a(Args)->uData.MDL_REALNUM.Value) ? True : False; } if(R == False) return(R); } } else if(pair_get_a(Args)->Type == MDL_REALNUM) { r64 Value = (pair_get_a(Args))->uData.MDL_REALNUM.Value; while(!is_nil(Args = pair_get_b(Args))) { if(is_fixnum(pair_get_a(Args))) { R = (Value <= (r64)pair_get_a(Args)->uData.MDL_FIXNUM.Value) ? True : False; } if(is_realnum(pair_get_a(Args))) { R = (Value <= pair_get_a(Args)->uData.MDL_REALNUM.Value) ? True : False; } if(R == False) return(R); } } return(R); } def_proc(concat) { TEMP_MEMORY StringTemp = begin_temp(&StringArena); char *Result = 0; OBJECT *Text = pair_get_a(Args); concat_tailcall: if(is_string(Text)) { Result = (char *)push_size(&StringArena, strlen((char *)Text->uData.MDL_STRING.Value)+1, default_arena_params()); strcpy(Result, (char *)Text->uData.MDL_STRING.Value); } else if(is_pair(Text)) { Text = concat_proc(Text); goto concat_tailcall; } else { Result = (char *)push_size(&StringArena,2,default_arena_params()); Result[0] = (char)Text->uData.MDL_CHARACTER.Value; Result[1] = 0; } while(!is_nil(Args = pair_get_b(Args))) { Text = pair_get_a(Args); concat_tailcall2: if(is_string(Text)) { Result = (char *)push_copy(&StringArena, strlen(Result) + strlen((char *)Text->uData.MDL_STRING.Value)+1, Result, default_arena_params()); strcat(Result, (char *)Text->uData.MDL_STRING.Value); } else if(is_nil(Text)) { break; } else if(is_pair(Text)) { Text = concat_proc(Text); goto concat_tailcall2; } else { mi ResultEnd = strlen(Result); Result = (char *)push_copy(&StringArena, strlen(Result) + 2, Result, default_arena_params()); Result[ResultEnd] = (char)Text->uData.MDL_CHARACTER.Value; Result[ResultEnd+1] = 0; } } end_temp(StringTemp); return(make_string((u8 *)Result)); } def_proc(cons) { pair_set_b(Args, pair_get_a(pair_get_b(Args))); return(Args); } def_proc(car) { if(is_string(pair_get_a(Args))) return(make_character(pair_get_a(Args)->uData.MDL_STRING.Value[0])); else return(pair_get_a(pair_get_a(Args))); } def_proc(cdr) { if(is_string(pair_get_a(Args)) && (strlen((char *)pair_get_a(Args)->uData.MDL_STRING.Value) > 1)) return(make_string(pair_get_a(Args)->uData.MDL_STRING.Value+1)); else if(is_pair(pair_get_a(Args))) return(pair_get_b(pair_get_a(Args))); else return(Nil); } def_proc(set_car) { pair_set_a(pair_get_a(Args), pair_get_a(pair_get_b(Args))); return OKSymbol; } def_proc(set_cdr) { pair_set_b(pair_get_a(Args), pair_get_a(pair_get_b(Args))); return OKSymbol; } def_proc(list) { return(Args); } def_proc(is_eq) { OBJECT *Obj1 = pair_get_a(Args); OBJECT *Obj2 = pair_get_a(pair_get_b(Args)); if(Obj1->Type != Obj2->Type) { return(False); } switch(Obj1->Type) { case MDL_REALNUM: case MDL_FIXNUM: { return((Obj1->uData.MDL_FIXNUM.Value == Obj2->uData.MDL_FIXNUM.Value) ? True : False); }break; case MDL_CHARACTER: { return((Obj1->uData.MDL_CHARACTER.Value == Obj2->uData.MDL_CHARACTER.Value) ? True : False); }break; case MDL_STRING: { return((!strcmp((char *)Obj1->uData.MDL_STRING.Value, (char *)Obj2->uData.MDL_STRING.Value)) ? True : False); }break; default: { return((Obj1 == Obj2) ? True : False); }break; } } def_proc(apply) { LOG(ERR_WARN, "illegal state: The body of the apply should not execute"); InvalidCodePath; Unreachable(Args); } def_proc(eval) { LOG(ERR_WARN, "illegal state: The body of the eval should not execute"); InvalidCodePath; Unreachable(Args); } def_proc(interaction_env) { return(GlobalEnv); Unreachable(Args); } def_proc(nil_env) { return(setup_env()); Unreachable(Args); } def_proc(env) { return(make_env()); Unreachable(Args); } def_proc(load) { b32 OldOk = PrintOk; PrintOk = 0; u8 *Filename; FILE *In; OBJECT *Exp; OBJECT *Result = 0; OBJECT *Env = GlobalEnv; Filename = (pair_get_a(Args))->uData.MDL_STRING.Value; In = fopen((char *)Filename, "r"); if(In == 0) { LOG(ERR_WARN, "Could not load file \"%s\"\n", Filename); PrintOk = OldOk; return(Nil); InvalidCodePath; } if(!is_nil(pair_get_b(Args))) { Env = pair_get_b(pair_get_a(Args)); } while((Exp = read(In)) != 0) { Result = eval(Exp, Env); } fclose(In); PrintOk = OldOk; return(Result); } def_proc(read) { FILE *In; OBJECT *Result; In = is_nil(Args) ? read_input(stdin) : (pair_get_a(Args))->uData.MDL_INPUT.Stream; Result = read(In); return((Result == 0) ? EOF_Obj : Result); } def_proc(write) { OBJECT *Exp; FILE *Out; Exp = pair_get_a(Args); Args = pair_get_b(Args); Out = is_nil(Args) ? stdout : (pair_get_a(Args))->uData.MDL_OUTPUT.Stream; b32 StripQuotes = is_nil(Args) ? 1 : is_nil(pair_get_b(Args)) ? 1 : (pair_get_a(pair_get_b(Args)))->uData.MDL_BOOLEAN.Value; write(Out, Exp, StripQuotes); fflush(Out); return(OKSymbol); } def_proc(peek_char) { FILE *In; s32 Result; In = is_nil(Args) ? read_input(stdin) : (pair_get_a(Args))->uData.MDL_INPUT.Stream; Result = peek(In); return((Result == EOF) ? EOF_Obj : make_character(Result)); } def_proc(open_input) { u8 *Filename; FILE *In; Filename = (pair_get_a(Args))->uData.MDL_STRING.Value; In = fopen((char *)Filename, "r"); if(In == 0) { LOG(ERR_WARN, "Could not load file \"%s\"\n", Filename); InvalidCodePath; } return(make_input(In)); } def_proc(close_input) { s32 Result; Result = fclose((pair_get_a(Args))->uData.MDL_INPUT.Stream); if(Result == EOF) { LOG(ERR_WARN, "Could not close input"); InvalidCodePath; } return(OKSymbol); } def_proc(is_input) { return(is_input(pair_get_a(Args)) ? True : False); } def_proc(open_output) { u8 *Filename; FILE *In; Filename = (pair_get_a(Args))->uData.MDL_STRING.Value; In = fopen((char *)Filename, "w"); if(In == 0) { LOG(ERR_WARN, "Could not load file \"%s\"\n", Filename); InvalidCodePath; } return(make_output(In)); } def_proc(close_output) { s32 Result; Result = fclose((pair_get_a(Args))->uData.MDL_INPUT.Stream); if(Result == EOF) { LOG(ERR_WARN, "Could not close output"); InvalidCodePath; } return(OKSymbol); } def_proc(is_output) { return(is_output(pair_get_a(Args)) ? True : False); } def_proc(is_eof_obj) { return(is_eof_obj(pair_get_a(Args)) ? True : False); } def_proc(write_char) { OBJECT *Char; FILE *Out; Char = pair_get_a(Args); Args = pair_get_b(Args); Out = is_nil(Args) ? stdout : (pair_get_a(Args))->uData.MDL_OUTPUT.Stream; putc(Char->uData.MDL_CHARACTER.Value, Out); fflush(Out); return(OKSymbol); } def_proc(write_string) { OBJECT *String; FILE *Out; String = pair_get_a(Args); if(!is_string(String) && (is_realnum(String) || is_fixnum(String))) { TEMP_MEMORY Temp = begin_temp(&StringArena); char *Buffer = (char *)push_size(&StringArena, 66, default_arena_params()); if(is_realnum(String)) { sprintf(Buffer, "%.17Lg", String->uData.MDL_REALNUM.Value); } else sprintf(Buffer, "%" PRId64, String->uData.MDL_FIXNUM.Value); String = make_string((u8 *)Buffer); end_temp(Temp); } else if(!is_string(String)) { LOG(ERR_WARN, "write-string expects 1 parameter to be: <MDL_STRING|MDL_REALNUM|MDL_FIXNUM>."); return(Nil); } Args = pair_get_b(Args); Out = is_nil(Args) ? stdout : (pair_get_a(Args))->uData.MDL_OUTPUT.Stream; fprintf(Out, "%s", (char *)String->uData.MDL_STRING.Value); fflush(Out); return(OKSymbol); } def_proc(read_string) { FILE *In; OBJECT *Result; In = (is_nil(pair_get_a(Args))) ? stdin : (pair_get_a(Args))->uData.MDL_INPUT.Stream; char *String = (char *)StringArena.Base; fgets(String, (int)StringArena.Size, In); Result = make_string((u8 *)String); StringArena.Used = 0; return((Result == 0) ? EOF_Obj : Result); } static inline u8 * trim_string(u8 *String); def_proc(trim) { if(!is_string(pair_get_a(Args))) return(pair_get_a(Args)); return(make_string(trim_string(pair_get_a(Args)->uData.MDL_STRING.Value))); } def_proc(read_char) { s32 Result; FILE *In; if(is_string(pair_get_a(Args))) { Result = *(pair_get_a(Args)->uData.MDL_STRING.Value); return(make_character(Result)); } In = is_nil(Args) ? stdin : (pair_get_a(Args))->uData.MDL_INPUT.Stream; Result = getc(In); #if _WIN32_ getc(In); // Consume '\r' #endif getc(In); // Consume '\n' return((Result == EOF) ? EOF_Obj : make_character(Result)); } def_proc(system) { #if _ELEVATED == 1 if(!is_string(pair_get_a(Args))) { return(Nil); } FILE *Out = stdout; if(!is_nil(pair_get_a(pair_get_b(Args)))) { Out = (pair_get_a(pair_get_b(Args)))->uData.MDL_OUTPUT.Stream; } #ifdef WIN32 FILE *Sys = _popen((char *)(pair_get_a(Args)->uData.MDL_STRING.Value), "r"); #else FILE *Sys = popen((char *)(pair_get_a(Args)->uData.MDL_STRING.Value), "r"); #endif if(!Sys) { goto system_end; } s32 C; while((C = getc(Sys)) != EOF) { putc((char)C, Out); } #ifdef WIN32 _pclose(Sys); #else pclose(Sys); #endif system_end: if(is_nil(pair_get_a(pair_get_b(Args)))) return(OKSymbol); else return(pair_get_a(pair_get_b(Args))); #else LOG(ERR_WARN, "Procedure requires elevation!"); return(OKSymbol); Unreachable(Args); #endif } def_proc(arena_mem) { return(make_fixnum(0)); /*make_pair(make_fixnum( get_arena_size_remaining(GlobalArena, default_arena_params())), make_fixnum(GlobalArena->Size)));*/ Unreachable(Args); } def_proc(log_mem) { PrintMemUsage = !PrintMemUsage; return(Args); } def_proc(error_reporting) { if(is_nil(pair_get_a(Args))) { LOG(ERR_WARN, "error-reporting is missing: <error-level>"); return(OKSymbol); } u8 Result = (u8)(pair_get_a(Args)->uData.MDL_FIXNUM.Value); error_reporting(Result); return(OKSymbol); } def_proc(random) { srand((unsigned int)time(0)); s64 RandomValue = (s64)rand(); if(!is_nil(pair_get_a(Args))) { RandomValue %= (pair_get_a(Args))->uData.MDL_FIXNUM.Value; } return(make_fixnum(RandomValue)); } def_proc(error) { if(is_nil(pair_get_a(Args))) { LOG(ERR_WARN, "error is missing: <message>"); return(OKSymbol); } LOG(ERR_WARN, "Exception -> %s", (char *)pair_get_a(Args)->uData.MDL_STRING.Value); return(OKSymbol); } def_proc(log) { return(make_realnum(log(pair_get_a(Args)->uData.MDL_REALNUM.Value))); } def_proc(log2) { r64 A = pair_get_a(Args)->uData.MDL_REALNUM.Value; return(make_realnum(log2(A))); } def_proc(sin) { if(pair_get_a(Args)->Type == MDL_REALNUM) { return(make_realnum(sin((double)(pair_get_a(Args)->uData.MDL_REALNUM.Value)))); } return(make_realnum(sin((double)(pair_get_a(Args)->uData.MDL_FIXNUM.Value)))); } def_proc(cos) { if(pair_get_a(Args)->Type == MDL_REALNUM) { return(make_realnum(cos((double)(pair_get_a(Args)->uData.MDL_REALNUM.Value)))); } return(make_realnum(cos((double)(pair_get_a(Args)->uData.MDL_FIXNUM.Value)))); } def_proc(tan) { if(pair_get_a(Args)->Type == MDL_REALNUM) { return(make_realnum(tan((double)(pair_get_a(Args)->uData.MDL_REALNUM.Value)))); } return(make_realnum(tan((double)(pair_get_a(Args)->uData.MDL_FIXNUM.Value)))); } def_proc(asin) { if(pair_get_a(Args)->Type == MDL_REALNUM) { return(make_realnum(asin((double)(pair_get_a(Args)->uData.MDL_REALNUM.Value)))); } return(make_realnum(asin((double)(pair_get_a(Args)->uData.MDL_FIXNUM.Value)))); } def_proc(acos) { if(pair_get_a(Args)->Type == MDL_REALNUM) { return(make_realnum(acos((double)(pair_get_a(Args)->uData.MDL_REALNUM.Value)))); } return(make_realnum(acos((double)(pair_get_a(Args)->uData.MDL_FIXNUM.Value)))); } def_proc(atan) { if(pair_get_a(Args)->Type == MDL_REALNUM) { return(make_realnum(atan((double)(pair_get_a(Args)->uData.MDL_REALNUM.Value)))); } return(make_realnum(atan((double)(pair_get_a(Args)->uData.MDL_FIXNUM.Value)))); } def_proc(sqrt) { if(pair_get_a(Args)->Type == MDL_REALNUM) { return(make_realnum(sqrt((double)(pair_get_a(Args)->uData.MDL_REALNUM.Value)))); } return(make_realnum(sqrt((double)(pair_get_a(Args)->uData.MDL_FIXNUM.Value)))); } def_proc(exit) { s64 ErrorCode = 0; if(!is_nil(pair_get_a(Args))) { ErrorCode = pair_get_a(Args)->uData.MDL_FIXNUM.Value; } exit((int)ErrorCode); } def_proc(log_verbose) { if(!is_nil(pair_get_a(Args)) && !is_boolean(pair_get_a(Args))) { LOG(ERR_WARN, "log-verbose is missing: <MDL_BOOLEAN>"); return(OKSymbol); } b32 Result = 0; if(!is_nil(pair_get_a(Args))) { Result = (is_true(pair_get_a(Args))) ? 1 : 0; } else { Result = !IsVerbose; } set_log_verbose(Result); return(OKSymbol); } def_proc(sleep) { if(!is_nil(pair_get_a(Args))) { sleepcp((int)pair_get_a(Args)->uData.MDL_FIXNUM.Value); } return(OKSymbol); Unreachable(Args); } static inline void init_builtins(OBJECT *Env) { add_procedure("inc", inc_proc); add_procedure("dec", dec_proc); add_procedure("+" , add_proc); add_procedure("-" , sub_proc); add_procedure("*" , mul_proc); add_procedure("/" , div_proc); add_procedure("//", div_full_proc); add_procedure("%" , mod_proc); add_procedure("nil?" , is_nil_proc); add_procedure("null?" , is_nil_proc); add_procedure("boolean?" , is_boolean_proc); add_procedure("symbol?" , is_symbol_proc); add_procedure("integer?" , is_integer_proc); add_procedure("char?" , is_char_proc); add_procedure("string?" , is_string_proc); add_procedure("pair?" , is_pair_proc); add_procedure("procedure?", is_procedure_proc); add_procedure("char->integer" , char_to_integer_proc); add_procedure("char->string" , char_to_string_proc); add_procedure("char->symbol" , char_to_symbol_proc); add_procedure("integer->char" , integer_to_char_proc); add_procedure("string->char" , string_to_char_proc); add_procedure("number->string", number_to_string_proc); add_procedure("string->number", string_to_number_proc); add_procedure("symbol->string", symbol_to_string_proc); add_procedure("string->symbol", string_to_symbol_proc); add_procedure("trim-string", trim_proc); add_procedure("=" , is_number_equal_proc); add_procedure("<" , is_less_than_proc); add_procedure(">" , is_greater_than_proc); add_procedure(">=" , is_greater_than_or_equal_proc); add_procedure("<=" , is_less_than_or_equal_proc); add_procedure("log" , log_proc); add_procedure("log2" , log2_proc); add_procedure("sin" , sin_proc); add_procedure("cos" , cos_proc); add_procedure("tan" , tan_proc); add_procedure("asin" , asin_proc); add_procedure("acos" , acos_proc); add_procedure("atan" , atan_proc); add_procedure("sqrt" , sqrt_proc); add_procedure("exit" , exit_proc); add_procedure("sleep", sleep_proc); add_procedure("cons" , cons_proc); add_procedure("car" , car_proc); add_procedure("cdr" , cdr_proc); add_procedure("set-car!", set_car_proc); add_procedure("set-cdr!", set_cdr_proc); add_procedure("list" , list_proc); add_procedure("apply" , apply_proc); add_procedure("eval" , eval_proc); add_procedure("eq?", is_eq_proc); add_procedure("env" , env_proc); add_procedure("i-env" , interaction_env_proc); add_procedure("nil-env" , nil_env_proc); add_procedure("load" , load_proc); add_procedure("open-input" , open_input_proc); add_procedure("close-input" , close_input_proc); add_procedure("input?" , is_input_proc); add_procedure("read" , read_proc); add_procedure("read-char" , read_char_proc); add_procedure("read-string" , read_string_proc); add_procedure("peek-char" , peek_char_proc); add_procedure("eof?" , is_eof_obj_proc); add_procedure("open-output" , open_output_proc); add_procedure("close-output", close_output_proc); add_procedure("output?" , is_output_proc); add_procedure("write-char" , write_char_proc); add_procedure("write-string" , write_string_proc); add_procedure("write" , write_proc); add_procedure("error" , error_proc); add_procedure("concat" , concat_proc); add_procedure("system" , system_proc); add_procedure("arena-mem" , arena_mem_proc); add_procedure("log-mem" , log_mem_proc); add_procedure("error-reporting", error_reporting_proc); add_procedure("log-verbose" , log_verbose_proc); add_procedure("random" , random_proc); install_thd_module(Env); install_net_module(Env); } #define DZM_PRC_H #endif
25.941221
153
0.568549
arogan-group
e6f69861901ec37b5cad0bb497aa89182bac1d70
290
cpp
C++
src/16000/16917.cpp17.cpp
upple/BOJ
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
[ "MIT" ]
8
2018-04-12T15:54:09.000Z
2020-06-05T07:41:15.000Z
src/16000/16917.cpp17.cpp
upple/BOJ
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
[ "MIT" ]
null
null
null
src/16000/16917.cpp17.cpp
upple/BOJ
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> const int INF=1e9; using namespace std; int main() { int a, b, c, x, y; cin >> a >> b >> c >> x >> y; int r1, r2, r3; r1 = min(x, y) * 2 * c + abs(x - y)*(x > y ? a : b); r2 = x*a + y*b; r3 = max(x, y) * 2 * c; cout << min({ r1, r2, r3 }); }
19.333333
53
0.482759
upple
e6fcff938d84109a6d190404bd506133a607e31f
3,685
cpp
C++
src/service_discovery.cpp
maxcong001/empty009
5fd7a4f2ef3f459ff869ffbd6fb6ac8e97725f64
[ "MIT" ]
null
null
null
src/service_discovery.cpp
maxcong001/empty009
5fd7a4f2ef3f459ff869ffbd6fb6ac8e97725f64
[ "MIT" ]
null
null
null
src/service_discovery.cpp
maxcong001/empty009
5fd7a4f2ef3f459ff869ffbd6fb6ac8e97725f64
[ "MIT" ]
null
null
null
#include "service_discovery.hpp" /*********************** Common ***********************/ /** * @brief Compare functions used for "sort" and "difference" * @param lhs: pointer reference to common data * @param rhs: pointer reference to common data * @return true if lhs < rhs, otherwise return false */ bool compareDiscoveryData(const service_discovery_interface::ptr_t &lhs, const service_discovery_interface::ptr_t &rhs) { return lhs->less(lhs, rhs); } /*********************** Service Discovery Base Data ***********************/ /** * @brief get host and port * @param type: address type * @return host and port */ HostAndPort service_discovery_interface::getHostAndPort(DwAddrType::type type, HostType::type hostType) { // error log return HostAndPort(); // return empty data } /** * @brief set host and port * @param data: host and port * @param type: address type * @return void */ void service_discovery_interface::setHostAndPort(HostAndPort &data, DwAddrType::type type) { // error log return; } /** * @brief get host type * @param type: address type * @return host type */ HostType::type service_discovery_interface::getHostType(DwAddrType::type type, HostType::type hostType) { // error log return HostType::DBW_MAX; // return an invalid value } /** * @brief set host type * @param type: host type * @param addrType: address type * @return host type */ void service_discovery_interface::setHostType(HostType::type type, DwAddrType::type addrType) { // error log return; } /** * @brief check host type exists or not * @param addrType: address type * @param type: host type * @return true/false */ bool service_discovery_interface::hasHostType(DwAddrType::type addrType, HostType::type type) { return (getHostType(addrType) == type); } /** * @brief operator == for service_discovery_interface * @param data: reference for common data * @return true if equal, otherwise return false */ bool service_discovery_interface::operator==(service_discovery_interface &data) { bool flag = ((this->svcLabel == data.svcLabel) && (this->dataType == data.dataType)); return flag; } /** * @brief operator < for service_discovery_interface * @param data: reference for common data * @return true if *this < data, otherwise return false */ bool service_discovery_interface::operator<(service_discovery_interface &data) { // compare based on priority: dataType > svcLabel if (this->dataType < data.dataType) { return true; } else if (this->dataType > data.dataType) { return false; } if (this->svcLabel < data.svcLabel) { return true; } else if (this->svcLabel > data.svcLabel) { return false; } return false; } /** * @brief Compare service_discovery_interface * @param lhs: pointer to common data * @param rhs: pointer to common data * @return true if *lhs < *rhs, otherwise return false */ bool service_discovery_interface::less(service_discovery_interface::ptr_t lhs, service_discovery_interface::ptr_t rhs) { if (!lhs || !rhs) { return false; } return (*lhs < *rhs); } /** * @brief Dump service_discovery_interface * @param prefix: prefix used when dumping data * @param onScreen: indicating whether dump log on stdout * @return void */ void service_discovery_interface::dump(std::string prefix, bool onScreen) { std::ostringstream os; os << prefix << "Dump service_discovery_interface(" << std::hex << this << ") ..." << std::endl; prefix += "\t"; os << prefix << "dataType: " << dataType << ", svcLabel: " << svcLabel << std::endl; if (onScreen) { printf("%s\n", os.str().c_str()); } else { } return; }
23.621795
119
0.674084
maxcong001
fc02c2816238aa40862f33daeab3d42036d3192e
1,966
hpp
C++
src/src/lib/geneial/core/population/builder/PermutationChromosomeFactory.hpp
geneial/geneial
5e525c32b7c1e1e88788644e448e9234c93b55e2
[ "MIT" ]
5
2015-08-25T15:40:09.000Z
2020-03-15T19:33:22.000Z
src/src/lib/geneial/core/population/builder/PermutationChromosomeFactory.hpp
geneial/geneial
5e525c32b7c1e1e88788644e448e9234c93b55e2
[ "MIT" ]
null
null
null
src/src/lib/geneial/core/population/builder/PermutationChromosomeFactory.hpp
geneial/geneial
5e525c32b7c1e1e88788644e448e9234c93b55e2
[ "MIT" ]
3
2019-01-24T13:14:51.000Z
2022-01-03T07:30:20.000Z
#pragma once #include <geneial/core/population/builder/PermutationChromosomeFactory.h> #include <geneial/utility/Random.h> #include <algorithm> #include <cassert> geneial_private_namespace(geneial) { geneial_private_namespace(population) { geneial_private_namespace(chromosome) { using ::geneial::population::chromosome::PermutationBuilderSettings; using ::geneial::population::chromosome::PermutationChromosomeFactory; geneial_export_namespace { template<typename VALUE_TYPE, typename FITNESS_TYPE> typename BaseChromosome<FITNESS_TYPE>::ptr PermutationChromosomeFactory<VALUE_TYPE, FITNESS_TYPE>::doCreateChromosome( typename BaseChromosomeFactory<FITNESS_TYPE>::PopulateBehavior populateValues) { using namespace geneial::utility; auto new_chromosome = this->allocateNewChromsome(); if (populateValues == BaseChromosomeFactory<FITNESS_TYPE>::CREATE_VALUES) { assert(_settings.getNum() > 1); const unsigned int amount = _settings.getNum(); for(unsigned int i = 0; i < amount; i++) { const VALUE_TYPE val = i; new_chromosome->getContainer()[i] = val; } const unsigned rounds = Random::generate<unsigned int>(_settings.getPermutationRoundsMin(),_settings.getPermutationRoundsMax()); for(unsigned int i = 0; i<rounds;i++) { unsigned int swapA = Random::generate<unsigned int>(0,_settings.getNum()-1); unsigned int swapB; do{ swapB = Random::generate<unsigned int>(0,_settings.getNum()-1); }while(swapA == swapB); auto iterBegin = new_chromosome->getContainer().begin(); iter_swap(iterBegin + swapA, iterBegin + swapB); } assert(new_chromosome->getSize() == _settings.getNum()); } return std::move(new_chromosome); } } /* geneial_export_namespace */ } /* private namespace chromosome */ } /* private namespace population */ } /* private namespace geneial */
31.206349
136
0.702442
geneial
fc058332b8302cf04188b381800a978a276c22d1
1,589
cpp
C++
algorithms/cpp/source/candy.cpp
straywarrior/leetcode-solutions
d94749daf7da895b83c6834cb3b1e2a0b8a52ccc
[ "MIT" ]
null
null
null
algorithms/cpp/source/candy.cpp
straywarrior/leetcode-solutions
d94749daf7da895b83c6834cb3b1e2a0b8a52ccc
[ "MIT" ]
null
null
null
algorithms/cpp/source/candy.cpp
straywarrior/leetcode-solutions
d94749daf7da895b83c6834cb3b1e2a0b8a52ccc
[ "MIT" ]
null
null
null
/* * candy.cpp * Copyright (C) 2018 StrayWarrior <i@straywarrior.com> * * Distributed under terms of the MIT license. */ #include "common.hpp" #define CATCH_CONFIG_MAIN #include "catch/catch.hpp" using namespace std; class Candy { public: int candy(vector<int> & ratings) { return this->solve_trivial(ratings); } int solve_trivial(vector<int> & ratings) { int m = ratings.size(); vector<int> candies(m, 1); for (int i = 0; i < m - 1; ++i) { if (ratings[i + 1] > ratings[i]) candies[i + 1] = candies[i] + 1; } // Here I use max operation to make sure the left neighbor get enough // candies. After the first pass, children with higher scores than // their right neighbors should have at least same number of candies as // their neighbors. It's obvious, so why do I type so many words here? for (int i = m - 1; i > 0; --i) { if (ratings[i - 1] > ratings[i]) candies[i - 1] = std::max(candies[i - 1], candies[i] + 1); } int sum = 0; for (auto c : candies) sum += c; return sum; } }; TEST_CASE( "test corectness", "leetcode.cpp.candy" ) { Candy sol; using TestCase = std::tuple< vector<int>, int >; std::vector<TestCase> test_cases { TestCase{ {1, 2}, 3 }, TestCase{ {1, 2, 3}, 6 }, TestCase{ {1, 4, 2, 3}, 6 }, TestCase{ {}, 0 }, }; for (auto & t : test_cases) { CHECK(sol.candy(std::get<0>(t)) == std::get<1>(t)); } }
27.877193
79
0.539962
straywarrior
fc093012ab6bb16f57f98c62993fecf93857f662
3,664
hxx
C++
src/private/httpparser.hxx
Targoman/qhttp
2351076d2e23c8820e6e94d064de689d99edb22f
[ "MIT" ]
2
2020-07-03T06:34:15.000Z
2020-07-03T19:19:09.000Z
src/private/httpparser.hxx
Targoman/QHttp
55df46aab918a1f923e8b1b79674cf9f82490bc5
[ "MIT" ]
null
null
null
src/private/httpparser.hxx
Targoman/QHttp
55df46aab918a1f923e8b1b79674cf9f82490bc5
[ "MIT" ]
null
null
null
/** @file httpparser.hxx * * @copyright (C) 2016 * @date 2016.05.26 * @version 1.0.0 * @author amir zamani <azadkuh@live.com> * */ #ifndef QHTTP_HTTPPARSER_HXX #define QHTTP_HTTPPARSER_HXX #include "qhttpbase.hpp" /////////////////////////////////////////////////////////////////////////////// namespace qhttp { namespace details { /////////////////////////////////////////////////////////////////////////////// /// base HttpParser based on joyent http_parser template<class TImpl> class HttpParser { public: explicit HttpParser(http_parser_type type) { // create http_parser object iparser.data = static_cast<TImpl*>(this); http_parser_init(&iparser, type); memset(&iparserSettings, 0, sizeof(http_parser_settings)); iparserSettings.on_message_begin = onMessageBegin; iparserSettings.on_url = onUrl; iparserSettings.on_status = onStatus; iparserSettings.on_header_field = onHeaderField; iparserSettings.on_header_value = onHeaderValue; iparserSettings.on_headers_complete = onHeadersComplete; iparserSettings.on_body = onBody; iparserSettings.on_message_complete = onMessageComplete; } size_t parse(const char* data, size_t length) { return http_parser_execute(&iparser, &iparserSettings, data, length); } public: // callback functions for http_parser_settings static int onMessageBegin(http_parser* p) { return me(p)->messageBegin(p); } static int onUrl(http_parser* p, const char* at, size_t length) { return me(p)->url(p, at, length); } static int onStatus(http_parser* p, const char* at, size_t length) { return me(p)->status(p, at, length); } static int onHeaderField(http_parser* p, const char* at, size_t length) { return me(p)->headerField(p, at, length); } static int onHeaderValue(http_parser* p, const char* at, size_t length) { return me(p)->headerValue(p, at, length); } static int onHeadersComplete(http_parser* p) { return me(p)->headersComplete(p); } static int onBody(http_parser* p, const char* at, size_t length) { return me(p)->body(p, at, length); } static int onMessageComplete(http_parser* p) { return me(p)->messageComplete(p); } protected: // The ones we are reading in from the parser QByteArray itempHeaderField; QByteArray itempHeaderValue; // if connection has a timeout, these fields will be used quint32 itimeOut = 0; QBasicTimer itimer; // uniform socket object QScopedPointer<QHttpAbstractSocket> isocket; // if connection should persist bool ikeepAlive = false; // joyent http_parser http_parser iparser; http_parser_settings iparserSettings; static auto me(http_parser* p) { return static_cast<TImpl*>(p->data); } }; // /// basic request parser (server) template<class TImpl> struct HttpRequestParser : public HttpParser<TImpl> { HttpRequestParser() : HttpParser<TImpl>(HTTP_REQUEST) {} }; /// basic response parser (clinet) template<class TImpl> struct HttpResponseParser : public HttpParser<TImpl> { HttpResponseParser() : HttpParser<TImpl>(HTTP_RESPONSE) {} }; /////////////////////////////////////////////////////////////////////////////// } // namespace details } // namespace qhttp /////////////////////////////////////////////////////////////////////////////// #endif // QHTTP_HTTPPARSER_HXX
30.533333
79
0.593341
Targoman
fc0b34e792d9a186d4cb20c5baf0ed4ef3de16f7
7,955
hh
C++
src/include/SchemaItem.hh
websurfer5/json-schema-enforcer
99211a602b1c8177d9f9e67cd7773015f74a4080
[ "Apache-2.0" ]
null
null
null
src/include/SchemaItem.hh
websurfer5/json-schema-enforcer
99211a602b1c8177d9f9e67cd7773015f74a4080
[ "Apache-2.0" ]
null
null
null
src/include/SchemaItem.hh
websurfer5/json-schema-enforcer
99211a602b1c8177d9f9e67cd7773015f74a4080
[ "Apache-2.0" ]
null
null
null
// SchemaItem.hh // // Copyright 2018 Jeffrey Kintscher <websurfer@surf2c.net> // // 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 __JSONSCHEMAENFORCER_SCHEMA_ITEM_HH #define __JSONSCHEMAENFORCER_SCHEMA_ITEM_HH namespace jsonschemaenforcer { class ParsedItemData; } #include "config.h" #include "FormatType.hh" #include "ItemType.hh" #include "JsonItem.hh" #include "stddefs.hh" #include <iostream> #include <list> #include <string> namespace jsonschemaenforcer { class SchemaData; class SchemaItem; typedef std::list<SchemaItem> SchemaItemList; class SchemaItem { public: SchemaItem(); SchemaItem(const SchemaItem& sitem); ~SchemaItem(); SchemaItem& operator =(const SchemaItem& sitem); bool operator ==(const SchemaItem& sitem) const; inline bool operator !=(const SchemaItem& sitem) const { return !(this->operator ==(sitem)); }; inline void add_item_type(const ItemType& _type) { type_set.insert(_type); }; void clear(); bool define_item(const std::string& _key, const ParsedItemData& idata); bool define_dependency_array(const std::string& _key, const StdStringList& s_list); bool empty() const; inline std::string emit_parser(SchemaData& sd, const std::string& start_state) const { return emit_parser(sd, start_state, ""); }; std::string emit_integer_parser_rules(SchemaData& sd, const std::string& start_state, const std::string& key_validation_state) const; std::string emit_number_parser_rules(SchemaData& sd, const std::string& start_state, const std::string& key_validation_state) const; std::string emit_string_parser_rules(SchemaData& sd, const std::string& start_state, const std::string& key_validation_state) const; std::string emit_object_parser_rules(SchemaData& sd, const std::string& start_state, const std::string& key_validation_state) const; std::string emit_array_parser_rules(SchemaData& sd, const std::string& start_state, const std::string& key_validation_state) const; // std::string emit_boolean_parser_rules(SchemaData& sd, const std::string& start_state) const; // std::string emit_null_parser_rules(SchemaData& sd, const std::string& start_state) const; # define DEF_VAR(vtype, vname, value, test_value, flag_name, flag_value, func_set, func_get) \ void func_set(vtype _##vname); \ inline vtype func_get() const { return vname; }; \ inline bool has_##vname() const { return flag_name; }; # define DEF_OBJ(objtype, vname, initfunc, emptyfunc, test_value, flag_name, flag_value, func_set, func_get) \ void func_set(const objtype& _##vname); \ inline const objtype& func_get() const { return vname; }; \ inline bool has_##vname() const { return flag_name; }; # define DEF_OBJ_PTR(objtype, vname, initfunc, emptyfunc, test_value, flag_name, flag_value, func_set, func_get) \ void func_set(const objtype& obj); \ const objtype& func_get() const; \ inline bool has_##vname() const { return flag_name; }; # define DEF_FLAG(fname, value, func_set, func_clear) \ inline void func_set() { fname = true; }; \ inline void func_set(bool b) { fname = b; }; \ inline void func_clear() { fname = false; }; \ inline bool is_##fname() const { return fname; }; # include "SchemaItem-vars.hh" # undef DEF_VAR # undef DEF_OBJ # undef DEF_OBJ_PTR # undef DEF_FLAG // // has item type functions // # define DEF_FLAG(fname, str_name) \ inline bool has_##fname##_type() const { return (type_set.find(ItemType::type_##fname) != type_set.end()); }; # include "ItemType-vars.hh" # undef DEF_FLAG protected: // // The set_data templated function ensures that a real // only gets assigned to an integer variable if the real // value is an integer. // template <class T, class U> bool set_data(bool& b_var1, bool b_var2, T& var1, const U& var2, const std::string& prop_type, const std::string& var_name) { bool error = false; if (b_var2) { if (var2 != (T) var2) { b_var1 = false; error = true; std::cerr << __FUNCTION__ << "(): \"" << var_name << "\" property value is not " << prop_type << ": " << var2 << std::endl; } else { b_var1 = true; var1 = (T) var2; } } else b_var1 = false; return !error; } std::string emit_parser(SchemaData& sd, const std::string& start_state, const std::string& key_validation_state) const; void emit_array_rule(SchemaData& sd, std::string& rule_str, bool& first, const SchemaItem& item, const std::string& array_state, const std::string& item_tag) const; void emit_default_rules(SchemaData& sd) const; void emit_object_rule(SchemaData& sd, std::string& rule_str, bool& first, const SchemaItem& item, const std::string& object_state, const std::string& prop_names_state) const; bool is_vanilla() const; bool set_array_data(const ParsedItemData& idata); bool set_integer_data(const ParsedItemData& idata); bool set_number_data(const ParsedItemData& idata); bool set_object_data(const ParsedItemData& idata); bool set_string_data(const ParsedItemData& idata); public: # define DEF_VAR(vtype, vname, value, test_value, flag_name, flag_value, func_set, func_get) \ vtype vname; \ bool flag_name; # define DEF_OBJ(objtype, vname, initfunc, emptyfunc, test_value, flag_name, flag_value, func_set, func_get) \ objtype vname; \ bool flag_name; # define DEF_OBJ_PTR(objtype, vname, initfunc, emptyfunc, test_value, flag_name, flag_value, func_set, func_get) \ objtype *vname; \ bool flag_name; # define DEF_FLAG(fname, value, func_set, func_clear) \ bool fname; # include "SchemaItem-vars.hh" # undef DEF_VAR # undef DEF_OBJ # undef DEF_OBJ_PTR # undef DEF_FLAG }; } #endif // __JSONSCHEMAENFORCER_SCHEMA_ITEM_HH
39.974874
120
0.565933
websurfer5
fc12f1bb40762427e02bff17cf8ae9659a485933
4,207
cc
C++
src/api/render/texture.cc
izzyaxel/Loft
809b4e3df2c2b08092c6b3a94073f4509240b4f2
[ "BSD-3-Clause" ]
null
null
null
src/api/render/texture.cc
izzyaxel/Loft
809b4e3df2c2b08092c6b3a94073f4509240b4f2
[ "BSD-3-Clause" ]
null
null
null
src/api/render/texture.cc
izzyaxel/Loft
809b4e3df2c2b08092c6b3a94073f4509240b4f2
[ "BSD-3-Clause" ]
null
null
null
#include "texture.hh" #include <glad/glad.h> Texture::Texture(uint32_t width, uint32_t height, ColorFormat colorFormat, InterpMode mode, bool sRGB) { this->fmt = colorFormat; this->width = width; this->height = height; glCreateTextures(GL_TEXTURE_2D, 1, &this->handle); int32_t f = 0; if(colorFormat == ColorFormat::RGB) //It's more efficient to use an extra 8 bits of VRAM per pixel { if(sRGB) f = GL_SRGB8; else f = GL_RGB8; } else if(colorFormat == ColorFormat::RGBA) { if(sRGB) f = GL_SRGB8_ALPHA8; else f = GL_RGBA8; } else if(colorFormat == ColorFormat::GREY) { f = GL_R8; } glTextureStorage2D(this->handle, 1, f, width, height); this->clear(); this->setInterpolation(mode, mode); this->setAnisotropyLevel(1); } Texture::Texture(uint8_t *data, uint32_t width, uint32_t height, ColorFormat colorFormat, InterpMode mode, bool sRGB) { this->fmt = colorFormat; this->width = width; this->height = height; int32_t f = 0, cf = 0; if(colorFormat == ColorFormat::RGB) //TODO It's more efficient to use an extra 8 bits of VRAM per pixel { if(sRGB) f = GL_SRGB8; else f = GL_RGB8; cf = GL_RGB; } else if(colorFormat == ColorFormat::RGBA) { if(sRGB) f = GL_SRGB8_ALPHA8; else f = GL_RGBA8; cf = GL_RGBA; } else if(colorFormat == ColorFormat::GREY) { f = GL_R8; cf = GL_RED; } glCreateTextures(GL_TEXTURE_2D, 1, &this->handle); glTextureStorage2D(this->handle, 1, f, width, height); glTextureSubImage2D(this->handle, 0, 0, 0, this->width, this->height, cf, GL_UNSIGNED_BYTE, data); this->setInterpolation(mode, mode); this->setAnisotropyLevel(1); } Texture::Texture(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha, bool sRGB) { this->fmt = ColorFormat::RGBA; this->width = 1; this->height = 1; uint8_t **data = new uint8_t *; data[0] = new uint8_t[4]; data[0][0] = red; data[0][1] = green; data[0][2] = blue; data[0][3] = alpha; glCreateTextures(GL_TEXTURE_2D, 1, &this->handle); glTextureStorage2D(this->handle, 1, sRGB ? GL_SRGB8_ALPHA8 : GL_RGBA8, this->width, this->height); glTextureSubImage2D(this->handle, 0, 0, 0, this->width, 1, GL_RGBA, GL_UNSIGNED_BYTE, data[0]); this->setInterpolation(InterpMode::Linear, InterpMode::Linear); this->setAnisotropyLevel(1); } Texture::~Texture() { glDeleteTextures(1, &this->handle); } Texture::Texture(Texture &other) { this->handle = other.handle; other.handle = 0; } Texture& Texture::operator=(Texture other) { this->handle = other.handle; other.handle = 0; return *this; } Texture::Texture(Texture &&other) { this->handle = other.handle; other.handle = 0; } Texture& Texture::operator=(Texture &&other) { this->handle = other.handle; other.handle = 0; return *this; } void Texture::use(uint32_t target) { int32_t curTex; glGetIntegerv(GL_TEXTURE_BINDING_2D, &curTex); glBindTextureUnit(target, this->handle); } void Texture::setInterpolation(InterpMode min, InterpMode mag) { GLenum glMin = GL_NEAREST, glMag = GL_NEAREST; switch(min) { case InterpMode::Nearest: glMin = GL_NEAREST; break; case InterpMode::Linear: glMin = GL_LINEAR; break; default: break; } switch(mag) { case InterpMode::Nearest: glMag = GL_NEAREST; break; case InterpMode::Linear: glMag = GL_LINEAR; break; default: break; } glTextureParameteri(this->handle, GL_TEXTURE_MIN_FILTER, glMin); glTextureParameteri(this->handle, GL_TEXTURE_MAG_FILTER, glMag); } void Texture::setAnisotropyLevel(uint32_t level) { glTextureParameterf(this->handle, GL_TEXTURE_MAX_ANISOTROPY, level); } void Texture::subImage(uint8_t *data, uint32_t w, uint32_t h, uint32_t xPos, uint32_t yPos, ColorFormat format) { int32_t f = 0; switch(format) { case ColorFormat::RGB: f = GL_RGB; break; case ColorFormat::RGBA: f = GL_RGBA; break; case ColorFormat::GREY: f = GL_RED; break; } glTextureSubImage2D(this->handle, 0, xPos, yPos, w, h, f, GL_UNSIGNED_BYTE, data); } void Texture::clear() { int32_t f = 0; switch(this->fmt) { case ColorFormat::RGB: f = GL_RGB; break; case ColorFormat::RGBA: f = GL_RGBA; break; case ColorFormat::GREY: f = GL_RED; break; } glClearTexImage(this->handle, 0, f, GL_UNSIGNED_BYTE, "\0\0\0\0"); }
23.634831
117
0.697884
izzyaxel
fc189b0e59158000429902dc22d56f8eff5d771f
2,647
hh
C++
kernel/host/host-common/util/FDReceiver.hh
ManyThreads/mythos
723a4b11e454a0c28e096755140c5e0eecf6a211
[ "MIT" ]
12
2016-10-06T14:02:17.000Z
2021-09-12T06:14:30.000Z
kernel/host/host-common/util/FDReceiver.hh
ManyThreads/mythos
723a4b11e454a0c28e096755140c5e0eecf6a211
[ "MIT" ]
110
2017-06-22T20:10:17.000Z
2022-01-18T12:58:40.000Z
kernel/host/host-common/util/FDReceiver.hh
ManyThreads/mythos
723a4b11e454a0c28e096755140c5e0eecf6a211
[ "MIT" ]
6
2016-12-09T08:30:08.000Z
2021-12-10T19:05:04.000Z
/* -*- mode:C++; indent-tabs-mode:nil; -*- */ /* MIT License -- MyThOS: The Many-Threads Operating System * * 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. * * Copyright 2016 Randolf Rotta, Robert Kuban, and contributors, BTU Cottbus-Senftenberg */ #pragma once #include <sys/socket.h> #include <iostream> #include <string.h> #include <unistd.h> #include <sys/un.h> class FDReceiver{ int sock; struct sockaddr_un addr; public: FDReceiver() : sock(-1) { } ~FDReceiver(){ disconnect(); } bool disconnect(){ if(sock >= 0) close(sock); } bool connectToSocket(const char *sockPath){ disconnect(); sock = socket(PF_LOCAL, SOCK_STREAM, 0); if (sock == -1){ std::cerr << "error: unable to open socket" << std::endl; return false; } addr.sun_family = AF_LOCAL; strcpy(addr.sun_path, sockPath); if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == -1){ std::cerr << "error: connecting to domain socket failed" << std::endl; disconnect(); return false; } return true; } int recvFD(){ if(sock < 0) return (-1); struct msghdr msg = {0}; char m_buffer[256]; struct iovec io = { .iov_base = m_buffer, .iov_len = sizeof(m_buffer) }; msg.msg_iov = &io; msg.msg_iovlen = 1; char c_buffer[256]; msg.msg_control = c_buffer; msg.msg_controllen = sizeof(c_buffer); int recvBytes = 0; do{ recvBytes = recvmsg(sock, &msg, 0); }while(recvBytes == 0); if (recvBytes < 0) return (-1); struct cmsghdr * cmsg = CMSG_FIRSTHDR(&msg); unsigned char * data = CMSG_DATA(cmsg); int fd = *((int*) data); return fd; } };
24.284404
88
0.68606
ManyThreads
fc1e1dedb28f9af089ad41fe9aa441064b3847a0
390
cpp
C++
src/top.chenqwwq/acwing/content/_52/_1.cpp
chenqwwq/_leetcode
a8055c53c9a68cedb1b57a56f98e83709448e4cb
[ "Apache-2.0" ]
null
null
null
src/top.chenqwwq/acwing/content/_52/_1.cpp
chenqwwq/_leetcode
a8055c53c9a68cedb1b57a56f98e83709448e4cb
[ "Apache-2.0" ]
null
null
null
src/top.chenqwwq/acwing/content/_52/_1.cpp
chenqwwq/_leetcode
a8055c53c9a68cedb1b57a56f98e83709448e4cb
[ "Apache-2.0" ]
null
null
null
// // Created by chenqwwq on 2022/5/21. // #include <iostream> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int num; cin >> num; int ans = 0, i = 1; while (num) { int cost = (i * (i + 1)) / 2; if (num < cost) break; num -= cost; ans++; i++; } printf("%d\n",ans); return 0; }
15.6
37
0.471795
chenqwwq
fc2206d293c8a442af3c660c9af9e2f2af7492de
282
cpp
C++
src/construction/Constraints.cpp
ShnitzelKiller/Reverse-Engineering-Carpentry
585b5ff053c7e3bf286b663a584bc83687691bd6
[ "MIT" ]
3
2021-09-08T07:28:13.000Z
2022-03-02T21:12:40.000Z
src/construction/Constraints.cpp
ShnitzelKiller/Reverse-Engineering-Carpentry
585b5ff053c7e3bf286b663a584bc83687691bd6
[ "MIT" ]
1
2021-09-21T14:40:55.000Z
2021-09-26T01:19:38.000Z
src/construction/Constraints.cpp
ShnitzelKiller/Reverse-Engineering-Carpentry
585b5ff053c7e3bf286b663a584bc83687691bd6
[ "MIT" ]
null
null
null
// // Created by James Noeckel on 1/16/21. // #include "Constraints.h" Edge2d ConnectionConstraint::getGuide() const { Eigen::Vector2d dir = (edge.second - edge.first).normalized(); return {edge.first - dir * startGuideExtention, edge.second + dir * endGuideExtension}; }
25.636364
91
0.702128
ShnitzelKiller
fc23b7dac87be87ec34d96a2f549355e6b66018c
3,965
hpp
C++
src/network.hpp
packetgenie/PacketGenie
cf09d39f53b9e6119c0ebe77134a032a082c81fd
[ "Apache-2.0" ]
1
2015-08-20T12:31:02.000Z
2015-08-20T12:31:02.000Z
src/network.hpp
packetgenie/PacketGenie
cf09d39f53b9e6119c0ebe77134a032a082c81fd
[ "Apache-2.0" ]
null
null
null
src/network.hpp
packetgenie/PacketGenie
cf09d39f53b9e6119c0ebe77134a032a082c81fd
[ "Apache-2.0" ]
2
2015-08-19T14:47:32.000Z
2019-08-30T15:58:07.000Z
// FILE: src/network.hpp Date Modified: March 17, 2015 // PacketGenie // Copyright 2014 The Regents of the University of Michigan // Dong-Hyeon Park, Ritesh Parikh, Valeria Bertacco // // PacketGenie is 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 _NETWORK_HPP_ #define _NETWORK_HPP_ #include <string> #include <map> #include <vector> #include <fstream> #include <list> #include "node.hpp" #include "node_configs.hpp" #include "node_group.hpp" #include "globals.hpp" #include "misc.cpp" #include "injection_process.hpp" #include "traffic_pattern.hpp" #include "packet_handler.hpp" #include "packet.hpp" #include "reply_job.hpp" namespace tf_gen { enum NetworkType { NETWORK_MESH = 0, //NETWORK_CROSSBAR, }; enum NetworkStatus { NETWORK_STATUS_READY = 0, NETWORK_STATUS_DONE, NETWORK_STATUS_ACTIVE, NETWORK_STATUS_WRAPPING_UP, NETWORK_STATUS_PRE_INIT, NETWORK_STATUS_ERROR, }; class Network { public: Network(NetworkType ntwk_type, size_t dim_x, size_t dim_y); virtual ~Network(); int set_inj_process(vector<string> *str_params); int set_sender_nodes(vector<string> *idx_list); int set_receiver_nodes(vector<string> *idx_list); int set_traffic_pattern(vector<string> *str_params); int set_packet_type_reply(vector<string> *str_params); int set_packet_type(vector<string> *str_params); int set_node_group(vector<string> *str_params); int config_nodes(vector<string> *str_params); #if _BOOKSIM int config_BookSim(const char* const config_file); #endif int init_sim(size_t sim_end); int step(); int get_traffic_records(string & printout); int print_traffic_records(); NetworkStatus get_status(); int set_dram_bank_config(vector<string> *str_params); int set_dram_timing_config(vector<string> *str_params); bool no_outstanding_reply(); private: int process_all_packet_queues(); void update_all_clocks(); int config_nodes_buffer(vector<string> *str_params, list<Node *> &nodes); int config_nodes_dram(vector<string> *str_params, list<Node*> &nodes); int config_nodes_clock(vector<string> *str_params, list<Node*> &nodes); #if _BOOKSIM int config_nodes_default_port(); // int config_nodes_port(vector<string> *str_params, // list<Node*> &nodes); #endif vector<Node> *node_list; size_t m_ntwk_size; NetworkType m_ntwk_type; NetworkStatus m_status; double base_inj_per_step; // Base injection rate, normalized // by step size size_t sim_end; long next_event_time; list<NodeGroup*> *group_list; list<NodeGroup*> *active_groups; list<NodeGroup*> *waiting_groups; list<NodeGroup*> *finished_groups; map<string, senders_t> *sender_map; map<string, receivers_t> *receiver_map; map<string, InjectionProcess *> *inj_proc_map; map<string, TrafficPattern *> *traf_pattern_map; map<string, Packet*> *packet_map; map<string, ReplyPacketHandler *> *reply_handler_map; map<string, Dram> *dram_map; // Packet pool of all existing packets. packet_pool_t global_packet_pool; }; } #endif
26.790541
76
0.669357
packetgenie
fc27a28e41f64ee3f80965bb901ed85a1e9059ce
3,560
cpp
C++
src/Models/NeuronNetwork.cpp
SpiritSeeker/SpikeSim
c0ce896df15ed4bd46deb1aa61a3df637c0b6078
[ "Apache-2.0" ]
null
null
null
src/Models/NeuronNetwork.cpp
SpiritSeeker/SpikeSim
c0ce896df15ed4bd46deb1aa61a3df637c0b6078
[ "Apache-2.0" ]
null
null
null
src/Models/NeuronNetwork.cpp
SpiritSeeker/SpikeSim
c0ce896df15ed4bd46deb1aa61a3df637c0b6078
[ "Apache-2.0" ]
null
null
null
#include "sspch.h" #include "NeuronNetwork.h" namespace SpikeSim { NeuronNetwork::NeuronNetwork() {} void NeuronNetwork::OnUpdate(const std::vector<std::vector<double>>& inputCurrents, uint32_t nIter) { uint32_t inputCounter = 0; for (int i = 0; i < m_Neurons.size(); i++) { if (m_InputNeuron[i]) m_Neurons[i]->OnUpdate(inputCurrents[inputCounter++]); else { std::vector<double> inputCurrent(m_Neurons[i]->GetDendriteCount(), 0); for (int j = 0; j < m_Connections.size(); j++) { if (m_Connections[j].PostNeuron == i) inputCurrent[m_Connections[j].Dendrite] = m_Synapses[m_Connections[j].SynapseID]->GetOutputCurrent(); } } } for (int i = 0; i < m_Synapses.size(); i++) { double inputVoltage = m_Neurons[m_Connections[i].PreNeuron]->GetTerminalVoltages()[m_Connections[i].Axon]; double outputVoltage = m_Neurons[m_Connections[i].PostNeuron]->GetInputVoltages()[m_Connections[i].Dendrite]; m_Synapses[i]->OnUpdate(inputVoltage, outputVoltage); } for (int i = 0; i < m_PlotInfo.size(); i++) { m_PlotData[i].X.push_back(nIter * m_Timestep); if (m_PlotInfo[i].Type == 0) { switch (m_PlotInfo[i].Component) { case 0: { m_PlotData[i].Y.push_back(m_Neurons[m_PlotInfo[i].ID]->GetDendriteCurrent()); break; } case 1: { m_PlotData[i].Y.push_back(m_Neurons[m_PlotInfo[i].ID]->GetMembranePotential()); break; } case 2: { m_PlotData[i].Y.push_back(m_Neurons[m_PlotInfo[i].ID]->GetTerminalVoltages()[m_PlotInfo[i].Index]); break; } } } else m_PlotData[i].Y.push_back(m_Synapses[m_PlotInfo[i].ID]->GetOutputCurrent()); } } void NeuronNetwork::AddNeuron(uint32_t dendrites, uint32_t axons, bool input) { struct NeuronProps props; props.n_Dendrites = dendrites; props.n_Axons = axons; auto neuron = Neuron::Create(props); neuron->SetTimestep(m_Timestep); m_Neurons.push_back(neuron); m_InputNeuron.push_back(input); } void NeuronNetwork::AddSynapse(uint32_t fromNeuronID, uint32_t fromAxonID, uint32_t toNeuronID, uint32_t toDendriteID) { auto synapse = Synapse::Create(SynapseType::FixedResistor); synapse->SetTimestep(m_Timestep); m_Synapses.push_back(synapse); m_Connections.push_back({ (uint32_t)m_Connections.size(), fromNeuronID, fromAxonID, toNeuronID, toDendriteID }); } void NeuronNetwork::TracePlot(PlotType type, uint32_t id) { switch (type) { case PlotType::MembranePotential: { m_PlotInfo.push_back({ 0, id, 1, 0 }); m_PlotData.push_back({ {0}, {-70} }); } case PlotType::SynapticCurrent: { m_PlotInfo.push_back({ 1, id, 0, 0 }); m_PlotData.push_back({ {0}, {0} }); } case PlotType::DendriteCurrent: { m_PlotInfo.push_back({ 0, id, 0, 0 }); m_PlotData.push_back({ {0}, {0} }); } } } void NeuronNetwork::TracePlot(PlotType type, uint32_t neuronID, uint32_t id) { m_PlotInfo.push_back({ 0, neuronID, 2, id }); m_PlotData.push_back({ {0}, {-70} }); } void NeuronNetwork::SetTimestep(double timestep) { m_Timestep = timestep; for (auto neuron : m_Neurons) neuron->SetTimestep(m_Timestep); for (auto synapse : m_Synapses) synapse->SetTimestep(m_Timestep); } }
29.666667
120
0.613764
SpiritSeeker
fc2be6da9d115404b750a37739abeeefef952fa1
1,658
hh
C++
src/thirdparty/acg_localizer/src/math/SFMT_src/SFMT-params607.hh
rajvishah/ms-sfm
0de1553c471c416ce5ca3d19c65abe36d8e17a07
[ "MIT" ]
1,102
2017-02-02T15:39:57.000Z
2022-03-23T09:43:29.000Z
src/thirdparty/acg_localizer/src/math/SFMT_src/SFMT-params607.hh
rajvishah/ms-sfm
0de1553c471c416ce5ca3d19c65abe36d8e17a07
[ "MIT" ]
339
2017-02-17T09:55:38.000Z
2022-03-29T11:44:01.000Z
src/thirdparty/acg_localizer/src/math/SFMT_src/SFMT-params607.hh
rajvishah/ms-sfm
0de1553c471c416ce5ca3d19c65abe36d8e17a07
[ "MIT" ]
331
2017-02-02T15:34:42.000Z
2022-03-23T02:42:24.000Z
#ifndef SFMT_PARAMS607_H #define SFMT_PARAMS607_H #define POS1 2 #define SL1 15 #define SL2 3 #define SR1 13 #define SR2 3 #define MSK1 0xfdff37ffU #define MSK2 0xef7f3f7dU #define MSK3 0xff777b7dU #define MSK4 0x7ff7fb2fU #define PARITY1 0x00000001U #define PARITY2 0x00000000U #define PARITY3 0x00000000U #define PARITY4 0x5986f054U /* PARAMETERS FOR ALTIVEC */ #if defined(__APPLE__) /* For OSX */ #define ALTI_SL1 (vector unsigned int)(SL1, SL1, SL1, SL1) #define ALTI_SR1 (vector unsigned int)(SR1, SR1, SR1, SR1) #define ALTI_MSK (vector unsigned int)(MSK1, MSK2, MSK3, MSK4) #define ALTI_MSK64 \ (vector unsigned int)(MSK2, MSK1, MSK4, MSK3) #define ALTI_SL2_PERM \ (vector unsigned char)(3,21,21,21,7,0,1,2,11,4,5,6,15,8,9,10) #define ALTI_SL2_PERM64 \ (vector unsigned char)(3,4,5,6,7,29,29,29,11,12,13,14,15,0,1,2) #define ALTI_SR2_PERM \ (vector unsigned char)(5,6,7,0,9,10,11,4,13,14,15,8,19,19,19,12) #define ALTI_SR2_PERM64 \ (vector unsigned char)(13,14,15,0,1,2,3,4,19,19,19,8,9,10,11,12) #else /* For OTHER OSs(Linux?) */ #define ALTI_SL1 {SL1, SL1, SL1, SL1} #define ALTI_SR1 {SR1, SR1, SR1, SR1} #define ALTI_MSK {MSK1, MSK2, MSK3, MSK4} #define ALTI_MSK64 {MSK2, MSK1, MSK4, MSK3} #define ALTI_SL2_PERM {3,21,21,21,7,0,1,2,11,4,5,6,15,8,9,10} #define ALTI_SL2_PERM64 {3,4,5,6,7,29,29,29,11,12,13,14,15,0,1,2} #define ALTI_SR2_PERM {5,6,7,0,9,10,11,4,13,14,15,8,19,19,19,12} #define ALTI_SR2_PERM64 {13,14,15,0,1,2,3,4,19,19,19,8,9,10,11,12} #endif /* For OSX */ #define IDSTR "SFMT-607:2-15-3-13-3:fdff37ff-ef7f3f7d-ff777b7d-7ff7fb2f" #endif /* SFMT_PARAMS607_H */
35.276596
72
0.693607
rajvishah
fc2fb291cd91df0b25212bfff4d27b4db24e9531
2,639
cpp
C++
HaloTAS/MCCTAS/speedometer.cpp
s3anyboy/HaloTAS
9584786f19e1475399298fda2d5783d47623cccd
[ "MIT" ]
6
2019-09-10T19:47:04.000Z
2020-11-26T08:32:36.000Z
HaloTAS/MCCTAS/speedometer.cpp
s3anyboy/HaloTAS
9584786f19e1475399298fda2d5783d47623cccd
[ "MIT" ]
13
2018-11-24T09:37:49.000Z
2021-10-22T02:29:11.000Z
HaloTAS/MCCTAS/speedometer.cpp
s3anyboy/HaloTAS
9584786f19e1475399298fda2d5783d47623cccd
[ "MIT" ]
3
2020-07-28T09:19:14.000Z
2020-09-02T04:48:49.000Z
#include "pch.h" #include "speedometer.h" void speedometer::clear() { mDataPoints.clear(); mSumTotalDistanceXYTravelled = 0.0f; mSumTotalDistanceXYZTravelled = 0.0f; mSumTotalDistanceCount = 0; } float vec3_xy_distance(glm::vec3 a, glm::vec3 b) { return glm::distance( glm::vec2(a.x, a.y), glm::vec2(b.x, b.y) ); } double speedometer::average_speed_per_second(axis a) { // Doesn't make sense to have a speed if we don't have at least 2 data points if (mDataPoints.size() < 2) return 0.0f; // Get the sum of distances between all data points double totalDistance = 0.0f; glm::vec3 lastPosition = mDataPoints.front(); for (auto& currentPosition : mDataPoints) { switch (a) { case speedometer::axis::X: totalDistance += glm::distance(lastPosition.x, currentPosition.x); break; case speedometer::axis::Y: totalDistance += glm::distance(lastPosition.y, currentPosition.y); break; case speedometer::axis::Z: totalDistance += glm::distance(lastPosition.z, currentPosition.z); break; case speedometer::axis::XY: totalDistance += vec3_xy_distance(lastPosition, currentPosition); break; case speedometer::axis::XYZ: totalDistance += glm::distance(lastPosition, currentPosition); break; } lastPosition = currentPosition; } auto speedCount = mDataPoints.size() - 1; // 2 data points = 1 speed value, etc return (totalDistance / speedCount) * mDataTickRate; } void speedometer::push_back(const glm::vec3& newPosition) { if (mDataPoints.size() > 0) { auto back = mDataPoints.back(); mSumTotalDistanceXYTravelled += vec3_xy_distance(back, newPosition); mSumTotalDistanceXYZTravelled += glm::distance(back, newPosition); mSumTotalDistanceCount++; } mDataPoints.push_back(newPosition); } std::vector<float> speedometer::display_data(axis axis) { std::vector<float> data; glm::vec3 lastPosition = mDataPoints.front(); bool skipFirst = false; for (auto& currentPosition : mDataPoints) { if (!skipFirst) { skipFirst = true; continue; } switch (axis) { case speedometer::axis::X: data.push_back(glm::distance(lastPosition.x, currentPosition.x)); break; case speedometer::axis::Y: data.push_back(glm::distance(lastPosition.y, currentPosition.y)); break; case speedometer::axis::Z: data.push_back(glm::distance(lastPosition.z, currentPosition.z)); break; case speedometer::axis::XY: data.push_back(vec3_xy_distance(lastPosition, currentPosition)); break; case speedometer::axis::XYZ: data.push_back(glm::distance(lastPosition, currentPosition)); break; } lastPosition = currentPosition; } return data; }
25.872549
80
0.71618
s3anyboy
fc3195ad06f02ab26d0c17c74229563b76f76652
2,208
cpp
C++
typo-poi/source/UTF8.cpp
mogemimi/daily-snippets
d9da3db8c62538e4a37f0f6b69c5d46d55c4225f
[ "MIT" ]
14
2017-06-16T22:52:38.000Z
2022-02-14T04:11:06.000Z
typo-poi/source/UTF8.cpp
mogemimi/daily-snippets
d9da3db8c62538e4a37f0f6b69c5d46d55c4225f
[ "MIT" ]
2
2016-03-13T14:50:04.000Z
2019-04-01T09:53:17.000Z
typo-poi/source/UTF8.cpp
mogemimi/daily-snippets
d9da3db8c62538e4a37f0f6b69c5d46d55c4225f
[ "MIT" ]
2
2016-03-13T14:05:17.000Z
2018-09-18T01:28:42.000Z
// Copyright (c) 2015 mogemimi. Distributed under the MIT license. #include "utf8.h" #include <cassert> #include <utility> #define USE_LLVM_CONVERTUTF 1 #if defined(USE_LLVM_CONVERTUTF) #include "thirdparty/ConvertUTF.h" #include <vector> #else #include <codecvt> #include <locale> #endif namespace somera { std::u32string toUtf32(const std::string& utf8) { if (utf8.empty()) { return {}; } #if defined(USE_LLVM_CONVERTUTF) auto src = reinterpret_cast<const UTF8*>(utf8.data()); auto srcEnd = reinterpret_cast<const UTF8*>(utf8.data() + utf8.size()); std::u32string result; result.resize(utf8.length() + 1); auto dest = reinterpret_cast<UTF32*>(&result[0]); auto destEnd = dest + result.size(); ConversionResult CR = ::ConvertUTF8toUTF32(&src, srcEnd, &dest, destEnd, strictConversion); assert(CR != targetExhausted); if (CR != conversionOK) { // error result.clear(); return result; } result.resize(reinterpret_cast<const char32_t*>(dest) - result.data()); result.shrink_to_fit(); return result; #else std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> convert; return convert.from_bytes(utf8); #endif } std::string toUtf8(const std::u32string& utf32) { if (utf32.empty()) { return {}; } #if defined(USE_LLVM_CONVERTUTF) auto src = reinterpret_cast<const UTF32*>(utf32.data()); auto srcEnd = reinterpret_cast<const UTF32*>(utf32.data() + utf32.size()); std::string result; result.resize(utf32.length() * UNI_MAX_UTF8_BYTES_PER_CODE_POINT + 1); auto dest = reinterpret_cast<UTF8*>(&result[0]); auto destEnd = dest + result.size(); ConversionResult CR = ::ConvertUTF32toUTF8(&src, srcEnd, &dest, destEnd, strictConversion); assert(CR != targetExhausted); if (CR != conversionOK) { // error result.clear(); return result; } result.resize(reinterpret_cast<const char*>(dest) - result.data()); result.shrink_to_fit(); return result; #else std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> convert; return convert.to_bytes(utf32); #endif } } // namespace somera
25.37931
78
0.664402
mogemimi
fc32a97b374aebf8f4b5f922eb78cb6b7e4e0e15
1,913
cpp
C++
Source/DScene_Main2.cpp
XDApp/DawnFramework
4963be2c4ead995a3b02fb0c683c3f77662b9916
[ "MIT" ]
1
2015-06-21T08:04:36.000Z
2015-06-21T08:04:36.000Z
Source/DScene_Main2.cpp
XDApp/DawnFramework
4963be2c4ead995a3b02fb0c683c3f77662b9916
[ "MIT" ]
null
null
null
Source/DScene_Main2.cpp
XDApp/DawnFramework
4963be2c4ead995a3b02fb0c683c3f77662b9916
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "DScene_Main2.h" DScene_Main2::DScene_Main2() { } DScene_Main2::~DScene_Main2() { } void DScene_Main2::Update() { DScene::Update(); } void DScene_Main2::Render() { DScene::Render(); glUseProgram(Program->GetProgram()); glEnableVertexAttribArray(vertexPosition_modelspaceID); glBindVertexArray(VertexArrayID); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer(vertexPosition_modelspaceID, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); glDrawArrays(GL_TRIANGLES, 0, 3); glDisableVertexAttribArray(vertexPosition_modelspaceID); } void DScene_Main2::Start() { VLoader = new DTextFileResourceLoader(DF->Config->ResourcePath() + "V2.vert.glsl"); FLoader = new DTextFileResourceLoader(DF->Config->ResourcePath() + "F2.frag.glsl"); VShader = new DGLVertexShader(VLoader); FShader = new DGLFragmentShader(FLoader); VLoader->Open(); VShader->Load(); VLoader->Close(); FLoader->Open(); FShader->Load(); FLoader->Close(); Program = new DGLProgram(); Program->AttachShader(VShader); Program->AttachShader(FShader); Program->Load(); delete VLoader; delete FLoader; static const GLfloat g_vertex_buffer_data[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, }; static const GLfloat g_vertex_buffer_data2[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, }; VertexArrayID = 0; vertexPosition_modelspaceID = glGetAttribLocation(Program->GetProgram(), "vertexPosition_modelspace"); glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); glGenBuffers(1, &vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW); } void DScene_Main2::End() { glDeleteBuffers(1, &vertexbuffer); glDeleteVertexArrays(1, &VertexArrayID); Program->Destroy(); VShader->Destroy(); FShader->Destroy(); }
22.505882
103
0.736017
XDApp
fc3dbcd1b30877ed8bea9d755e097cc036f440b9
1,103
hpp
C++
src/prsClass.hpp
GeoKon/GKE-L1
1ae69b3fdcdf0bb20df1a5afc011ad2d682e29d2
[ "MIT" ]
3
2019-01-09T04:30:41.000Z
2019-08-17T03:08:48.000Z
src/prsClass.hpp
GeoKon/GKE-L1
1ae69b3fdcdf0bb20df1a5afc011ad2d682e29d2
[ "MIT" ]
null
null
null
src/prsClass.hpp
GeoKon/GKE-L1
1ae69b3fdcdf0bb20df1a5afc011ad2d682e29d2
[ "MIT" ]
null
null
null
#pragma once #define DQUOTE '"' #define LCURL pr.moveAfter( '{' ) #define RCURL pr.moveAfter( '}' ) #define COLON pr.moveAfter( ':' ) #define COMMA pr.moveAfter( ',' ) #define COPYS pr.copyString() #define COPYD pr.copyDigits() #define EXPECT(A) pr.expect(A) #define FIND(A) pr.find(A) #define INIT(A) pr.init(A) #define ERROR pr.error() class PRS { private: void nospace(); // advances pointer to next non-space char *buffer; int maxsiz; // max size of the buffer int nextbf; // next available byte into buffer char *p; // walking pointer into buffer char *porg; // original p-pointer int errcode; // error Code int errfunc; // where the error occured public: PRS( int size ); ~PRS(); void init( char *text ); int error(); void moveAfter( int c ); void expect( char *t ); void find( char *t ); char *copyString(); // expects a string in quotes char *copyDigits(); // expects a string in quotes };
23.978261
78
0.563917
GeoKon
fc3e0e20de7584ae0fc60495db6d357ca298add9
39,391
cpp
C++
nfc/src/DOOM/doomclassic/doom/p_enemy.cpp
1337programming/leviathan
ca9a31b45c25fd23f361d67136ae5ac6b98d2628
[ "Apache-2.0" ]
1
2018-11-07T22:44:23.000Z
2018-11-07T22:44:23.000Z
ekronclassic/ekron/p_enemy.cpp
vic3t3chn0/OpenKrown
201c8fb6895cb0439e39c984d2fbc2c2eaf185b4
[ "MIT" ]
null
null
null
ekronclassic/ekron/p_enemy.cpp
vic3t3chn0/OpenKrown
201c8fb6895cb0439e39c984d2fbc2c2eaf185b4
[ "MIT" ]
null
null
null
/* =========================================================================== Doom 3 BFG Edition GPL Source Code Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code"). Doom 3 BFG Edition Source Code 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. Doom 3 BFG Edition Source Code 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 Doom 3 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 BFG Edition Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 BFG Edition Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #include "Precompiled.h" #include "globaldata.h" #include <stdlib.h> #include "m_random.h" #include "i_system.h" #include "doomdef.h" #include "p_local.h" #include "s_sound.h" #include "g_game.h" // State. #include "doomstat.h" #include "r_state.h" // Data. #include "sounds.h" extern bool globalNetworking; // // P_NewChaseDir related LUT. // const dirtype_t opposite[] = { DI_WEST, DI_SOUTHWEST, DI_SOUTH, DI_SOUTHEAST, DI_EAST, DI_NORTHEAST, DI_NORTH, DI_NORTHWEST, DI_NODIR }; const dirtype_t diags[] = { DI_NORTHWEST, DI_NORTHEAST, DI_SOUTHWEST, DI_SOUTHEAST }; extern "C" void A_Fall (mobj_t *actor, void *); // // ENEMY THINKING // Enemies are allways spawned // with targetplayer = -1, threshold = 0 // Most monsters are spawned unaware of all ::g->players, // but some can be made preaware // // // Called by P_NoiseAlert. // Recursively traverse adjacent ::g->sectors, // sound blocking ::g->lines cut off traversal. // void P_RecursiveSound ( sector_t* sec, int soundblocks ) { int i; line_t* check; sector_t* other; // wake up all monsters in this sector if (sec->validcount == ::g->validcount && sec->soundtraversed <= soundblocks+1) { return; // already flooded } sec->validcount = ::g->validcount; sec->soundtraversed = soundblocks+1; sec->soundtarget = ::g->soundtarget; for (i=0 ;i<sec->linecount ; i++) { check = sec->lines[i]; if (! (check->flags & ML_TWOSIDED) ) continue; P_LineOpening (check); if (::g->openrange <= 0) continue; // closed door if ( ::g->sides[ check->sidenum[0] ].sector == sec) other = ::g->sides[ check->sidenum[1] ] .sector; else other = ::g->sides[ check->sidenum[0] ].sector; if (check->flags & ML_SOUNDBLOCK) { if (!soundblocks) P_RecursiveSound (other, 1); } else P_RecursiveSound (other, soundblocks); } } // // P_NoiseAlert // If a monster yells at a player, // it will alert other monsters to the player. // void P_NoiseAlert ( mobj_t* target, mobj_t* emmiter ) { ::g->soundtarget = target; ::g->validcount++; P_RecursiveSound (emmiter->subsector->sector, 0); } // // P_CheckMeleeRange // qboolean P_CheckMeleeRange (mobj_t* actor) { mobj_t* pl; fixed_t dist; if (!actor->target) return false; pl = actor->target; dist = P_AproxDistance (pl->x-actor->x, pl->y-actor->y); if (dist >= MELEERANGE-20*FRACUNIT+pl->info->radius) return false; if (! P_CheckSight (actor, actor->target) ) return false; return true; } // // P_CheckMissileRange // qboolean P_CheckMissileRange (mobj_t* actor) { fixed_t dist; if (! P_CheckSight (actor, actor->target) ) return false; if ( actor->flags & MF_JUSTHIT ) { // the target just hit the enemy, // so fight back! actor->flags &= ~MF_JUSTHIT; return true; } if (actor->reactiontime) return false; // do not attack yet // OPTIMIZE: get this from a global checksight dist = P_AproxDistance ( actor->x-actor->target->x, actor->y-actor->target->y) - 64*FRACUNIT; if (!actor->info->meleestate) dist -= 128*FRACUNIT; // no melee attack, so fire more dist >>= 16; if (actor->type == MT_VILE) { if (dist > 14*64) return false; // too far away } if (actor->type == MT_UNDEAD) { if (dist < 196) return false; // close for fist attack dist >>= 1; } if (actor->type == MT_CYBORG || actor->type == MT_SPIDER || actor->type == MT_SKULL) { dist >>= 1; } if (dist > 200) dist = 200; if (actor->type == MT_CYBORG && dist > 160) dist = 160; if (P_Random () < dist) return false; return true; } // // P_Move // Move in the current direction, // returns false if the move is blocked. // const fixed_t xspeed[8] = {FRACUNIT,47000,0,-47000,-FRACUNIT,-47000,0,47000}; const fixed_t yspeed[8] = {0,47000,FRACUNIT,47000,0,-47000,-FRACUNIT,-47000}; qboolean P_Move (mobj_t* actor) { fixed_t tryx; fixed_t tryy; line_t* ld; // warning: 'catch', 'throw', and 'try' // are all C++ reserved words qboolean try_ok; qboolean good; if (actor->movedir == DI_NODIR) return false; if ((unsigned)actor->movedir >= 8) I_Error ("Weird actor->movedir!"); tryx = actor->x + actor->info->speed*xspeed[actor->movedir]; tryy = actor->y + actor->info->speed*yspeed[actor->movedir]; try_ok = P_TryMove (actor, tryx, tryy); if (!try_ok) { // open any specials if (actor->flags & MF_FLOAT && ::g->floatok) { // must adjust height if (actor->z < ::g->tmfloorz) actor->z += FLOATSPEED; else actor->z -= FLOATSPEED; actor->flags |= MF_INFLOAT; return true; } if (!::g->numspechit) return false; actor->movedir = DI_NODIR; good = false; while (::g->numspechit--) { ld = ::g->spechit[::g->numspechit]; // if the special is not a door // that can be opened, // return false if (P_UseSpecialLine (actor, ld,0)) good = true; } return good; } else { actor->flags &= ~MF_INFLOAT; } if (! (actor->flags & MF_FLOAT) ) actor->z = actor->floorz; return true; } // // TryWalk // Attempts to move actor on // in its current (ob->moveangle) direction. // If blocked by either a wall or an actor // returns FALSE // If move is either clear or blocked only by a door, // returns TRUE and sets... // If a door is in the way, // an OpenDoor call is made to start it opening. // qboolean P_TryWalk (mobj_t* actor) { if (!P_Move (actor)) { return false; } actor->movecount = P_Random()&15; return true; } void P_NewChaseDir (mobj_t* actor) { fixed_t deltax; fixed_t deltay; dirtype_t d[3]; int tdir; dirtype_t olddir; dirtype_t turnaround; if (!actor->target) I_Error ("P_NewChaseDir: called with no target"); olddir = (dirtype_t)actor->movedir; turnaround=opposite[olddir]; deltax = actor->target->x - actor->x; deltay = actor->target->y - actor->y; if (deltax>10*FRACUNIT) d[1]= DI_EAST; else if (deltax<-10*FRACUNIT) d[1]= DI_WEST; else d[1]=DI_NODIR; if (deltay<-10*FRACUNIT) d[2]= DI_SOUTH; else if (deltay>10*FRACUNIT) d[2]= DI_NORTH; else d[2]=DI_NODIR; // try direct route if (d[1] != DI_NODIR && d[2] != DI_NODIR) { actor->movedir = diags[((deltay<0)<<1)+(deltax>0)]; if (actor->movedir != turnaround && P_TryWalk(actor)) return; } // try other directions if (P_Random() > 200 || abs(deltay)>abs(deltax)) { tdir=d[1]; d[1]=d[2]; d[2]=(dirtype_t)tdir; } if (d[1]==turnaround) d[1]=DI_NODIR; if (d[2]==turnaround) d[2]=DI_NODIR; if (d[1]!=DI_NODIR) { actor->movedir = d[1]; if (P_TryWalk(actor)) { // either moved forward or attacked return; } } if (d[2]!=DI_NODIR) { actor->movedir =d[2]; if (P_TryWalk(actor)) return; } // there is no direct path to the player, // so pick another direction. if (olddir!=DI_NODIR) { actor->movedir =olddir; if (P_TryWalk(actor)) return; } // randomly determine direction of search if (P_Random()&1) { for ( tdir=DI_EAST; tdir<=DI_SOUTHEAST; tdir++ ) { if (tdir!=turnaround) { actor->movedir =tdir; if ( P_TryWalk(actor) ) return; } } } else { for ( tdir=DI_SOUTHEAST; tdir != (DI_EAST-1); tdir-- ) { if (tdir!=turnaround) { actor->movedir =tdir; if ( P_TryWalk(actor) ) return; } } } if (turnaround != DI_NODIR) { actor->movedir =turnaround; if ( P_TryWalk(actor) ) return; } actor->movedir = DI_NODIR; // can not move } // // P_LookForPlayers // If allaround is false, only look 180 degrees in front. // Returns true if a player is targeted. // qboolean P_LookForPlayers ( mobj_t* actor, qboolean allaround ) { int c; int stop; player_t* player; sector_t* sector; angle_t an; fixed_t dist; sector = actor->subsector->sector; c = 0; stop = (actor->lastlook-1)&3; for ( ; ; actor->lastlook = (actor->lastlook+1)&3 ) { if (!::g->playeringame[actor->lastlook]) continue; if (c++ == 2 || actor->lastlook == stop) { // done looking return false; } player = &::g->players[actor->lastlook]; if (player->health <= 0) continue; // dead if (!P_CheckSight (actor, player->mo)) continue; // out of sight if (!allaround) { an = R_PointToAngle2 (actor->x, actor->y, player->mo->x, player->mo->y) - actor->angle; if (an > ANG90 && an < ANG270) { dist = P_AproxDistance (player->mo->x - actor->x, player->mo->y - actor->y); // if real close, react anyway if (dist > MELEERANGE) continue; // behind back } } actor->target = player->mo; return true; } return false; } extern "C" { // // A_KeenDie // DOOM II special, map 32. // Uses special tag 666. // void A_KeenDie (mobj_t* mo, void * ) { thinker_t* th; mobj_t* mo2; line_t junk; A_Fall (mo, 0); // scan the remaining thinkers // to see if all Keens are dead for (th = ::g->thinkercap.next ; th != &::g->thinkercap ; th=th->next) { if (th->function.acp1 != (actionf_p1)P_MobjThinker) continue; mo2 = (mobj_t *)th; if (mo2 != mo && mo2->type == mo->type && mo2->health > 0) { // other Keen not dead return; } } junk.tag = 666; EV_DoDoor(&junk,opened); } // // ACTION ROUTINES // // // A_Look // Stay in state until a player is sighted. // void A_Look (mobj_t* actor, void * ) { mobj_t* targ; actor->threshold = 0; // any shot will wake up targ = actor->subsector->sector->soundtarget; if (targ && (targ->flags & MF_SHOOTABLE) ) { actor->target = targ; if ( actor->flags & MF_AMBUSH ) { if (P_CheckSight (actor, actor->target)) goto seeyou; } else goto seeyou; } if (!P_LookForPlayers (actor, false) ) return; // go into chase state seeyou: if (actor->info->seesound) { int sound; switch (actor->info->seesound) { case sfx_posit1: case sfx_posit2: case sfx_posit3: sound = sfx_posit1+P_Random()%3; break; case sfx_bgsit1: case sfx_bgsit2: sound = sfx_bgsit1+P_Random()%2; break; default: sound = actor->info->seesound; break; } if (actor->type==MT_SPIDER || actor->type == MT_CYBORG) { // full volume S_StartSound (NULL, sound); } else S_StartSound (actor, sound); } P_SetMobjState (actor, (statenum_t)actor->info->seestate); } // // A_Chase // Actor has a melee attack, // so it tries to close as fast as possible // void A_Chase (mobj_t* actor, void * ) { int delta; if (actor->reactiontime) actor->reactiontime--; // modify target threshold if (actor->threshold) { if (!actor->target || actor->target->health <= 0) { actor->threshold = 0; } else actor->threshold--; } // turn towards movement direction if not there yet if (actor->movedir < 8) { actor->angle &= (7<<29); delta = actor->angle - (actor->movedir << 29); if (delta > 0) actor->angle -= ANG90/2; else if (delta < 0) actor->angle += ANG90/2; } if (!actor->target || !(actor->target->flags&MF_SHOOTABLE)) { // look for a new target if (P_LookForPlayers(actor,true)) return; // got a new target P_SetMobjState (actor, (statenum_t)actor->info->spawnstate); return; } // do not attack twice in a row if (actor->flags & MF_JUSTATTACKED) { actor->flags &= ~MF_JUSTATTACKED; if (::g->gameskill != sk_nightmare && !::g->fastparm) P_NewChaseDir (actor); return; } // check for melee attack if (actor->info->meleestate && P_CheckMeleeRange (actor)) { if (actor->info->attacksound) S_StartSound (actor, actor->info->attacksound); P_SetMobjState (actor, (statenum_t)actor->info->meleestate); return; } // check for missile attack if (actor->info->missilestate) { if (::g->gameskill < sk_nightmare && !::g->fastparm && actor->movecount) { goto nomissile; } if (!P_CheckMissileRange (actor)) goto nomissile; P_SetMobjState (actor, (statenum_t)actor->info->missilestate); actor->flags |= MF_JUSTATTACKED; return; } // ? nomissile: // possibly choose another target if (::g->netgame && !actor->threshold && !P_CheckSight (actor, actor->target) ) { if (P_LookForPlayers(actor,true)) return; // got a new target } // chase towards player if (--actor->movecount<0 || !P_Move (actor)) { P_NewChaseDir (actor); } // make active sound if (actor->info->activesound && P_Random () < 3) { S_StartSound (actor, actor->info->activesound); } } // // A_FaceTarget // void A_FaceTarget (mobj_t* actor, void * ) { if (!actor->target) return; actor->flags &= ~MF_AMBUSH; actor->angle = R_PointToAngle2 (actor->x, actor->y, actor->target->x, actor->target->y); if (actor->target->flags & MF_SHADOW) actor->angle += (P_Random()-P_Random())<<21; } // // A_PosAttack // void A_PosAttack (mobj_t* actor, void * ) { int angle; int damage; int slope; if (!actor->target) return; A_FaceTarget (actor, 0); angle = actor->angle; slope = P_AimLineAttack (actor, angle, MISSILERANGE); S_StartSound (actor, sfx_pistol); angle += (P_Random()-P_Random())<<20; damage = ((P_Random()%5)+1)*3; P_LineAttack (actor, angle, MISSILERANGE, slope, damage); } void A_SPosAttack (mobj_t* actor, void * ) { int i; int angle; int bangle; int damage; int slope; if (!actor->target) return; S_StartSound (actor, sfx_shotgn); A_FaceTarget (actor, 0); bangle = actor->angle; slope = P_AimLineAttack (actor, bangle, MISSILERANGE); for (i=0 ; i<3 ; i++) { angle = bangle + ((P_Random()-P_Random())<<20); damage = ((P_Random()%5)+1)*3; P_LineAttack (actor, angle, MISSILERANGE, slope, damage); } } void A_CPosAttack (mobj_t* actor, void * ) { int angle; int bangle; int damage; int slope; if (!actor->target) return; S_StartSound (actor, sfx_shotgn); A_FaceTarget (actor, 0); bangle = actor->angle; slope = P_AimLineAttack (actor, bangle, MISSILERANGE); angle = bangle + ((P_Random()-P_Random())<<20); damage = ((P_Random()%5)+1)*3; P_LineAttack (actor, angle, MISSILERANGE, slope, damage); } void A_CPosRefire (mobj_t* actor, void * ) { // keep firing unless target got out of sight A_FaceTarget (actor, 0); if (P_Random () < 40) return; if (!actor->target || actor->target->health <= 0 || !P_CheckSight (actor, actor->target) ) { P_SetMobjState (actor, (statenum_t)actor->info->seestate); } } void A_SpidRefire (mobj_t* actor, void * ) { // keep firing unless target got out of sight A_FaceTarget (actor, 0); if (P_Random () < 10) return; if (!actor->target || actor->target->health <= 0 || !P_CheckSight (actor, actor->target) ) { P_SetMobjState (actor, (statenum_t)actor->info->seestate); } } void A_BspiAttack (mobj_t *actor, void * ) { if (!actor->target) return; A_FaceTarget (actor, 0); // launch a missile P_SpawnMissile (actor, actor->target, MT_ARACHPLAZ); } // // A_TroopAttack // void A_TroopAttack (mobj_t* actor, void * ) { int damage; if (!actor->target) return; A_FaceTarget (actor, 0); if (P_CheckMeleeRange (actor)) { S_StartSound (actor, sfx_claw); damage = (P_Random()%8+1)*3; P_DamageMobj (actor->target, actor, actor, damage); return; } // launch a missile P_SpawnMissile (actor, actor->target, MT_TROOPSHOT); } void A_SargAttack (mobj_t* actor, void * ) { int damage; if (!actor->target) return; A_FaceTarget (actor, 0); if (P_CheckMeleeRange (actor)) { damage = ((P_Random()%10)+1)*4; P_DamageMobj (actor->target, actor, actor, damage); } } void A_HeadAttack (mobj_t* actor, void * ) { int damage; if (!actor->target) return; A_FaceTarget (actor, 0); if (P_CheckMeleeRange (actor)) { damage = (P_Random()%6+1)*10; P_DamageMobj (actor->target, actor, actor, damage); return; } // launch a missile P_SpawnMissile (actor, actor->target, MT_HEADSHOT); } void A_CyberAttack (mobj_t* actor, void * ) { if (!actor->target) return; A_FaceTarget (actor, 0); P_SpawnMissile (actor, actor->target, MT_ROCKET); } void A_BruisAttack (mobj_t* actor, void * ) { int damage; if (!actor->target) return; if (P_CheckMeleeRange (actor)) { S_StartSound (actor, sfx_claw); damage = (P_Random()%8+1)*10; P_DamageMobj (actor->target, actor, actor, damage); return; } // launch a missile P_SpawnMissile (actor, actor->target, MT_BRUISERSHOT); } // // A_SkelMissile // void A_SkelMissile (mobj_t* actor, void * ) { mobj_t* mo; if (!actor->target) return; A_FaceTarget (actor, 0); actor->z += 16*FRACUNIT; // so missile spawns higher mo = P_SpawnMissile (actor, actor->target, MT_TRACER); actor->z -= 16*FRACUNIT; // back to normal mo->x += mo->momx; mo->y += mo->momy; mo->tracer = actor->target; } void A_Tracer (mobj_t* actor, void * ) { angle_t exact; fixed_t dist; fixed_t slope; mobj_t* dest; mobj_t* th; //if (::g->gametic & 3) //return; // DHM - Nerve :: Demo fix - Keep the game state deterministic!!! if ( ::g->leveltime & 3 ) { return; } // spawn a puff of smoke behind the rocket P_SpawnPuff (actor->x, actor->y, actor->z); th = P_SpawnMobj (actor->x-actor->momx, actor->y-actor->momy, actor->z, MT_SMOKE); th->momz = FRACUNIT; th->tics -= P_Random()&3; if (th->tics < 1) th->tics = 1; // adjust direction dest = actor->tracer; if (!dest || dest->health <= 0) return; // change angle exact = R_PointToAngle2 (actor->x, actor->y, dest->x, dest->y); if (exact != actor->angle) { if (exact - actor->angle > 0x80000000) { actor->angle -= ::g->TRACEANGLE; if (exact - actor->angle < 0x80000000) actor->angle = exact; } else { actor->angle += ::g->TRACEANGLE; if (exact - actor->angle > 0x80000000) actor->angle = exact; } } exact = actor->angle>>ANGLETOFINESHIFT; actor->momx = FixedMul (actor->info->speed, finecosine[exact]); actor->momy = FixedMul (actor->info->speed, finesine[exact]); // change slope dist = P_AproxDistance (dest->x - actor->x, dest->y - actor->y); dist = dist / actor->info->speed; if (dist < 1) dist = 1; slope = (dest->z+40*FRACUNIT - actor->z) / dist; if (slope < actor->momz) actor->momz -= FRACUNIT/8; else actor->momz += FRACUNIT/8; } void A_SkelWhoosh (mobj_t* actor, void * ) { if (!actor->target) return; A_FaceTarget (actor, 0); S_StartSound (actor,sfx_skeswg); } void A_SkelFist (mobj_t* actor, void * ) { int damage; if (!actor->target) return; A_FaceTarget (actor, 0); if (P_CheckMeleeRange (actor)) { damage = ((P_Random()%10)+1)*6; S_StartSound (actor, sfx_skepch); P_DamageMobj (actor->target, actor, actor, damage); } } // // PIT_VileCheck // Detect a corpse that could be raised. // qboolean PIT_VileCheck (mobj_t* thing ) { int maxdist; qboolean check; if (!(thing->flags & MF_CORPSE) ) return true; // not a monster if (thing->tics != -1) return true; // not lying still yet if (thing->info->raisestate == S_NULL) return true; // monster doesn't have a raise state maxdist = thing->info->radius + mobjinfo[MT_VILE].radius; if ( abs(thing->x - ::g->viletryx) > maxdist || abs(thing->y - ::g->viletryy) > maxdist ) return true; // not actually touching ::g->corpsehit = thing; ::g->corpsehit->momx = ::g->corpsehit->momy = 0; ::g->corpsehit->height <<= 2; check = P_CheckPosition (::g->corpsehit, ::g->corpsehit->x, ::g->corpsehit->y); ::g->corpsehit->height >>= 2; if (!check) return true; // doesn't fit here return false; // got one, so stop checking } // // A_VileChase // Check for ressurecting a body // void A_VileChase (mobj_t* actor, void * ) { int xl; int xh; int yl; int yh; int bx; int by; const mobjinfo_t* info; mobj_t* temp; if (actor->movedir != DI_NODIR) { // check for corpses to raise ::g->viletryx = actor->x + actor->info->speed*xspeed[actor->movedir]; ::g->viletryy = actor->y + actor->info->speed*yspeed[actor->movedir]; xl = (::g->viletryx - ::g->bmaporgx - MAXRADIUS*2)>>MAPBLOCKSHIFT; xh = (::g->viletryx - ::g->bmaporgx + MAXRADIUS*2)>>MAPBLOCKSHIFT; yl = (::g->viletryy - ::g->bmaporgy - MAXRADIUS*2)>>MAPBLOCKSHIFT; yh = (::g->viletryy - ::g->bmaporgy + MAXRADIUS*2)>>MAPBLOCKSHIFT; ::g->vileobj = actor; for (bx=xl ; bx<=xh ; bx++) { for (by=yl ; by<=yh ; by++) { // Call PIT_VileCheck to check // whether object is a corpse // that canbe raised. if (!P_BlockThingsIterator(bx,by,PIT_VileCheck)) { // got one! temp = actor->target; actor->target = ::g->corpsehit; A_FaceTarget (actor, 0); actor->target = temp; P_SetMobjState (actor, S_VILE_HEAL1); S_StartSound (::g->corpsehit, sfx_slop); info = ::g->corpsehit->info; P_SetMobjState (::g->corpsehit,(statenum_t)info->raisestate); ::g->corpsehit->height <<= 2; ::g->corpsehit->flags = info->flags; ::g->corpsehit->health = info->spawnhealth; ::g->corpsehit->target = NULL; return; } } } } // Return to normal attack. A_Chase (actor, 0); } // // A_VileStart // void A_VileStart (mobj_t* actor, void * ) { S_StartSound (actor, sfx_vilatk); } // // A_Fire // Keep fire in front of player unless out of sight // void A_Fire (mobj_t* actor, void * ); void A_StartFire (mobj_t* actor, void * ) { S_StartSound(actor,sfx_flamst); A_Fire(actor, 0 ); } void A_FireCrackle (mobj_t* actor, void * ) { S_StartSound(actor,sfx_flame); A_Fire(actor, 0); } void A_Fire (mobj_t* actor, void * ) { mobj_t* dest; unsigned an; dest = actor->tracer; if (!dest) return; // don't move it if the vile lost sight if (!P_CheckSight (actor->target, dest) ) return; an = dest->angle >> ANGLETOFINESHIFT; P_UnsetThingPosition (actor); actor->x = dest->x + FixedMul (24*FRACUNIT, finecosine[an]); actor->y = dest->y + FixedMul (24*FRACUNIT, finesine[an]); actor->z = dest->z; P_SetThingPosition (actor); } // // A_VileTarget // Spawn the hellfire // void A_VileTarget (mobj_t* actor, void * ) { mobj_t* fog; if (!actor->target) return; A_FaceTarget (actor, 0); fog = P_SpawnMobj (actor->target->x, actor->target->x, actor->target->z, MT_FIRE); actor->tracer = fog; fog->target = actor; fog->tracer = actor->target; A_Fire (fog, 0); } // // A_VileAttack // void A_VileAttack (mobj_t* actor, void * ) { mobj_t* fire; int an; if (!actor->target) return; A_FaceTarget (actor, 0); if (!P_CheckSight (actor, actor->target) ) return; S_StartSound (actor, sfx_barexp); P_DamageMobj (actor->target, actor, actor, 20); actor->target->momz = 1000*FRACUNIT/actor->target->info->mass; an = actor->angle >> ANGLETOFINESHIFT; fire = actor->tracer; if (!fire) return; // move the fire between the vile and the player fire->x = actor->target->x - FixedMul (24*FRACUNIT, finecosine[an]); fire->y = actor->target->y - FixedMul (24*FRACUNIT, finesine[an]); P_RadiusAttack (fire, actor, 70 ); } // // Mancubus attack, // firing three missiles (bruisers) // in three different directions? // Doesn't look like it. // void A_FatRaise (mobj_t *actor, void * ) { A_FaceTarget (actor, 0); S_StartSound (actor, sfx_manatk); } void A_FatAttack1 (mobj_t* actor, void * ) { mobj_t* mo; int an; A_FaceTarget (actor, 0); // Change direction to ... actor->angle += FATSPREAD; P_SpawnMissile (actor, actor->target, MT_FATSHOT); mo = P_SpawnMissile (actor, actor->target, MT_FATSHOT); mo->angle += FATSPREAD; an = mo->angle >> ANGLETOFINESHIFT; mo->momx = FixedMul (mo->info->speed, finecosine[an]); mo->momy = FixedMul (mo->info->speed, finesine[an]); } void A_FatAttack2 (mobj_t* actor, void * ) { mobj_t* mo; int an; A_FaceTarget (actor, 0); // Now here choose opposite deviation. actor->angle -= FATSPREAD; P_SpawnMissile (actor, actor->target, MT_FATSHOT); mo = P_SpawnMissile (actor, actor->target, MT_FATSHOT); mo->angle -= FATSPREAD*2; an = mo->angle >> ANGLETOFINESHIFT; mo->momx = FixedMul (mo->info->speed, finecosine[an]); mo->momy = FixedMul (mo->info->speed, finesine[an]); } void A_FatAttack3 (mobj_t* actor, void * ) { mobj_t* mo; int an; A_FaceTarget (actor, 0); mo = P_SpawnMissile (actor, actor->target, MT_FATSHOT); mo->angle -= FATSPREAD/2; an = mo->angle >> ANGLETOFINESHIFT; mo->momx = FixedMul (mo->info->speed, finecosine[an]); mo->momy = FixedMul (mo->info->speed, finesine[an]); mo = P_SpawnMissile (actor, actor->target, MT_FATSHOT); mo->angle += FATSPREAD/2; an = mo->angle >> ANGLETOFINESHIFT; mo->momx = FixedMul (mo->info->speed, finecosine[an]); mo->momy = FixedMul (mo->info->speed, finesine[an]); } // // SkullAttack // Fly at the player like a missile. // void A_SkullAttack (mobj_t* actor, void * ) { mobj_t* dest; angle_t an; int dist; if (!actor->target) return; dest = actor->target; actor->flags |= MF_SKULLFLY; S_StartSound (actor, actor->info->attacksound); A_FaceTarget (actor, 0); an = actor->angle >> ANGLETOFINESHIFT; actor->momx = FixedMul (SKULLSPEED, finecosine[an]); actor->momy = FixedMul (SKULLSPEED, finesine[an]); dist = P_AproxDistance (dest->x - actor->x, dest->y - actor->y); dist = dist / SKULLSPEED; if (dist < 1) dist = 1; actor->momz = (dest->z+(dest->height>>1) - actor->z) / dist; } // // A_PainShootSkull // Spawn a lost soul and launch it at the target // void A_PainShootSkull ( mobj_t* actor, angle_t angle ) { fixed_t x; fixed_t y; fixed_t z; mobj_t* newmobj; angle_t an; int prestep; int count; thinker_t* currentthinker; // count total number of skull currently on the level count = 0; currentthinker = ::g->thinkercap.next; while (currentthinker != &::g->thinkercap) { if ( (currentthinker->function.acp1 == (actionf_p1)P_MobjThinker) && ((mobj_t *)currentthinker)->type == MT_SKULL) count++; currentthinker = currentthinker->next; } // if there are allready 20 skulls on the level, // don't spit another one if (count > 20) return; // okay, there's playe for another one an = angle >> ANGLETOFINESHIFT; prestep = 4*FRACUNIT + 3*(actor->info->radius + mobjinfo[MT_SKULL].radius)/2; x = actor->x + FixedMul (prestep, finecosine[an]); y = actor->y + FixedMul (prestep, finesine[an]); z = actor->z + 8*FRACUNIT; newmobj = P_SpawnMobj (x , y, z, MT_SKULL); // Check for movements. if (!P_TryMove (newmobj, newmobj->x, newmobj->y)) { // kill it immediately P_DamageMobj (newmobj,actor,actor,10000); return; } newmobj->target = actor->target; A_SkullAttack (newmobj, 0); } // // A_PainAttack // Spawn a lost soul and launch it at the target // void A_PainAttack (mobj_t* actor, void * ) { if (!actor->target) return; A_FaceTarget (actor, 0); A_PainShootSkull (actor, actor->angle); } void A_PainDie (mobj_t* actor, void * ) { A_Fall (actor, 0); A_PainShootSkull (actor, actor->angle+ANG90); A_PainShootSkull (actor, actor->angle+ANG180); A_PainShootSkull (actor, actor->angle+ANG270); } void A_Scream (mobj_t* actor, void * ) { int sound; switch (actor->info->deathsound) { case 0: return; case sfx_podth1: case sfx_podth2: case sfx_podth3: sound = sfx_podth1 + P_Random ()%3; break; case sfx_bgdth1: case sfx_bgdth2: sound = sfx_bgdth1 + P_Random ()%2; break; default: sound = actor->info->deathsound; break; } // Check for bosses. if (actor->type==MT_SPIDER || actor->type == MT_CYBORG) { // full volume S_StartSound (NULL, sound); } else S_StartSound (actor, sound); } void A_XScream (mobj_t* actor, void * ) { S_StartSound (actor, sfx_slop); } void A_Pain (mobj_t* actor, void * ) { if (actor->info->painsound ) S_StartSound (actor, actor->info->painsound); } void A_Fall (mobj_t *actor, void * ) { // actor is on ground, it can be walked over actor->flags &= ~MF_SOLID; // So change this if corpse objects // are meant to be obstacles. } // // A_Explode // void A_Explode (mobj_t* thingy, void * ) { P_RadiusAttack ( thingy, thingy->target, 128 ); } // // A_BossDeath // Possibly trigger special effects // if on first boss level // void A_BossDeath (mobj_t* mo, void * ) { thinker_t* th; mobj_t* mo2; line_t junk; int i; if ( ::g->gamemode == commercial) { if (::g->gamemap != 7) return; if ((mo->type != MT_FATSO) && (mo->type != MT_BABY)) return; } else { switch(::g->gameepisode) { case 1: if (::g->gamemap != 8) return; if (mo->type != MT_BRUISER) return; break; case 2: if (::g->gamemap != 8) return; if (mo->type != MT_CYBORG) return; break; case 3: if (::g->gamemap != 8) return; if (mo->type != MT_SPIDER) return; break; case 4: switch(::g->gamemap) { case 6: if (mo->type != MT_CYBORG) return; break; case 8: if (mo->type != MT_SPIDER) return; break; default: return; break; } break; default: if (::g->gamemap != 8) return; break; } } // make sure there is a player alive for victory for (i=0 ; i<MAXPLAYERS ; i++) if (::g->playeringame[i] && ::g->players[i].health > 0) break; if (i==MAXPLAYERS) return; // no one left alive, so do not end game // scan the remaining thinkers to see // if all bosses are dead for (th = ::g->thinkercap.next ; th != &::g->thinkercap ; th=th->next) { if (th->function.acp1 != (actionf_p1)P_MobjThinker) continue; mo2 = (mobj_t *)th; if (mo2 != mo && mo2->type == mo->type && mo2->health > 0) { // other boss not dead return; } } // victory! if ( ::g->gamemode == commercial) { if (::g->gamemap == 7) { if (mo->type == MT_FATSO) { junk.tag = 666; EV_DoFloor(&junk,lowerFloorToLowest); return; } if (mo->type == MT_BABY) { junk.tag = 667; EV_DoFloor(&junk,raiseToTexture); return; } } } else { switch(::g->gameepisode) { case 1: junk.tag = 666; EV_DoFloor (&junk, lowerFloorToLowest); return; break; case 4: switch(::g->gamemap) { case 6: junk.tag = 666; EV_DoDoor (&junk, blazeOpen); return; break; case 8: junk.tag = 666; EV_DoFloor (&junk, lowerFloorToLowest); return; break; } } } G_ExitLevel (); } void A_Hoof (mobj_t* mo, void * ) { S_StartSound (mo, sfx_hoof); A_Chase (mo, 0); } void A_Metal (mobj_t* mo, void * ) { S_StartSound (mo, sfx_metal); A_Chase (mo, 0); } void A_BabyMetal (mobj_t* mo, void * ) { S_StartSound (mo, sfx_bspwlk); A_Chase (mo, 0); } void A_OpenShotgun2 ( player_t* player, pspdef_t* psp ) { if (globalNetworking || (player == &::g->players[::g->consoleplayer])) S_StartSound (player->mo, sfx_dbopn); } void A_LoadShotgun2 ( player_t* player, pspdef_t* psp ) { if (globalNetworking || (player == &::g->players[::g->consoleplayer])) S_StartSound (player->mo, sfx_dbload); } void A_ReFire ( player_t* player, pspdef_t* psp ); void A_CloseShotgun2 ( player_t* player, pspdef_t* psp ) { if (globalNetworking || (player == &::g->players[::g->consoleplayer])) S_StartSound (player->mo, sfx_dbcls); A_ReFire(player,psp); } void A_BrainAwake (mobj_t* mo, void * ) { thinker_t* thinker; mobj_t* m; // find all the target spots ::g->easy = 0; ::g->numbraintargets = 0; ::g->braintargeton = 0; thinker = ::g->thinkercap.next; for (thinker = ::g->thinkercap.next ; thinker != &::g->thinkercap ; thinker = thinker->next) { if (thinker->function.acp1 != (actionf_p1)P_MobjThinker) continue; // not a mobj m = (mobj_t *)thinker; if (m->type == MT_BOSSTARGET ) { ::g->braintargets[::g->numbraintargets] = m; ::g->numbraintargets++; } } S_StartSound (NULL,sfx_bossit); } void A_BrainPain (mobj_t* mo, void * ) { S_StartSound (NULL,sfx_bospn); } void A_BrainScream (mobj_t* mo, void * ) { int x; int y; int z; mobj_t* th; for (x=mo->x - 196*FRACUNIT ; x< mo->x + 320*FRACUNIT ; x+= FRACUNIT*8) { y = mo->y - 320*FRACUNIT; z = 128 + P_Random()*2*FRACUNIT; th = P_SpawnMobj (x,y,z, MT_ROCKET); th->momz = P_Random()*512; P_SetMobjState (th, S_BRAINEXPLODE1); th->tics -= P_Random()&7; if (th->tics < 1) th->tics = 1; } S_StartSound (NULL,sfx_bosdth); } void A_BrainExplode (mobj_t* mo, void * ) { int x; int y; int z; mobj_t* th; x = mo->x + (P_Random () - P_Random ())*2048; y = mo->y; z = 128 + P_Random()*2*FRACUNIT; th = P_SpawnMobj (x,y,z, MT_ROCKET); th->momz = P_Random()*512; P_SetMobjState (th, S_BRAINEXPLODE1); th->tics -= P_Random()&7; if (th->tics < 1) th->tics = 1; } void A_BrainDie (mobj_t* mo, void * ) { G_ExitLevel (); } void A_BrainSpit (mobj_t* mo, void * ) { mobj_t* targ; mobj_t* newmobj; ::g->easy ^= 1; if (::g->gameskill <= sk_easy && (!::g->easy)) return; if ( 1 ) { // count number of thinkers int numCorpse = 0; int numEnemies = 0; for ( thinker_t* th = ::g->thinkercap.next; th != &::g->thinkercap; th = th->next ) { if ( th->function.acp1 == (actionf_p1)P_MobjThinker ) { mobj_t* obj = (mobj_t*)th; if ( obj->flags & MF_CORPSE ) { numCorpse++; } else if ( obj->type > MT_PLAYER && obj->type < MT_KEEN ) { numEnemies++; } } } if ( numCorpse > 48 ) { for ( int i = 0; i < 12; i++ ) { for ( thinker_t* th = ::g->thinkercap.next; th != &::g->thinkercap; th = th->next ) { if ( th->function.acp1 == (actionf_p1)P_MobjThinker ) { mobj_t* obj = (mobj_t*)th; if ( obj->flags & MF_CORPSE ) { P_RemoveMobj( obj ); break; } } } } } if ( numEnemies > 32 ) { return; } } // shoot a cube at current target targ = ::g->braintargets[::g->braintargeton]; ::g->braintargeton = (::g->braintargeton+1) % ::g->numbraintargets; // spawn brain missile newmobj = P_SpawnMissile (mo, targ, MT_SPAWNSHOT); newmobj->target = targ; newmobj->reactiontime = ((targ->y - mo->y)/newmobj->momy) / newmobj->state->tics; S_StartSound(NULL, sfx_bospit); } void A_SpawnFly (mobj_t* mo, void * ); // travelling cube sound void A_SpawnSound (mobj_t* mo, void * ) { S_StartSound (mo,sfx_boscub); A_SpawnFly(mo, 0); } void A_SpawnFly (mobj_t* mo, void * ) { mobj_t* newmobj; mobj_t* fog; mobj_t* targ; int r; mobjtype_t type; if (--mo->reactiontime) return; // still flying targ = mo->target; // First spawn teleport fog. fog = P_SpawnMobj (targ->x, targ->y, targ->z, MT_SPAWNFIRE); S_StartSound (fog, sfx_telept); // Randomly select monster to spawn. r = P_Random (); // Probability distribution (kind of :), // decreasing likelihood. if ( r<50 ) type = MT_TROOP; else if (r<90) type = MT_SERGEANT; else if (r<120) type = MT_SHADOWS; else if (r<130) type = MT_PAIN; else if (r<160) type = MT_HEAD; else if (r<162) type = MT_VILE; else if (r<172) type = MT_UNDEAD; else if (r<192) type = MT_BABY; else if (r<222) type = MT_FATSO; else if (r<246) type = MT_KNIGHT; else type = MT_BRUISER; newmobj = P_SpawnMobj (targ->x, targ->y, targ->z, type); if (P_LookForPlayers (newmobj, true) ) P_SetMobjState (newmobj, (statenum_t)newmobj->info->seestate); // telefrag anything in this spot P_TeleportMove (newmobj, newmobj->x, newmobj->y); // remove self (i.e., cube). P_RemoveMobj (mo); } void A_PlayerScream (mobj_t* mo, void * ) { // Default death sound. int sound = sfx_pldeth; if ( (::g->gamemode == commercial) && (mo->health < -50)) { // IF THE PLAYER DIES // LESS THAN -50% WITHOUT GIBBING sound = sfx_pdiehi; } if ( ::g->demoplayback || globalNetworking || (mo == ::g->players[::g->consoleplayer].mo)) S_StartSound (mo, sound); } }; // extern "C"
19.413997
366
0.595796
1337programming
fc46f81abc7ae8be166f4cabead98178c3e38f0a
7,157
cpp
C++
source/NanairoCore/Color/spectral_transport.cpp
byzin/Nanairo
23fb6deeec73509c538a9c21009e12be63e8d0e4
[ "MIT" ]
30
2015-09-06T03:14:29.000Z
2021-06-18T11:00:19.000Z
source/NanairoCore/Color/spectral_transport.cpp
byzin/Nanairo
23fb6deeec73509c538a9c21009e12be63e8d0e4
[ "MIT" ]
31
2016-01-14T14:50:34.000Z
2018-06-25T13:21:48.000Z
source/NanairoCore/Color/spectral_transport.cpp
byzin/Nanairo
23fb6deeec73509c538a9c21009e12be63e8d0e4
[ "MIT" ]
6
2017-04-09T13:07:47.000Z
2021-05-29T21:17:34.000Z
/*! \file spectral_transport.cpp \author Sho Ikeda Copyright (c) 2015-2018 Sho Ikeda This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ #include "spectral_transport.hpp" // Standard C++ library #include <cmath> #include <vector> // Zisc #include "zisc/arith_array.hpp" #include "zisc/error.hpp" #include "zisc/matrix.hpp" #include "zisc/memory_resource.hpp" #include "zisc/utility.hpp" // Nanairo #include "color.hpp" #include "color_conversion.hpp" #include "xyz_color.hpp" #include "xyz_color_matching_function.hpp" #include "yxy_color.hpp" #include "NanairoCore/nanairo_core_config.hpp" #include "NanairoCore/Color/SpectralTransportParameter/spectral_transport_parameters.hpp" #include "SpectralDistribution/spectral_distribution.hpp" namespace nanairo { /*! */ constexpr std::array<int, 2> SpectralTransport::gridResolution() noexcept { using zisc::cast; return std::array<int, 2>{{cast<int>(spectral_transport::kGridResolution[0]), cast<int>(spectral_transport::kGridResolution[1])}}; } /*! */ constexpr int SpectralTransport::gridSize() noexcept { using zisc::cast; return cast<int>(spectral_transport::kGridResolution[0] * spectral_transport::kGridResolution[1]); } /*! */ void SpectralTransport::toSpectra( const XyzColor& xyz, SpectralDistribution* spectra, zisc::pmr::memory_resource* work_resource) noexcept { using zisc::cast; const auto yxy = ColorConversion::toYxy(xyz); const auto uv = toUv(yxy); // Rotate to align with grid constexpr auto grid_res = gridResolution(); if (zisc::isInBounds(uv[0], 0.0, cast<Float>(grid_res[0])) && zisc::isInBounds(uv[1], 0.0, cast<Float>(grid_res[1]))) { std::array<int, 2> uvi{{cast<int>(uv[0]), cast<int>(uv[1])}}; const int cell_index = uvi[0] + grid_res[0] * uvi[1]; ZISC_ASSERT(zisc::isInBounds(cell_index, 0, gridSize()), "The cell index is out of range."); for (uint i = 0; i < spectra->size(); ++i) { const uint16 lambda = spectra->getWavelength(i); Float spectrum = toSpectrum(lambda, cell_index, uv, work_resource); // Now we have a spectrum which corresponds to the xy chromaticities of the input. // Need to scale according to the input brightness X+Y+Z now spectrum = spectrum * (xyz.x() + xyz.y() + xyz.z()); // The division by equal energy reflectance is here to make sure // that xyz = (1, 1, 1) maps to a spectrum that is constant 1. spectrum = spectrum * spectral_transport::kInvEqualEnergyReflectance; spectra->set(i, spectrum); } } } /*! */ inline zisc::ArithArray<Float, 3> SpectralTransport::hom( const zisc::ArithArray<Float, 2>& x) noexcept { return zisc::ArithArray<Float, 3>{x[0], x[1], 1.0}; } /*! */ inline zisc::ArithArray<Float, 2> SpectralTransport::dehom( const zisc::ArithArray<Float, 3>& x) noexcept { return zisc::ArithArray<Float, 2>{x[0] / x[2], x[1] / x[2]}; } /*! */ Float SpectralTransport::toSpectrum( const uint16 lambda, const int cell_index, const UvColor& uv, zisc::pmr::memory_resource* work_resource) noexcept { using zisc::cast; const auto& cell = spectral_transport::kGrid[cell_index]; // Get Linearly interpolated spectral power for the corner vertices. zisc::pmr::vector<Float> p{work_resource}; p.resize(cell.num_points_, 0.0); // This clamping is only necessary if lambda is not sure to be [min, max]. constexpr int spectra_size = cast<int>(CoreConfig::spectraSize()); const Float sb = cast<Float>(lambda - CoreConfig::shortestWavelength()) / cast<Float>(CoreConfig::longestWavelength()-CoreConfig::shortestWavelength()) * cast<Float>(spectra_size - 1); const int sb0 = cast<int>(sb); const int sb1 = (sb0 + 1 < spectra_size) ? sb0 + 1 : sb0; ZISC_ASSERT(zisc::isInBounds(sb0, 0, spectra_size), "The sb0 is out of range."); ZISC_ASSERT(zisc::isInBounds(sb1, 0, spectra_size), "The sb1 is out of range."); const Float sbf = sb - cast<Float>(sb0); for (int i = 0; i < cast<int>(p.size()); ++i) { ZISC_ASSERT(0 <= cell.indices_[i], "The index is minus."); const auto& point = spectral_transport::kDataPoints[cell.indices_[i]]; p[i] = (1.0 - sbf) * point.spectra_[sb0] + sbf * point.spectra_[sb1]; } Float interpolated_p = 0.0; if (cell.inside_) { // fast path for normal inner quads const UvColor uvf{uv[0] - std::floor(uv[0]), uv[1] - std::floor(uv[1])}; ZISC_ASSERT(zisc::isInBounds(uvf[0], 0.0, 1.0), "The uvf[0] is out of range."); ZISC_ASSERT(zisc::isInBounds(uvf[1], 0.0, 1.0), "The uvf[1] is out of range."); // The layout of the vertices in the quad is: // 2 3 // 0 1 interpolated_p = p[0] * (1.0 - uvf[0]) * (1.0 - uvf[1]) + p[2] * (1.0 - uvf[0]) * uvf[1] + p[3] * uvf[0] * uvf[1] + p[1] * uvf[0] * (1.0 - uvf[1]); } else { // Need to go through triangulation // We get the indices in such an order that they form a triangle fan around idx[0] // Compute barycentric coordinates of our xy* point for all triangles in the fan: const auto& point0 = spectral_transport::kDataPoints[cell.indices_[0]]; const auto& point1 = spectral_transport::kDataPoints[cell.indices_[1]]; const auto e = uv.data() - point0.uv_.data(); auto e0 = point1.uv_.data() - point0.uv_.data(); Float uu = e0[0] * e[1] - e[0] * e0[1]; for (int i = 0; i < cast<int>(cell.num_points_ - 1); ++i) { zisc::ArithArray<Float, 2> e1{0.0, 0.0}; if (i == cast<int>(cell.num_points_ - 2)) // Close the circle e1 = point1.uv_.data() - point0.uv_.data(); else e1 = spectral_transport::kDataPoints[cell.indices_[i + 2]].uv_.data() - point0.uv_.data(); const Float vv = e[0] * e1[1] - e1[0] * e[1]; //! \todo with some sign magic, this division could be deferred to the last iteration! const Float area = e0[0] * e1[1] - e1[0] * e0[1]; // normalize const Float u = uu / area; const Float v = vv / area; const Float w = 1.0 - (u + v); if ((u < 0.0) || (v < 0.0) || (w < 0.0)) { uu = -vv; e0 = e1; continue; } // This seems to be triangle we've been looking for . interpolated_p = p[0] * w + p[i + 1] * v + p[(i == cast<int>(cell.num_points_ - 2)) ? 1 : (i+2)] * u; break; } } return interpolated_p; } /*! */ inline auto SpectralTransport::toUv(const YxyColor& yxy) noexcept -> UvColor { zisc::Matrix<Float, 3, 1> v3{yxy.x(), yxy.y(), 1.0}; const auto v2 = spectral_transport::kToUvFromXy * v3; return UvColor{v2(0, 0), v2(1, 0)}; } /*! */ inline auto SpectralTransport::toXystar(const YxyColor& yxy) noexcept -> XystarColor { zisc::Matrix<Float, 3, 1> v3{yxy.x(), yxy.y(), 1.0}; const auto v2 = spectral_transport::kToXystarFromXy * v3; return XystarColor{v2(0, 0), v2(1, 0)}; } } // namespace nanairo
34.244019
98
0.623585
byzin
fc491731ed86969ef7c98516499272f89a2775e6
751
cpp
C++
LeetCode/Check If It Is a Straight Line.cpp
Rupali409/CPP-Questions-and-Solutions
a42664302f18b7d99aac2501bcf956950e3cc61a
[ "MIT" ]
42
2021-09-26T18:02:52.000Z
2022-03-15T01:52:15.000Z
LeetCode/Check If It Is a Straight Line.cpp
Rupali409/CPP-Questions-and-Solutions
a42664302f18b7d99aac2501bcf956950e3cc61a
[ "MIT" ]
404
2021-09-24T19:55:10.000Z
2021-11-03T05:47:47.000Z
LeetCode/Check If It Is a Straight Line.cpp
Rupali409/CPP-Questions-and-Solutions
a42664302f18b7d99aac2501bcf956950e3cc61a
[ "MIT" ]
140
2021-09-22T20:50:04.000Z
2022-01-22T16:59:09.000Z
//1232. Check If It Is a Straight Line //https://leetcode.com/problems/check-if-it-is-a-straight-line/ class Solution { public: bool checkStraightLine(vector<vector<int>>& coordinates) { //if points are two then return true if(coordinates.size()==2) return true; else{ int x1=coordinates[0][0],x2=coordinates[1][0],y1=coordinates[0] [1],y2=coordinates[1][1]; for(int i=2;i<coordinates.size();i++){ int x= coordinates[i][0]; int y= coordinates[i][1]; //this is equation of line every points should satisfies this if((y-y1)*(x2-x1)!=(y2-y1)*(x-x1)) return false; } } return true; } };
34.136364
107
0.54727
Rupali409
fc54ebae2d6bc709d29b0f08c882c3a4bb9d7360
9,852
cxx
C++
bpkg/manifest-utility.cxx
build2/bpkg
bd939839b44d90d027517e447537dd52539269ff
[ "MIT" ]
19
2018-05-30T12:01:25.000Z
2022-01-29T21:37:23.000Z
bpkg/manifest-utility.cxx
build2/bpkg
bd939839b44d90d027517e447537dd52539269ff
[ "MIT" ]
2
2019-03-18T22:31:45.000Z
2020-07-28T06:44:03.000Z
bpkg/manifest-utility.cxx
build2/bpkg
bd939839b44d90d027517e447537dd52539269ff
[ "MIT" ]
1
2019-02-04T02:58:14.000Z
2019-02-04T02:58:14.000Z
// file : bpkg/manifest-utility.cxx -*- C++ -*- // license : MIT; see accompanying LICENSE file #include <bpkg/manifest-utility.hxx> #include <cstring> // strcspn() #include <libbutl/b.hxx> #include <libbutl/sha256.hxx> #include <bpkg/package.hxx> // wildcard_version #include <bpkg/diagnostics.hxx> #include <bpkg/common-options.hxx> using namespace std; using namespace butl; namespace bpkg { const path repositories_file ("repositories.manifest"); const path packages_file ("packages.manifest"); const path signature_file ("signature.manifest"); const path manifest_file ("manifest"); vector<package_info> package_b_info (const common_options& o, const dir_paths& ds, bool ext_mods) { path b (name_b (o)); vector<package_info> r; try { b_info (r, ds, ext_mods, verb, [] (const char* const args[], size_t n) { if (verb >= 2) print_process (args, n); }, b, exec_dir, o.build_option ()); return r; } catch (const b_error& e) { if (e.normal ()) throw failed (); // Assume the build2 process issued diagnostics. diag_record dr (fail); dr << "unable to parse project "; if (r.size () < ds.size ()) dr << ds[r.size ()] << ' '; dr << "info: " << e << info << "produced by '" << b << "'; use --build to override" << endf; } } package_scheme parse_package_scheme (const char*& s) { // Ignore the character case for consistency with a case insensitivity of // URI schemes some of which we may support in the future. // if (icasecmp (s, "sys:", 4) == 0) { s += 4; return package_scheme::sys; } return package_scheme::none; } package_name parse_package_name (const char* s, bool allow_version) { try { return extract_package_name (s, allow_version); } catch (const invalid_argument& e) { fail << "invalid package name " << (allow_version ? "in " : "") << "'" << s << "': " << e << endf; } } version parse_package_version (const char* s, bool allow_wildcard, version::flags fl) { using traits = string::traits_type; if (const char* p = traits::find (s, traits::length (s), '/')) { if (*++p == '\0') fail << "empty package version in '" << s << "'"; if (allow_wildcard && strcmp (p, "*") == 0) return wildcard_version; try { return extract_package_version (s, fl); } catch (const invalid_argument& e) { fail << "invalid package version '" << p << "' in '" << s << "': " << e; } } return version (); } optional<version_constraint> parse_package_version_constraint (const char* s, bool allow_wildcard, version::flags fl, bool version_only) { // Calculate the version specification position as a length of the prefix // that doesn't contain slashes and the version constraint starting // characters. // size_t n (strcspn (s, "/=<>([~^")); if (s[n] == '\0') // No version (constraint) is specified? return nullopt; const char* v (s + n); // Constraint or version including '/'. // If only the version is allowed or the package name is followed by '/' // then fallback to the version parsing. // if (version_only || v[0] == '/') try { return version_constraint ( parse_package_version (s, allow_wildcard, fl)); } catch (const invalid_argument& e) { fail << "invalid package version '" << v + 1 << "' in '" << s << "': " << e; } try { version_constraint r (v); if (!r.complete ()) throw invalid_argument ("incomplete"); // There doesn't seem to be any good reason to allow specifying a stub // version in the version constraint. Note that the constraint having // both endpoints set to the wildcard version (which is a stub) denotes // the system package wildcard version and may result only from the '/*' // string representation. // auto stub = [] (const optional<version>& v) { return v && v->compare (wildcard_version, true) == 0; }; if (stub (r.min_version) || stub (r.max_version)) throw invalid_argument ("endpoint is a stub"); return r; } catch (const invalid_argument& e) { fail << "invalid package version constraint '" << v << "' in '" << s << "': " << e << endf; } } repository_location parse_location (const string& s, optional<repository_type> ot) try { typed_repository_url tu (s); repository_url& u (tu.url); assert (u.path); // Make the relative path absolute using the current directory. // if (u.scheme == repository_protocol::file && u.path->relative ()) u.path->complete ().normalize (); // Guess the repository type to construct the repository location: // // 1. If the type is specified in the URL scheme, then use that (but // validate that it matches the --type option, if present). // // 2. If the type is specified as an option, then use that. // // Validate the protocol/type compatibility (e.g. git:// vs pkg) for both // cases. // // 3. See the guess_type() function description in <libbpkg/manifest.hxx> // for the algorithm details. // if (tu.type && ot && tu.type != ot) fail << to_string (*ot) << " repository type mismatch for location '" << s << "'"; repository_type t (tu.type ? *tu.type : ot ? *ot : guess_type (tu.url, true /* local */)); try { // Don't move the URL since it may still be needed for diagnostics. // return repository_location (u, t); } catch (const invalid_argument& e) { diag_record dr; dr << fail << "invalid " << t << " repository location '" << u << "': " << e; // If the pkg repository type was guessed, then suggest the user to // specify the type explicitly. // if (!tu.type && !ot && t == repository_type::pkg) dr << info << "consider using --type to specify repository type"; dr << endf; } } catch (const invalid_path& e) { fail << "invalid repository path '" << s << "': " << e << endf; } catch (const invalid_argument& e) { fail << "invalid repository location '" << s << "': " << e << endf; } catch (const system_error& e) { fail << "failed to guess repository type for '" << s << "': " << e << endf; } dir_path repository_state (const repository_location& rl) { switch (rl.type ()) { case repository_type::pkg: case repository_type::dir: return dir_path (); // No state. case repository_type::git: { // Strip the fragment, so all the repository fragments of the same // git repository can reuse the state. So, for example, the state is // shared for the fragments fetched from the following git repository // locations: // // https://www.example.com/foo.git#master // git://example.com/foo#stable // repository_url u (rl.url ()); u.fragment = nullopt; repository_location l (u, rl.type ()); return dir_path (sha256 (l.canonical_name ()).abbreviated_string (12)); } } assert (false); // Can't be here. return dir_path (); } bool repository_name (const string& s) { size_t p (s.find (':')); // If it has no scheme, then this is not a canonical name. // if (p == string::npos) return false; // This is a canonical name if the scheme is convertible to the repository // type and is followed by the colon and no more than one slash. // // Note that the approach is valid unless we invent the file scheme for the // canonical name. // try { string scheme (s, 0, p); to_repository_type (scheme); bool r (!(p + 2 < s.size () && s[p + 1] == '/' && s[p + 2] == '/')); assert (!r || scheme != "file"); return r; } catch (const invalid_argument&) { return false; } } package_version_infos package_versions (const common_options& o, const dir_paths& ds) { vector<b_project_info> pis (package_b_info (o, ds, false /* ext_mods */)); package_version_infos r; r.reserve (pis.size ()); for (const b_project_info& pi: pis) { // An empty version indicates that the version module is not enabled for // the project. // optional<version> v (!pi.version.empty () ? version (pi.version.string ()) : optional<version> ()); r.push_back (package_version_info {move (v), move (pi)}); } return r; } string package_checksum (const common_options& o, const dir_path& d, const package_info* pi) { path f (d / manifest_file); try { ifdstream is (f, fdopen_mode::binary); sha256 cs (is); const vector<package_info::subproject>& sps ( pi != nullptr ? pi->subprojects : package_b_info (o, d, false /* ext_mods */).subprojects); for (const package_info::subproject& sp: sps) cs.append (sp.path.string ()); return cs.string (); } catch (const io_error& e) { fail << "unable to read from " << f << ": " << e << endf; } } }
27.290859
79
0.554101
build2
fc61559c4a4edb821cb64c7d5840c59af574094c
940
cpp
C++
Stp/Base/Thread/ThreadChecker.cpp
markazmierczak/Polonite
240f099cafc5c38dc1ae1cc6fc5773e13f65e9de
[ "MIT" ]
1
2019-07-11T12:47:52.000Z
2019-07-11T12:47:52.000Z
Stp/Base/Thread/ThreadChecker.cpp
Polonite/Polonite
240f099cafc5c38dc1ae1cc6fc5773e13f65e9de
[ "MIT" ]
null
null
null
Stp/Base/Thread/ThreadChecker.cpp
Polonite/Polonite
240f099cafc5c38dc1ae1cc6fc5773e13f65e9de
[ "MIT" ]
1
2019-07-11T12:47:53.000Z
2019-07-11T12:47:53.000Z
// Copyright 2017 Polonite Authors. All rights reserved. // Copyright (c) 2011 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 "Base/Thread/ThreadChecker.h" #if ASSERT_IS_ON namespace stp { ThreadChecker::ThreadChecker() { EnsureThreadIdAssigned(); } ThreadChecker::~ThreadChecker() {} bool ThreadChecker::calledOnValidThread() const { EnsureThreadIdAssigned(); AutoLock auto_lock(borrow(lock_)); return valid_thread_ == NativeThread::currentHandle(); } void ThreadChecker::DetachFromThread() { AutoLock auto_lock(borrow(lock_)); valid_thread_ = InvalidNativeThreadHandle; } void ThreadChecker::EnsureThreadIdAssigned() const { AutoLock auto_lock(borrow(lock_)); if (valid_thread_ == InvalidNativeThreadHandle) valid_thread_ = NativeThread::currentHandle(); } } // namespace stp #endif // ASSERT_IS_ON
24.736842
73
0.760638
markazmierczak
fc6a4314f477dffa086ae1c52382c4b19b12fe46
1,774
cpp
C++
applications/about/main.cpp
innerout/skift
e44a77adafa99676fa1a011d94b7a44eefbce18c
[ "MIT" ]
2
2021-08-14T16:03:48.000Z
2021-11-09T10:29:36.000Z
applications/about/main.cpp
optimisticside/skift
3d59b222d686c83e370e8075506d129f8ff1fdac
[ "MIT" ]
null
null
null
applications/about/main.cpp
optimisticside/skift
3d59b222d686c83e370e8075506d129f8ff1fdac
[ "MIT" ]
2
2020-10-13T14:25:30.000Z
2020-10-13T14:39:40.000Z
#include <libsystem/BuildInfo.h> #include <libwidget/Application.h> #include <libwidget/Markup.h> #include <libwidget/Widgets.h> #include <libwidget/widgets/TextField.h> static auto logo_based_on_color_scheme() { auto path = theme_is_dark() ? "/Applications/about/logo-white.png" : "/Applications/about/logo-black.png"; return Bitmap::load_from_or_placeholder(path); } int main(int argc, char **argv) { application_initialize(argc, argv); Window *window = window_create_from_file("/Applications/about/about.markup"); window->with_widget<Image>("system-image", [&](auto image) { image->change_bitmap(logo_based_on_color_scheme()); }); window->with_widget<Label>("version-label", [&](auto label) { label->text(__BUILD_VERSION__); }); window->with_widget<Label>("commit-label", [&](auto label) { label->text(__BUILD_GITREF__ "/" __BUILD_CONFIG__); }); window->with_widget<Button>("license-button", [&](auto button) { button->on(Event::ACTION, [window](auto) { auto license_window = new Window(WINDOW_NONE); license_window->title("License"); license_window->size({556, 416}); auto field = new TextField(license_window->root(), TextModel::from_file("/Files/license.md")); field->attributes(LAYOUT_FILL); field->readonly(true); field->font(Font::create("mono").take_value()); field->focus(); license_window->show(); }); }); window->with_widget<Button>("ok-button", [&](auto button) { button->on(Event::ACTION, [window](auto) { window->hide(); }); }); window->show(); return application_run(); }
30.067797
106
0.614994
innerout
fc6ff2dbce458572e2e499af449318b67ccb40a3
2,115
cpp
C++
modules/libavparser/libavparser.cpp
Colinwang531/av_converged_communication_system_architecture
d8d8a2ff72b5342fd0c3426978884c0e9c43dde8
[ "MIT" ]
2
2021-12-10T07:45:30.000Z
2021-12-17T01:42:36.000Z
modules/libavparser/libavparser.cpp
Colinwang531/av_converged_communication_system_architecture
d8d8a2ff72b5342fd0c3426978884c0e9c43dde8
[ "MIT" ]
null
null
null
modules/libavparser/libavparser.cpp
Colinwang531/av_converged_communication_system_architecture
d8d8a2ff72b5342fd0c3426978884c0e9c43dde8
[ "MIT" ]
null
null
null
#include "boost/bind/bind.hpp" using namespace boost::placeholders; #include "boost/make_shared.hpp" #include "error_code.h" #include "map/unordered_map.h" #include "buffer/buffer_parser.h" #include "ps/ps_parser.h" #include "rtp/rtp_es_parser.h" #include "libavparser.h" using namespace module::av::stream; using AVParserNodePtr = boost::shared_ptr<AVParserNode>; using AVParserNodePtrs = UnorderedMap<const uint32_t, AVParserNodePtr>; static AVParserNodePtrs nodes; Libavparser::Libavparser() {} Libavparser::~Libavparser() {} int Libavparser::addConf(const AVParserModeConf& conf) { int ret{ 0 < conf.id ? Error_Code_Success : Error_Code_Invalid_Param}; if (Error_Code_Success == ret) { AVParserNodePtr node; if (AVParserType::AV_PARSER_TYPE_BUFFER_PARSER == conf.type) { node = boost::make_shared<BufferParser>( boost::bind(&Libavparser::afterParsedDataNotification, this, _1, _2), conf.id, conf.cache); } else if (AVParserType::AV_PARSER_TYPE_PS_PARSER == conf.type) { node = boost::make_shared<PSParser>( boost::bind(&Libavparser::afterParsedDataNotification, this, _1, _2), conf.id); } else if (AVParserType::AV_PARSER_TYPE_RTP_ES_PARSER == conf.type) { node = boost::make_shared<RTPESParser>( boost::bind(&Libavparser::afterParsedDataNotification, this, _1, _2), conf.id); } else { ret = Error_Code_Operate_Not_Support; } if (node) { nodes.add(conf.id, node); } } return ret; } int Libavparser::removeConf(const uint32_t id/* = 0*/) { int ret{0 < id ? Error_Code_Success : Error_Code_Invalid_Param}; if (Error_Code_Success == ret) { AVParserNodePtr node{nodes.at(id)}; if (node) { nodes.remove(id); } else { ret = Error_Code_Object_Not_Exist; } } return ret; } int Libavparser::input( const uint32_t id/* = 0*/, const void* avpkt/* = nullptr*/) { int ret{0 < id && avpkt ? Error_Code_Success : Error_Code_Invalid_Param}; if(Error_Code_Success == ret) { AVParserNodePtr node{nodes.at(id)}; ret = node ? node->input(avpkt) : Error_Code_Object_Not_Exist; } return ret; }
21.15
74
0.705437
Colinwang531
fc713583a57526add1657960aa4e6191346c46ac
753
hpp
C++
cpp_kernels/global/mean_std_dev_u8.hpp
HipaccVX/HipaccVX
0d469748df11c95f916b5a70f0006878f8550e3c
[ "MIT" ]
1
2021-06-08T08:58:54.000Z
2021-06-08T08:58:54.000Z
cpp_kernels/global/mean_std_dev_u8.hpp
HipaccVX/HipaccVX
0d469748df11c95f916b5a70f0006878f8550e3c
[ "MIT" ]
1
2021-11-13T14:55:55.000Z
2021-11-13T14:55:55.000Z
cpp_kernels/global/mean_std_dev_u8.hpp
HipaccVX/HipaccVX
0d469748df11c95f916b5a70f0006878f8550e3c
[ "MIT" ]
null
null
null
void Mean_Std_Dev_u8(float *out_mean, float *out_stddev, unsigned char *in_data, const unsigned int in_width, const unsigned int in_height) { float fmean = 0.0f, fstddev = 0.0f; double sum = 0.0, sum_diff_sqrs = 0.0; for (long long y = 0; y < in_height; y++) { for (long long x = 0; x < in_width; x++) { sum += in_data[y * in_width + x]; } } fmean = (float)(sum / (in_width * in_height)); for (long long y = 0; y < in_height; y++) { for (long long x = 0; x < in_width; x++) { double value = in_data[y * in_width + x] - fmean; sum_diff_sqrs += value * value; } } fstddev = (float)sqrt(sum_diff_sqrs / (in_width * in_height)); *out_mean = fmean; if (out_stddev != nullptr) *out_stddev = fstddev; }
26.892857
103
0.609562
HipaccVX
fc720d7eca2c7568df0133c28d7a5ef10fff7931
3,317
cpp
C++
Code/GeometryCommand/GeoCommandCreateFace.cpp
baojunli/FastCAE
a3f99f6402da564df87fcef30674ce5f44379962
[ "BSD-3-Clause" ]
2
2020-02-21T01:04:35.000Z
2020-02-21T03:35:37.000Z
Code/GeometryCommand/GeoCommandCreateFace.cpp
Sunqia/FastCAE
cbc023fe07b6e306ceefae8b8bd7c12bc1562acb
[ "BSD-3-Clause" ]
1
2020-03-06T04:49:42.000Z
2020-03-06T04:49:42.000Z
Code/GeometryCommand/GeoCommandCreateFace.cpp
Sunqia/FastCAE
cbc023fe07b6e306ceefae8b8bd7c12bc1562acb
[ "BSD-3-Clause" ]
null
null
null
#include "GeoCommandCreateFace.h" #include "geometry/geometrySet.h" #include "geometry/geometryData.h" #include <BRepFilletAPI_MakeChamfer.hxx> #include <TopExp.hxx> #include <TopoDS.hxx> #include <TopoDS_TShape.hxx> #include <TopoDS_Shape.hxx> #include <TopoDS_Wire.hxx> #include <TopoDS_Edge.hxx> #include <TopoDS_Face.hxx> #include <TopExp_Explorer.hxx> #include <BRepBuilderAPI_MakeWire.hxx> #include <BRepBuilderAPI_MakeFace.hxx> #include <QDebug> #include "GeoCommandCommon.h" #include <list> #include "geometry/geometryParaFace.h" namespace Command { CommandCreateFace::CommandCreateFace(GUI::MainWindow* m, MainWidget::PreWindow* p) :GeoCommandBase(m,p) { } bool CommandCreateFace::execute() { if (_shapeHash.size() < 1) return false; QList<Geometry::GeometrySet*> setList = _shapeHash.uniqueKeys(); std::list<TopoDS_Edge> edgeList; for (int i = 0; i < setList.size(); ++i) { Geometry::GeometrySet* set = setList.at(i); TopoDS_Shape* parent = set->getShape(); QList<int> shapes = _shapeHash.values(set); const int count = shapes.size(); for (int j=0; j < count; ++j) { const int index = shapes.at(j); TopExp_Explorer edgeExp(*parent, TopAbs_EDGE); for (int k = 0; k < index; ++k) edgeExp.Next(); const TopoDS_Shape& shape = edgeExp.Current(); const TopoDS_Edge& E = TopoDS::Edge(shape); edgeList.push_back(E); } } std::vector<TopoDS_Wire> wireList = GeoCommandCommon::bulidWire(edgeList); TopoDS_Shape resShape = GeoCommandCommon::makeFace(wireList); if (resShape.IsNull()) return false; TopoDS_Shape* successShape = new TopoDS_Shape; *successShape = resShape; Geometry::GeometrySet* newset = new Geometry::GeometrySet(Geometry::STEP); newset->setName(_name); newset->setShape(successShape); //_geoData->appendGeometrySet(newset); _result = newset; if (_isEdit) { newset->setName(_editSet->getName()); _geoData->replaceSet(newset, _editSet); emit removeDisplayActor(_editSet); } else { newset->setName(_name); _geoData->appendGeometrySet(newset); } Geometry::GeometryParaFace* para = new Geometry::GeometryParaFace; para->setName(_name); para->setShapeHash(_shapeHash); _result->setParameter(para); GeoCommandBase::execute(); emit showSet(newset); emit updateGeoTree(); return true; } void CommandCreateFace::undo() { emit removeDisplayActor(_result); if (_isEdit) { _geoData->replaceSet(_editSet, _result); emit showSet(_editSet); } else { _geoData->removeTopGeometrySet(_result); } emit updateGeoTree(); } void CommandCreateFace::redo() { if (_isEdit) { _geoData->replaceSet(_result, _editSet); emit removeDisplayActor(_editSet); } else _geoData->appendGeometrySet(_result); emit updateGeoTree(); emit showSet(_result); } void CommandCreateFace::releaseResult() { if (_result != nullptr) delete _result; } void CommandCreateFace::setShapeList(QMultiHash<Geometry::GeometrySet*, int> s) { _shapeHash = s; } void CommandCreateFace::setActor(QList<vtkActor*> ac) { _actor = ac; } void CommandCreateFace::setName(QString name) { _name = name; } }
23.863309
84
0.678324
baojunli
fc74bb7873f7a111ff7dc13f49fcb913a6a953cd
564
cpp
C++
BFEngine/src/core/window.cpp
YnopTafGib/BigFatEngine
267758779747adfd9e1d0eb6c7674158ecbe15c6
[ "MIT" ]
null
null
null
BFEngine/src/core/window.cpp
YnopTafGib/BigFatEngine
267758779747adfd9e1d0eb6c7674158ecbe15c6
[ "MIT" ]
null
null
null
BFEngine/src/core/window.cpp
YnopTafGib/BigFatEngine
267758779747adfd9e1d0eb6c7674158ecbe15c6
[ "MIT" ]
null
null
null
#include "bfepch.hpp" #include "window.hpp" namespace BFE { Window::Window( const std::string& p_title, const ivec2& p_size ) : m_title( p_title ), m_size( p_size ) { glfwInit(); glfwWindowHint( GLFW_CLIENT_API, GLFW_NO_API ); glfwWindowHint( GLFW_RESIZABLE, GLFW_FALSE ); m_window = glfwCreateWindow( m_size.x, m_size.y, m_title.c_str(), nullptr, nullptr ); LOG_INFO( "Created GLFW window." ); } Window::~Window() { glfwDestroyWindow( m_window ); glfwTerminate(); } void Window::update() { glfwPollEvents(); } } // namespace BFE
21.692308
104
0.684397
YnopTafGib
fc778e36a0b8f448698928817006dc79942c08d6
5,032
hxx
C++
OCC/opencascade-7.2.0/x64/debug/inc/BRepOffsetAPI_MakeEvolved.hxx
jiaguobing/FastCAE
2348ab87e83fe5c704e4c998cf391229c25ac5d5
[ "BSD-3-Clause" ]
2
2020-02-21T01:04:35.000Z
2020-02-21T03:35:37.000Z
OCC/opencascade-7.2.0/x64/debug/inc/BRepOffsetAPI_MakeEvolved.hxx
Sunqia/FastCAE
cbc023fe07b6e306ceefae8b8bd7c12bc1562acb
[ "BSD-3-Clause" ]
1
2020-03-06T04:49:42.000Z
2020-03-06T04:49:42.000Z
OCC/opencascade-7.2.0/x64/debug/inc/BRepOffsetAPI_MakeEvolved.hxx
Sunqia/FastCAE
cbc023fe07b6e306ceefae8b8bd7c12bc1562acb
[ "BSD-3-Clause" ]
1
2021-11-21T13:03:26.000Z
2021-11-21T13:03:26.000Z
// Created on: 1995-09-18 // Created by: Bruno DUMORTIER // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BRepOffsetAPI_MakeEvolved_HeaderFile #define _BRepOffsetAPI_MakeEvolved_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <BRepFill_Evolved.hxx> #include <BRepBuilderAPI_MakeShape.hxx> #include <GeomAbs_JoinType.hxx> #include <Standard_Boolean.hxx> #include <Standard_Real.hxx> #include <TopTools_ListOfShape.hxx> class TopoDS_Wire; class TopoDS_Face; class BRepFill_Evolved; class TopoDS_Shape; //! Describes functions to build evolved shapes. //! An evolved shape is built from a planar spine (face or //! wire) and a profile (wire). The evolved shape is the //! unlooped sweep (pipe) of the profile along the spine. //! Self-intersections are removed. //! A MakeEvolved object provides a framework for: //! - defining the construction of an evolved shape, //! - implementing the construction algorithm, and //! - consulting the result. //! Computes an Evolved by //! 1 - sweeping a profil along a spine. //! 2 - removing the self-intersections. //! //! The profile is defined in a Referential R. The position of //! the profile at the current point of the spine is given by //! confusing R and the local referential given by ( D0, D1 //! and the normal of the Spine) //! //! If the Boolean <AxeProf> is true, R is O,X,Y,Z //! else R is defined as the local refential at the nearest //! point of the profil to the spine. //! //! if <Solid> is TRUE the Shape result is completed to be a //! solid or a compound of solids. class BRepOffsetAPI_MakeEvolved : public BRepBuilderAPI_MakeShape { public: DEFINE_STANDARD_ALLOC Standard_EXPORT BRepOffsetAPI_MakeEvolved(); Standard_EXPORT BRepOffsetAPI_MakeEvolved(const TopoDS_Wire& Spine, const TopoDS_Wire& Profil, const GeomAbs_JoinType Join = GeomAbs_Arc, const Standard_Boolean AxeProf = Standard_True, const Standard_Boolean Solid = Standard_False, const Standard_Boolean ProfOnSpine = Standard_False, const Standard_Real Tol = 0.0000001); //! These constructors construct an evolved shape by sweeping the profile //! Profile along the spine Spine. //! The profile is defined in a coordinate system R. //! The coordinate system is determined by AxeProf: //! - if AxeProf is true, R is the global coordinate system, //! - if AxeProf is false, R is computed so that: //! - its origin is given by the point on the spine which is //! closest to the profile, //! - its "X Axis" is given by the tangent to the spine at this point, and //! - its "Z Axis" is the normal to the plane which contains the spine. //! The position of the profile at the current point of the //! spine is given by making R coincident with the local //! coordinate system given by the current point, the //! tangent vector and the normal to the spine. //! Join defines the type of pipe generated by the salient //! vertices of the spine. The default type is GeomAbs_Arc //! where the vertices generate revolved pipes about the //! axis passing along the vertex and the normal to the //! plane of the spine. At present, this is the only //! construction type implemented. Standard_EXPORT BRepOffsetAPI_MakeEvolved(const TopoDS_Face& Spine, const TopoDS_Wire& Profil, const GeomAbs_JoinType Join = GeomAbs_Arc, const Standard_Boolean AxeProf = Standard_True, const Standard_Boolean Solid = Standard_False, const Standard_Boolean ProfOnSpine = Standard_False, const Standard_Real Tol = 0.0000001); Standard_EXPORT const BRepFill_Evolved& Evolved() const; //! Builds the resulting shape (redefined from MakeShape). Standard_EXPORT virtual void Build() Standard_OVERRIDE; //! Returns the shapes created from a subshape //! <SpineShape> of the spine and a subshape //! <ProfShape> on the profile. Standard_EXPORT const TopTools_ListOfShape& GeneratedShapes (const TopoDS_Shape& SpineShape, const TopoDS_Shape& ProfShape) const; //! Return the face Top if <Solid> is True in the constructor. Standard_EXPORT const TopoDS_Shape& Top() const; //! Return the face Bottom if <Solid> is True in the constructor. Standard_EXPORT const TopoDS_Shape& Bottom() const; protected: private: BRepFill_Evolved myEvolved; }; #endif // _BRepOffsetAPI_MakeEvolved_HeaderFile
37.552239
325
0.75159
jiaguobing
fc77e164cdb591239d9a443b9f3675442011aae5
2,690
cc
C++
control/vanes_generated.cc
sentree/hover-jet
7c0f03e57ecfd07a7a167b3ae509700fb48b8764
[ "MIT" ]
10
2018-12-26T23:08:40.000Z
2021-02-04T23:22:01.000Z
control/vanes_generated.cc
sentree/hover-jet
7c0f03e57ecfd07a7a167b3ae509700fb48b8764
[ "MIT" ]
40
2018-12-15T21:10:04.000Z
2021-07-29T06:21:22.000Z
control/vanes_generated.cc
sentree/hover-jet
7c0f03e57ecfd07a7a167b3ae509700fb48b8764
[ "MIT" ]
6
2018-12-15T20:46:19.000Z
2020-11-27T09:39:34.000Z
/* Don't edit this; this code was generated by op_graph */ #include "control/vanes_generated.hh" namespace jet { namespace control { VecNd<4> QuadraframeStatusDelta::to_vector(const QuadraframeStatusDelta &in_grp) { const VecNd<4> out = (VecNd<4>() << (in_grp.servo_0_angle_rad_error), (in_grp.servo_1_angle_rad_error), (in_grp.servo_2_angle_rad_error), (in_grp.servo_3_angle_rad_error)) .finished(); return out; } QuadraframeStatusDelta QuadraframeStatusDelta::from_vector(const VecNd<4> &in_vec) { const QuadraframeStatusDelta out = QuadraframeStatusDelta{ (in_vec[0]), (in_vec[1]), (in_vec[2]), (in_vec[3])}; return out; } QuadraframeStatus operator-(const QuadraframeStatus &a, const QuadraframeStatus &b) { const QuadraframeStatus difference = QuadraframeStatus{((a.servo_0_angle_rad) - (b.servo_0_angle_rad)), ((a.servo_1_angle_rad) - (b.servo_1_angle_rad)), ((a.servo_2_angle_rad) - (b.servo_2_angle_rad)), ((a.servo_3_angle_rad) - (b.servo_3_angle_rad))}; return difference; } QuadraframeStatus operator+(const QuadraframeStatus &a, const QuadraframeStatusDelta &grp_b) { const QuadraframeStatus out = QuadraframeStatus{ ((a.servo_0_angle_rad) + (grp_b.servo_0_angle_rad_error)), ((a.servo_1_angle_rad) + (grp_b.servo_1_angle_rad_error)), ((a.servo_2_angle_rad) + (grp_b.servo_2_angle_rad_error)), ((a.servo_3_angle_rad) + (grp_b.servo_3_angle_rad_error))}; return out; } VecNd<4> QuadraframeStatus::compute_delta(const QuadraframeStatus &a, const QuadraframeStatus &b) { const QuadraframeStatus difference = a - b; const double servo_3_angle_rad_error = difference.servo_3_angle_rad; const double servo_2_angle_rad_error = difference.servo_2_angle_rad; const double servo_0_angle_rad_error = difference.servo_0_angle_rad; const double servo_1_angle_rad_error = difference.servo_1_angle_rad; const QuadraframeStatusDelta delta = QuadraframeStatusDelta{servo_0_angle_rad_error, servo_1_angle_rad_error, servo_2_angle_rad_error, servo_3_angle_rad_error}; const VecNd<4> out_vec = QuadraframeStatusDelta::to_vector(delta); return out_vec; } QuadraframeStatus QuadraframeStatus::apply_delta(const QuadraframeStatus &a, const VecNd<4> &delta) { const QuadraframeStatusDelta grp_b = QuadraframeStatusDelta::from_vector(delta); const QuadraframeStatus out = a + grp_b; return out; } } // namespace control } // namespace jet
44.833333
79
0.697026
sentree
fc79a4d089f7c42a53a09a502b9c66313b473aa1
660
cpp
C++
leetcode/852_easy_peak-index-in-a-mountain-array.cpp
shoryaconsul/code_practice
f04eeff266beffbba6d9f22e6f8c5861f0dbf998
[ "MIT" ]
null
null
null
leetcode/852_easy_peak-index-in-a-mountain-array.cpp
shoryaconsul/code_practice
f04eeff266beffbba6d9f22e6f8c5861f0dbf998
[ "MIT" ]
null
null
null
leetcode/852_easy_peak-index-in-a-mountain-array.cpp
shoryaconsul/code_practice
f04eeff266beffbba6d9f22e6f8c5861f0dbf998
[ "MIT" ]
null
null
null
class Solution { public: int peakIndexInMountainArray(vector<int>& arr) { int start = 0; int end = arr.size()-1; int mid; while(start+2 <= end){ mid = start + (end-start)/2; if(arr[mid] > arr[mid-1] && arr[mid] > arr[mid+1]) return mid; if(arr[mid] > arr[mid-1]){ // peak lies to the right of mid start = mid + 1; } else{ // peak lies to the left of mid end = mid - 1; } } if(start == end) return start; if(arr[start] > arr[end]) return start; return end; } };
28.695652
74
0.442424
shoryaconsul
fc79af0f5598d3a659a11f37aa347ffabfa0e670
9,022
cpp
C++
source/xbox360/brfilenamexbox360.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
115
2015-01-18T17:29:30.000Z
2022-01-30T04:31:48.000Z
source/xbox360/brfilenamexbox360.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
9
2015-01-22T04:53:38.000Z
2015-01-31T13:52:40.000Z
source/xbox360/brfilenamexbox360.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
9
2015-01-23T20:06:46.000Z
2020-05-20T16:06:00.000Z
/*************************************** Filename Class Xbox 360 specific code Copyright (c) 1995-2017 by Rebecca Ann Heineman <becky@burgerbecky.com> It is released under an MIT Open Source license. Please see LICENSE for license details. Yes, you can use it in a commercial title without paying anything, just give me a credit. Please? It's not like I'm asking you for money! ***************************************/ #include "brfilename.h" #if defined(BURGER_XBOX360) #include "brfilemanager.h" #include "brmemoryfunctions.h" #define NOD3D #define NONET #include <xtl.h> /*! ************************************ \brief Expand a filename into XBox 360 format. Using the rules for a Burgerlib type pathname, expand a path into a FULL pathname native to the Xbox 360 file system. Directory delimiters are colons only. If the path starts with a colon, then it is a full pathname starting with a volume name. If the path starts with ".D2:" then it is a full pathname starting with a drive number. If the path starts with a "$:","*:" or "@:" then use special prefix numbers 32-34 If the path starts with 0: through 31: then use prefix 0-31. Otherwise prepend the pathname with the contents of prefix 8 ("Default") If the path after the prefix is removed is a period then POP the number of directories from the pathname for each period present after the first. Example "..:PrevDir:File:" will go down one directory and up the directory PrevDir All returned pathnames will NOT have a trailing "\", they will take the form of c:\\foo\\bar\\file.txt or similar Examples:<br> If drive C: is named "boot" then ":boot:foo:bar.txt" = "c:\foo\bar.txt"<br> If there is no drive named "boot" then ":boot:foo:bar.txt" = "\\boot\foo\bar.txt"<br> ".D2:foo:bar.txt" = "c:\foo\bar.txt"<br> ".D4:foo:bar.txt" = "e:\foo\bar.txt"<br> "@:game:data.dat" = "c:\users\<Current user>\appdata\roaming\game\data.dat" \param pInput Pointer to a pathname string \sa Burger::Filename::Set(const char *) ***************************************/ const char* Burger::Filename::GetNative(void) BURGER_NOEXCEPT { // First step, expand myself to a fully qualified pathname Expand(); /*************************************** DOS version and Win 95 version I prefer for all paths intended for DOS use a generic drive specifier before the working directory. The problem is that Volume LABEL are very difficult to parse and slow to access. ***************************************/ // First parse either the volume name of a .DXX device number // I hopefully will get a volume number since DOS prefers it const uint8_t* pPath = reinterpret_cast<uint8_t*>(m_pFilename); // Copy to running pointer // Now that I have the drive number, determine the length // of the output buffer and start the conversion uintptr_t uPathLength = StringLength(reinterpret_cast<const char*>(pPath)); // Reserve 6 extra bytes for the prefix and/or the trailing / and null char* pOutput = m_NativeFilename; if (uPathLength >= (sizeof(m_NativeFilename) - 6)) { pOutput = static_cast<char*>(Alloc(uPathLength + 6)); if (!pOutput) { pOutput = m_NativeFilename; uPathLength = 0; // I'm so boned } else { m_pNativeFilename = pOutput; // This is my buffer } } // Ignore the first colon, it's to the device name if (pPath[0] == ':') { ++pPath; --uPathLength; } if (uPathLength) { uint_t uTemp; uint_t uFirst = TRUE; do { uTemp = pPath[0]; ++pPath; if (uTemp == ':') { if (uFirst) { pOutput[0] = ':'; ++pOutput; uFirst = FALSE; } uTemp = '\\'; } pOutput[0] = static_cast<char>(uTemp); ++pOutput; } while (--uPathLength); // Remove trailing slash if (uTemp == '\\') { --pOutput; } } pOutput[0] = 0; // Terminate the "C" string return m_pNativeFilename; } /*************************************** \brief Set the filename to the current working directory Query the operating system for the current working directory and set the filename to that directory. The path is converted into UTF8 character encoding and stored in Burgerlib filename format On platforms where a current working directory doesn't make sense, like an ROM based system, the filename is cleared out. ***************************************/ Burger::eError BURGER_API Burger::Filename::SetSystemWorkingDirectory( void) BURGER_NOEXCEPT { Set(":GAME:"); return kErrorNone; } /*************************************** \brief Set the filename to the application's directory Determine the directory where the application resides and set the filename to that directory. The path is converted into UTF8 character encoding and stored in Burgerlib filename format. On platforms where a current working directory doesn't make sense, like an ROM based system, the filename is cleared out. ***************************************/ Burger::eError BURGER_API Burger::Filename::SetApplicationDirectory( void) BURGER_NOEXCEPT { Set(":GAME:"); return kErrorNone; } /*************************************** \brief Set the filename to the boot volume directory Determine the directory of the drive volume that the operating system was loaded from. The path is converted into UTF8 character encoding and stored in Burgerlib filename format. On platforms where a current working directory doesn't make sense, like a ROM based system, the filename is cleared out. ***************************************/ Burger::eError BURGER_API Burger::Filename::SetBootVolumeDirectory( void) BURGER_NOEXCEPT { Set(":GAME:"); return kErrorNone; } /*************************************** \brief Set the filename to the local machine preferences directory Determine the directory where the user's preferences that are local to the machine is located. The path is converted into UTF8 character encoding and stored in Burgerlib filename format. On platforms where a current working directory doesn't make sense, like an ROM based system, the filename is cleared out. ***************************************/ Burger::eError BURGER_API Burger::Filename::SetMachinePrefsDirectory( void) BURGER_NOEXCEPT { Set(":GAME:"); return kErrorNone; } /*************************************** \brief Set the filename to the user's preferences directory Determine the directory where the user's preferences that could be shared among all machines the user has an account with is located. The path is converted into UTF8 character encoding and stored in Burgerlib filename format. On platforms where a current working directory doesn't make sense, like an ROM based system, the filename is cleared out. ***************************************/ Burger::eError BURGER_API Burger::Filename::SetUserPrefsDirectory( void) BURGER_NOEXCEPT { Set(":GAME:"); return kErrorNone; } /*************************************** Convert a Windows path to a Burgerlib path Paths without a leading '\' are prefixed with the current working directory Paths with a drive letter but no leading \ will use the drive's current working directory If it's a network path "\\" then use that as the volume name. The Windows version converts these types of paths: "C:\foo\bar2" = ".D2:foo:bar2:"<br> "foo" = "(working directory from 8):foo:"<br> "foo\bar2" = "(working directory from 8):foo:bar2:"<br> "\foo" = ".D(Mounted drive number):foo:"<br> "\\foo\bar\file.txt" = ":foo:bar:file.txt:" ***************************************/ Burger::eError BURGER_API Burger::Filename::SetFromNative( const char* pInput) BURGER_NOEXCEPT { Clear(); if (!pInput || !pInput[0]) { // No directory at all? pInput = "D:\\"; // Just get the current directory } // How long would the string be if it was UTF8? uintptr_t uExpandedLength = StringLength(pInput); uintptr_t uOutputLength = uExpandedLength + 6; char* pOutput = m_Filename; if (uOutputLength >= sizeof(m_Filename)) { pOutput = static_cast<char*>(Alloc(uOutputLength)); if (!pOutput) { return kErrorOutOfMemory; } } m_pFilename = pOutput; const char* pSrc = pInput; pOutput[0] = ':'; ++pOutput; // Turn the drive name into the root segment const char* pColon = StringCharacter(pSrc, ':'); if (pColon) { uintptr_t uVolumeNameSize = pColon - pInput; MemoryCopy(pOutput, pSrc, uVolumeNameSize); pOutput += uVolumeNameSize; pSrc = pColon + 1; } // Append the rest of the path, and change slashes to colons uint_t uTemp2 = reinterpret_cast<const uint8_t*>(pSrc)[0]; ++pSrc; if (uTemp2) { do { if (uTemp2 == '\\') { // Convert directory holders uTemp2 = ':'; // To generic paths } pOutput[0] = static_cast<char>(uTemp2); // Save char ++pOutput; uTemp2 = pSrc[0]; // Next char ++pSrc; } while (uTemp2); // Still more? } // The wrap up... // Make sure it's appended with a colon if (pOutput[-1] != ':') { // Last char a colon? pOutput[0] = ':'; // End with a colon! pOutput[1] = 0; } return kErrorNone; } #endif
28.282132
79
0.656728
Olde-Skuul
fc7e58b4c347acde1e49ff082be26e051fff46f3
958
cpp
C++
source/ashespp/Buffer/VertexBuffer.cpp
DragonJoker/Ashes
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
[ "MIT" ]
227
2018-09-17T16:03:35.000Z
2022-03-19T02:02:45.000Z
source/ashespp/Buffer/VertexBuffer.cpp
DragonJoker/RendererLib
0f8ad8edec1b0929ebd10247d3dd0a9ee8f8c91a
[ "MIT" ]
39
2018-02-06T22:22:24.000Z
2018-08-29T07:11:06.000Z
source/ashespp/Buffer/VertexBuffer.cpp
DragonJoker/Ashes
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
[ "MIT" ]
8
2019-05-04T10:33:32.000Z
2021-04-05T13:19:27.000Z
/* This file belongs to Ashes. See LICENSE file in root folder. */ #include "ashespp/Buffer/VertexBuffer.hpp" namespace ashes { VertexBufferBase::VertexBufferBase( Device const & device , VkDeviceSize size , VkBufferUsageFlags usage , QueueShare sharingMode ) : VertexBufferBase{ device, "VertexBuffer", size, usage, std::move( sharingMode ) } { } VertexBufferBase::VertexBufferBase( Device const & device , std::string const & debugName , VkDeviceSize size , VkBufferUsageFlags usage , QueueShare sharingMode ) : m_device{ device } , m_size{ size } , m_buffer{ m_device.createBuffer( debugName , size , usage | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT , std::move( sharingMode ) ) } { } void VertexBufferBase::bindMemory( DeviceMemoryPtr memory ) { m_buffer->bindMemory( std::move( memory ) ); } VkMemoryRequirements VertexBufferBase::getMemoryRequirements()const { return m_buffer->getMemoryRequirements(); } }
23.365854
85
0.729645
DragonJoker
fc8093dd6f33bc5e48bbc5b987201084ac954fd8
594
cc
C++
bindings.cc
jwerle/repo
15d07ce6d039766e7c3f4bda6652430eb7686d7b
[ "MIT" ]
1
2022-02-27T20:41:57.000Z
2022-02-27T20:41:57.000Z
bindings.cc
jwerle/repo
15d07ce6d039766e7c3f4bda6652430eb7686d7b
[ "MIT" ]
null
null
null
bindings.cc
jwerle/repo
15d07ce6d039766e7c3f4bda6652430eb7686d7b
[ "MIT" ]
null
null
null
#include <v8.h> #include <node.h> #include "repo.h" #define str(s) v8::String::New(s) class User { // repo_user_t *ref_; v8::Persistent<v8::Object> obj_; public: User () { // ref_ = repo_user_new(); obj_->SetPointerInInternalField(0, this); } v8::Handle<v8::Object> ToObject () { return obj_; } }; v8::Handle<v8::Value> NewUser (const v8::Arguments &args) { v8::HandleScope scope; User *user = new User(); return scope.Close(user->ToObject()); } void Init (v8::Handle<v8::Object> exports) { NODE_SET_METHOD(exports, "User", NewUser); } NODE_MODULE(repo, Init);
16.5
44
0.648148
jwerle
fc8ac01aa8ee29821a616a46a192c8b5dacf67df
1,223
cpp
C++
searching-algorithms/binarySearch.cpp
Divyansh1315/data-structures-and-algorithms-code
46b0bec41f022b60be4798227a5f5fc86dccee1a
[ "MIT" ]
1
2022-02-09T14:28:28.000Z
2022-02-09T14:28:28.000Z
searching-algorithms/binarySearch.cpp
Divyansh1315/data-structures-and-algorithms-code
46b0bec41f022b60be4798227a5f5fc86dccee1a
[ "MIT" ]
1
2022-02-02T04:58:10.000Z
2022-02-02T04:58:10.000Z
searching-algorithms/binarySearch.cpp
Divyansh1315/data-structures-and-algorithms-code
46b0bec41f022b60be4798227a5f5fc86dccee1a
[ "MIT" ]
1
2022-02-02T00:23:59.000Z
2022-02-02T00:23:59.000Z
#include <bits/stdc++.h> using namespace std; // iterative approach /* int binarySearch(int arr[],int element, int low, int high) { while(low <= high) { int mid = low + (high - low)/2; if(arr[mid] == element) return mid; else if(arr[mid] < element) low = mid + 1; else high = mid - 1; } return -1; } */ // recursive approach int binarySearch(int arr[], int element, int low, int high) { if(low <= high) { int mid = low + (high - low)/2; return arr[mid] == element ? mid : (arr[mid] < element ? binarySearch(arr, element, mid + 1, high) : binarySearch(arr, element, low, mid - 1)); // if(arr[mid] == element) // return mid; // else if (arr[mid] < element) // return binarySearch(arr, element, mid + 1, high); // else // return binarySearch(arr, element, low, mid - 1); } return -1; } int main() { int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int element = 1; int size = sizeof(arr)/sizeof(arr[0]); int result = binarySearch(arr, element, 0, size - 1); if (result == -1) cout << "Element is not found" << endl; else cout << "Element is found at " << result << " index" << endl; return 0; }
23.075472
65
0.553557
Divyansh1315
fc8c396a25870fcdf1cf16138b72464a1dfeab9a
7,917
cc
C++
nox/src/nox/netapps/hoststate/hosttracker.cc
ayjazz/OESS
deadc504d287febc7cbd7251ddb102bb5c8b1f04
[ "Apache-2.0" ]
28
2015-02-04T13:59:25.000Z
2021-12-29T03:44:47.000Z
nox/src/nox/netapps/hoststate/hosttracker.cc
ayjazz/OESS
deadc504d287febc7cbd7251ddb102bb5c8b1f04
[ "Apache-2.0" ]
552
2015-01-05T18:25:54.000Z
2022-03-16T18:51:13.000Z
nox/src/nox/netapps/hoststate/hosttracker.cc
ayjazz/OESS
deadc504d287febc7cbd7251ddb102bb5c8b1f04
[ "Apache-2.0" ]
25
2015-02-04T18:48:20.000Z
2020-06-18T15:51:05.000Z
#include "hosttracker.hh" #include <boost/bind.hpp> namespace vigil { static Vlog_module lg("hosttracker"); Host_location_event::Host_location_event(const ethernetaddr host_, const list<hosttracker::location> loc_, enum type type_): Event(static_get_name()), host(host_), eventType(type_) { for (list<hosttracker::location>::const_iterator i = loc_.begin(); i != loc_.end(); i++) loc.push_back(*(new hosttracker::location(i->dpid, i->port, i->lastTime))); } hosttracker::location::location(datapathid dpid_, uint16_t port_, time_t tv): dpid(dpid_), port(port_), lastTime(tv) { } void hosttracker::location::set(const hosttracker::location& loc) { dpid = loc.dpid; port = loc.port; lastTime = loc.lastTime; } void hosttracker::configure(const Configuration* c) { defaultnBindings = DEFAULT_HOST_N_BINDINGS; hostTimeout = DEFAULT_HOST_TIMEOUT; register_event(Host_location_event::static_get_name()); } void hosttracker::install() { } void hosttracker::check_timeout() { if (hostlocation.size() == 0) return; time_t timenow; time(&timenow); hash_map<ethernetaddr,list<hosttracker::location> >::iterator i = \ hostlocation.find(oldest_host()); if (i == hostlocation.end()) return; list<hosttracker::location>::iterator j = get_oldest(i->second); while (j->lastTime+hostTimeout < timenow) { //Remove old entry i->second.erase(j); if (i->second.size() == 0) hostlocation.erase(i); //Get next oldest i = hostlocation.find(oldest_host()); if (i == hostlocation.end()) return; j = get_oldest(i->second); } //Post next one timeval tv = {get_oldest(i->second)->lastTime+hostTimeout-timenow, 0}; post(boost::bind(&hosttracker::check_timeout, this), tv); } const ethernetaddr hosttracker::oldest_host() { ethernetaddr oldest((uint64_t) 0); time_t oldest_time = 0; hash_map<ethernetaddr,list<hosttracker::location> >::iterator i = \ hostlocation.begin(); while (i != hostlocation.end()) { if (oldest_time == 0 || get_oldest(i->second)->lastTime < oldest_time) { oldest_time = get_oldest(i->second)->lastTime; oldest = i->first; } i++; } return oldest; } void hosttracker::add_location(ethernetaddr host, datapathid dpid, uint16_t port, time_t tv, bool postEvent) { //Set default time as now if (tv == 0) time(&tv); add_location(host, hosttracker::location(dpid,port,tv), postEvent); } void hosttracker::add_location(ethernetaddr host, hosttracker::location loc, bool postEvent) { hash_map<ethernetaddr,list<hosttracker::location> >::iterator i = \ hostlocation.find(host); if (i == hostlocation.end()) { //New host list<location> j = list<location>(); j.push_front(loc); hostlocation.insert(make_pair(host,j)); if (postEvent) post(new Host_location_event(host,j,Host_location_event::ADD)); VLOG_DBG(lg, "New host %"PRIx64" at %"PRIx64":%"PRIx16"", host.hb_long(), loc.dpid.as_host(), loc.port); } else { //Existing host list<location>::iterator k = i->second.begin(); while (k->dpid != loc.dpid || k->port != loc.port) { k++; if (k == i->second.end()) break; } if (k == i->second.end()) { //New location while (i->second.size() >= getBindingNumber(host)) i->second.erase(get_oldest(i->second)); i->second.push_front(loc); VLOG_DBG(lg, "Host %"PRIx64" at new location %"PRIx64":%"PRIx16"", i->first.hb_long(), loc.dpid.as_host(), loc.port); if (postEvent) post(new Host_location_event(host,i->second, Host_location_event::MODIFY)); } else { //Update timeout k->lastTime = loc.lastTime; VLOG_DBG(lg, "Host %"PRIx64" at old location %"PRIx64":%"PRIx16"", i->first.hb_long(), loc.dpid.as_host(), loc.port); } } VLOG_DBG(lg, "Added host %"PRIx64" to location %"PRIx64":%"PRIx16"", host.hb_long(), loc.dpid.as_host(), loc.port); //Schedule timeout if first entry if (hostlocation.size() == 0) { timeval tv= {hostTimeout,0}; post(boost::bind(&hosttracker::check_timeout, this), tv); } } void hosttracker::remove_location(ethernetaddr host, datapathid dpid, uint16_t port, bool postEvent) { remove_location(host, hosttracker::location(dpid,port,0), postEvent); } void hosttracker::remove_location(ethernetaddr host, hosttracker::location loc, bool postEvent) { hash_map<ethernetaddr,list<hosttracker::location> >::iterator i = \ hostlocation.find(host); if (i != hostlocation.end()) { bool changed = false; list<location>::iterator k = i->second.begin(); while (k != i->second.end()) { if (k->dpid == loc.dpid || k->port == loc.port) { k = i->second.erase(k); changed = true; } else k++; } if (postEvent && changed) post(new Host_location_event(host,i->second, (i->second.size() == 0)? Host_location_event::REMOVE: Host_location_event::MODIFY)); if (i->second.size() == 0) hostlocation.erase(i); } else VLOG_DBG(lg, "Host %"PRIx64" has no location, cannot unset.", host.hb_long()); } const hosttracker::location hosttracker::get_latest_location(ethernetaddr host) { list<hosttracker::location> locs = \ (list<hosttracker::location>) get_locations(host); if (locs.size() == 0) return hosttracker::location(datapathid(), 0, 0); else return *(get_newest(locs)); } const list<ethernetaddr> hosttracker::get_hosts() { list<ethernetaddr> hostlist; hash_map<ethernetaddr,list<hosttracker::location> >::iterator i = \ hostlocation.begin(); while (i != hostlocation.end()) { hostlist.push_back(i->first); i++; } return hostlist; } const list<hosttracker::location> hosttracker::get_locations(ethernetaddr host) { hash_map<ethernetaddr,list<hosttracker::location> >::iterator i = \ hostlocation.find(host); if (i == hostlocation.end()) return list<hosttracker::location>(); else return i->second; } list<hosttracker::location>::iterator hosttracker::get_newest(list<hosttracker::location>& loclist) { list<location>::iterator newest = loclist.begin(); list<location>::iterator j = loclist.begin(); while (j != loclist.end()) { if (j->lastTime > newest->lastTime) newest = j; j++; } return newest; } list<hosttracker::location>::iterator hosttracker::get_oldest(list<hosttracker::location>& loclist) { list<location>::iterator oldest = loclist.begin(); list<location>::iterator j = loclist.begin(); while (j != loclist.end()) { if (j->lastTime < oldest->lastTime) oldest = j; j++; } return oldest; } uint8_t hosttracker::getBindingNumber(ethernetaddr host) { hash_map<ethernetaddr,uint8_t>::iterator i = nBindings.find(host); if (i != nBindings.end()) return i->second; return defaultnBindings; } const list<hosttracker::location> hosttracker::getLocations(ethernetaddr host) { hash_map<ethernetaddr,list<hosttracker::location> >::iterator i = \ hostlocation.find(host); if (i == hostlocation.end()) return list<hosttracker::location>(); return i->second; } void hosttracker::getInstance(const Context* c, hosttracker*& component) { component = dynamic_cast<hosttracker*> (c->get_by_interface(container::Interface_description (typeid(hosttracker).name()))); } REGISTER_COMPONENT(Simple_component_factory<hosttracker>, hosttracker); } // vigil namespace
26.215232
81
0.629784
ayjazz
475c6b2d3279c433fdf8b7adeaa360ee3671a805
661
cpp
C++
cses/graph-algorithms/flight-discount.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
4
2020-10-05T19:24:10.000Z
2021-07-15T00:45:43.000Z
cses/graph-algorithms/flight-discount.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
null
null
null
cses/graph-algorithms/flight-discount.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
null
null
null
#include <cpplib/stdinc.hpp> #include <cpplib/graph/shortest-path/dijkstra.hpp> int32_t main(){ // https://cses.fi/problemset/task/1195 desync(); int n, m; cin >> n >> m; vvii adj(n+1), adjinv(n+1); for(int i=0; i<m; ++i){ int a, b, c; cin >> a >> b >> c; adj[a].pb({b, c}); adjinv[b].pb({a, c}); } vi from = dijkstra(1, adj, INF*INF), to = dijkstra(n, adjinv, INF*INF); int ans = from[n]; for(int u=1; u<=n; ++u){ for(ii vw:adj[u]){ int v = vw.ff, w = vw.ss; ans = min(ans, from[u] + w/2 + to[v]); } } cout << ans << endl; return 0; }
24.481481
75
0.465961
tysm
47614d5c08eaa65b87512ced2d003ab1dd8dc524
21,690
cpp
C++
Extensions/ZilchShaders/LibraryTranslator.cpp
RachelWilSingh/ZeroCore
e9a2f82d395e5c89fb98eceac44ce60d016dbff3
[ "MIT" ]
52
2018-09-11T17:18:35.000Z
2022-03-13T15:28:21.000Z
Extensions/ZilchShaders/LibraryTranslator.cpp
RachelWilSingh/ZeroCore
e9a2f82d395e5c89fb98eceac44ce60d016dbff3
[ "MIT" ]
1,409
2018-09-19T18:03:43.000Z
2021-06-09T08:33:33.000Z
Extensions/ZilchShaders/LibraryTranslator.cpp
RachelWilSingh/ZeroCore
e9a2f82d395e5c89fb98eceac44ce60d016dbff3
[ "MIT" ]
26
2018-09-11T17:16:32.000Z
2021-11-22T06:21:19.000Z
/////////////////////////////////////////////////////////////////////////////// /// /// Authors: Joshua Davis /// Copyright 2015, DigiPen Institute of Technology /// /////////////////////////////////////////////////////////////////////////////// #include "Precompiled.hpp" namespace Zero { //-------------------------------------------------------------------MemberAccessResolverWrapper FunctionCallResolverWrapper::FunctionCallResolverWrapper() : mFnCall(nullptr), mConstructorCallResolver(nullptr) { } FunctionCallResolverWrapper::FunctionCallResolverWrapper(FunctionCallResolverFn fnCall) : mFnCall(fnCall), mConstructorCallResolver(nullptr) { } FunctionCallResolverWrapper::FunctionCallResolverWrapper(ConstructorCallResolverFn constructorCall) : mFnCall(nullptr), mConstructorCallResolver(constructorCall) { } FunctionCallResolverWrapper::FunctionCallResolverWrapper(StringParam str) : mFnCall(nullptr), mConstructorCallResolver(nullptr) { mBackupString = str; } void FunctionCallResolverWrapper::Translate(ZilchShaderTranslator* translator, Zilch::FunctionCallNode* fnCallNode, Zilch::MemberAccessNode* memberAccessNode, ZilchShaderTranslatorContext* context) { // Call the function pointer if we have it, otherwise use the backup string if(mFnCall != nullptr) mFnCall(translator, fnCallNode, memberAccessNode, context); else context->GetBuilder() << mBackupString; } void FunctionCallResolverWrapper::Translate(ZilchShaderTranslator* translator, Zilch::FunctionCallNode* fnCallNode, Zilch::StaticTypeNode* staticTypeNode, ZilchShaderTranslatorContext* context) { // Call the function pointer if we have it, otherwise use the backup string if(mConstructorCallResolver != nullptr) mConstructorCallResolver(translator, fnCallNode, staticTypeNode, context); else context->GetBuilder() << mBackupString; } void FunctionCallResolverWrapper::Translate(ZilchShaderTranslator* translator, ZilchShaderTranslatorContext* context) { context->GetBuilder() << mBackupString; } //-------------------------------------------------------------------MemberAccessResolverWrapper MemberAccessResolverWrapper::MemberAccessResolverWrapper() : mResolverFn(nullptr) { } MemberAccessResolverWrapper::MemberAccessResolverWrapper(MemberAccessResolverFn resolverFn) : mResolverFn(resolverFn) { } MemberAccessResolverWrapper::MemberAccessResolverWrapper(StringParam replacementStr) : mResolverFn(nullptr), mNameReplacementString(replacementStr) { } void MemberAccessResolverWrapper::Translate(ZilchShaderTranslator* translator, Zilch::MemberAccessNode* memberAccessNode, ZilchShaderTranslatorContext* context) { // Call the function pointer if we have it, otherwise use the backup string if(mResolverFn != nullptr) mResolverFn(translator, memberAccessNode, context); else context->GetBuilder() << mNameReplacementString; } //-------------------------------------------------------------------BinaryOpResolverWrapper BinaryOpResolverWrapper::BinaryOpResolverWrapper() : mResolverFn(nullptr) { } BinaryOpResolverWrapper::BinaryOpResolverWrapper(BinaryOpResolver resolverFn) : mResolverFn(resolverFn) { } BinaryOpResolverWrapper::BinaryOpResolverWrapper(StringParam replacementFnCallStr) : mResolverFn(nullptr), mReplacementFnCallStr(replacementFnCallStr) { } void BinaryOpResolverWrapper::Translate(ZilchShaderTranslator* translator, Zilch::BinaryOperatorNode* node, ZilchShaderTranslatorContext* context) { // Call the function pointer if we have it, otherwise use the backup string if(mResolverFn != nullptr) mResolverFn(translator, node, context); else { ScopedShaderCodeBuilder subBuilder(context); subBuilder << mReplacementFnCallStr << "("; context->Walker->Walk(translator, node->LeftOperand, context); subBuilder.Write(", "); context->Walker->Walk(translator, node->RightOperand, context); subBuilder.Write(")"); subBuilder.PopFromStack(); context->GetBuilder().Write(subBuilder.ToString()); } } //-------------------------------------------------------------------LibraryTranslator LibraryTranslator::LibraryTranslator() { Reset(); } void LibraryTranslator::Reset() { mNativeLibraryParser = nullptr; mTemplateTypeResolver = nullptr; mFunctionCallResolvers.Clear(); mBackupConstructorResolvers.Clear(); mMemberAccessFieldResolvers.Clear(); mMemberAccessPropertyResolvers.Clear(); mMemberAccessFunctionResolvers.Clear(); mBackupMemberAccessResolvers.Clear(); mBinaryOpResolvers.Clear(); mIntializerResolvers.Clear(); mRegisteredTemplates.Clear(); } void LibraryTranslator::RegisterNativeLibraryParser(NativeLibraryParser nativeLibraryParser) { mNativeLibraryParser = nativeLibraryParser; } void LibraryTranslator::ParseNativeLibrary(ZilchShaderTranslator* translator, ZilchShaderLibrary* shaderLibrary) { ErrorIf(mNativeLibraryParser == nullptr, "No native library parser registered"); (*mNativeLibraryParser)(translator, shaderLibrary); } void LibraryTranslator::RegisterFunctionCallResolver(Zilch::Function* fn, const FunctionCallResolverWrapper& wrapper) { ErrorIf(fn == nullptr, "Cannot register a null function. Many things will break in this case."); mFunctionCallResolvers[fn] = wrapper; } void LibraryTranslator::RegisterFunctionCallResolver(Zilch::Function* fn, FunctionCallResolverFn resolver) { ErrorIf(fn == nullptr, "Cannot register a null function. Many things will break in this case."); RegisterFunctionCallResolver(fn, FunctionCallResolverWrapper(resolver)); } void LibraryTranslator::RegisterFunctionCallResolver(Zilch::Function* fn, ConstructorCallResolverFn resolver) { ErrorIf(fn == nullptr, "Cannot register a null function. Many things will break in this case."); RegisterFunctionCallResolver(fn, FunctionCallResolverWrapper(resolver)); } void LibraryTranslator::RegisterFunctionCallResolver(Zilch::Function* fn, StringParam replacementStr) { ErrorIf(fn == nullptr, "Cannot register a null function. Many things will break in this case."); RegisterFunctionCallResolver(fn, FunctionCallResolverWrapper(replacementStr)); } void LibraryTranslator::RegisterBackupConstructorResolver(Zilch::Type* type, ConstructorCallResolverFn resolver) { mBackupConstructorResolvers[type] = FunctionCallResolverWrapper(resolver); } bool LibraryTranslator::ResolveFunctionCall(ZilchShaderTranslator* translator, Zilch::FunctionCallNode* fnCallNode, ZilchShaderTranslatorContext* context) { // Check and see if the left node is a static type node. This happens when constructing a type, such as Real2(); Zilch::StaticTypeNode* staticTypeNode = Zilch::Type::DynamicCast<Zilch::StaticTypeNode*>(fnCallNode->LeftOperand); if(staticTypeNode != nullptr) { FunctionCallResolverWrapper* wrapper = mFunctionCallResolvers.FindPointer(staticTypeNode->ConstructorFunction); if(wrapper != nullptr) { wrapper->Translate(translator, fnCallNode, staticTypeNode, context); return true; } wrapper = mBackupConstructorResolvers.FindPointer(staticTypeNode->ResultType); if(wrapper != nullptr) { wrapper->Translate(translator, fnCallNode, staticTypeNode, context); return true; } if(staticTypeNode->ConstructorFunction != nullptr && !translator->IsInOwningLibrary(staticTypeNode->ConstructorFunction->GetOwningLibrary())) { String msg = String::Format("Constructor of type '%s' is not able to be translated.", staticTypeNode->ResultType->ToString().c_str()); translator->SendTranslationError(staticTypeNode->Location, msg); } } // Otherwise try a member access node. This happens on both static and instance function calls. Zilch::MemberAccessNode* memberAccessNode = Zilch::Type::DynamicCast<Zilch::MemberAccessNode*>(fnCallNode->LeftOperand); if(memberAccessNode != nullptr) { FunctionCallResolverWrapper* wrapper = mFunctionCallResolvers.FindPointer(memberAccessNode->AccessedFunction); if(wrapper != nullptr) { wrapper->Translate(translator, fnCallNode, memberAccessNode, context); return true; } // If we are calling an extension function then mark the class with the extension function as a dependency. // There's no need to alter the translation though as the member access node and function translation should be the same as normal. ShaderFunction* extensionFunction = mTranslator->mCurrentLibrary->FindExtension(memberAccessNode->AccessedFunction); if(extensionFunction != nullptr) { context->mCurrentType->AddDependency(extensionFunction->mOwner); return false; } // Don't make it an error to not translate a function here. Since this is a member // access node we'll have another chance to translate it when we resolve MemberAccessNode. // This location allows a simpler replacement of just the function name (eg. Math.Dot -> dot). // If we can't translate it by the time we get there then it'll be an error. } // Otherwise we didn't have a special translation for this function, let the normal translation happen. return false; } bool LibraryTranslator::ResolveDefaultConstructor(ZilchShaderTranslator* translator, Zilch::Type* type, Zilch::Function* constructorFn, ZilchShaderTranslatorContext* context) { FunctionCallResolverWrapper* wrapper = mFunctionCallResolvers.FindPointer(constructorFn); if(wrapper != nullptr) { wrapper->Translate(translator, context); return true; } if(constructorFn != nullptr && !translator->IsInOwningLibrary(constructorFn->GetOwningLibrary())) { String msg = String::Format("Default constructor of type '%s' is not able to be translated", type->ToString().c_str()); translator->SendTranslationError(constructorFn->Location, msg); } return false; } void LibraryTranslator::RegisterMemberAccessResolver(Zilch::Field* field, const MemberAccessResolverWrapper& wrapper) { mMemberAccessFieldResolvers[field] = wrapper; } void LibraryTranslator::RegisterMemberAccessResolver(Zilch::Field* field, MemberAccessResolverFn resolverFn) { RegisterMemberAccessResolver(field, MemberAccessResolverWrapper(resolverFn)); } void LibraryTranslator::RegisterMemberAccessResolver(Zilch::Field* field, StringParam replacementStr) { RegisterMemberAccessResolver(field, MemberAccessResolverWrapper(replacementStr)); } void LibraryTranslator::RegisterMemberAccessResolver(Zilch::Property* prop, const MemberAccessResolverWrapper& wrapper) { ErrorIf(prop == nullptr, "Cannot register a null property. Many things will break in this case."); mMemberAccessPropertyResolvers[prop] = wrapper; } void LibraryTranslator::RegisterMemberAccessResolver(Zilch::Property* prop, MemberAccessResolverFn resolverFn) { RegisterMemberAccessResolver(prop, MemberAccessResolverWrapper(resolverFn)); } void LibraryTranslator::RegisterMemberAccessResolver(Zilch::Property* prop, StringParam replacementStr) { RegisterMemberAccessResolver(prop, MemberAccessResolverWrapper(replacementStr)); } void LibraryTranslator::RegisterMemberAccessResolver(Zilch::Function* function, const MemberAccessResolverWrapper& wrapper) { mMemberAccessFunctionResolvers[function] = wrapper; } void LibraryTranslator::RegisterMemberAccessResolver(Zilch::Function* function, MemberAccessResolverFn resolverFn) { RegisterMemberAccessResolver(function, MemberAccessResolverWrapper(resolverFn)); } void LibraryTranslator::RegisterMemberAccessResolver(Zilch::Function* function, StringParam replacementStr) { RegisterMemberAccessResolver(function, MemberAccessResolverWrapper(replacementStr)); } void LibraryTranslator::RegisterMemberAccessBackupResolver(Zilch::Type* type, MemberAccessResolverFn resolverFn) { mBackupMemberAccessResolvers[type] = MemberAccessResolverWrapper(resolverFn); } bool LibraryTranslator::ResolveMemberAccess(ZilchShaderTranslator* translator, Zilch::MemberAccessNode* memberAccessNode, ZilchShaderTranslatorContext* context) { if(memberAccessNode->AccessedField != nullptr) { Zilch::Field* field = memberAccessNode->AccessedField; MemberAccessResolverWrapper* wrapper = mMemberAccessFieldResolvers.FindPointer(field); if(wrapper != nullptr) { wrapper->Translate(translator, memberAccessNode, context); return true; } // Get the bound type (converts indirection types to bound types) Zilch::Type* resultType = Zilch::BoundType::GetBoundType(memberAccessNode->LeftOperand->ResultType); wrapper = mBackupMemberAccessResolvers.FindPointer(resultType); if(wrapper != nullptr) { wrapper->Translate(translator, memberAccessNode, context); return true; } else if(!mTranslator->IsInOwningLibrary(field->GetOwningLibrary())) { String msg = String::Format("Member Field '%s' is not able to be translated.", memberAccessNode->Name.c_str()); translator->SendTranslationError(memberAccessNode->Location, msg); } } if(memberAccessNode->AccessedProperty != nullptr) { Zilch::Property* prop = memberAccessNode->AccessedProperty; // If this is actually a get/set property then mark a dependency on the type that actually implements the extension function Zilch::GetterSetter* getSet = memberAccessNode->AccessedGetterSetter; if(getSet != nullptr) { if(memberAccessNode->IoUsage == Zilch::IoMode::ReadRValue) { ShaderFunction* extensionFunction = mTranslator->mCurrentLibrary->FindExtension(getSet->Get); if(extensionFunction != nullptr) { context->mCurrentType->AddDependency(extensionFunction->mOwner); return false; } // See if this function has been implemented by another class ShaderFunction* implementsFunction = mTranslator->mCurrentLibrary->FindImplements(getSet->Get); if(implementsFunction != nullptr) { // Mark the implementing class as a dependency of this one context->mCurrentType->AddDependency(implementsFunction->mOwner); // Instead of printing the function's name from zilch, replace it with the name of the implementing function context->GetBuilder() << implementsFunction->mShaderName; // Since we replaced a member with a function we have to manually add the function call parenthesis context->GetBuilder() << "("; // If this is an instance function then we have to pass through and translate 'this' if(!implementsFunction->IsStatic()) context->Walker->Walk(translator, memberAccessNode->LeftOperand, context); context->GetBuilder() << ")"; // Return that we replaced this member access return true; } } } MemberAccessResolverWrapper* wrapper = mMemberAccessPropertyResolvers.FindPointer(prop); if(wrapper != nullptr) { wrapper->Translate(translator, memberAccessNode, context); return true; } // Check backup resolvers last, after we've tried all other options wrapper = mBackupMemberAccessResolvers.FindPointer(memberAccessNode->LeftOperand->ResultType); if(wrapper != nullptr) { wrapper->Translate(translator, memberAccessNode, context); return true; } else if(!mTranslator->IsInOwningLibrary(prop->GetOwningLibrary())) { String resultType = memberAccessNode->LeftOperand->ResultType->ToString(); String propertyResultType = memberAccessNode->ResultType->ToString(); String msg = String::Format("Member property '%s:%s' on type '%s' is not able to be translated.", memberAccessNode->Name.c_str(), propertyResultType.c_str(), resultType.c_str()); translator->SendTranslationError(memberAccessNode->Location, msg); } } if(memberAccessNode->AccessedFunction != nullptr) { Zilch::Function* fn = memberAccessNode->AccessedFunction; // See if this function has been implemented by another class ShaderFunction* implementsFunction = mTranslator->mCurrentLibrary->FindImplements(fn); if(implementsFunction != nullptr) { // Mark the implementing class as a dependency of this one context->mCurrentType->AddDependency(implementsFunction->mOwner); // Instead of printing the function's name from zilch, replace it with the name of the implementing function context->GetBuilder() << implementsFunction->mShaderName; // Return that we replaced this function name return true; } MemberAccessResolverWrapper* wrapper = mMemberAccessFunctionResolvers.FindPointer(fn); if(wrapper != nullptr) { wrapper->Translate(translator, memberAccessNode, context); return true; } // For now just mark that extension functions are not errors (let translation happen as normal) // @JoshD: Cleanup and merge somehow with the function call portion! ShaderFunction* extensionFunction = mTranslator->mCurrentLibrary->FindExtension(fn); if(extensionFunction != nullptr) { return false; } else if(!mTranslator->IsInOwningLibrary(fn->GetOwningLibrary())) { String fnName = GetFunctionDescription(memberAccessNode->Name, memberAccessNode->AccessedFunction); String msg = String::Format("Member function '%s' is not able to be translated.", fnName.c_str()); translator->SendTranslationError(memberAccessNode->Location, msg); } } // Otherwise we didn't have a special translation for this member, let the normal translation happen. return false; } void LibraryTranslator::RegisterBinaryOpResolver(Zilch::Type* typeA, Zilch::Grammar::Enum op, Zilch::Type* typeB, const BinaryOpResolverWrapper wrapper) { String key = BuildString(typeA->ToString(), Zilch::Grammar::GetKeywordOrSymbol(op), typeB->ToString()); RegisterBinaryOpResolver(key, wrapper); } void LibraryTranslator::RegisterBinaryOpResolver(Zilch::Type* typeA, Zilch::Grammar::Enum op, Zilch::Type* typeB, StringParam replacementFnCallStr) { RegisterBinaryOpResolver(typeA, op, typeB, BinaryOpResolverWrapper(replacementFnCallStr)); } void LibraryTranslator::RegisterBinaryOpResolver(Zilch::Type* typeA, Zilch::Grammar::Enum op, Zilch::Type* typeB, BinaryOpResolver resolverFn) { RegisterBinaryOpResolver(typeA, op, typeB, BinaryOpResolverWrapper(resolverFn)); } void LibraryTranslator::RegisterBinaryOpResolver(StringParam key, const BinaryOpResolverWrapper wrapper) { mBinaryOpResolvers[key] = wrapper; } void LibraryTranslator::RegisterBinaryOpResolver(StringParam key, StringParam replacementFnCallStr) { RegisterBinaryOpResolver(key, BinaryOpResolverWrapper(replacementFnCallStr)); } void LibraryTranslator::RegisterBinaryOpResolver(StringParam key, BinaryOpResolver resolverFn) { RegisterBinaryOpResolver(key, BinaryOpResolverWrapper(resolverFn)); } bool LibraryTranslator::ResolveBinaryOp(ZilchShaderTranslator* translator, Zilch::BinaryOperatorNode* node, ZilchShaderTranslatorContext* context) { // Build the key for this operator which is (type)(operator)(type) and use that to lookup a replacement String operatorSignature = BuildString(node->LeftOperand->ResultType->ToString(), node->Operator->Token, node->RightOperand->ResultType->ToString()); BinaryOpResolverWrapper* resolverWrapper = mBinaryOpResolvers.FindPointer(operatorSignature); if(resolverWrapper != nullptr) resolverWrapper->Translate(translator, node, context); return resolverWrapper != nullptr; } void LibraryTranslator::RegisterTemplateTypeResolver(TemplateTypeResolver resolver) { mTemplateTypeResolver = resolver; } void LibraryTranslator::RegisterInitializerNodeResolver(Zilch::Type* type, InitializerResolver resolver) { mIntializerResolvers[type] = resolver; } bool LibraryTranslator::ResolveInitializerNode(ZilchShaderTranslator* translator, Zilch::Type* type, Zilch::ExpressionInitializerNode* initializerNode, ZilchShaderTranslatorContext* context) { InitializerResolver resolver = mIntializerResolvers.FindValue(type, nullptr); if(resolver == nullptr) return false; (*resolver)(translator, type, initializerNode, context); return true; } String LibraryTranslator::GetFunctionDescription(StringParam fnName, Zilch::Function* fn) { StringBuilder builder; builder.Append(fnName); fn->FunctionType->BuildSignatureString(builder, false); return builder.ToString(); } bool LibraryTranslator::IsUserLibrary(Zilch::Library* library) { //@JoshD: Fix! Array<ZilchShaderLibrary*> libraryStack; libraryStack.PushBack(mTranslator->mCurrentLibrary); while(!libraryStack.Empty()) { ZilchShaderLibrary* testLibrary = libraryStack.Back(); libraryStack.PopBack(); Zilch::Library* testZilchLibrary = testLibrary->mZilchLibrary; // If the library is the same and it's user code // (as in we compiled zilch scripts, not C++) then this is a user library if(testZilchLibrary == library && testLibrary->mIsUserCode) return true; // Add all dependencies of this library ZilchShaderModule* dependencies = testLibrary->mDependencies; if(dependencies != nullptr) { for(size_t i = 0; i < dependencies->Size(); ++i) libraryStack.PushBack((*dependencies)[i]); } } return false; } }//namespace Zero
41.235741
198
0.734071
RachelWilSingh
47684729576dfa76505d3551eec1f5544e4b1749
325
cc
C++
common/buffer/buffer_error.cc
changchengx/ReplicWBCache
f0a8ef3108513fcac3a2291dafaebfb52cacfcac
[ "Apache-2.0" ]
null
null
null
common/buffer/buffer_error.cc
changchengx/ReplicWBCache
f0a8ef3108513fcac3a2291dafaebfb52cacfcac
[ "Apache-2.0" ]
null
null
null
common/buffer/buffer_error.cc
changchengx/ReplicWBCache
f0a8ef3108513fcac3a2291dafaebfb52cacfcac
[ "Apache-2.0" ]
null
null
null
/* * SPDX-License-Identifier: Apache-2.0 * Copyright(c) 2020 Liu, Changcheng <changcheng.liu@aliyun.com> */ #include <iostream> #include "buffer/buffer_error.h" std::ostream& spec::buffer::operator<<(std::ostream& out, const spec::buffer::error& berror) { const char* info = berror.what(); return out << info; }
25
94
0.683077
changchengx
476c479cdfcd3cbd35ea8f9f9d6f33c1e5e24777
338
cc
C++
lib/AST/OutputPort.cc
rawatamit/scheme
2c5e121fa873a2fb7762b69027480e28686bbb87
[ "MIT" ]
null
null
null
lib/AST/OutputPort.cc
rawatamit/scheme
2c5e121fa873a2fb7762b69027480e28686bbb87
[ "MIT" ]
null
null
null
lib/AST/OutputPort.cc
rawatamit/scheme
2c5e121fa873a2fb7762b69027480e28686bbb87
[ "MIT" ]
null
null
null
#include "AST/OutputPort.h" Scheme::OutputPort::OutputPort(FILE* out) : Scheme::SchemeObject(Scheme::SchemeObject::OUTPUT_PORT_TY), out_(out) {} Scheme::OutputPort::~OutputPort() {} FILE* Scheme::OutputPort::getOutputStream() const { return out_; } int Scheme::OutputPort::closeOutputStream() { return fclose(out_); }
19.882353
77
0.707101
rawatamit
476e156b97f8e3552d02104d5edbe3c0bde6a514
9,400
cpp
C++
BesImage/appConfig.cpp
BensonLaur/BesImage
63e32cc35db093fbe3f3033c32837ee6595d8c49
[ "MIT" ]
2
2019-10-17T06:13:13.000Z
2020-05-24T12:39:47.000Z
BesImage/appConfig.cpp
BensonLaur/BesImage
63e32cc35db093fbe3f3033c32837ee6595d8c49
[ "MIT" ]
null
null
null
BesImage/appConfig.cpp
BensonLaur/BesImage
63e32cc35db093fbe3f3033c32837ee6595d8c49
[ "MIT" ]
3
2019-06-30T02:31:42.000Z
2021-11-30T02:14:24.000Z
#include "appConfig.h" AppConfig& AppConfig::GetInstance() { static AppConfig* instance = nullptr; if(instance == nullptr) instance = new AppConfig(); return *instance; } //获得打数 (如果未加载自动去文件读取,已加载则使用已载入的参数。bForceLoadFromFile 强制从文件获得最新参数) bool AppConfig::GetAppParameter(AppConfigParameter& param, bool bForceLoadFromFile) { if(!m_hasLoad || bForceLoadFromFile) { QString confPath; if(!MakeSureConfigPathAvailable(confPath)) //获得路径 return false; if(!QFile::exists(confPath)) //不存在,自动创建配置,并提示 { param = AppConfigParameter(); if(SetAppParameter(param)) QMessageBox::information(nullptr,tr("提示"),tr("配置文件不存在,已自动创建")+":" + confPath, QMessageBox::Yes,QMessageBox::Yes); else QMessageBox::information(nullptr,tr("提示"),tr("配置文件不存在,自动创建失败")+":" + confPath, QMessageBox::Yes,QMessageBox::Yes); m_param = param; } else //存在,读取配置 { if(!LoadAppConfig()) QMessageBox::information(nullptr,tr("提示"),tr("载入配置文件失败")+":" + confPath, QMessageBox::Yes,QMessageBox::Yes); } m_hasLoad = true; } param = m_param; return true; } //设置参数 bool AppConfig::SetAppParameter(const AppConfigParameter& param) { m_param = param; return SaveAppConfig(); } //判断当前配置是否是有效的“只显示一张图片” bool AppConfig::IsValidOnlyShowOneImage() { if(m_param.onlyShowOneImage) //有设置onluyShowOneImage { if(m_param.initPath.size() != 0) { QFileInfo fi(m_param.initPath); if(fi.isFile()) //传入的路径确实是一个文件 return true; } } return false; } //从默认路径中加载打印参数 bool AppConfig::LoadAppConfig() { QString confPath; if(!MakeSureConfigPathAvailable(confPath)) //确保配置路径可用,并获得了路径 return false; //打开文件 QFile file(confPath); if (!file.open(QFile::ReadOnly | QFile::Text)) { // 只读模式打开文件 qDebug() << QString("Cannot read file %1(%2).").arg(confPath).arg(file.errorString()); return false; } AppConfigParameter param; //读取示例参考: https://blog.csdn.net/liang19890820/article/details/52808829 //将配置从xml文件读出 QXmlStreamReader reader(&file); QString strElementName = ""; // 解析 XML,直到结束 while (!reader.atEnd()) { // 读取下一个元素 QXmlStreamReader::TokenType nType = reader.readNext(); if (nType == QXmlStreamReader::StartElement) { strElementName = reader.name().toString(); if (QString::compare(strElementName, "appConfig") == 0) // 根元素 { parseConfig(reader, param); //解析 printConfig } } } if (reader.hasError()) { // 解析出错 qDebug() << QObject::tr("错误信息:%1 行号:%2 列号:%3 字符位移:%4").arg(reader.errorString()).arg(reader.lineNumber()).arg(reader.columnNumber()).arg(reader.characterOffset()); } file.close(); // 关闭文件 m_param = param; return true; } //解析config void AppConfig::parseConfig(QXmlStreamReader &reader, AppConfigParameter &param) { while (!reader.atEnd()) { reader.readNext(); if (reader.isStartElement()) { // 开始元素 QString strElementName = reader.name().toString(); if(strElementName == "user") { parseUser(reader, param); } else if(strElementName == "default") { parseDefault(reader, param); } } else if(reader.isEndElement()) { QString strElementName = reader.name().toString(); if (QString::compare(strElementName, "appConfig") == 0) { break; // 跳出 } } } } //解析user void AppConfig::parseUser(QXmlStreamReader &reader, AppConfigParameter &param) { while (!reader.atEnd()) { reader.readNext(); if (reader.isStartElement()) { // 开始元素 QString strElementName = reader.name().toString(); if(strElementName == "functionMode") { param.functionMode = (FunctionMode)reader.readElementText().toInt(); } else if(strElementName == "appTitle") { param.appTitle = reader.readElementText(); } else if(strElementName == "iconPath") { param.iconPath = reader.readElementText(); } else if(strElementName == "backgroundImagePath") { param.backgroundImagePath = reader.readElementText(); } else if(strElementName == "initPath") { param.initPath = reader.readElementText(); } else if(strElementName == "onlyShowOneImage") { param.onlyShowOneImage = reader.readElementText().toInt()== 0 ? false:true; } else if(strElementName == "closeDirTreeOnOpen") { param.closeDirTreeOnOpen = reader.readElementText().toInt() == 0 ? false:true; } } else if(reader.isEndElement()) { QString strElementName = reader.name().toString(); if (QString::compare(strElementName, "user") == 0) { break; // 跳出 } } } } //解析default void AppConfig::parseDefault(QXmlStreamReader &reader, AppConfigParameter &param) { while (!reader.atEnd()) { reader.readNext(); if (reader.isStartElement()) { // 开始元素 QString strElementName = reader.name().toString(); if(strElementName == "defaultBackgroundPath") { param.defaultBackgroundPath = reader.readElementText(); } else if(strElementName == "besimageBlackIcon") { param.besimageBlackIcon = reader.readElementText(); } else if(strElementName == "besimageWhiteIcon") { param.besimageWhiteIcon = reader.readElementText(); } else if(strElementName == "isWindowHeaderColorBlack") { param.isWindowHeaderColorBlack = reader.readElementText().toInt()== 0 ? false:true; } else if(strElementName == "bgFillMode") { param.bgFillMode = (BGFillMode)reader.readElementText().toInt(); } } else if(reader.isEndElement()) { QString strElementName = reader.name().toString(); if (QString::compare(strElementName, "default") == 0) { break; // 跳出 } } } } //保存到打印参数 bool AppConfig::SaveAppConfig() { QString confPath; if(!MakeSureConfigPathAvailable(confPath)) //确保配置路径可用,并获得了路径 return false; //打开文件 QFile file(confPath); if (!file.open(QFile::WriteOnly | QFile::Text)) { // 只写模式打开文件 qDebug() << QString("Cannot write file %1(%2).").arg(confPath).arg(file.errorString()); return false; } //将配置写入xml文件 QXmlStreamWriter writer(&file); writer.setAutoFormatting(true); // 自动格式化 writer.writeStartDocument("1.0", true); // 开始文档(XML 声明) writer.writeStartElement("appConfig"); // 开始元素<appConfig> writer.writeStartElement("user"); // 开始元素<user> writer.writeTextElement("functionMode", QString::number((int)m_param.functionMode)); writer.writeTextElement("appTitle", m_param.appTitle); writer.writeTextElement("iconPath", m_param.iconPath); writer.writeTextElement("backgroundImagePath", m_param.backgroundImagePath); writer.writeTextElement("initPath", m_param.initPath); writer.writeTextElement("onlyShowOneImage", QString::number(m_param.onlyShowOneImage ? 1 : 0)); writer.writeTextElement("closeDirTreeOnOpen", QString::number(m_param.closeDirTreeOnOpen? 1 : 0)); writer.writeEndElement(); // 结束子元素 </user> writer.writeStartElement("default"); // 开始元素<default> writer.writeTextElement("defaultBackgroundPath", m_param.defaultBackgroundPath); writer.writeTextElement("besimageBlackIcon", m_param.besimageBlackIcon); writer.writeTextElement("besimageWhiteIcon", m_param.besimageWhiteIcon); writer.writeTextElement("isWindowHeaderColorBlack", QString::number(m_param.isWindowHeaderColorBlack ? 1 : 0)); writer.writeTextElement("bgFillMode", QString::number((int)m_param.bgFillMode)); writer.writeEndElement(); // 结束子元素 </default> writer.writeEndElement(); // 结束子元素 </appConfig> writer.writeEndDocument(); // 结束文档 file.close(); // 关闭文件 return true; } //确保配置路径可用,返回配置路径 bool AppConfig::MakeSureConfigPathAvailable(QString &path) { QString StrSettingsDir = QCoreApplication::applicationDirPath() + "/settings"; //如果settings 目录不存在则创建目录 QDir SettingDir(StrSettingsDir); if(!SettingDir.exists()) { if(!SettingDir.mkpath(StrSettingsDir)) { QMessageBox::information(nullptr,tr("提示"),tr("无法为配置创建目录")+":" + StrSettingsDir, QMessageBox::Yes,QMessageBox::Yes); return false; } } //得到目标路径 path = StrSettingsDir + "/app.config"; return true; }
29.936306
177
0.58266
BensonLaur
47796a9a1dbf55676661038472e0926a913caf1b
820
cpp
C++
CorrelationApp/CheckCorrelation/main.cpp
zkbreeze/KunPBR
9f545a4e589998691b469bbcadb65a63ac826ebd
[ "BSD-3-Clause" ]
null
null
null
CorrelationApp/CheckCorrelation/main.cpp
zkbreeze/KunPBR
9f545a4e589998691b469bbcadb65a63ac826ebd
[ "BSD-3-Clause" ]
null
null
null
CorrelationApp/CheckCorrelation/main.cpp
zkbreeze/KunPBR
9f545a4e589998691b469bbcadb65a63ac826ebd
[ "BSD-3-Clause" ]
null
null
null
// // main.cpp // // // Created by Kun Zhao on 2015-12-11 15:22:50. // // #include <iostream> #include <fstream> #include "Correlation.h" // Load test csv data int main( int argc, char** argv ) { std::ifstream ifs( argv[1], std::ifstream::in ); char* buf = new char[256]; ifs.getline( buf, 256 ); // Skip ifs.getline( buf, 256 ); // Skip kvs::ValueArray<float> sequences1; sequences1.allocate( 27 ); kvs::ValueArray<float> sequences2; sequences2.allocate( 27 ); for( size_t i = 0; i < 27; i++ ) { ifs.getline( buf, 256 ); std::sscanf( buf, "%f,%f", &sequences1.data()[i], &sequences2.data()[i] ); std::cout << sequences1.data()[i] << ", " << sequences2.data()[i] <<std::endl; } float correlation = kun::Correlation::calculate( sequences1, sequences2 ); std::cout << correlation << std::endl; }
23.428571
80
0.62439
zkbreeze
47796f2012760298993adf0f73bdbf77d162e967
3,064
cpp
C++
higan/sfc/coprocessor/icd2/interface/interface.cpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
3
2016-03-23T01:17:36.000Z
2019-10-25T06:41:09.000Z
higan/sfc/coprocessor/icd2/interface/interface.cpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
null
null
null
higan/sfc/coprocessor/icd2/interface/interface.cpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
null
null
null
auto ICD2::lcdScanline() -> void { if(GameBoy::ppu.status.ly > 143) return; //Vblank if((GameBoy::ppu.status.ly & 7) == 0) { write_bank = (write_bank + 1) & 3; write_addr = 0; } } auto ICD2::lcdOutput(uint2 color) -> void { uint y = write_addr / 160; uint x = write_addr % 160; uint addr = write_bank * 512 + y * 2 + x / 8 * 16; output[addr + 0] = (output[addr + 0] << 1) | (bool)(color & 1); output[addr + 1] = (output[addr + 1] << 1) | (bool)(color & 2); write_addr = (write_addr + 1) % 1280; } auto ICD2::joypWrite(bool p15, bool p14) -> void { //joypad handling if(p15 == 1 && p14 == 1) { if(joyp15lock == 0 && joyp14lock == 0) { joyp15lock = 1; joyp14lock = 1; joyp_id = (joyp_id + 1) & 3; } } if(p15 == 0 && p14 == 1) joyp15lock = 0; if(p15 == 1 && p14 == 0) joyp14lock = 0; //packet handling if(p15 == 0 && p14 == 0) { //pulse pulselock = false; packetoffset = 0; bitoffset = 0; strobelock = true; packetlock = false; return; } if(pulselock) return; if(p15 == 1 && p14 == 1) { strobelock = false; return; } if(strobelock) { if(p15 == 1 || p14 == 1) { //malformed packet packetlock = false; pulselock = true; bitoffset = 0; packetoffset = 0; } else { return; } } //p15:1, p14:0 = 0 //p15:0, p14:1 = 1 bool bit = (p15 == 0); strobelock = true; if(packetlock) { if(p15 == 1 && p14 == 0) { if((joyp_packet[0] >> 3) == 0x11) { mlt_req = joyp_packet[1] & 3; if(mlt_req == 2) mlt_req = 3; joyp_id = 0; } if(packetsize < 64) packet[packetsize++] = joyp_packet; packetlock = false; pulselock = true; } return; } bitdata = (bit << 7) | (bitdata >> 1); if(++bitoffset < 8) return; bitoffset = 0; joyp_packet[packetoffset] = bitdata; if(++packetoffset < 16) return; packetlock = true; } auto ICD2::videoColor(uint source, uint16 red, uint16 green, uint16 blue) -> uint32 { return source; } auto ICD2::videoRefresh(const uint32* data, uint pitch, uint width, uint height) -> void { } auto ICD2::audioSample(int16 left, int16 right) -> void { audio.coprocessor_sample(left, right); } auto ICD2::inputPoll(uint port, uint device, uint id) -> int16 { GameBoy::cpu.status.mlt_req = joyp_id & mlt_req; uint data = 0x00; switch(joyp_id & mlt_req) { case 0: data = ~r6004; break; case 1: data = ~r6005; break; case 2: data = ~r6006; break; case 3: data = ~r6007; break; } switch((GameBoy::Input)id) { case GameBoy::Input::Start: return (bool)(data & 0x80); case GameBoy::Input::Select: return (bool)(data & 0x40); case GameBoy::Input::B: return (bool)(data & 0x20); case GameBoy::Input::A: return (bool)(data & 0x10); case GameBoy::Input::Down: return (bool)(data & 0x08); case GameBoy::Input::Up: return (bool)(data & 0x04); case GameBoy::Input::Left: return (bool)(data & 0x02); case GameBoy::Input::Right: return (bool)(data & 0x01); } return 0; }
24.910569
90
0.574739
ameer-bauer
477a2dce24aedf16869dd3b5bd5701dc2f7b277c
5,374
hh
C++
src/Damage/ScalarDamageModel.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/Damage/ScalarDamageModel.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
41
2020-09-28T23:14:27.000Z
2022-03-28T17:01:33.000Z
src/Damage/ScalarDamageModel.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
//---------------------------------Spheral++----------------------------------// // ScalarDamageModel -- Base class for the scalar damage physics models. // This class does not know how to seed the flaw distribution -- that is // required of descendant classes. // // Created by JMO, Sun Oct 10 17:22:05 PDT 2004 //----------------------------------------------------------------------------// #ifndef __Spheral_ScalarDamageModel_hh__ #define __Spheral_ScalarDamageModel_hh__ #include "Geometry/GeomPlane.hh" #include "NodeList/FluidNodeList.hh" #include "DamageModel.hh" #include <vector> // Forward declarations. namespace Spheral { template<typename Dimension> class State; template<typename Dimension> class StateDerivatives; template<typename Dimension> class GeomPlane; template<typename Dimension> class FluidNodeList; template<typename Dimension> class SolidNodeList; template<typename Dimension> class DataBase; template<typename Dimension, typename DataType> class Field; template<typename Dimension, typename DataType> class FieldList; } namespace Spheral { template<typename Dimension> class ScalarDamageModel: public DamageModel<Dimension> { public: //--------------------------- Public Interface ---------------------------// // Useful typedefs. typedef typename Dimension::Scalar Scalar; typedef typename Dimension::Vector Vector; typedef typename Dimension::Tensor Tensor; typedef typename Dimension::SymTensor SymTensor; typedef GeomPlane<Dimension> Plane; typedef typename Physics<Dimension>::TimeStepType TimeStepType; typedef typename Physics<Dimension>::ConstBoundaryIterator ConstBoundaryIterator; typedef Field<Dimension, std::vector<double> > FlawStorageType; // Constructors, destructor. ScalarDamageModel(SolidNodeList<Dimension>& nodeList, FluidNodeList<Dimension>& damagedNodeList, const double kernelExtent, const double crackGrowthMultiplier, const FlawStorageType& flaws); virtual ~ScalarDamageModel(); //........................................................................... // Provide the required physics package interface. // Compute the derivatives. virtual void evaluateDerivatives(const Scalar time, const Scalar dt, const DataBase<Dimension>& dataBase, const State<Dimension>& state, StateDerivatives<Dimension>& derivatives) const; // Vote on a time step. virtual TimeStepType dt(const DataBase<Dimension>& dataBase, const State<Dimension>& state, const StateDerivatives<Dimension>& derivs, const Scalar currentTime) const; // Register our state. virtual void registerState(DataBase<Dimension>& dataBase, State<Dimension>& state); // Register the derivatives/change fields for updating state. virtual void registerDerivatives(DataBase<Dimension>& dataBase, StateDerivatives<Dimension>& derivs); //........................................................................... // Finalize method, called at the end of a time step. virtual void finalize(const Scalar time, const Scalar dt, DataBase<Dimension>& db, State<Dimension>& state, StateDerivatives<Dimension>& derivs); // Access the damaged NodeList. const FluidNodeList<Dimension>& damagedNodeList() const; // Specify whether to split or refine fully failed nodes. bool splitFailedNodes() const; void splitFailedNodes(const bool x); // Provide access to the state fields we maintain. const Field<Dimension, Scalar>& strain() const; const Field<Dimension, Scalar>& damage() const; const Field<Dimension, Scalar>& DdamageDt() const; // Return a vector of undamged -> damaged node indicies. std::vector<int> undamagedToDamagedNodeIndicies() const; // The set of boundary planes to respect if creating new nodes. std::vector<Plane>& boundPlanes(); // Determine if the given position violates any of the specified boundary // planes. bool positionOutOfBounds(const Vector& r) const; //************************************************************************** // Restart methods. virtual void dumpState(FileIO& file, const std::string& pathName) const; virtual void restoreState(const FileIO& file, const std::string& pathName); //************************************************************************** private: //--------------------------- Private Interface ---------------------------// FluidNodeList<Dimension>* mDamagedNodeListPtr; bool mSplitFailedNodes; Field<Dimension, Scalar> mStrain; Field<Dimension, Scalar> mDamage; Field<Dimension, Scalar> mDdamageDt; Field<Dimension, Scalar> mMass0; Field<Dimension, int> mUndamagedToDamagedIndex; std::vector<Plane> mBoundPlanes; // No default constructor, copying or assignment. ScalarDamageModel(); ScalarDamageModel(const ScalarDamageModel&); ScalarDamageModel& operator=(const ScalarDamageModel&); }; } #else // Forward declaration. namespace Spheral { template<typename Dimension> class ScalarDamageModel; } #endif
36.557823
83
0.628768
jmikeowen
477f6910f6b332be8565a1020006d12339e9f4d7
1,693
cpp
C++
src/lib/slo/SloInfo.cpp
MarkLeone/PostHaste
56083e30a58489338e39387981029488d7af2390
[ "MIT" ]
4
2015-05-07T03:29:52.000Z
2016-08-29T17:30:15.000Z
src/lib/slo/SloInfo.cpp
MarkLeone/PostHaste
56083e30a58489338e39387981029488d7af2390
[ "MIT" ]
1
2018-05-14T04:41:04.000Z
2018-05-14T04:41:04.000Z
src/lib/slo/SloInfo.cpp
MarkLeone/PostHaste
56083e30a58489338e39387981029488d7af2390
[ "MIT" ]
null
null
null
// Copyright 2009 Mark Leone (markleone@gmail.com). All rights reserved. // Licensed under the terms of the MIT License. // See http://www.opensource.org/licenses/mit-license.php. #include "slo/SloInfo.h" #include "slo/SloInputFile.h" #include "slo/SloOutputFile.h" #include <string.h> int SloInfo::Read(SloInputFile* in) { if (const char* line = in->ReadLine()) { // Extract name. size_t delimIndex = strcspn(line, " \t"); mName = std::string(line, delimIndex); line += delimIndex; // Extract remaining fields. mOptUnknown = -1; int shaderType; int numFields = sscanf(line, " %i %i %i %i %i %i %i %i %i %i %i %i", &mNumSyms, &mNumConstants, &mNumStrings, &mUnknown3, &mNumInsts, &mUnknown1, &mNumInits, &mNumInits2, &mUnknown2, &mBeginPC, &shaderType, &mOptUnknown); mType = static_cast<SloShaderType>(shaderType); if (!SloIsKnown(mType)) in->Report(kUtWarning, "Unknown shader type %i", mType); if (numFields == 11 || numFields == 12) return 0; } in->Report(kUtError, "Error reading SLO info"); return 1; } void SloInfo::Write(SloOutputFile* file) const { file->Write("%s %i %i %i %i %i %i %i %i %i %i %i", mName.c_str(), mNumSyms, mNumConstants, mNumStrings, mUnknown3, mNumInsts, mUnknown1, mNumInits, mNumInits2, mUnknown2, mBeginPC, mType, mOptUnknown); if (mOptUnknown != -1) file->Write(" %i\n", mOptUnknown); else file->Write("\n"); }
33.86
79
0.558771
MarkLeone
4784403837a3640e1fa74c8ff40704737246c70f
3,593
cpp
C++
sample/gl/kalmanfilter/main.cpp
sanko-shoko/simplesp
6a71022dbb9a304e5a68d60885a04906dc78913a
[ "MIT" ]
24
2017-09-07T16:08:33.000Z
2022-02-26T16:32:48.000Z
sample/gl/kalmanfilter/main.cpp
sanko-shoko/simplesp
6a71022dbb9a304e5a68d60885a04906dc78913a
[ "MIT" ]
null
null
null
sample/gl/kalmanfilter/main.cpp
sanko-shoko/simplesp
6a71022dbb9a304e5a68d60885a04906dc78913a
[ "MIT" ]
8
2018-11-30T02:53:24.000Z
2021-05-18T06:30:42.000Z
#include "simplesp.h" #include "spex/spgl.h" using namespace sp; class KalmanfilterGUI : public BaseWindow { private: void help() { printf("\n"); } virtual void init() { help(); } virtual void display() { glClearColor(0.10f, 0.12f, 0.12f, 0.00f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); Mem2<Col3> img(320, 240); static int cnt = 0; // delta time const double dt = 0.1; // observation noise (sigma) const double onoize = 5.0; // system noize (sigma) const double snoize = 0.1; // observation Mat Z(2, 1); { // circle radius const double radius = 100.0; const double time = cnt * dt; const double angle = time * SP_PI / 180.0; const Vec2 pos = getVec2(::cos(angle), ::sin(angle)) * radius + getVec2(img.dsize[0] - 1, img.dsize[1] - 1) * 0.5; Z(0, 0) = pos.x + randg() * onoize; Z(1, 0) = pos.y + randg() * onoize; } static Mat X, Q, P, R, F, H; if (cnt == 0) { // initialize state // X (position 2d & velocity 2d) { double m[]{ Z(0, 0), Z(1, 0), 0.0, 0.0 }; X.resize(4, 1, m); } // Q (system noize covariance) { const double a = sq(dt * dt / 2.0); const double b = (dt * dt / 2.0) * dt; const double c = dt * dt; double m[]{ a, 0.0, b, 0.0, 0.0, a, 0.0, b, b, 0.0, c, 0.0, 0.0, b, 0.0, c }; Q.resize(4, 4, m); Q *= sq(snoize); } // P (state covariance) P = Q; // R (observation noize covariance) { double m[]{ 1.0, 0.0, 0.0, 1.0 }; R.resize(2, 2, m); R *= sq(onoize); } // F (prediction matrix) { double m[]{ 1.0, 0.0, dt, 0.0, 0.0, 1.0, 0.0, dt, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 }; F.resize(4, 4, m); } // H (observation matrix) { double m[]{ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, }; H.resize(2, 4, m); } } else { // predict X = F * X; P = F * P * trnMat(F) + Q; // kalman gain const Mat K = P * trnMat(H) * invMat(H * P * trnMat(H) + R); // update X = X + K * (Z - H * X); P = (eyeMat(4, 4) - K * H) * P; } setElm(img, getCol3(255, 255, 255)); renderPoint(img, getVec2(Z[0], Z[1]), getCol3(0, 0, 0), 3); renderPoint(img, getVec2(X[0], X[1]), getCol3(0, 0, 255), 5); glLoadView2D(img.dsize[0], img.dsize[1], m_viewPos, m_viewScale); glTexImg(img); //char path[256]; //sprintf(path, "img%03d.bmp", cnt); //saveBMP(img, path); cnt++; } }; int main(){ KalmanfilterGUI win; win.execute("kalmanfilter", 800, 600); return 0; }
23.180645
126
0.367659
sanko-shoko
47883c640e13051e023540983403195e1dca9627
820
cpp
C++
docs/mfc/codesnippet/CPP/ccolordialog-class_5.cpp
jmittert/cpp-docs
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
[ "CC-BY-4.0", "MIT" ]
14
2018-01-28T18:10:55.000Z
2021-11-16T13:21:18.000Z
docs/mfc/codesnippet/CPP/ccolordialog-class_5.cpp
jmittert/cpp-docs
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
[ "CC-BY-4.0", "MIT" ]
null
null
null
docs/mfc/codesnippet/CPP/ccolordialog-class_5.cpp
jmittert/cpp-docs
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
[ "CC-BY-4.0", "MIT" ]
2
2018-11-01T12:33:08.000Z
2021-11-16T13:21:19.000Z
// Override OnColorOK to validate the color entered to the // Red, Green, and Blue edit controls. If the color // is BLACK (i.e. RGB(0, 0,0)), then force the current color // selection to be the color initially selected when the // dialog box is created. The color dialog won't close so // user can enter a new color. BOOL CMyColorDlg::OnColorOK() { // Value in Red edit control. COLORREF clrref = GetColor(); if (RGB(0, 0, 0) == clrref) { AfxMessageBox(_T("BLACK is not an acceptable color. ") _T("Please enter a color again")); // GetColor() returns initially selected color. SetCurrentColor(GetColor()); // Won't dismiss color dialog. return TRUE; } // OK to dismiss color dialog. return FALSE; }
32.8
60
0.614634
jmittert
478b8065eb80f55e29466001e75deb52edbbb88c
1,900
cpp
C++
Ch04/comp3.cpp
rzotya0327/UDProg-Introduction
c64244ee541d4ad0c85645385ef4f0c2e1886621
[ "CC0-1.0" ]
null
null
null
Ch04/comp3.cpp
rzotya0327/UDProg-Introduction
c64244ee541d4ad0c85645385ef4f0c2e1886621
[ "CC0-1.0" ]
null
null
null
Ch04/comp3.cpp
rzotya0327/UDProg-Introduction
c64244ee541d4ad0c85645385ef4f0c2e1886621
[ "CC0-1.0" ]
null
null
null
#include "std_lib_facilities.h" int main() { double number = 0, smallest = 0, largest = 0, convert = 0; string unit; const double m_to_cm = 100; const double in_to_cm = 2.54; const double ft_to_in = 12; const double cm_to_m = 0.01; vector<double> distances; //értékek eltárolása a vectorban cout << "Please enter a number and a measurement unit (cm, m, in, ft)!" << endl; while (cin >> number >> unit) { if (unit != "cm" && unit != "ft" && unit != "in" && unit != "m") { cout << "This is an invalid unit. Please enter a number and a valid unit!" << endl; } else { cout << "You entered this: " << number << unit << endl; if (unit == "m") { convert = number; } else if (unit == "in") { convert = (number * in_to_cm) * cm_to_m; } else if (unit == "ft") { convert = (number * ft_to_in) * in_to_cm * cm_to_m; } else if (unit == "cm") { convert = number * cm_to_m; } distances.push_back(convert); //a méterré alakított értékek hozzáadása a vectorhoz if (largest == 0 && smallest == 0) { largest = number; smallest = number; cout << "The smallest so far: " << smallest << unit << endl; cout << "The largest so far: " << largest << unit <<endl; } else if (convert > smallest) { largest = number; cout << "The smallest so far: " << smallest << unit << endl; cout << "The largest so far: " << largest << unit << endl; } } } sort(distances); //a vector elemeinek rendezése double sum = 0; for(double distance : distances) { sum += distance; cout << distance << endl; } cout << "The sum of the values: " << sum << endl; cout << "The smallest value: " << distances[0] << endl; //első (0.) elem kiírása cout << "The largest value: " << distances[distances.size()-1] << endl; //utolsó elem kiírása return 0; }
23.75
96
0.568947
rzotya0327
478ed2e73e827ab55a48aadc2eae9190dcdb2147
2,302
cpp
C++
src/ZJGUIDataExchange.cpp
sowicm/mb-savedata-editor
73dfb1c906ea651c0a9eb21b71702af895a3589c
[ "MIT" ]
null
null
null
src/ZJGUIDataExchange.cpp
sowicm/mb-savedata-editor
73dfb1c906ea651c0a9eb21b71702af895a3589c
[ "MIT" ]
null
null
null
src/ZJGUIDataExchange.cpp
sowicm/mb-savedata-editor
73dfb1c906ea651c0a9eb21b71702af895a3589c
[ "MIT" ]
null
null
null
#include "StdAfx.h" #include "ZJGUIDataExchange.h" #include "ZJ_Algorithm.h" void DDX_Text(CDataExchange* pDX, CZJGUI& gui, UINT iView, int nIDC, CString& value) { CZJGUIView *pView = gui.GetView(iView); for (int i = 0; i < pView->GetNumControls(); ++i) { if (pView->GetControl(i)->GetID() == nIDC) { if (pDX->m_bSaveAndValidate) { value = pView->GetControl(i)->GetText(); } else { pView->GetControl(i)->SetText(value.GetBuffer()); } break; } } } void DDX_Text(CDataExchange* pDX, CZJGUI& gui, UINT iView, int nIDC, DWORD& value) { CZJGUIView *pView = gui.GetView(iView); for (int i = 0; i < pView->GetNumControls(); ++i) { if (pView->GetControl(i)->GetID() == nIDC) { if (pDX->m_bSaveAndValidate) { value = wtou(pView->GetControl(i)->GetText()); } else { pView->GetControl(i)->SetTextDirectly(utow(value)); } break; } } } void DDX_Text(CDataExchange* pDX, CZJGUI& gui, UINT iView, int nIDC, int& value) { CZJGUIView *pView = gui.GetView(iView); for (int i = 0; i < pView->GetNumControls(); ++i) { if (pView->GetControl(i)->GetID() == nIDC) { if (pDX->m_bSaveAndValidate) { value = wtoi(pView->GetControl(i)->GetText()); } else { pView->GetControl(i)->SetTextDirectly(itow(value)); } break; } } } void DDX_Check(CDataExchange* pDX, CZJGUI& gui, UINT iView, int nIDC, bool& value) { CZJGUIView *pView = gui.GetView(iView); for (int i = 0; i < pView->GetNumControls(); ++i) { if (pView->GetControl(i)->GetID() == nIDC) { if (pDX->m_bSaveAndValidate) { value = ((CZJGUICheckBox*)pView->GetControl(i))->GetChecked(); } else { ((CZJGUICheckBox*)pView->GetControl(i))->SetChecked(value); } break; } } }
28.419753
85
0.470026
sowicm
4796a51b0812e1f9b09a9121f7572f0d11bd228b
7,078
cpp
C++
samples/openNI2_2d-icp-slam/test.cpp
yhexie/mrpt
0bece2883aa51ad3dc88cb8bb84df571034ed261
[ "OLDAP-2.3" ]
2
2017-03-25T18:09:17.000Z
2017-05-22T08:14:48.000Z
samples/openNI2_2d-icp-slam/test.cpp
yhexie/mrpt
0bece2883aa51ad3dc88cb8bb84df571034ed261
[ "OLDAP-2.3" ]
null
null
null
samples/openNI2_2d-icp-slam/test.cpp
yhexie/mrpt
0bece2883aa51ad3dc88cb8bb84df571034ed261
[ "OLDAP-2.3" ]
1
2021-08-16T11:50:47.000Z
2021-08-16T11:50:47.000Z
/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ #include <mrpt/hwdrivers/COpenNI2Sensor.h> #include <mrpt/gui.h> #include <mrpt/utils/CTicTac.h> #include <mrpt/opengl.h> #include <mrpt/opengl/CPlanarLaserScan.h> // This class is in mrpt-maps using namespace mrpt; using namespace mrpt::obs; using namespace mrpt::opengl; using namespace mrpt::utils; using namespace mrpt::hwdrivers; using namespace std; const float vert_FOV = DEG2RAD( 4.0 ); // This demo records from an OpenNI2 device, convert observations to 2D scans // and runs 2d-icp-slam with them. int main ( int argc, char** argv ) { try { if (argc>2) { cerr << "Usage: " << argv[0] << " <sensor_id/sensor_serial\n"; cerr << "Example: " << argv[0] << " 0 \n"; return 1; } //const unsigned sensor_id = 0; COpenNI2Sensor rgbd_sensor; //rgbd_sensor.loadConfig_sensorSpecific(const mrpt::utils::CConfigFileBase &configSource, const std::string &iniSection ); unsigned sensor_id_or_serial = 0; if(argc == 2) { sensor_id_or_serial = atoi(argv[1]); if(sensor_id_or_serial > 10) rgbd_sensor.setSerialToOpen(sensor_id_or_serial); else rgbd_sensor.setSensorIDToOpen(sensor_id_or_serial); } // Open: //cout << "Calling COpenNI2Sensor::initialize()..."; rgbd_sensor.initialize(); if(rgbd_sensor.getNumDevices() == 0) return 0; cout << "OK " << rgbd_sensor.getNumDevices() << " available devices." << endl; cout << "\nUse device " << sensor_id_or_serial << endl << endl; // Create window and prepare OpenGL object in the scene: // -------------------------------------------------------- mrpt::gui::CDisplayWindow3D win3D("OpenNI2 3D view",800,600); win3D.setCameraAzimuthDeg(140); win3D.setCameraElevationDeg(20); win3D.setCameraZoom(8.0); win3D.setFOV(90); win3D.setCameraPointingToPoint(2.5,0,0); mrpt::opengl::CPointCloudColouredPtr gl_points = mrpt::opengl::CPointCloudColoured::Create(); gl_points->setPointSize(2.5); // The 2D "laser scan" OpenGL object: mrpt::opengl::CPlanarLaserScanPtr gl_2d_scan = mrpt::opengl::CPlanarLaserScan::Create(); gl_2d_scan->enablePoints(true); gl_2d_scan->enableLine(true); gl_2d_scan->enableSurface(true); gl_2d_scan->setSurfaceColor(0,0,1, 0.3); // RGBA opengl::COpenGLViewportPtr viewInt; // Extra viewports for the RGB images. { mrpt::opengl::COpenGLScenePtr &scene = win3D.get3DSceneAndLock(); // Create the Opengl object for the point cloud: scene->insert( gl_points ); scene->insert( mrpt::opengl::CGridPlaneXY::Create() ); scene->insert( mrpt::opengl::stock_objects::CornerXYZ() ); scene->insert( gl_2d_scan ); const double aspect_ratio = 480.0 / 640.0; const int VW_WIDTH = 400; // Size of the viewport into the window, in pixel units. const int VW_HEIGHT = aspect_ratio*VW_WIDTH; // Create an extra opengl viewport for the RGB image: viewInt = scene->createViewport("view2d_int"); viewInt->setViewportPosition(5, 30, VW_WIDTH,VW_HEIGHT ); win3D.addTextMessage(10, 30+VW_HEIGHT+10,"Intensity data",TColorf(1,1,1), 2, MRPT_GLUT_BITMAP_HELVETICA_12 ); win3D.addTextMessage(5,5, format("'o'/'i'-zoom out/in, ESC: quit"), TColorf(0,0,1), 110, MRPT_GLUT_BITMAP_HELVETICA_18 ); win3D.unlockAccess3DScene(); win3D.repaint(); } // Grab frames continuously and show //======================================================================================== bool bObs = false, bError = true; mrpt::system::TTimeStamp last_obs_tim = INVALID_TIMESTAMP; while (!win3D.keyHit()) //Push any key to exit // win3D.isOpen() { // cout << "Get new observation\n"; CObservation3DRangeScanPtr newObs = CObservation3DRangeScan::Create(); rgbd_sensor.getNextObservation(*newObs, bObs, bError); CObservation2DRangeScanPtr obs_2d; // The equivalent 2D scan if (bObs && !bError && newObs && newObs->timestamp!=INVALID_TIMESTAMP && newObs->timestamp!=last_obs_tim ) { // It IS a new observation: last_obs_tim = newObs->timestamp; // Convert ranges to an equivalent 2D "fake laser" scan: if (newObs->hasRangeImage ) { // Convert to scan: obs_2d = CObservation2DRangeScan::Create(); T3DPointsTo2DScanParams p2s; p2s.angle_sup = .5f*vert_FOV; p2s.angle_inf = .5f*vert_FOV; p2s.sensorLabel = "KINECT_2D_SCAN"; newObs->convertTo2DScan(*obs_2d, p2s); } // Update visualization --------------------------------------- win3D.get3DSceneAndLock(); // Estimated grabbing rate: win3D.addTextMessage(-350,-13, format("Timestamp: %s", mrpt::system::dateTimeLocalToString(last_obs_tim).c_str()), TColorf(0.6,0.6,0.6),"mono",10,mrpt::opengl::FILL, 100); // Show intensity image: if (newObs->hasIntensityImage ) { viewInt->setImageView(newObs->intensityImage); // This is not "_fast" since the intensity image may be needed later on. } win3D.unlockAccess3DScene(); // ------------------------------------------------------- // Create 3D points from RGB+D data // // There are several methods to do this. // Switch the #if's to select among the options: // See also: http://www.mrpt.org/Generating_3D_point_clouds_from_RGB_D_observations // ------------------------------------------------------- if (newObs->hasRangeImage) { // Pathway: RGB+D --> XYZ+RGB opengl win3D.get3DSceneAndLock(); newObs->project3DPointsFromDepthImageInto(*gl_points, false /* without obs.sensorPose */); win3D.unlockAccess3DScene(); } // And load scan in the OpenGL object: gl_2d_scan->setScan(*obs_2d); win3D.repaint(); } // end update visualization: } cout << "\nClosing RGBD sensor...\n"; return 0; } catch (std::exception &e) { std::cout << "MRPT exception caught: " << e.what() << std::endl; return -1; } catch (...) { printf("Untyped exception!!"); return -1; } }
35.747475
182
0.567816
yhexie
4799f417e923c2b78dc497746a1dd3e6c2a2f1ec
762
cpp
C++
MrGimmick/BaseEnemySound.cpp
CodingC1402/SpaghettiEngine
80fddf7c68ae7476a5880aae8fd0eac5bbf6ad1a
[ "MIT" ]
1
2021-06-02T09:31:15.000Z
2021-06-02T09:31:15.000Z
MrGimmick/BaseEnemySound.cpp
CornyCodingCorn/SpaghettiEngine
80fddf7c68ae7476a5880aae8fd0eac5bbf6ad1a
[ "MIT" ]
1
2021-07-13T13:56:18.000Z
2021-07-13T13:56:18.000Z
MrGimmick/BaseEnemySound.cpp
CodingC1402/SpaghettiEngine
80fddf7c68ae7476a5880aae8fd0eac5bbf6ad1a
[ "MIT" ]
2
2021-04-25T02:08:42.000Z
2021-04-29T04:18:34.000Z
#include "BaseEnemySound.h" #include "FieldNames.h" REGISTER_FINISH(BaseEnemySound, BaseSoundScript) {} void BaseEnemySound::OnStart() { _health = GET_FIRST_SCRIPT_OF_TYPE(HealthScript); _health->AddToHealthEvent([&](const int& health, const int& delta) { this->Play(health, delta); }); BaseSoundScript::OnStart(); } void BaseEnemySound::PlayDeadSound() { _soundManager->Play(Fields::SoundManager::_explode); } void BaseEnemySound::StopDeadSound() { _soundManager->Stop(Fields::SoundManager::_explode); } void BaseEnemySound::Play(const int& health, const int& delta) { if (health <= 0) { PlayDeadSound(); } } ScriptBase* BaseEnemySound::Clone() const { auto clone = dynamic_cast<BaseEnemySound*>(ScriptBase::Clone()); return clone; }
18.585366
69
0.730971
CodingC1402
479c8c6bdcf1594041d33deddb256f189d88cc6e
9,743
cpp
C++
KeyWords/DX10AsmKeyWords.cpp
GPUOpen-Tools/common-src-ShaderUtils
545195d74ff0758f74ebf9a8b4c541f9390a1df7
[ "MIT" ]
18
2017-01-28T14:18:44.000Z
2020-04-29T00:05:10.000Z
KeyWords/DX10AsmKeyWords.cpp
GPUOpen-Archive/common-src-ShaderUtils
545195d74ff0758f74ebf9a8b4c541f9390a1df7
[ "MIT" ]
1
2019-02-09T18:00:53.000Z
2019-02-09T18:00:53.000Z
KeyWords/DX10AsmKeyWords.cpp
GPUOpen-Tools/common-src-ShaderUtils
545195d74ff0758f74ebf9a8b4c541f9390a1df7
[ "MIT" ]
5
2018-04-29T09:46:06.000Z
2019-11-01T23:11:27.000Z
//===================================================================== // // Author: AMD Developer Tools Team // Graphics Products Group // Developer Tools // AMD, Inc. // // DX10AsmKeywords.cpp // File contains <Seth file description here> // //===================================================================== // $Id: //devtools/main/Common/Src/ShaderUtils/KeyWords/DX10AsmKeyWords.cpp#3 $ // // Last checkin: $DateTime: 2016/04/14 04:43:34 $ // Last edited by: $Author: AMD Developer Tools Team //===================================================================== // ( C ) AMD, Inc. 2009,2010 All rights reserved. //===================================================================== #include "DX10AsmKeywords.h" #include <tchar.h> #include <boost/foreach.hpp> #include <boost/format.hpp> #include "D3D10ShaderUtils.h" #include "Swizzles.h" using namespace D3D10ShaderUtils; using boost::format; bool ShaderUtils::GetDX10InstKeyWords(ShaderUtils::KeyWordsList& keyWords, const D3D10ShaderObject::CD3D10ShaderObject& shader) { // Ops KeyWords opKeyWords; opKeyWords.type = KW_Op; opKeyWords.strKeywords = "constant linear centroid linearCentroid linearNoperspective linearNoperspectiveCentroid dynamicIndexed immediateIndexed mode_default float noperspective position refactoringAllowed " "ClipDistance CullDistance Coverage Depth IsFrontFace Position RenderTargetArrayIndex SampleIndex Target ViewportArrayIndex InstanceID PrimitiveID VertexID " "Buffer Texture1D Texture1DArray Texture2D Texture2DArray Texture3D TextureCube Texture2DMS Texture2DMSArray TextureCubeArray " "buffer texture1d texture1darray texture2d texture2darray texture3d texturecube texture2dms texture2dmsarray texturecubearray " "UNORM SNORM SINT UINT FLOAT unorm snorm sint uint float default mode_default comparison mode_comparison mono mode_mono "; KeyWords texOpKeyWords; texOpKeyWords.type = KW_TextureOp; texOpKeyWords.strKeywords = ""; KeyWords intOpKeyWords; intOpKeyWords.type = KW_IntOp; intOpKeyWords.strKeywords = ""; KeyWords doubleOpKeyWords; doubleOpKeyWords.type = KW_DoubleOp; doubleOpKeyWords.strKeywords = ""; D3D10ShaderUtils::ShaderType shaderType = D3D10ShaderUtils::None; switch (shader.GetShaderType()) { case D3D10_SB_VERTEX_SHADER: opKeyWords.strKeywords += "vs_4_0 vs_4_1 vs_5_0 dcl_input_vertexID dcl_input_instanceID instance_id "; shaderType = VS; break; case D3D10_SB_GEOMETRY_SHADER: opKeyWords.strKeywords += "gs_4_0 gs_4_1 gs_5_0 dcl_input_primitiveID dcl_output_primitiveID dcl_output_isFrontFace dcl_maxout rendertarget_array_index "; shaderType = GS; break; case D3D10_SB_PIXEL_SHADER: opKeyWords.strKeywords += "ps_4_0 ps_4_1 ps_5_0 dcl_input_ps dcl_input_primitiveID dcl_input_isFrontFace dcl_input_clipDistance dcl_input_cullDistance dcl_input_position dcl_input_renderTargetArrayIndex dcl_input_viewportArrayIndex "; shaderType = PS; break; case D3D11_SB_HULL_SHADER: opKeyWords.strKeywords += "hs_5_0 "; shaderType = HS; break; case D3D11_SB_DOMAIN_SHADER: opKeyWords.strKeywords += "ds_5_0 "; shaderType = DS; break; case D3D11_SB_COMPUTE_SHADER: opKeyWords.strKeywords += "cs_4_0 cs_4_1 cs_5_0 "; shaderType = CS; break; } const OpCodeInfo* pOpCodeInfo = GetOpCodeInfoTable(); for (DWORD i = 0; i < GetOpCodeInfoCount(); i++) { if ((pOpCodeInfo[i].shaderTypes & shaderType) != 0) { switch (pOpCodeInfo[i].instructionType) { case IT_Integer: // Fall-through case IT_Atomic: intOpKeyWords.strKeywords += pOpCodeInfo[i].pszKeyWords; intOpKeyWords.strKeywords += _T(" "); break; case IT_Double: doubleOpKeyWords.strKeywords += pOpCodeInfo[i].pszKeyWords; doubleOpKeyWords.strKeywords += _T(" "); break; case IT_Load: // Fall-through case IT_Store: texOpKeyWords.strKeywords += pOpCodeInfo[i].pszKeyWords; texOpKeyWords.strKeywords += _T(" "); break; case IT_Declaration: // Fall-through case IT_ALU: // Fall-through case IT_FlowControl: // Fall-through case IT_Other: // Fall-through default: opKeyWords.strKeywords += pOpCodeInfo[i].pszKeyWords; opKeyWords.strKeywords += _T(" "); break; } } } keyWords.push_back(opKeyWords); keyWords.push_back(texOpKeyWords); keyWords.push_back(intOpKeyWords); keyWords.push_back(doubleOpKeyWords); return !keyWords.empty(); } const std::string GenerateRegKeyWords(const TCHAR* pszFormat, DWORD dwCount) { std::string strRegKeyWords; for (DWORD i = 0; i < dwCount; i++) { strRegKeyWords += str(format(pszFormat) % i); } return strRegKeyWords; } const std::string GenerateArrayRegKeyWords(const TCHAR* pszFormat, DWORD dwRegIndex, DWORD dwArraySize) { std::string strRegKeyWords; for (DWORD i = 0; i < dwArraySize; i++) { strRegKeyWords += str(format(pszFormat) % dwRegIndex % i); } return strRegKeyWords; } const std::string GenerateRegKeyWords(const TCHAR* pszFormat, DWORD dwStart, DWORD dwCount) { std::string strRegKeyWords; for (DWORD i = dwStart; i < dwStart + dwCount; i++) { strRegKeyWords += str(format(pszFormat) % i); } return strRegKeyWords; } bool ShaderUtils::GetDX10RegKeyWords(ShaderUtils::KeyWordsList& keyWords, const D3D10ShaderObject::CD3D10ShaderObject& shader) { KeyWords regKeyWords; regKeyWords.type = KW_Reg; regKeyWords.strKeywords = _T("null l icb ") + GenerateRegKeyWords(_T("icb%i "), shader.GetImmediateConstantCount()) + GenerateRegKeyWords(_T("r%i "), shader.GetStats().TempRegisterCount); if (shader.GetShaderModel() >= SM_5_0) { regKeyWords.strKeywords += "this "; } if (shader.GetShaderType() == D3D11_SB_COMPUTE_SHADER) { regKeyWords.strKeywords += "vThreadID vThreadGroupID vThreadIDInGroupFlattened vThreadIDInGroup "; } BOOST_FOREACH(D3D10ShaderObject::D3D10_ResourceBinding resource, shader.GetBoundResources()) { if (resource.Type == D3D10_SIT_CBUFFER) { regKeyWords.strKeywords += GenerateRegKeyWords(_T("cb%i "), resource.dwBindPoint, resource.dwBindCount); } else if (resource.Type == D3D10_SIT_SAMPLER) { regKeyWords.strKeywords += GenerateRegKeyWords(_T("s%i "), resource.dwBindPoint, resource.dwBindCount); } else if (resource.Type == D3D10_SIT_TBUFFER || resource.Type == D3D10_SIT_TEXTURE || resource.Type == D3D11_SIT_STRUCTURED || resource.Type == D3D11_SIT_BYTEADDRESS || resource.Type == D3D11_SIT_UAV_CONSUME_STRUCTURED) { regKeyWords.strKeywords += GenerateRegKeyWords(_T("t%i "), resource.dwBindPoint, resource.dwBindCount); } else if (resource.Type == D3D11_SIT_UAV_RWTYPED || resource.Type == D3D11_SIT_UAV_RWSTRUCTURED || resource.Type == D3D11_SIT_UAV_RWBYTEADDRESS || resource.Type == D3D11_SIT_UAV_APPEND_STRUCTURED || resource.Type == D3D11_SIT_UAV_RWSTRUCTURED_WITH_COUNTER) { regKeyWords.strKeywords += GenerateRegKeyWords(_T("t%i "), resource.dwBindPoint, resource.dwBindCount) + GenerateRegKeyWords(_T("u%i "), resource.dwBindPoint, resource.dwBindCount); } else if (resource.Type == D3D11_SIT_STRUCTURED) { regKeyWords.strKeywords += GenerateRegKeyWords(_T("g%i "), resource.dwBindPoint, resource.dwBindCount); } else { regKeyWords.strKeywords += GenerateRegKeyWords(_T("u%i "), resource.dwBindPoint, resource.dwBindCount); } } regKeyWords.strKeywords += "v "; BOOST_FOREACH(D3D10ShaderObject::D3D10_Signature inputSignature, shader.GetInputSignatures()) { regKeyWords.strKeywords += str(format(_T("v%i ")) % inputSignature.dwRegister); } BOOST_FOREACH(std::string strInputSemanticName, shader.GetInputSemanticNames()) { regKeyWords.strKeywords += strInputSemanticName + " "; } BOOST_FOREACH(D3D10ShaderObject::D3D10_Signature outputSignature, shader.GetOutputSignatures()) { regKeyWords.strKeywords += str(format(_T("o%i ")) % outputSignature.dwRegister); } // Just hack in oDepth & oMask for all pixel shaders for now if (shader.GetShaderType() == D3D10_SB_PIXEL_SHADER) { regKeyWords.strKeywords += "oDepth oMask "; } BOOST_FOREACH(std::string strOutputSemanticName, shader.GetOutputSemanticNames()) { regKeyWords.strKeywords += strOutputSemanticName + " "; } BOOST_FOREACH(D3D10ShaderObject::D3D10_IndexableTempRegister indexableTempRegister, shader.GetIndexableTempRegisters()) { regKeyWords.strKeywords += str(format(_T("x%i ")) % indexableTempRegister.dwIndex); } BOOST_FOREACH(D3D10ShaderObject::D3D10_GlobalMemoryRegister globalMemoryRegister, shader.GetGlobalMemoryRegisters()) { regKeyWords.strKeywords += str(format(_T("g%i ")) % globalMemoryRegister.dwIndex); } regKeyWords.strKeywords += GetRGBASwizzles() + GetXYZWSwizzles(); keyWords.push_back(regKeyWords); return true; }
39.445344
248
0.655548
GPUOpen-Tools
479db04fb3008cba1e3ec58ea4e97fd851c6c5b7
3,044
cc
C++
day-10/ten.cc
JoBoCl/advent-of-code-2018
536bcd422a8289a8944d847c7806a81a1044442d
[ "MIT" ]
null
null
null
day-10/ten.cc
JoBoCl/advent-of-code-2018
536bcd422a8289a8944d847c7806a81a1044442d
[ "MIT" ]
null
null
null
day-10/ten.cc
JoBoCl/advent-of-code-2018
536bcd422a8289a8944d847c7806a81a1044442d
[ "MIT" ]
null
null
null
#include <algorithm> #include <fstream> #include <functional> #include <iostream> #include <limits> #include <list> #include <map> #include <numeric> #include <queue> #include <regex> #include <set> #include <string> #include <utility> #include <vector> using namespace std; struct Star { int x; int y; int u; int v; }; struct Box { int x0; int x1; int y0; int y1; }; int area(struct Box *b) { return (b->x1 - b->x0) * (b->y1 - b->y0); } int perimeter(struct Box *b) { return (b->x1 - b->x0) + (b->y1 - b->y0); } bool lessThan(struct Box *l, struct Box *r) { return perimeter(l) < perimeter(r); } vector<struct Star> readSequence() { vector<struct Star> stars; std::ifstream myfile("10.input"); string line; regex matcher("position=<\\s*(-?\\d+),\\s*(-?\\d+)> " "velocity=<\\s*(-?\\d+),\\s*(-?\\d+)>"); if (myfile.is_open()) { while (getline(myfile, line)) { struct Star star; smatch match; if (regex_match(line, match, matcher)) { struct Star star; star.x = stoi(match[1].str()); star.y = stoi(match[2].str()); star.u = stoi(match[3].str()); star.v = stoi(match[4].str()); stars.push_back(star); } } } return stars; } Box maxSize(vector<Star> *stars) { struct Box box; box.x0 = numeric_limits<int>::max(); box.y0 = numeric_limits<int>::max(); box.x1 = numeric_limits<int>::min(); box.y1 = numeric_limits<int>::min(); for (Star &star : *stars) { if (star.x < box.x0) box.x0 = star.x; if (star.y < box.y0) box.y0 = star.y; if (star.x > box.x1) box.x1 = star.x; if (star.y > box.y1) box.y1 = star.y; } return box; } void advance(Star *star) { star->x += star->u; star->y += star->v; } void retreat(Star *star) { star->x -= star->u; star->y -= star->v; } void partOne(vector<Star> stars) { struct Box oldBounds; struct Box newBounds = maxSize(&stars); int iterations = 0; do { oldBounds = newBounds; for (auto &star : stars) { advance(&star); } newBounds = maxSize(&stars); iterations++; } while (lessThan(&newBounds, &oldBounds)); cout << "Current bounds: " << oldBounds.x1 - oldBounds.x0 << ", " << oldBounds.y1 - oldBounds.y0 << " after " << iterations - 1 << " iterations. Print [y/N]?"; char print = 'Y'; // cin >> print; for (auto &star : stars) { retreat(&star); } if (toupper(print) == 'Y') { for (int j = oldBounds.y0; j <= oldBounds.y1; j++) { for (int i = oldBounds.x0; i <= oldBounds.x1; i++) { bool print = false; for (auto &star : stars) { if (star.x == i && star.y == j) { print = true; break; } } cout << (print ? '#' : ' '); } cout << "\n"; } } } void partTwo(vector<Star> stars) {} int main() { vector<struct Star> node = readSequence(); cout << "==== Part One ====\n"; partOne(node); cout << "\n==== Part Two ====\n"; partTwo(node); }
20.993103
74
0.538436
JoBoCl
47a41b1dff642d2d8441b83a3b1f3f79aa7397b4
2,990
cpp
C++
demo/dataflow/pipeline.cpp
DanieleDeSensi/Nornir
60587824d6b0a6e61b8fc75bdea37c9fc69199c7
[ "MIT" ]
2
2018-10-31T08:09:03.000Z
2021-01-18T19:23:54.000Z
demo/dataflow/pipeline.cpp
DanieleDeSensi/Nornir
60587824d6b0a6e61b8fc75bdea37c9fc69199c7
[ "MIT" ]
1
2020-02-02T11:58:22.000Z
2020-02-02T11:58:22.000Z
demo/dataflow/pipeline.cpp
DanieleDeSensi/Nornir
60587824d6b0a6e61b8fc75bdea37c9fc69199c7
[ "MIT" ]
1
2019-04-13T09:54:49.000Z
2019-04-13T09:54:49.000Z
/* * pipeline.cpp * * Created on: 04/05/2016 * * ========================================================================= * Copyright (C) 2015-, Daniele De Sensi (d.desensi.software@gmail.com) * * This file is part of nornir. * * nornir is free software: you can redistribute it and/or * modify it under the terms of the Lesser GNU General Public * License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. * nornir 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 * Lesser GNU General Public License for more details. * * You should have received a copy of the Lesser GNU General Public * License along with nornir. * If not, see <http://www.gnu.org/licenses/>. * * ========================================================================= */ #include <iostream> #include <stdlib.h> #include <nornir/nornir.hpp> using namespace nornir::dataflow; #define MAX_SIZE 10; class DemoInputStream: public nornir::dataflow::InputStream{ private: size_t _currentElem; size_t _streamSize; bool _eos; public: explicit inline DemoInputStream(size_t streamSize): _currentElem(0), _streamSize(streamSize), _eos(false){ srand(time(NULL)); } inline void* next(){ if(_currentElem < _streamSize){ int* x; ++_currentElem; x = new int(); *x = rand() % 1000; std::cout << "Generated: " << *x << std::endl; std::cout << "ExpectedOutput: " << ((*x + 3) * 4) + 1 << std::endl; return (void*) x; }else{ _eos = true; return NULL; } } inline bool hasNext(){ return !_eos; } }; class DemoOutputStream: public nornir::dataflow::OutputStream{ public: void put(void* a){ int* x = (int*) a; std::cout << "Result: " << *x << std::endl; delete x; } }; int* fun1(int* x){ *x = *x + 3; return (int*) x; } int* fun2(int* x){ *x = *x * 4; return (int*) x; } class LastStage: public Computable{ public: void compute(Data* d){ int* in = (int*) d->getInput(); *in = *in + 1; d->setOutput((void*) in); } }; int main(int argc, char** argv){ if(argc < 2){ std::cerr << "Usage: " << argv[0] << " streamSize" << std::endl; return -1; } /* Create streams. */ DemoInputStream inp(atoi(argv[1])); DemoOutputStream out; Computable* pipeTmp = createStandardPipeline<int, int, int, fun1, fun2>(); Computable* lastStage = new LastStage(); Pipeline* pipe = new Pipeline(pipeTmp, lastStage); nornir::Parameters p("parameters.xml"); nornir::dataflow::Interpreter m(&p, pipe, &inp, &out); m.start(); m.wait(); delete pipe; delete lastStage; }
25.338983
79
0.563211
DanieleDeSensi
47a839414bbddb9f1dfcfcf391b5a446432faaad
1,420
hpp
C++
test_funcs.hpp
wagavulin/ropencv2
c57b8611ccc241e0953eb04451bb21cc4d589611
[ "Apache-2.0" ]
null
null
null
test_funcs.hpp
wagavulin/ropencv2
c57b8611ccc241e0953eb04451bb21cc4d589611
[ "Apache-2.0" ]
6
2021-05-24T14:29:40.000Z
2021-07-04T15:31:46.000Z
test_funcs.hpp
wagavulin/ropencv2
c57b8611ccc241e0953eb04451bb21cc4d589611
[ "Apache-2.0" ]
null
null
null
#include "opencv2/core.hpp" namespace cv { CV_EXPORTS_W double bindTest1(int a, CV_IN_OUT Point& b, CV_OUT int* c, int d=10, RNG* rng=0, double e=1.2); CV_EXPORTS_W void bindTest2(int a); CV_EXPORTS_W int bindTest3(int a); CV_EXPORTS_W void bindTest4(int a, CV_IN_OUT Point& pt); CV_EXPORTS_W void bindTest5(int a, CV_IN_OUT Point& pt, CV_OUT int* x); CV_EXPORTS_W bool bindTest6(int a, CV_IN_OUT Point& pt, CV_OUT int* x); CV_EXPORTS_W double bindTest_overload(Point a, Point b, double c); CV_EXPORTS_W double bindTest_overload(RotatedRect a); CV_EXPORTS_W void bindTest_InOut_Mat(CV_IN_OUT Mat& a); CV_EXPORTS_W void bindTest_InOut_bool(CV_IN_OUT bool& a); CV_EXPORTS_W void bindTest_InOut_uchar(CV_IN_OUT uchar& a); CV_EXPORTS_W void bindTest_InOut_int(CV_IN_OUT int& a); CV_EXPORTS_W void bindTest_Out_intp(CV_OUT int* a); CV_EXPORTS_W void bindTest_InOut_size_t(CV_IN_OUT size_t& a); CV_EXPORTS_W void bindTest_InOut_float(CV_IN_OUT float& a); CV_EXPORTS_W void bindTest_InOut_double(CV_IN_OUT double& a); CV_EXPORTS_W void bindTest_InOut_Size(CV_IN_OUT Size& a); CV_EXPORTS_W void bindTest_InOut_Size2f(CV_IN_OUT Size2f& a); CV_EXPORTS_W void bindTest_InOut_Point(CV_IN_OUT Point& a); CV_EXPORTS_W void bindTest_InOut_Point2f(CV_IN_OUT Point2f& a); CV_EXPORTS_W void bindTest_InOut_RotatedRect(CV_IN_OUT RotatedRect& a); CV_EXPORTS_W void bindTest_InOut_vector_Point(CV_IN_OUT std::vector<Point>& a); } // cv
44.375
108
0.814789
wagavulin
47aaad505c523dbf9a61dde609f519c82c5c0414
6,339
cpp
C++
buffer_stream/buffer_stream_test.cpp
churuxu/codesnippets
9d01c53a5bd7be29168e3c8bfb27ebacc5164f03
[ "MIT" ]
4
2018-11-05T03:21:02.000Z
2021-09-25T15:33:52.000Z
buffer_stream/buffer_stream_test.cpp
churuxu/codesnippets
9d01c53a5bd7be29168e3c8bfb27ebacc5164f03
[ "MIT" ]
null
null
null
buffer_stream/buffer_stream_test.cpp
churuxu/codesnippets
9d01c53a5bd7be29168e3c8bfb27ebacc5164f03
[ "MIT" ]
2
2021-01-28T08:14:07.000Z
2021-09-25T15:33:54.000Z
#include "gtest.h" #include "buffer_stream.h" //默认模式基本测试 TEST(buffer_stream, test_default){ int len; void* data; buffer_stream* s = buffer_stream_create(64); ASSERT_TRUE(s); //写入两次,一次读取 buffer_stream_push(s, "hello", 5); buffer_stream_push(s, "world", 5); data = buffer_stream_fetch(s, &len); EXPECT_EQ(10, len); EXPECT_TRUE(data); EXPECT_TRUE(0==memcmp(data, "helloworld", 10)); buffer_stream_pop(s, len); //无数据时,预期获取到NULL data = buffer_stream_fetch(s, &len); EXPECT_EQ(0, len); EXPECT_TRUE(data == NULL); //写入两次,一次读取 buffer_stream_push(s, "hello1", 6); buffer_stream_push(s, "world1", 6); data = buffer_stream_fetch(s, &len); EXPECT_EQ(12, len); EXPECT_TRUE(data); EXPECT_TRUE(0==memcmp(data, "hello1world1", 10)); buffer_stream_pop(s, len); buffer_stream_destroy(s); } //fix模式基本测试 TEST(buffer_stream, test_fix){ int len; void* data; buffer_stream* s = buffer_stream_create(64); ASSERT_TRUE(s); //每次固定读4字节 buffer_stream_set_fix_mode(s, 4); //写入数据 buffer_stream_push(s, "hello", 5); buffer_stream_push(s, "world", 5); //读第1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(4, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "hell", 4)); buffer_stream_pop(s, len); //读第2次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(4, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "owor", 4)); buffer_stream_pop(s, len); //读第3次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(0, len); EXPECT_TRUE(data == NULL); //再写一次 buffer_stream_push(s, "hello", 5); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(4, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "ldhe", 4)); buffer_stream_pop(s, len); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(0, len); EXPECT_TRUE(data == NULL); buffer_stream_destroy(s); } //计算动态长度,例如AT+5hello static int calc_testat_length(void* data, int len){ char* str = (char*)data; if(len<4)return 0; //数据不足 if(str[0] == 'A' && str[1] == 'T' && str[2] == '+'){ //数据足够 return 4 + (str[3] - '0'); } //数据有误 return -1; } //dynamic模式基本测试 TEST(buffer_stream, test_dynamic){ int len; void* data; buffer_stream* s = buffer_stream_create(64); ASSERT_TRUE(s); //每次读动态长度 buffer_stream_set_dynamic_mode(s, calc_testat_length); //写入数据 buffer_stream_push(s, "AT+5helloAT+6world!A", 20); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(9, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "AT+5hello", 9)); buffer_stream_pop(s, len); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(10, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "AT+6world!", 10)); buffer_stream_pop(s, len); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(0, len); EXPECT_TRUE(data == NULL); //写入数据 buffer_stream_push(s, "T+3bye", 6); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(7, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "AT+3bye", 7)); buffer_stream_pop(s, len); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(0, len); EXPECT_TRUE(data == NULL); //写入错误数据 buffer_stream_push(s, "T+3bye", 6); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(0, len); EXPECT_TRUE(data == NULL); //写入数据 buffer_stream_push(s, "AT+3bye", 7); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(7, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "AT+3bye", 7)); buffer_stream_pop(s, len); buffer_stream_destroy(s); } //split模式基本测试 TEST(buffer_stream, test_split){ int len; void* data; buffer_stream* s = buffer_stream_create(64); ASSERT_TRUE(s); //每次读取一行 buffer_stream_set_split_mode(s, '\n'); //写入数据 buffer_stream_push(s, "hello\nworld\nhaha", 16); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(6, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "hello\n", 6)); buffer_stream_pop(s, len); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(6, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "world\n", 6)); buffer_stream_pop(s, len); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(0, len); EXPECT_TRUE(data == NULL); //写入数据 buffer_stream_push(s, " bye\n", 6); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(9, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "haha bye\n", 9)); buffer_stream_pop(s, len); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(0, len); EXPECT_TRUE(data == NULL); buffer_stream_destroy(s); } //模式切换测试 TEST(buffer_stream, test_change_mode){ int len; void* data; buffer_stream* s = buffer_stream_create(64); ASSERT_TRUE(s); //写入数据 buffer_stream_push(s, "recv 5\nhellorecv 6\nworld!aaa", 26); //读取一行 buffer_stream_set_split_mode(s, '\n'); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(7, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "recv 5\n", 7)); buffer_stream_pop(s, len); //读取固定长度 buffer_stream_set_fix_mode(s, 5); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(5, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "hello", 5)); buffer_stream_pop(s, len); //读取一行 buffer_stream_set_split_mode(s, '\n'); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(7, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "recv 6\n", 7)); buffer_stream_pop(s, len); //读取固定长度 buffer_stream_set_fix_mode(s, 6); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(6, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "world!", 6)); buffer_stream_pop(s, len); buffer_stream_destroy(s); }
25.560484
65
0.589525
churuxu
47ace847e2d274e60f2f7f77dbbfabf7e2094d83
5,951
cpp
C++
buildpng.cpp
iggyvolz/GDD1-Assets
80449c6860f63460db589727bbc6655537236f73
[ "MIT" ]
null
null
null
buildpng.cpp
iggyvolz/GDD1-Assets
80449c6860f63460db589727bbc6655537236f73
[ "MIT" ]
null
null
null
buildpng.cpp
iggyvolz/GDD1-Assets
80449c6860f63460db589727bbc6655537236f73
[ "MIT" ]
null
null
null
#include <png++/png.hpp> #include "buildpng.h" #include<cmath> #include <ft2build.h> #include<iostream> using namespace std; #include FT_FREETYPE_H bool about(double a, double b, double delta) { if(a>b) { return (a-b)<delta; } return (b-a)<delta; } void red(Image& image, png::uint_32 startX, png::uint_32 startY) { for(png::uint_32 y=0; y < TILE_SIZE; y++) { for (png::uint_32 x = 0; x < TILE_SIZE; x++) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(255,0,0); } } } void green(Image& image, png::uint_32 startX, png::uint_32 startY) { for(png::uint_32 y=0; y < TILE_SIZE; y++) { for (png::uint_32 x = 0; x < TILE_SIZE; x++) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(0,255,0); } } } void blue(Image& image, png::uint_32 startX, png::uint_32 startY) { for(png::uint_32 y=0; y < TILE_SIZE; y++) { for (png::uint_32 x = 0; x < TILE_SIZE; x++) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(0,0,255); } } } void yellow(Image& image, png::uint_32 startX, png::uint_32 startY) { for(png::uint_32 y=0; y < TILE_SIZE; y++) { for (png::uint_32 x = 0; x < TILE_SIZE; x++) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(255,255,0); } } } // Draw moneybag on image void moneybag(Image& image, png::uint_32 startX, png::uint_32 startY) { for(png::uint_32 y=0; y < TILE_SIZE; y++) { for (png::uint_32 x = 0; x < TILE_SIZE; x++) { // Circle if((x-28)*(x-28)+(y-28)*(y-28)<=15*15-5) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(219, 138, 67); } // Lines else if(about(y,5,1) && x>=17 && x<=39) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(0,0,0); } else if(y>=5&&y<=28 && about(x,(y+12), 1)) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(0,0,0); } else if(y>=5 && y<=28 && about(x,TILE_SIZE-(y+12), 1)) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(0,0,0); } else if(y>=5 && y<=28 && x>=(y+12) && x<=(44-y)) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(219, 138, 67); } // Border else if((x-28)*(x-28)+(y-28)*(y-28)<=16*16-5) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(0,0,0); } } } } void lightblue_piece(Image& image, png::uint_32 startX, png::uint_32 startY) { for(png::uint_32 y=0; y < TILE_SIZE; y++) { for (png::uint_32 x = 0; x < TILE_SIZE*2; x++) { markXY(x+startX,y+startY);image[y+startY][x+startX]=png::rgb_pixel(135,206,250); } } } void yellow_piece(Image& image, png::uint_32 startX, png::uint_32 startY) { for(png::uint_32 y=TILE_SIZE*2; y < TILE_SIZE*3; y++) { for (png::uint_32 x = 0; x < TILE_SIZE*5; x++) { markXY(x+startX,y+startY);image[y+startY][x+startX]=png::rgb_pixel(255,255,0); } } for(png::uint_32 y=0; y < TILE_SIZE*5; y++) { for (png::uint_32 x = TILE_SIZE*2; x < TILE_SIZE*3; x++) { markXY(x+startX,y+startY);image[y+startY][x+startX]=png::rgb_pixel(255,255,0); } } } void green_piece(Image& image, png::uint_32 startX, png::uint_32 startY) { for(png::uint_32 y=0;y<TILE_SIZE*3;y++) { for(png::uint_32 x=0;x<TILE_SIZE;x++) { markXY(x+startX,y+startY);image[y+startY][x+startX]=png::rgb_pixel(0,255,0); } } } void orange_piece(Image& image, png::uint_32 startX, png::uint_32 startY) { for(png::uint_32 y=0; y < TILE_SIZE; y++) { for (png::uint_32 x = 0; x < TILE_SIZE; x++) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(255,165,0); } } } void purple_piece(Image& image, png::uint_32 startX, png::uint_32 startY) { for(png::uint_32 y=0; y < TILE_SIZE; y++) { for (png::uint_32 x = 0; x < TILE_SIZE*2; x++) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(128,0,128); } } for(png::uint_32 y=0; y<TILE_SIZE*6;y++) { for (png::uint_32 x = TILE_SIZE; x < TILE_SIZE*2; x++) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(128,0,128); } } } void door(Image& image, png::uint_32 startX, png::uint_32 startY) { for(png::uint_32 y=0; y < TILE_SIZE; y++) { for (png::uint_32 x = 0; x < 2*TILE_SIZE; x++) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(139,69,19); } } } void laser(Image& image, png::uint_32 startX, png::uint_32 startY) { for(png::uint_32 y=0; y < TILE_SIZE; y++) { for (png::uint_32 x = 0; x < 3*TILE_SIZE; x++) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(255,0,0); } } } template<typename T> T square(T val) { return val*val; } png::uint_32 maxX=0; png::uint_32 maxY=0; void markXY(png::uint_32 x, png::uint_32 y) { if(x>maxX) maxX=x; if(y>maxY) maxY=y; } void printMax() { cout << "x: " << maxX << ", y: " << maxY << endl; } void reverse(Image& source, Image& dest) { for(png::uint_32 y=0; y < source.get_height(); y++) { for (png::uint_32 x = 0; x < source.get_width(); x++) { dest[y][source.get_width()-x-1] = source[y][x]; } } }
27.298165
99
0.524282
iggyvolz
47b049c9e4869ebbbd4de24229d857dc7f9d8ba3
712
cpp
C++
Cpp_primer_5th/code_part7/prog7_12.cpp
Links789/Cpp_primer_5th
18a60b75c358a79fdf006f8cb978c9be6e6aedd5
[ "MIT" ]
null
null
null
Cpp_primer_5th/code_part7/prog7_12.cpp
Links789/Cpp_primer_5th
18a60b75c358a79fdf006f8cb978c9be6e6aedd5
[ "MIT" ]
null
null
null
Cpp_primer_5th/code_part7/prog7_12.cpp
Links789/Cpp_primer_5th
18a60b75c358a79fdf006f8cb978c9be6e6aedd5
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; /*****?????*****/ struct Sales_data; istream &read(istream&, Sales_data&) /*****?????****/ struct Sales_data{ Sales_data() = default; Sales_data(const string &s): bookNo(s){} Sales_data(const string &s, unsigned n, double p): bookNo(s), units_sold(n), revenue(p*n){} Sales_data(istream &); string isbn() const{ return bookNo;} Sales_data& combin(const Sales_data&); double avg_price() const; string bookNo; unsigned units_sold = 0; double revenue = 0.0; }; istream &read(istream &is , Sales_data &item){ double price = 0.0; is >> item.bookNo >> item.units_sold >> price; item.revenue = price * item.units_sold; return is; }
22.25
51
0.664326
Links789
47ba25b5b6bb5c35f5de6f1d7d57d2d57f51f8eb
939
cc
C++
test_rank.cc
kjwilder/ranker
ff0dd14e29443759e5047d093aa42c83ad9c5f37
[ "Unlicense" ]
null
null
null
test_rank.cc
kjwilder/ranker
ff0dd14e29443759e5047d093aa42c83ad9c5f37
[ "Unlicense" ]
null
null
null
test_rank.cc
kjwilder/ranker
ff0dd14e29443759e5047d093aa42c83ad9c5f37
[ "Unlicense" ]
null
null
null
#include <iostream> #include <cstdlib> #include <string> #include "./ranker.h" int main(int argc, char** argv) { uint num = 10, dump = 1; string method = "average"; // Can also be "min" or "max" or "default" if (argc > 1) num = (uint) atol(argv[1]); if (argc > 2) method = argv[2]; if (argc > 3) dump = (uint) atol(argv[3]); std::cerr << "Running: [" << argv[0] << " num=" << num << " method=" << method << " dump=" << dump << "]" << std::endl; vector<double> b(num); for (uint i = 0; i < num; ++i) b[i] = arc4random() % 8; vector<double> ranks; rank(b, ranks, method); if (dump) { for (uint i = 0; i < ranks.size(); ++i) { std::cout << b[i] << " " << ranks[i] << std::endl; } } std::cout << std::endl; rankhigh(b, ranks, method); if (dump) { for (uint i = 0; i < ranks.size(); ++i) { std::cout << b[i] << " " << ranks[i] << std::endl; } } return 0; }
24.076923
72
0.497338
kjwilder
47bb1acf4ff47f8f113f2614ea4efc6c29f40a96
720
cpp
C++
1100/10/1117b.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
1
2020-07-03T15:55:52.000Z
2020-07-03T15:55:52.000Z
1100/10/1117b.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
null
null
null
1100/10/1117b.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
3
2020-10-01T14:55:28.000Z
2021-07-11T11:33:58.000Z
#include <algorithm> #include <iostream> #include <vector> template <typename T> std::istream& operator >>(std::istream& input, std::vector<T>& v) { for (T& a : v) input >> a; return input; } void answer(unsigned long long h) { std::cout << h << '\n'; } void solve(std::vector<unsigned>& a, unsigned m, unsigned k) { std::sort(a.begin(), a.end(), std::greater<unsigned>()); const unsigned c = m / (k + 1); const unsigned r = m % (k + 1); answer(c * (1ull * a[0] * k + a[1]) + 1ull * r * a[0]); } int main() { size_t n; std::cin >> n; unsigned m, k; std::cin >> m >> k; std::vector<unsigned> a(n); std::cin >> a; solve(a, m, k); return 0; }
16
65
0.529167
actium
47c06b8d3ea9f4cfcee2a13f492820d16fceebdf
1,527
hpp
C++
include/boost/simd/constant/fourthrooteps.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
include/boost/simd/constant/fourthrooteps.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
include/boost/simd/constant/fourthrooteps.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
//================================================================================================== /*! @file @copyright 2012-2015 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_CONSTANT_FOURTHROOTEPS_HPP_INCLUDED #define BOOST_SIMD_CONSTANT_FOURTHROOTEPS_HPP_INCLUDED #if defined(DOXYGEN_ONLY) namespace boost { namespace simd { /*! @ingroup group-constant Generate the 4th root of constant @ref Eps : \f$\sqrt[4]\epsilon\f$. @par Semantic: @code T r = Fourthrooteps<T>(); @endcode is similar to: @code if T is integral r = T(1) else if T is double r = pow(2.0, -13); else if T is float r = pow(2.0f, -5.75f); @endcode @return The Fourthrooteps constant for the proper type **/ template<typename T> T Fourthrooteps(); namespace functional { /*! @ingroup group-callable-constant Generate the constant fourthrooteps. @return The Fourthrooteps constant for the proper type **/ const boost::dispatch::functor<tag::fourthrooteps_> fourthrooteps = {}; } } } #endif #include <boost/simd/constant/definition/fourthrooteps.hpp> #include <boost/simd/arch/common/scalar/constant/constant_value.hpp> #include <boost/simd/arch/common/simd/constant/constant_value.hpp> #endif
25.032787
100
0.599214
yaeldarmon
47c30f2e4a346afa32e383094f6e32de924e1f01
5,742
cpp
C++
src/Buffer.cpp
twh2898/glpp
b413293b525d885fefd20fedb51988edf1999b70
[ "MIT" ]
null
null
null
src/Buffer.cpp
twh2898/glpp
b413293b525d885fefd20fedb51988edf1999b70
[ "MIT" ]
null
null
null
src/Buffer.cpp
twh2898/glpp
b413293b525d885fefd20fedb51988edf1999b70
[ "MIT" ]
null
null
null
#include "glpp/Buffer.hpp" namespace glpp { void Attribute::enable() const { glVertexAttribPointer(index, size, type, normalized, stride, pointer); glVertexAttribDivisor(index, divisor); glEnableVertexAttribArray(index); } void Attribute::disable() const { glDisableVertexAttribArray(index); } } namespace glpp { Buffer::Buffer(Target target) : target(target) { glGenBuffers(1, &buffer); } Buffer::Buffer(Buffer && other) : target(other.target), buffer(other.buffer) { other.buffer = 0; } Buffer & Buffer::operator=(Buffer && other) { target = other.target; buffer = other.buffer; other.buffer = 0; return *this; } Buffer::~Buffer() { if (buffer) glDeleteBuffers(1, &buffer); } Buffer::Target Buffer::getTarget() const { return target; } GLuint Buffer::getBufferId() const { return buffer; } void Buffer::bind() const { glBindBuffer(target, buffer); } void Buffer::unbind() const { glBindBuffer(target, 0); } void Buffer::bufferData(GLsizeiptr size, const void * data, Usage usage) { bind(); glBufferData(target, size, data, usage); } void Buffer::bufferSubData(GLintptr offset, GLsizeiptr size, const void * data) { bind(); glBufferSubData(target, offset, size, data); } } namespace glpp { AttributedBuffer::AttributedBuffer(const std::vector<Attribute> & attrib, Buffer && buffer) : attrib(attrib), buffer(std::move(buffer)) {} AttributedBuffer::AttributedBuffer(AttributedBuffer && other) : attrib(std::move(other.attrib)), buffer(std::move(other.buffer)) {} AttributedBuffer & AttributedBuffer::operator=(AttributedBuffer && other) { attrib = std::move(other.attrib); buffer = std::move(other.buffer); return *this; } void AttributedBuffer::bufferData(GLsizeiptr size, const void * data, Usage usage) { buffer.bufferData(size, data, usage); for (auto & a : attrib) { a.enable(); } } } namespace glpp { BufferArray::BufferArray() : elementBuffer(nullptr) { glGenVertexArrays(1, &array); } BufferArray::BufferArray(const std::vector<std::vector<Attribute>> & attributes) : BufferArray() { for (auto & attr : attributes) { Buffer buffer(Buffer::Array); buffers.emplace_back(attr, std::move(buffer)); } } BufferArray::BufferArray(std::vector<Buffer> && buffers) : BufferArray() { buffers = std::move(buffers); } BufferArray::BufferArray(BufferArray && other) : array(other.array), buffers(std::move(other.buffers)), elementBuffer(std::move(other.elementBuffer)) { other.array = 0; } BufferArray & BufferArray::operator=(BufferArray && other) { array = other.array; other.array = 0; buffers = std::move(other.buffers); elementBuffer = std::move(other.elementBuffer); return *this; } BufferArray::~BufferArray() { if (array) glDeleteVertexArrays(1, &array); } GLuint BufferArray::getArrayId() const { return array; } std::size_t BufferArray::size() const { return buffers.size(); } const std::vector<AttributedBuffer> & BufferArray::getBuffers() const { return buffers; } std::vector<AttributedBuffer> & BufferArray::getBuffers() { return buffers; } void BufferArray::bind() const { glBindVertexArray(array); } void BufferArray::unbind() const { glBindVertexArray(0); } void BufferArray::bufferData(size_t index, GLsizeiptr size, const void * data, Usage usage) { buffers[index].bufferData(size, data, usage); } void BufferArray::bufferSubData(size_t index, GLintptr offset, GLsizeiptr size, const void * data) { buffers[index].bufferSubData(offset, size, data); } void BufferArray::bufferElements(GLsizeiptr size, const void * data, Usage usage) { if (!elementBuffer) elementBuffer = std::make_unique<Buffer>(Buffer::Index); elementBuffer->bufferData(size, data, usage); } void BufferArray::drawArrays(Mode mode, GLint first, GLsizei count) const { bind(); glDrawArrays(mode, first, count); } void BufferArray::drawArraysInstanced(Mode mode, GLint first, GLsizei count, GLsizei primcount) const { bind(); glDrawArraysInstanced(mode, first, count, primcount); } void BufferArray::drawElements(Mode mode, GLsizei count, GLenum type, const void * indices) const { bind(); glDrawElements(mode, count, type, indices); } void BufferArray::drawElementsInstanced(Mode mode, GLsizei count, GLenum type, const void * indices, GLsizei primcount) const { bind(); glDrawElementsInstanced(mode, count, type, indices, primcount); } }
29.147208
88
0.547893
twh2898
47c3f83ad828e82b70371511ad1432f7cbc01dcc
229
hpp
C++
apps/smart_switch/messaging_config.hpp
ecrampton1/MspPeripheralmm
ae1f64cc785b9a3b994074e851e68c170aef613f
[ "MIT" ]
null
null
null
apps/smart_switch/messaging_config.hpp
ecrampton1/MspPeripheralmm
ae1f64cc785b9a3b994074e851e68c170aef613f
[ "MIT" ]
1
2021-03-07T14:18:31.000Z
2021-03-07T14:18:31.000Z
apps/smart_switch/messaging_config.hpp
ecrampton1/MspPeripheralmm
ae1f64cc785b9a3b994074e851e68c170aef613f
[ "MIT" ]
null
null
null
#ifndef MESSAGING_CONFIG_HPP_ #define MESSAGING_CONFIG_HPP_ static constexpr uint8_t NODEID = 12; #define FOR_ALL_INCOMING_MESSAGES(ACTION) \ ACTION( SwitchQuery ) \ ACTION( SwitchRequest ) #endif //MESSAGING_CONFIG_HPP_
16.357143
43
0.799127
ecrampton1
47cf64f750b91e4cf5b82e79ad54c4b1f14cd3ac
3,947
cc
C++
pkg/src/bibliography/reference.cc
saaymeen/bib-parser
e1a5a2db7fa5dfef9b09c032beeeca6129043419
[ "Unlicense" ]
1
2020-06-12T10:33:56.000Z
2020-06-12T10:33:56.000Z
pkg/src/bibliography/reference.cc
saaymeen/bib-parser
e1a5a2db7fa5dfef9b09c032beeeca6129043419
[ "Unlicense" ]
null
null
null
pkg/src/bibliography/reference.cc
saaymeen/bib-parser
e1a5a2db7fa5dfef9b09c032beeeca6129043419
[ "Unlicense" ]
2
2020-06-12T10:31:41.000Z
2020-06-12T13:19:08.000Z
#include <string> #include <unordered_map> #include <vector> #include "bib-parser/bibliography/reference.h" using std::string; using std::unordered_map; using std::vector; using TUCSE::EntryType; using TUCSE::FieldType; using TUCSE::Reference; Reference::Reference(string const &citationKey, EntryType const entryType) : citationKey{citationKey}, entryType{entryType}, fields{} {}; EntryType Reference::getEntryType() const noexcept { return entryType; } void Reference::addField(FieldType const fieldType, string const &value) noexcept { fields.insert({fieldType, value}); } string Reference::getCitationKey() const noexcept { return citationKey; } unordered_map<FieldType, string> Reference::getFields() const noexcept { return fields; } std::string Reference::getFieldValue(FieldType const fieldType) const { return fields.at(fieldType); } bool Reference::isValid() const noexcept { bool valid{false}; vector<FieldType> requiredFieldTypes; switch (entryType) { case EntryType::Article: requiredFieldTypes.push_back(FieldType::Author); requiredFieldTypes.push_back(FieldType::Title); requiredFieldTypes.push_back(FieldType::Journal); requiredFieldTypes.push_back(FieldType::Year); break; case EntryType::Book: requiredFieldTypes.push_back(FieldType::Title); break; case EntryType::Booklet: requiredFieldTypes.push_back(FieldType::Title); break; case EntryType::Conference: case EntryType::InProceedings: // Same as conference requiredFieldTypes.push_back(FieldType::Author); requiredFieldTypes.push_back(FieldType::Title); requiredFieldTypes.push_back(FieldType::Booktitle); requiredFieldTypes.push_back(FieldType::Year); break; case EntryType::InBook: requiredFieldTypes.push_back(FieldType::Author); requiredFieldTypes.push_back(FieldType::Editor); requiredFieldTypes.push_back(FieldType::Title); requiredFieldTypes.push_back(FieldType::Chapter); requiredFieldTypes.push_back(FieldType::Pages); requiredFieldTypes.push_back(FieldType::Publisher); requiredFieldTypes.push_back(FieldType::Year); break; case EntryType::InCollection: requiredFieldTypes.push_back(FieldType::Author); requiredFieldTypes.push_back(FieldType::Title); requiredFieldTypes.push_back(FieldType::Booktitle); requiredFieldTypes.push_back(FieldType::Publisher); requiredFieldTypes.push_back(FieldType::Year); break; case EntryType::Manual: requiredFieldTypes.push_back(FieldType::Title); break; case EntryType::MastersThesis: requiredFieldTypes.push_back(FieldType::Author); requiredFieldTypes.push_back(FieldType::Title); requiredFieldTypes.push_back(FieldType::School); requiredFieldTypes.push_back(FieldType::Year); break; case EntryType::Miscellaneous: valid = true; // Misc does not require any specific fields break; case EntryType::PHDThesis: requiredFieldTypes.push_back(FieldType::Author); requiredFieldTypes.push_back(FieldType::Title); requiredFieldTypes.push_back(FieldType::School); requiredFieldTypes.push_back(FieldType::Year); break; case EntryType::Proceedings: requiredFieldTypes.push_back(FieldType::Title); requiredFieldTypes.push_back(FieldType::Year); break; case EntryType::TechReport: requiredFieldTypes.push_back(FieldType::Author); requiredFieldTypes.push_back(FieldType::Title); requiredFieldTypes.push_back(FieldType::Institution); requiredFieldTypes.push_back(FieldType::Year); break; case EntryType::Unpublished: requiredFieldTypes.push_back(FieldType::Author); requiredFieldTypes.push_back(FieldType::Title); requiredFieldTypes.push_back(FieldType::Note); break; default: valid = false; break; } if (requiredFieldTypes.empty() == false) { bool containsAll{true}; for (auto const &requiredFieldType : requiredFieldTypes) { if (fields.count(requiredFieldType) == 0) { containsAll = false; } } if (containsAll) { valid = true; } } return valid; }
25.62987
81
0.776032
saaymeen
c51a1573724e40f8ea13aecbcc47a8ed7cec6052
737
cpp
C++
AIC/AIC'20 - Level 2 Training Contests/Contest #10/B.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
3
2020-11-01T06:31:30.000Z
2022-02-21T20:37:51.000Z
AIC/AIC'20 - Level 2 Training Contests/Contest #10/B.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
null
null
null
AIC/AIC'20 - Level 2 Training Contests/Contest #10/B.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
1
2021-05-05T18:56:31.000Z
2021-05-05T18:56:31.000Z
//https://vjudge.net/contest/436257#problem/B #include <bits/stdc++.h> using namespace std; bool solve(string A, string B) { if (A == B) { return true; } string X = A, Y = B; sort(X.begin(), X.end()); sort(Y.begin(), Y.end()); if ((A.size() & 1) || (X != Y)) { return false; } string A1 = A.substr(0, A.size() / 2), A2 = A.substr(A.size() / 2, A.size() / 2); string B1 = B.substr(0, B.size() / 2), B2 = B.substr(B.size() / 2, B.size() / 2); return ((solve(A1, B1) && solve(A2, B2)) || (solve(A1, B2) && solve(A2, B1))); } int main () { ios_base::sync_with_stdio (0); cin.tie (0); cout.tie (0); string A, B; cin >> A >> B; cout << (solve(A, B) ? "YES" : "NO"); }
27.296296
85
0.497965
MaGnsio
c51a70404b06ddc50ef0b305ed28bc0d083e84be
1,708
cpp
C++
ESP01_NowSender/src/esp_now_ext/esp_now_ext.cpp
Pliskin707/ESPNOW_SmartHome
6d09049fd39a4995e0cb4fb647aa9c260253f7aa
[ "MIT" ]
null
null
null
ESP01_NowSender/src/esp_now_ext/esp_now_ext.cpp
Pliskin707/ESPNOW_SmartHome
6d09049fd39a4995e0cb4fb647aa9c260253f7aa
[ "MIT" ]
2
2021-12-23T14:48:25.000Z
2021-12-23T23:49:06.000Z
ESP01_NowSender/src/esp_now_ext/esp_now_ext.cpp
Pliskin707/ESPNOW_SmartHome
6d09049fd39a4995e0cb4fb647aa9c260253f7aa
[ "MIT" ]
null
null
null
#include "esp_now_ext.hpp" EspNowExtClass EspNowExt; static uint8_t _txRetries = 0; static struct { uint8_t txRetriesRemaining; uint8_t len; mac dest; const uint8_t * data; } _txPackage = {0, 0, {0}, nullptr}; bool EspNowExtClass::begin (const uint8_t txRetries) { if (esp_now_init() == 0) { _txRetries = txRetries; esp_now_set_self_role(ESP_NOW_ROLE_CONTROLLER); // priority is given to the station interface (not the SoftAP) esp_now_register_send_cb(&this->_txCallback); return true; } return false; } int EspNowExtClass::addPeer (const uint8_t mac[6]) { return esp_now_add_peer((uint8_t *) mac, ESP_NOW_ROLE_IDLE, 11, nullptr, 0); // from the documentation: "The peer's Role does not affect any function, but only stores the Role information for the application layer." } int EspNowExtClass::send (const mac destination, const void * data, const uint8_t len) { _txPackage.txRetriesRemaining = _txRetries; _txPackage.len = len; memcpy(_txPackage.dest, destination, sizeof(mac)); _txPackage.data = (const uint8_t *) data; return esp_now_send((uint8_t *) _txPackage.dest, (uint8_t *) _txPackage.data, _txPackage.len); } int EspNowExtClass::send (const void * data, const uint8_t len) { return this->send(nullptr, data, len); } void EspNowExtClass::_txCallback (uint8_t * mac_addr, uint8_t status) { if ((status != 0) && _txPackage.txRetriesRemaining) EspNowExt._retrySend(); } void EspNowExtClass::_retrySend (void) { if (_txPackage.txRetriesRemaining) _txPackage.txRetriesRemaining--; esp_now_send((uint8_t *) _txPackage.dest, (uint8_t *) _txPackage.data, _txPackage.len); }
29.448276
221
0.70726
Pliskin707
c51a83a62be319f139825ca299feea89f5fbee2d
91,003
cpp
C++
src/plugins/DreamColor/DreamColorCalib.cpp
SchademanK/Ookala
9a5112e1d3067d589c150fb9c787ae36801a67dc
[ "MIT" ]
null
null
null
src/plugins/DreamColor/DreamColorCalib.cpp
SchademanK/Ookala
9a5112e1d3067d589c150fb9c787ae36801a67dc
[ "MIT" ]
null
null
null
src/plugins/DreamColor/DreamColorCalib.cpp
SchademanK/Ookala
9a5112e1d3067d589c150fb9c787ae36801a67dc
[ "MIT" ]
null
null
null
// -------------------------------------------------------------------------- // $Id: DreamColorCalib.cpp 135 2008-12-19 00:49:58Z omcf $ // -------------------------------------------------------------------------- // Copyright (c) 2008 Hewlett-Packard Development Company, L.P. // // 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 <math.h> #include <vector> #include <algorithm> #ifdef _WIN32 #include <time.h> #endif #include "Dict.h" #include "DictHash.h" #include "PluginRegistry.h" #include "PluginChain.h" #include "DataSavior.h" #include "Sensor.h" #include "Ddc.h" #include "Color.h" #include "Interpolate.h" #include "plugins/DreamColor/DreamColorSpaceInfo.h" #include "plugins/DreamColor/DreamColorCtrl.h" #include "plugins/WsLut/WsLut.h" #include "DreamColorCalib.h" namespace Ookala { struct DataPoint { Yxy measuredYxy; Rgb linearRgb; uint32_t backlightReg[4]; }; }; // ===================================== // // DreamColorCalib // // ------------------------------------- Ookala::DreamColorCalib::DreamColorCalib(): Plugin() { setName("DreamColorCalib"); mNumGraySamples = 16; } // ------------------------------------- Ookala::DreamColorCalib::DreamColorCalib(const DreamColorCalib &src): Plugin(src) { mNumGraySamples = src.mNumGraySamples; } // ------------------------------------- // // virtual Ookala::DreamColorCalib::~DreamColorCalib() { } // ---------------------------- // Ookala::DreamColorCalib & Ookala::DreamColorCalib::operator=(const DreamColorCalib &src) { if (this != &src) { Plugin::operator=(src); mNumGraySamples = src.mNumGraySamples; } return *this; } // ------------------------------------- // // virtual bool Ookala::DreamColorCalib::checkCalibRecord(CalibRecordDictItem *calibRec) { DreamColorCalibRecord *myCalibRec; if (calibRec->getCalibrationPluginName() != std::string("DreamColorCalib")) { return false; } myCalibRec = dynamic_cast<DreamColorCalibRecord *>(calibRec); if (!myCalibRec) { return false; } // Check the preset and the brightness register on the // display. // // XXX: We should really be scanning by EDID here, but // we're not serializing that yet, so just pick a display // for now. if (!mRegistry) { setErrorString("No Registry in DreamColorCalib."); return false; } std::vector<Plugin *> plugins = mRegistry->queryByName("DreamColorCtrl"); if (plugins.empty()) { setErrorString("No DreamColorCtrl plugin found."); return false; } DreamColorCtrl *disp = dynamic_cast<DreamColorCtrl *>(plugins[0]); if (!disp) { setErrorString("No DreamColorCtrl plugin found."); return false; } // Go ahead and just re-enumerate now, in case this hasn't happened, // or someone has been re-plugging their displays. disp->enumerate(); // Now check the display to see how its' doing. uint32_t currCsIdx, regValues[4]; if (!disp->getColorSpace(currCsIdx)) { setErrorString("Unable to get color space from display."); return false; } if (!disp->getBacklightRegRaw(regValues[0], regValues[1], regValues[2], regValues[3])) { setErrorString("Unable to get backlight registers from display."); return false; } if (myCalibRec->getPreset() != currCsIdx) { setErrorString("Color space preset does not match calibration."); return false; } if (myCalibRec->getBrightnessReg() != regValues[3]) { setErrorString("Color space brightness does not match calibration."); return false; } return true; } // ------------------------------------- // // protected void Ookala::DreamColorCalib::gatherOptions(PluginChain *chain) { std::vector<Plugin *> plugins; DictHash *hash; Dict *dict; DictItem *item; IntDictItem *intItem; DoubleArrayDictItem *doubleArrayItem; // Reset default values mNumGraySamples = 16; // Look for the proper dict if (!mRegistry) { return; } plugins = mRegistry->queryByName("DictHash"); if (plugins.empty()) { return; } hash = dynamic_cast<DictHash *>(plugins[0]); if (!hash) { return; } dict = hash->getDict(chain->getDictName()); if (dict == NULL) { return; } // Look for the items we care about item = dict->get("DreamColorCalib::graySamples"); intItem = dynamic_cast<IntDictItem *>(item); if (intItem) { mNumGraySamples = intItem->get(); // Just for sanity... if (mNumGraySamples > 1024) { mNumGraySamples = 1024; } } // Figure out measurement tolerances. Look in the provided dictionary for: // // DreamColorCalib::whiteTolerance (vec3, Yxy) -> same value for +- // DreamColorCalib::redTolerance (vec2, xy) -> same value for +- // DreamColorCalib::greenTolerance (vec2, xy) -> same value for +- // DreamColorCalib::blueTolerance (vec2, xy) -> same value for +- // DreamColorCalib::whiteTolerancePlus (vec3, Yxy) -> White + tolerance // DreamColorCalib::whiteToleranceMinus (vec3, Yxy) -> White - tolerance // // DreamColorCalib::redTolerancePlus (vec2, xy) -> Red + tolerance // DreamColorCalib::redToleranceMinus (vec2, xy) -> Red - tolerance // // DreamColorCalib::greenTolerancePlus (vec2, xy) -> Green + tolerance // DreamColorCalib::greenToleranceMinus (vec2, xy) -> Green - tolerance // // DreamColorCalib::blueTolerancePlus (vec2, xy) -> Blue + tolerance // DreamColorCalib::blueToleranceMinus (vec2, xy) -> Blue - tolerance mWhiteTolerancePlus.Y = 1.0; mWhiteToleranceMinus.Y = mWhiteTolerancePlus.x = mWhiteToleranceMinus.x = mWhiteTolerancePlus.y = mWhiteToleranceMinus.y = 0.0025; mRedTolerancePlus.x = mRedToleranceMinus.x = mRedTolerancePlus.y = mRedToleranceMinus.y = 0.0025; mGreenTolerancePlus.x = mGreenToleranceMinus.x = mGreenTolerancePlus.y = mGreenToleranceMinus.y = 0.0025; mBlueTolerancePlus.x = mBlueToleranceMinus.x = mBlueTolerancePlus.y = mBlueToleranceMinus.y = 0.0025; // White user tolerances item = dict->get("DreamColorCalib::whiteTolerance"); if (item) { doubleArrayItem = dynamic_cast<DoubleArrayDictItem *>(item); if (doubleArrayItem) { if (doubleArrayItem->get().size() >= 3) { mWhiteTolerancePlus.Y = mWhiteToleranceMinus.Y = (doubleArrayItem->get())[0]; mWhiteTolerancePlus.x = mWhiteToleranceMinus.x = (doubleArrayItem->get())[1]; mWhiteTolerancePlus.y = mWhiteToleranceMinus.y = (doubleArrayItem->get())[2]; } } } item = dict->get("DreamColorCalib::whiteTolerancePlus"); if (item) { doubleArrayItem = dynamic_cast<DoubleArrayDictItem *>(item); if (doubleArrayItem) { if (doubleArrayItem->get().size() >= 3) { mWhiteTolerancePlus.Y = (doubleArrayItem->get())[0]; mWhiteTolerancePlus.x = (doubleArrayItem->get())[1]; mWhiteTolerancePlus.y = (doubleArrayItem->get())[2]; } } } item = dict->get("DreamColorCalib::whiteToleranceMinus"); if (item) { doubleArrayItem = dynamic_cast<DoubleArrayDictItem *>(item); if (doubleArrayItem) { if (doubleArrayItem->get().size() >= 3) { mWhiteToleranceMinus.Y = (doubleArrayItem->get())[0]; mWhiteToleranceMinus.x = (doubleArrayItem->get())[1]; mWhiteToleranceMinus.y = (doubleArrayItem->get())[2]; } } } // Red user tolerances item = dict->get("DreamColorCalib::redTolerance"); if (item) { doubleArrayItem = dynamic_cast<DoubleArrayDictItem *>(item); if (doubleArrayItem) { if (doubleArrayItem->get().size() >= 2) { mRedTolerancePlus.x = mRedToleranceMinus.x = (doubleArrayItem->get())[0]; mRedTolerancePlus.y = mRedToleranceMinus.y = (doubleArrayItem->get())[1]; } } } item = dict->get("DreamColorCalib::redTolerancePlus"); if (item) { doubleArrayItem = dynamic_cast<DoubleArrayDictItem *>(item); if (doubleArrayItem) { if (doubleArrayItem->get().size() >= 2) { mRedTolerancePlus.x = (doubleArrayItem->get())[0]; mRedTolerancePlus.y = (doubleArrayItem->get())[1]; } } } item = dict->get("DreamColorCalib::redToleranceMinus"); if (item) { doubleArrayItem = dynamic_cast<DoubleArrayDictItem *>(item); if (doubleArrayItem) { if (doubleArrayItem->get().size() >= 2) { mRedToleranceMinus.x = (doubleArrayItem->get())[0]; mRedToleranceMinus.y = (doubleArrayItem->get())[1]; } } } // Green user tolerances item = dict->get("DreamColorCalib::greenTolerance"); if (item) { doubleArrayItem = dynamic_cast<DoubleArrayDictItem *>(item); if (doubleArrayItem) { if (doubleArrayItem->get().size() >= 2) { mGreenTolerancePlus.x = mGreenToleranceMinus.x = (doubleArrayItem->get())[0]; mGreenTolerancePlus.y = mGreenToleranceMinus.y = (doubleArrayItem->get())[1]; } } } item = dict->get("DreamColorCalib::greenTolerancePlus"); if (item) { doubleArrayItem = dynamic_cast<DoubleArrayDictItem *>(item); if (doubleArrayItem) { if (doubleArrayItem->get().size() >= 2) { mGreenTolerancePlus.x = (doubleArrayItem->get())[0]; mGreenTolerancePlus.y = (doubleArrayItem->get())[1]; } } } item = dict->get("DreamColorCalib::greenToleranceMinus"); if (item) { doubleArrayItem = dynamic_cast<DoubleArrayDictItem *>(item); if (doubleArrayItem) { if (doubleArrayItem->get().size() >= 2) { mGreenToleranceMinus.x = (doubleArrayItem->get())[0]; mGreenToleranceMinus.y = (doubleArrayItem->get())[1]; } } } // Blue user tolerances item = dict->get("DreamColorCalib::blueTolerance"); if (item) { doubleArrayItem = dynamic_cast<DoubleArrayDictItem *>(item); if (doubleArrayItem) { if (doubleArrayItem->get().size() >= 2) { mBlueTolerancePlus.x = mBlueToleranceMinus.x = (doubleArrayItem->get())[0]; mBlueTolerancePlus.y = mBlueToleranceMinus.y = (doubleArrayItem->get())[1]; } } } item = dict->get("DreamColorCalib::blueTolerancePlus"); if (item) { doubleArrayItem = dynamic_cast<DoubleArrayDictItem *>(item); if (doubleArrayItem) { if (doubleArrayItem->get().size() >= 2) { mBlueTolerancePlus.x = (doubleArrayItem->get())[0]; mBlueTolerancePlus.y = (doubleArrayItem->get())[1]; } } } item = dict->get("DreamColorCalib::blueToleranceMinus"); if (item) { doubleArrayItem = dynamic_cast<DoubleArrayDictItem *>(item); if (doubleArrayItem) { if (doubleArrayItem->get().size() >= 2) { mBlueToleranceMinus.x = (doubleArrayItem->get())[0]; mBlueToleranceMinus.y = (doubleArrayItem->get())[1]; } } } } // ------------------------------------- // // protected std::vector<Ookala::DreamColorSpaceInfo> Ookala::DreamColorCalib::gatherTargets(PluginChain *chain) { std::vector<DreamColorSpaceInfo> targets; std::vector<Plugin *> plugins; DictHash *hash; Dict *dict; StringArrayDictItem *nameListItem; std::vector<std::string> nameList; if (!mRegistry) { return targets; } plugins = mRegistry->queryByName("DictHash"); if (plugins.empty()) { setErrorString("No DictHash found"); return targets; } hash = dynamic_cast<DictHash *>(plugins[0]); if (!hash) { setErrorString("No DictHash cast"); return targets; } dict = hash->getDict(chain->getDictName()); if (dict == NULL) { setErrorString("No chain dict found."); return targets; } nameListItem = dynamic_cast<StringArrayDictItem *>( dict->get("DreamColorCalib::targets")); if (!nameListItem) { return targets; } nameList = nameListItem->get(); for (std::vector<std::string>::iterator name = nameList.begin(); name != nameList.end(); ++name) { DreamColorSpaceInfo *targetItem = dynamic_cast<DreamColorSpaceInfo *>(dict->get(*name)); if (!targetItem) { continue; } // If we're not the first one, check the device/connection id if (!targets.empty()) { if (targets[0].getConnId() != targetItem->getConnId()) { continue; } } targets.push_back(*targetItem); } return targets; } // ------------------------------------- // // virtual protected bool Ookala::DreamColorCalib::gatherPlugins(PluginData &pi, PluginChain *chain) { std::vector<Plugin *>plugins; setErrorString(""); if (mRegistry == NULL) { setErrorString("No registry found."); return false; } // Check for a DreamColorCtrl plugins = mRegistry->queryByName("DreamColorCtrl"); if (plugins.empty()) { setErrorString("No DreamColorCtrl plugin found."); return false; } pi.disp = dynamic_cast<DreamColorCtrl *>(plugins[0]); if (!(pi.disp)) { setErrorString("No DreamColorCtrl plugin found."); return false; } pi.dispId = 0; // Check for a sensor in the chain bool testReg = true; plugins = chain->queryByAttribute("sensor"); if (!plugins.empty()) { pi.sensor = dynamic_cast<Sensor *>(plugins[0]); if ((pi.sensor) != NULL) { testReg = false; } } if (testReg) { plugins = mRegistry->queryByAttribute("sensor"); if (!plugins.empty()) { pi.sensor = dynamic_cast<Sensor *>(plugins[0]); if ((pi.sensor) == NULL) { setErrorString("No sensor found."); return false; } } else { setErrorString("No sensor found."); return false; } } // And make sure the sensor is ready to go - it's ok to enumerate // sensors if we haven't done that yet (pi.sensor)->actionTaken(SENSOR_ACTION_DETECT, chain); if ( (pi.sensor)->sensors().empty() ) { setErrorString("No sensors found."); return false; } if (!(pi.sensor)->actionNeeded(chain).empty()) { setErrorString("Sensor is not ready for measuring."); return false; } pi.sensorId = 0; // Check for a color space plugin - it's build it, so it had // best be there, less extreme badness has occurred. plugins = mRegistry->queryByName("Color"); if (plugins.empty()) { setErrorString("No Color plugin found."); return false; } pi.color = dynamic_cast<Color *>(plugins[0]); if (!(pi.color)) { setErrorString("No Color plugin found."); return false; } // Similarly, for an interpolator plugins = mRegistry->queryByName("Interpolate"); if (plugins.empty()) { setErrorString("No Interpolate plugin found."); return false; } pi.interp = dynamic_cast<Interpolate *>(plugins[0]); if (!(pi.interp)) { setErrorString("No Interpolate plugin found."); return false; } // Make sure we have a WsLut plugin as well; and that it // has some data plugins = mRegistry->queryByName("WsLut"); if (plugins.empty()) { setErrorString("No WsLut plugin found."); return false; } pi.lut = dynamic_cast<WsLut *>(plugins[0]); if (!pi.lut) { setErrorString("No WsLut plugin found."); return false; } if (pi.lut->luts().empty()) { setErrorString("WsLut plugin has not Luts available."); return false; } return true; } // ------------------------------------- // // virtual protected bool Ookala::DreamColorCalib::_run(PluginChain *chain) { PluginData pi; DreamColorCalibrationData calib; Yxy goalWhite; Npm panelNpm; uint32_t backlightReg[4]; // Mapping from the display connection id to the preset // state that the device is in when we start out. std::map<uint32_t, uint32_t> origPresets; setErrorString(""); gatherOptions(chain); if (!gatherPlugins(pi, chain)) { return false; } // Gather all the calibration targets we're going to try // and deal with. NOTE: we're not going to accept targets // on different devices for now. std::vector<DreamColorSpaceInfo> targets = gatherTargets(chain); printf("%d targets to calibrate\n", (int)targets.size()); if (targets.size() == 0) { return true; } // Run over all the targets and record the initial state of // the preset for the displays we're going to touch for (std::vector<DreamColorSpaceInfo>::iterator theTarget = targets.begin(); theTarget != targets.end(); ++theTarget) { std::map<uint32_t, uint32_t>::iterator thePreset; thePreset = origPresets.find((*theTarget).getConnId()); if (thePreset == origPresets.end()) { uint32_t csIdx; if (pi.disp->getColorSpace(csIdx, (*theTarget).getConnId(), chain)) { origPresets[(*theTarget).getConnId()] = csIdx; } } } // Run over all our targets. If we have multiple targets, we don't need // to re-measure the gray ramp each time. Just do it once and that should // be sufficient. std::map<double, double> grayRampR, grayRampG, grayRampB; for (uint32_t targetIdx=0; targetIdx<targets.size(); ++targetIdx) { if (wasCancelled(pi, chain, false)) return false; if (chain) { char buf[1024]; #ifdef _WIN32 sprintf_s(buf, 1023, "Calibrating target %d of %d", targetIdx+1, (int)targets.size()); #else sprintf(buf, "Calibrating target %d of %d", targetIdx+1, (int)targets.size()); #endif chain->setUiString("Ui::status_string_major", std::string(buf)); chain->setUiString("Ui::status_string_minor", std::string("")); } // Set the target primaries + white in the display if (chain) { chain->setUiYxy("Ui::target_red_Yxy", targets[targetIdx].getRed()); chain->setUiYxy("Ui::target_green_Yxy", targets[targetIdx].getGreen()); chain->setUiYxy("Ui::target_blue_Yxy", targets[targetIdx].getBlue()); chain->setUiYxy("Ui::target_white_Yxy", targets[targetIdx].getWhite()); } // Restruct data for the approprate format calib.setColorSpaceInfo(targets[targetIdx]); pi.dispId = targets[targetIdx].getConnId(); goalWhite = targets[targetIdx].getWhite(); // Switch into the color space if interest if (!pi.disp->setColorSpace(targets[targetIdx].getPresetId(), pi.dispId)) { setErrorString( std::string("Unable to select calibrated color space. ") + pi.disp->errorString() ); return false; } if (!idle(5, chain)) { for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } if (wasCancelled(pi, chain, false)) { for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } // Disable color processing if (!pi.disp->setColorProcessingEnabled(false, pi.dispId)) { setErrorString( pi.disp->errorString() ); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } if (chain) { chain->setUiString("Ui::status_string_minor", "Enabling pattern generator."); } // Turn on the pattern generator - take care to disable // it when we return in this method then. if (!pi.disp->setPatternGeneratorEnabled(true, pi.dispId)) { setErrorString("ERROR: Can't enable pattern generator."); pi.disp->setColorProcessingEnabled(true, pi.dispId); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } printf("Waiting %d seconds...\n", pi.disp->patternGeneratorEnableTime(pi.dispId)); if (!idle(pi.disp->patternGeneratorEnableTime(pi.dispId), chain)) { pi.disp->setColorProcessingEnabled(true, pi.dispId); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, NULL); } return false; } if (wasCancelled(pi, chain, true)) { pi.disp->setColorProcessingEnabled(true, pi.dispId); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } if (chain) { chain->setUiString("Ui::status_string_minor", "Calibrating backlight."); } // Run the backlight processing loop + hang onto the registers if (!backlightLoop(pi, chain, goalWhite, backlightReg, pi.panelWhite)) { pi.disp->setColorProcessingEnabled(true, pi.dispId); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } calib.setRegP0(backlightReg[0]); calib.setRegP1(backlightReg[1]); calib.setRegP2(backlightReg[2]); calib.setRegBrightness(backlightReg[3]); if (wasCancelled(pi, chain, true)) { pi.disp->setColorProcessingEnabled(true, pi.dispId); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } if (chain) { chain->setUiString("Ui::status_string_minor", "Measuring primaries for matrix correction."); } // Measure the primaries + find the native NPM if (!measurePrimaries(pi, chain, pi.panelRed, pi.panelGreen, pi.panelBlue)) { pi.disp->setColorProcessingEnabled(true, pi.dispId); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } if (wasCancelled(pi, chain, true)) { pi.disp->setColorProcessingEnabled(true, pi.dispId); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } if (!pi.color->computeNpm(pi.panelRed, pi.panelGreen, pi.panelBlue, pi.panelWhite, panelNpm)) { setErrorString("Unable to compute native NPM."); pi.disp->setColorProcessingEnabled(true, pi.dispId); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } printf("Actual white: %f %f %f\n", pi.panelWhite.Y, pi.panelWhite.x, pi.panelWhite.y); // Compute the 3x3 if (!compute3x3CalibMatrix(pi, calib, panelNpm)) { pi.disp->setColorProcessingEnabled(true, pi.dispId); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } if (wasCancelled(pi, chain, true)) { pi.disp->setColorProcessingEnabled(true, pi.dispId); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } // Measure the gray ramp if (targetIdx == 0) { if (!measureGrayRamp(pi, chain, calib, panelNpm, mNumGraySamples, grayRampR, grayRampG, grayRampB, calib.getMatrix())) { pi.disp->setColorProcessingEnabled(true, pi.dispId); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } } if (wasCancelled(pi, chain, true)) { pi.disp->setColorProcessingEnabled(true, pi.dispId); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } // Turn off the pattern generator if (!pi.disp->setPatternGeneratorEnabled(false, pi.dispId)) { setErrorString( std::string("ERROR: Can't disable pattern generator: ") + pi.disp->errorString()); pi.disp->setColorProcessingEnabled(true, pi.dispId); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } // If this happens, well, that sucks. I'm not sure we // can recover without power-cycling return false; } idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); computeLuts(pi, calib, grayRampR, grayRampG, grayRampB, panelNpm); if (wasCancelled(pi, chain, false)) { pi.disp->setColorProcessingEnabled(true, pi.dispId); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } // Upload! if (!pi.disp->setCalibration(targets[targetIdx].getPresetId(), calib, pi.dispId, chain)) { setErrorString( std::string("Unable to upload calibration data: ") + pi.disp->errorString()); pi.disp->setColorProcessingEnabled(true, pi.dispId); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } if (wasCancelled(pi, chain, false)) { pi.disp->setColorProcessingEnabled(true, pi.dispId); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } // Enable color processing somehow and plop us back // in the right color space if (!pi.disp->setColorProcessingEnabled(true, pi.dispId)) { setErrorString(pi.disp->errorString()); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } if (wasCancelled(pi, chain, false)) { for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } // For some reason, we end up in a wierd state on some systems if we don't // re-select the current color space. But just re-selecting does not // seem to be sufficent. We first need to flip the pattern generator // on and off. How odd? Yes indeed. #if 1 // Begin workaround: if (!pi.disp->setPatternGeneratorEnabled(true, targets[targetIdx].getConnId())) { setErrorString("ERROR: Can't enable pattern generator."); return false; } if (!idle(pi.disp->patternGeneratorEnableTime(pi.dispId), chain)) { pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); printf("Re-selecting color space\n"); if (!pi.disp->setColorSpace(targets[targetIdx].getPresetId(), pi.dispId)) { setErrorString( std::string("Unable to select calibrated color space. ") + pi.disp->errorString() ); return false; } if (!idle(5, chain)) { for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } // End workaround: #else fprintf(stderr, "\tStuck luminance workaround disabled!!\n"); #endif if (chain) { chain->setUiString("Ui::status_string_minor", "Verifing calibration."); } // Reset any other Luts that sit in the way. if (!pi.lut->reset()) { setErrorString(pi.lut->errorString()); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } if (!validate(pi, targets[targetIdx], chain)) { for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } if (wasCancelled(pi, chain, false)) { for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } } return true; } // ------------------------------------- // // virtual protected bool Ookala::DreamColorCalib::_checkDeps() { std::vector<Plugin *> plugins; if (mRegistry == NULL) { setErrorString("No PluginRegistry found for DreamColorCalib."); return false; } plugins = mRegistry->queryByName("DreamColorCtrl"); if (plugins.empty()) { setErrorString("No DreamColorCtrl plugin found for DreamColorCalib."); return false; } plugins = mRegistry->queryByName("WsLut"); if (plugins.empty()) { setErrorString("No WsLut plugin found for DreamColorCalib."); return false; } return true; } // ------------------------------------- // // Before discussing how to find a good configuration for the // backlight, it's worthwhile to touch upon what /is/ a good // configuration for the backlight. // // With this display, the goal is not necessarily to just minimize // dE of the native backlight Yxy w.r.t. the target Yxy. It's // entirely possible that even with a very small dE, it would // still be impossible to reach the goal Yxy. // // The reason is headroom. Recall that the backlight is not // the sole determinate of white point - the rest of the color // processing chain comes into play. This is handy for the // really fine tweaking to get close to the goal Yxy. // // Consider the 3x3 matrix that maps target colorimetry onto // measured colorimetry. For mapping an incoming (1,1,1) value // all the components of the output value must be less than 1 - // otherwise we're clipping. In other words, if we measure // the panel's native RGB chromaticies and build an NPM // matrix using these and the backlight w.p (NPM = RGB -> XYZ) // we'll see: // // [R] [ ]^-1 [Target White X] // [G] = [ NPM ] [Target White Y] // [B] [ ] [Target White Z] // // (XXX: An example would be good here). // // If the resulting R,G,B > 1, we're out of luck. // // So, a valid backlight white point must allow for the mapping of // the target XYZ back to RGB, where max(R,G,B) <= 1.0. // // Now, that said, we don't want to waste bits. So we also want // to make sure that min(R,G,B) >= some threshold. // // Combining these two conditions, we can classify a "solution" as // a backlight white point where max(R,G,B) <= 1.0 and // min(R,G,B) >= T, where T is some threshold and R,G,B result // from the target XYZ and the NPM matrix formed by the backlight // white point and the native panel chromaticies. // // Ok. So that's a solution. But what's a _good_ solution, and how // to we find it? // // First, we need to give ourselves a better shot at finding a // backlight w.p with max(R,G,B) <= 1.0. This means adding in a little // headroom to the luminance goal we're trying to hit. In our // search, we're not really searching for the target w.p., but // rather the target w.p. plus some Y headroom - say, 2% headroom. // // Now - if we have a target with some headroom, this can become // the object of our dE affection. We'll drive towards this goal, // and we'll stop if we find a valid solution that has a really // good dE (where really good is some threshold that you pick). // // If we've searched for a fair number of iterations, but haven't // found a really good dE, we should stop and not run forever. // But, if we haven't found a really good dE, what should our // backlight white be? It makes sense to pick the best (in a dE sense) // "valid solution" that we found over the course of the iterations. // We'll then force the matrix to re-balance to the eventual target w.p. // If we haven't found any valid solutions, with max(R,G,B) <= 1.0 and // min(R,G,B) >= T), then we're out of luck and we're going to fail. // Alternativly, if this ends up being a problem, increase the max // number of iterations, or increase them only if we don't have any // valid solutions. // // The backlight has a set of 4 registers that control it. One register // is 'brightness' and is tied to the OSD brightness control. It's // a 1-byte register. At 0xff, the OSD reads out 250 cd/m^2. At // 0x51, the OSD reads out 50 cd/m^2. Note that the scaling is not // quite 1 code value / cd/m^2, so we should manually figure out the // OSD setting that maps to a goal luminance. The remaining 3 backlight // registers control (approximately) Y, x, and y. There is some cross // talk. For the x and y controls, there's approx. .001 change per // code value. For the Y control, there's approx 1 cd/m^2 change per // code value when brightness = 0xff. // // To try and approach a good solution, we iterate over adjusting // the Y, x, and y, backlight registers. To figure how far to // move, we keep a running estimate of how much change per register // code value we hit. Then, using this, we estimate how far to // adjust each register. From this, we move the register with the // largest step, and continue the process. // // It's fairly brain-dead, but it usually converges fairly quickly. // We have experimented with gradient-descent type stratagies, but // they're often rather sensitive to measurement noise - which has // a tendency to send us off in the wrong direction and diverge. // // // NOTE: Color processing should be disabled before entering this function. // // NOTE: Pattern generator should be enabled before entering. // // virtual protected bool Ookala::DreamColorCalib::backlightLoop( PluginData &pi, PluginChain *chain, const Yxy &goalWhite, uint32_t *backlightReg, Yxy &currWhite) { uint32_t lastReg[4], origReg[4]; Yxy lastWhite, red, green, blue; Yxy headroomGoal; Rgb linearRgb; int32_t chromaRegStep[3]; double diff[3]; DataPoint point; std::vector<DataPoint> solutions; bool convergedOnGoal = false; // --------------------------------------------------------- // Tweakable parameters: // // We should consider ourselves good enough if a solution // is within some threshold of a dE from our headroom goal. double dEStoppingThreshold = 1; // If we don't converge because of small dE, we should stop // after some fixed number of attempts. uint32_t maxIter = 12; // The amount of luminance headroom to start aiming for. double initialHeadroom = 1.02; // The current lower threshold on the linear RGB of our // goalYxy - given the native RGB of the panel and the current // white of the backlight - is 2.0x the difference from 1 given // 2% headroom. We'll update this below to adapt if // the headroom increases. double lowerLinearRgbThresh = 1. - 2.0*(initialHeadroom - 1.); double upperLinearRgbThresh = 1. - 0.50*(initialHeadroom - 1.); // One step in the Y register is appromatly a change of // 1 cd/m^2 at max brightness. Lets assume that it scales // linearly as brighteness decreases. These are only // initial estimates. As we take steps below, we'll update // these estimates to reflect reality. It won't be perfect, // thanks to noise and cross-channel issues (e.g. we're // really have dX/dRegister, dY/dRegister, dZ/dRegister), // but in practice it works fairly well. double unitsPerStep[3]; // // --------------------------------------------------------- unitsPerStep[0] = goalWhite.Y / 250.0; unitsPerStep[1] = 1./1000.; unitsPerStep[2] = 1./1000.; // The color we _actually_ want to hit in this loop has // some headroom in it. // // For now, we'll pick a fixed % of the goal Y headroomGoal.Y = initialHeadroom * goalWhite.Y; headroomGoal.x = goalWhite.x; headroomGoal.y = goalWhite.y; // Enforce some limits on the goals. We probably don't want to // dip much below 40 cd/m^2, and probably not much above 250 cd/m^2 if ((goalWhite.Y < 40) || (goalWhite.Y > 250)) { setErrorString("Target luminance is out of range [40,250]."); return false; } if (!measurePrimaries(pi, chain, red, green, blue)) { return false; } if (!pi.disp->setPatternGeneratorColor(1023, 1023, 1023, pi.dispId)) { setErrorString( std::string("Can't set pattern generator color: ") + pi.disp->errorString()); return false; } if (!idle(pi.disp->patternGeneratorSettleTime(pi.dispId), chain)) { return false; } if (wasCancelled(pi, chain, true)) return false; // It's probably best to start the backlight registers in // their current position (except for a change in the // brightness register. if (!pi.disp->getBacklightRegRaw(origReg[0], origReg[1], origReg[2], origReg[3], pi.dispId)) { setErrorString( std::string("Can't read initial backlight registers.") + pi.disp->errorString()); return false; } lastReg[0] = backlightReg[0] = origReg[0]; lastReg[1] = backlightReg[1] = origReg[1]; lastReg[2] = backlightReg[2] = origReg[2]; lastReg[3] = backlightReg[3] = pi.disp->brightnessRegister(goalWhite.Y, pi.dispId); // Set an initial position for the backlight registers if (!pi.disp->setBacklightRegRaw(backlightReg[0], backlightReg[1], backlightReg[2], backlightReg[3], true, true, true, true, pi.dispId)) { setErrorString( std::string("Can't set backlight registers: ") + pi.disp->errorString()); return false; } if (wasCancelled(pi, chain, true)) return false; // Wait for the backlight to settle - we could be smarter about // this by examining the current values. It takes ~15-20 sec to // settle over a min -> max brightness swing. But, if we're // not swinging that long, no need to wait that long. if (!idle(pi.disp->backlightBrightnessSettleTime(pi.dispId), chain)) { return false; } for (uint32_t mainIter=0; mainIter<maxIter; ++mainIter) { if (wasCancelled(pi, chain, true)) return false; // Measure where we are lastWhite = currWhite; if (!pi.sensor->measureYxy(currWhite, chain, pi.sensorId)) { setErrorString( std::string("Can't read sensor: ") + pi.sensor->errorString()); return false; } if (wasCancelled(pi, chain, true)) return false; // If our headroom has increased, we'll need to set our lower // tolerance of linear RGB accordingly. This sets it to // 2x the range of being dead on the current head room if (!computeGoalRgb(pi.color, red, green, blue, headroomGoal, goalWhite, linearRgb)) { return false; } lowerLinearRgbThresh = 1.0 - 2.0*(1.0-linearRgb.r); printf( "If dead on headroom goal, real goal rgb: %f [thresh: %f - %f]\n", linearRgb.r, upperLinearRgbThresh, lowerLinearRgbThresh); if (!computeGoalRgb(pi.color, red, green, blue, currWhite, goalWhite, linearRgb)) { return false; } double rgbDat[3]; rgbDat[0] = linearRgb.r; rgbDat[1] = linearRgb.g; rgbDat[2] = linearRgb.b; int minRgb = 0; int maxRgb = 0; for (int idx=1; idx<3; ++idx) { if (rgbDat[idx] > rgbDat[maxRgb]) maxRgb = idx; if (rgbDat[idx] < rgbDat[minRgb]) minRgb = idx; } printf("Linear RGB: %f %f %f\n", linearRgb.r, linearRgb.g, linearRgb.b); // If we have enough head room (that is, all RGB < 1) but yet // aren't wasting too may bits (min RGB is too low), then // stop because we'll fix the rest in the 3x3 matrix. // // The min threshold probably shouldn't be fixed - we should // look at what it would be if we hit our headroom goal // dead-nuts on, and then back off a little. if ((rgbDat[maxRgb] <= upperLinearRgbThresh) && (rgbDat[minRgb] > lowerLinearRgbThresh)) { // If we've found a valid solution which is pretty darn // close to where we want to be, go ahead and stop. // Otherwise, just record the solution so we can // find the best one later on if we get stuck point.linearRgb = linearRgb; point.measuredYxy = currWhite; for (int idx=0; idx<4; ++idx) { point.backlightReg[idx] = backlightReg[idx]; } solutions.push_back(point); if (pi.color->dELab(headroomGoal, currWhite, headroomGoal) < dEStoppingThreshold) { printf("Converged because dE < %f\n", dEStoppingThreshold); convergedOnGoal = true; break; } } printf("%4d %4d %4d %4d %f %f %f\n", backlightReg[0], backlightReg[1], backlightReg[2], backlightReg[3], currWhite.Y, currWhite.x, currWhite.y); // And re-estimate how much the display changes with response // to a given adjustment in value. Only update our estimate // if its a sane value thought. diff[0] = currWhite.Y - lastWhite.Y; diff[1] = currWhite.x - lastWhite.x; diff[2] = currWhite.y - lastWhite.y; for (int idx=0; idx<3; ++idx) { if (backlightReg[idx] != lastReg[idx]) { double dx = (double)backlightReg[idx] - (double)lastReg[idx]; double change = diff[idx] / dx; // Limit the change to .1 Y change / unit for luminance // and .0005/unit in the x,y registers. if ((idx == 0) && (change > .1)) { unitsPerStep[idx] = change; } else if ((idx > 0) && (change > 5e-4)) { unitsPerStep[idx] = change; } } } // Approximate which direction should move the farthest diff[0] = headroomGoal.Y - currWhite.Y; diff[1] = headroomGoal.x - currWhite.x; diff[2] = headroomGoal.y - currWhite.y; chromaRegStep[0] = chromaRegStep[1] = chromaRegStep[2] = 0; int maxIdx = -1; for (int idx=0; idx<3; ++idx) { chromaRegStep[idx] = static_cast<int32_t>(diff[idx] / unitsPerStep[idx] + .5); if (chromaRegStep[idx] != 0) { if (maxIdx == -1) { maxIdx = idx; } else if ( abs(chromaRegStep[idx]) > abs(chromaRegStep[maxIdx])) { maxIdx = idx; } } } printf("\t\t\t\t\tchroma reg step: %d %d %d [%.2f %.4f %.4f]\n", chromaRegStep[0], chromaRegStep[1], chromaRegStep[2], headroomGoal.Y - currWhite.Y, headroomGoal.x - currWhite.x, headroomGoal.y - currWhite.y); printf("\t\t\t\t\tdE: %f\n", pi.color->dELab(headroomGoal, currWhite, headroomGoal)); // If we got stuck and we're still not in a good RGB spot, // then what? Raise the headroom... if (maxIdx == -1) { //printf("Converged because of lack of movement.. breaking for success!\n"); //break; printf("It appears that we got stuck - increasing headroom\n"); headroomGoal.Y += 0.01*goalWhite.Y; } // Only move in the most important direction. for (uint32_t idx=0; idx<3; ++idx) { lastReg[idx] = backlightReg[idx]; } if (maxIdx != -1) { // If we're already close to our goal, be conservative in // our step size so we don't overshoot if (pi.color->dELab(headroomGoal, currWhite, headroomGoal) < 2) { backlightReg[maxIdx] += chromaRegStep[maxIdx] / abs(chromaRegStep[maxIdx]); } else { backlightReg[maxIdx] += chromaRegStep[maxIdx]; } } // These should probably have better upper bounds? if ((backlightReg[0] < 0) || (backlightReg[0] > 400) || //was 350 (backlightReg[1] < 0) || (backlightReg[1] > 2000) || (backlightReg[2] < 0) || (backlightReg[2] > 2000)) { fprintf(stderr, "ERROR: Backlight registers out of range 0<%d<350 0<%d<2000 0<%d<2000\n", backlightReg[0], backlightReg[1], backlightReg[2]); setErrorString("Backlight registers out of range."); return false; } // Update the backlight registers if (!pi.disp->setBacklightRegRaw(backlightReg[0], backlightReg[1], backlightReg[2], backlightReg[3], true, true, true, false)) { fprintf(stderr, "ERROR: Can't set backlight registers\n"); setErrorString( std::string("Can't set backlight register: ") + pi.disp->errorString()); return false; } if (wasCancelled(pi, chain, true)) return false; if (!idle(pi.disp->backlightGenericSettleTime(pi.dispId), chain)) { return false; } } // If we didn't happen to stop because we found a good point, // hopefully we at least found some valid solutions (where the // linearRGB of our goal point was within our tolerance. If we // did find some of these "solution" points, pick the one with // the lowest dE to the real goal (not the goal with headroom). // If we didn't find any solutions, then we have to fail. if (!convergedOnGoal) { if (solutions.empty()) { setErrorString("No solutions found."); return false; } std::vector<DataPoint>::iterator bestSoln = solutions.begin(); for (std::vector<DataPoint>::iterator soln = solutions.begin(); soln != solutions.end(); ++soln) { if (pi.color->dELab(goalWhite, (*soln).measuredYxy, goalWhite) < pi.color->dELab(goalWhite, (*bestSoln).measuredYxy, goalWhite)) { bestSoln = soln; } } if (!pi.disp->setBacklightRegRaw((*bestSoln).backlightReg[0], (*bestSoln).backlightReg[1], (*bestSoln).backlightReg[2], 0, true, true, true, false, pi.dispId)) { fprintf(stderr, "ERROR: Can't set backlight registers\n"); setErrorString( std::string("Can't set backlight register: ") + pi.disp->errorString()); return false; } if (!idle(pi.disp->backlightGenericSettleTime(pi.dispId), chain)) { return false; } } return true; } // ------------------------------------------------ // // NOTE: Pattern generator should be enabled before // entering this function. // // virtual bool Ookala::DreamColorCalib::measurePrimaries( PluginData &pi, PluginChain *chain, Yxy &red, Yxy &green, Yxy &blue) { // Setup for measuring red if (!pi.disp->setPatternGeneratorColor(1023, 0, 0, pi.dispId)) { setErrorString("ERROR: Can't set pattern generator color."); return false; } if (!idle(pi.disp->patternGeneratorSettleTime(pi.dispId), chain)) { return false; } if (wasCancelled(pi, chain, true)) return false; // Measure red if (!pi.sensor->measureYxy(red, chain, pi.sensorId)) { setErrorString( std::string("Can't read sensor: ") + pi.sensor->errorString()); return false; } if (wasCancelled(pi, chain, true)) return false; // Setup for measuring green if (!pi.disp->setPatternGeneratorColor(0, 1023, 0, pi.dispId)) { fprintf(stderr, "ERROR: Can't set pattern generator color\n"); return false; } if (!idle(pi.disp->patternGeneratorSettleTime(pi.dispId), chain)) { return false; } if (wasCancelled(pi, chain, true)) return false; // Measure green if (!pi.sensor->measureYxy(green, chain, pi.sensorId)) { setErrorString( std::string("Can't read sensor: ") + pi.sensor->errorString()); return false; } if (wasCancelled(pi, chain, true)) return false; // Setup for measuring blue if (!pi.disp->setPatternGeneratorColor(0, 0, 1023, pi.dispId)) { fprintf(stderr, "ERROR: Can't set pattern generator color\n"); return false; } if (!idle(pi.disp->patternGeneratorSettleTime(pi.dispId), chain)) { return false; } if (wasCancelled(pi, chain, true)) return false; // Measure blue if (!pi.sensor->measureYxy(blue, chain, pi.sensorId)) { setErrorString( std::string("Can't read sensor: ") + pi.sensor->errorString()); return false; } if (wasCancelled(pi, chain, true)) return false; return true; } // ------------------------------------------------ // // NOTE: Pattern generator should be enabled and // color processing disabled. // // We'll take the raw grey measurements and conver them // back to panel RGB. Then, we'll store the panel RGB // (linear, not nonlinear) in the maps ramp{R,G,B}. // // This won't measure white - because presumable we've // already done that to get the XYZ->RGB matrix. And // if we process that value, then we're just going // to get 1.0, so there isn't much point!! // // virtual protected bool Ookala::DreamColorCalib::measureGrayRamp( PluginData &pi, PluginChain *chain, DreamColorCalibrationData &calib, const Npm &panelNpm, uint32_t numSteps, std::map<double, double> &rampR, std::map<double, double> &rampG, std::map<double, double> &rampB, Mat33 calibMat) { std::vector<uint32_t> grayVals; int32_t val, max; uint32_t stepSize; Yxy adjMeasure, black; Yxy measure; Rgb linearRgb; // Maximum code value max = (1 << pi.disp->patternGeneratorBitDepth(pi.dispId)) - 1; // Somehow need to set this based on user data. stepSize = (max) / (numSteps-1); // Don't even bother trying to read black, just go ahead and // estimate what it should be. if (!estimateBlack(pi, chain, pi.panelRed, pi.panelGreen, pi.panelBlue, black)) { black.Y = pi.panelWhite.Y / 1100.0; black.x = 0.3333; black.y = 0.3333; } printf("black: %f %f %f\n", black.Y, black.x, black.y); rampR[0.0] = 0.0; rampG[0.0] = 0.0; rampB[0.0] = 0.0; // Don't bother pushing white, just put it where its' supposed to go. //grayVals.push_back(max); rampR[1.0] = 1.0; rampG[1.0] = 1.0; rampB[1.0] = 1.0; // If we have a sane matrix, figure out where 'white' is going // to land, and make sure we sample in that area. Vec3 colorVec; colorVec.v0 = colorVec.v1 = colorVec.v2 = 1.0; Vec3 colorVecAdj = pi.color->mat33VectorMul(calibMat, colorVec); colorVecAdj.v0 = (double)((uint32_t)(max*colorVecAdj.v0 + 0.5)); colorVecAdj.v1 = (double)((uint32_t)(max*colorVecAdj.v1 + 0.5)); colorVecAdj.v2 = (double)((uint32_t)(max*colorVecAdj.v2 + 0.5)); // If someone has passed in an idenity matrix, don't worry // about measuring, because we'll catch the max value below. if (colorVecAdj.v1 < max-5) { val = static_cast<uint32_t>(colorVecAdj.v1); grayVals.push_back(val); } val = max-stepSize; while (val > 0) { if (val > 24) { grayVals.push_back(val); } val -= stepSize; } std::sort(grayVals.begin(), grayVals.end()); std::reverse(grayVals.begin(), grayVals.end()); uint32_t grayCnt = 1; for (std::vector<uint32_t>::iterator theGray = grayVals.begin(); theGray != grayVals.end(); ++theGray) { if (chain) { char buf[1024]; #ifdef _WIN32 sprintf_s(buf, 1023, "Measuring gray ramp, %d of %d", (int)grayCnt, (int)grayVals.size()); #else sprintf(buf, "Measuring gray ramp, %d of %d", (int)grayCnt, (int)grayVals.size()); #endif chain->setUiString("Ui::status_string_minor", std::string(buf)); } val = *theGray; if (!pi.disp->setPatternGeneratorColor(val, val, val, pi.dispId)) { setErrorString("ERROR: Can't set pattern generator color."); return false; } if (wasCancelled(pi, chain, true)) return false; if (!idle(pi.disp->patternGeneratorSettleTime(pi.dispId), chain)) { return false; } // If this fails, it's probably because we're too dark for // the sensor to measure. If we already have some data, this // is probably ok. if (!pi.sensor->measureYxy(measure, chain, pi.sensorId)) { if (rampR.size() < 6) { setErrorString( std::string("Can't read sensor: ") + pi.sensor->errorString()); return false; } else { return true; } } if (wasCancelled(pi, chain, true)) return false; adjMeasure = pi.color->subYxy(measure, black); linearRgb = pi.color->cvtYxyToRgb(adjMeasure, panelNpm); printf("%d -> %f %f %f [%f %f %f]\n", val, adjMeasure.Y, adjMeasure.x, adjMeasure.y, linearRgb.r, linearRgb.g, linearRgb.b); rampR[ static_cast<double>(val) / static_cast<double>(max) ] = linearRgb.r; rampG[ static_cast<double>(val) / static_cast<double>(max) ] = linearRgb.g; rampB[ static_cast<double>(val) / static_cast<double>(max) ] = linearRgb.b; grayCnt++; } return true; } // ------------------------------------------------ // // Call this assuming that the pattern generator is // enabled // // protected bool Ookala::DreamColorCalib::estimateBlack( PluginData &pi, PluginChain *chain, const Yxy &measuredRed, const Yxy &measuredGreen, const Yxy &measuredBlue, Yxy &estimatedBlack) { std::vector<uint32_t> targetPnts; std::vector<Yxy> rampRed, rampGreen, rampBlue; bool readRed, readGreen, readBlue; Yxy curr, newBlack[6]; XYZ tmpXYZ, estimatedBlackXYZ, grad; double err[6], step, delta, currErr, lastErr, len; int32_t count; // Maximum code value uint32_t max = (1 << pi.disp->patternGeneratorBitDepth(pi.dispId)) - 1; for (int32_t i=static_cast<int32_t>(0.2*max); i>static_cast<int32_t>(0.15*max); i-=20) { targetPnts.push_back(i); } readRed = readGreen = readBlue = true; count = 0; for (std::vector<uint32_t>::iterator theVal = targetPnts.begin(); theVal != targetPnts.end(); ++theVal) { if (chain) { char buf[1024]; #ifdef _WIN32 sprintf_s(buf, 1023, "Estimating black point, pass %d of %d", count+1, static_cast<int>(targetPnts.size())); #else sprintf(buf, "Estimating black point, pass %d of %d", count+1, static_cast<int>(targetPnts.size())); #endif chain->setUiString("Ui::status_string_minor", std::string(buf)); } count++; printf("Measuring rgb for %d\n", (*theVal)); // Measure the red. if (readRed) { if (!pi.disp->setPatternGeneratorColor((*theVal), 0, 0, pi.dispId)) { setErrorString("ERROR: Can't set pattern generator color."); return false; } if (wasCancelled(pi, chain, true)) return false; if (!idle(pi.disp->patternGeneratorSettleTime(pi.dispId), chain)) { return false; } printf("Reading red..\n"); if (!pi.sensor->measureYxy(curr, chain, pi.sensorId)) { readRed = false; printf("Failed to read red %d: %s\n", (*theVal), pi.sensor->errorString().c_str()); } else { printf("Read red %d ok (%f %f %f)\n", (*theVal), curr.x, curr.y, curr.Y); rampRed.push_back(curr); } } // Measure the green. if (readGreen) { if (!pi.disp->setPatternGeneratorColor(0, (*theVal), 0, pi.dispId)) { setErrorString("ERROR: Can't set pattern generator color."); return false; } if (wasCancelled(pi, chain, true)) return false; if (!idle(pi.disp->patternGeneratorSettleTime(pi.dispId), chain)) { return false; } printf("Reading green..\n"); if (!pi.sensor->measureYxy(curr, chain, pi.sensorId)) { readGreen = false; printf("Failed to read green %d: %s\n", (*theVal), pi.sensor->errorString().c_str()); } else { rampGreen.push_back(curr); printf("Read green %d ok (%f %f %f)\n", (*theVal), curr.x, curr.y, curr.Y); } } // And measure the blue. if (readBlue) { if (!pi.disp->setPatternGeneratorColor(0, 0, (*theVal), pi.dispId)) { setErrorString("ERROR: Can't set pattern generator color."); return false; } if (wasCancelled(pi, chain, true)) return false; if (!idle(pi.disp->patternGeneratorSettleTime(pi.dispId), chain)) { return false; } printf("Reading blue..\n"); if (!pi.sensor->measureYxy(curr, chain, pi.sensorId)) { readBlue = false; printf("Failed to read blue %d: %s\n", (*theVal), pi.sensor->errorString().c_str()); } else { rampBlue.push_back(curr); printf("Read blue %d ok (%f %f %f)\n", (*theVal), curr.x, curr.y, curr.Y); } } if ((!readRed) && (!readGreen) && (!readBlue)) break; } if (rampRed.size() + rampGreen.size() + rampBlue.size() == 0) { return false; } estimatedBlack.x = 0.333; estimatedBlack.y = 0.333; estimatedBlack.Y = 0.04; step = 0.001; delta = 0.0001; grad.X = grad.Y = grad.Z = 0; lastErr = 1e60; for (uint32_t iter=0; iter<2500; ++iter) { for (int idx=0; idx<6; ++idx) { tmpXYZ = pi.color->cvtYxyToXYZ(estimatedBlack); switch (idx) { case 0: tmpXYZ.X += delta; break; case 1: tmpXYZ.X -= delta; break; case 2: tmpXYZ.Y += delta; break; case 3: tmpXYZ.Y -= delta; break; case 4: tmpXYZ.Z += delta; break; case 5: tmpXYZ.Z -= delta; break; } newBlack[idx] = pi.color->cvtXYZToYxy(tmpXYZ); } // Compute the gradient of the error, using central differences err[0] = err[1] = err[2] = err[3] = err[4] = err[5] = currErr = 0; for (std::vector<Yxy>::iterator theVal = rampRed.begin(); theVal != rampRed.end(); ++theVal) { currErr += estimateBlackError(pi, measuredRed, estimatedBlack, *theVal); for (int idx=0; idx<6; ++idx) { err[idx] += estimateBlackError(pi, measuredRed, newBlack[idx], *theVal); } } for (std::vector<Yxy>::iterator theVal = rampGreen.begin(); theVal != rampGreen.end(); ++theVal) { currErr += estimateBlackError(pi, measuredGreen, estimatedBlack, *theVal); for (int idx=0; idx<6; ++idx) { err[idx] += estimateBlackError(pi, measuredGreen, newBlack[idx], *theVal); } } for (std::vector<Yxy>::iterator theVal = rampBlue.begin(); theVal != rampBlue.end(); ++theVal) { currErr += estimateBlackError(pi, measuredBlue, estimatedBlack, *theVal); for (int idx=0; idx<6; ++idx) { err[idx] += estimateBlackError(pi, measuredBlue, newBlack[idx], *theVal); } } if (currErr > lastErr) { estimatedBlackXYZ = pi.color->cvtYxyToXYZ(estimatedBlack); estimatedBlackXYZ.X -= grad.X; estimatedBlackXYZ.Y -= grad.Y; estimatedBlackXYZ.Z -= grad.Z; estimatedBlack = pi.color->cvtXYZToYxy(estimatedBlackXYZ); step *= 0.5; delta *= 0.5; grad.X = grad.Y = grad.Z = 0; continue; } if (lastErr - currErr < 1e-10) break; lastErr = currErr; // And take a small step towards the gradient grad.X = (err[0] - err[1]) / (2.0*delta); grad.Y = (err[2] - err[3]) / (2.0*delta); grad.Z = (err[4] - err[5]) / (2.0*delta); len = sqrt(grad.X*grad.X + grad.Y*grad.Y + grad.Z*grad.Z); if (fabs(len) > 1e-6) { grad.X = grad.X / len * step; grad.Y = grad.Y / len * step; grad.Z = grad.Z / len * step; } estimatedBlackXYZ = pi.color->cvtYxyToXYZ(estimatedBlack); estimatedBlackXYZ.X -= grad.X; estimatedBlackXYZ.Y -= grad.Y; estimatedBlackXYZ.Z -= grad.Z; estimatedBlack = pi.color->cvtXYZToYxy(estimatedBlackXYZ); } return true; } // ------------------------------------------------ // double Ookala::DreamColorCalib::estimateBlackError( PluginData &pi, const Yxy &goal, const Yxy &estimatedBlack, const Yxy &measurement) { // subtract black from the measurement Yxy measMinusBlack = pi.color->subYxy(measurement, estimatedBlack); // And compute the chromaticity error return sqrt(pow(measMinusBlack.x - goal.x, 2.0) + pow(measMinusBlack.y - goal.y, 2.0)); } // ------------------------------------------------ // // Computes the 3x3 matrix for calibration, and sets it // in the CalibrationData, ready for uploading. // // This assumes that we've already computed the panel // XYZ -> rgb matrix (which we would need for the gray // ramp measurements. bool Ookala::DreamColorCalib::compute3x3CalibMatrix( PluginData &pi, DreamColorCalibrationData &calib, const Npm &panelNpm) { Npm modelNpm; if (!pi.color->computeNpm(calib.getColorSpaceInfo().getRed(), calib.getColorSpaceInfo().getGreen(), calib.getColorSpaceInfo().getBlue(), calib.getColorSpaceInfo().getWhite(), modelNpm)) { setErrorString("Unable to compute model NPM."); return false; } // Now, the calibration matrix is just: // // [ ] [ panel ] [ model ] // [ calib ] = [ XYZ -> ] [ rgb -> ] // [ ] [ rgb ] [ XYZ ] calib.setMatrix(pi.color->mat33MatMul( panelNpm.invRgbToXYZ, modelNpm.rgbToXYZ)); printf("Model RGB -> XYZ:\n"); printf("%f %f %f\n", modelNpm.rgbToXYZ.m00, modelNpm.rgbToXYZ.m01, modelNpm.rgbToXYZ.m02); printf("%f %f %f\n", modelNpm.rgbToXYZ.m10, modelNpm.rgbToXYZ.m11, modelNpm.rgbToXYZ.m12); printf("%f %f %f\n", modelNpm.rgbToXYZ.m20, modelNpm.rgbToXYZ.m21, modelNpm.rgbToXYZ.m22); printf("Panel XYZ -> RGB:\n"); printf("%f %f %f\n", panelNpm.invRgbToXYZ.m00, panelNpm.invRgbToXYZ.m01, panelNpm.invRgbToXYZ.m02); printf("%f %f %f\n", panelNpm.invRgbToXYZ.m10, panelNpm.invRgbToXYZ.m11, panelNpm.invRgbToXYZ.m12); printf("%f %f %f\n", panelNpm.invRgbToXYZ.m20, panelNpm.invRgbToXYZ.m21, panelNpm.invRgbToXYZ.m22); printf("Calib 3x3 matrix:\n"); printf("%f %f %f [%f]\n", calib.getMatrix().m00, calib.getMatrix().m01, calib.getMatrix().m02, calib.getMatrix().m00 + calib.getMatrix().m01 + calib.getMatrix().m02); printf("%f %f %f [%f]\n", calib.getMatrix().m10, calib.getMatrix().m11, calib.getMatrix().m12, calib.getMatrix().m10 + calib.getMatrix().m11 + calib.getMatrix().m12); printf("%f %f %f [%f]\n", calib.getMatrix().m20, calib.getMatrix().m21, calib.getMatrix().m22, calib.getMatrix().m20 + calib.getMatrix().m21 + calib.getMatrix().m22); return true; } // ------------------------------------------------ // // Compute the pre and post luts, and store them in // the CalibrationData struct. bool Ookala::DreamColorCalib::computeLuts( PluginData &pi, DreamColorCalibrationData &calib, std::map<double, double> &rampR, std::map<double, double> &rampG, std::map<double, double> &rampB, const Npm &panelNpm) { std::vector<uint32_t> preLut[3], postLut[3]; // Compute the pre-lut for (uint32_t cv=0; cv<pi.disp->getPreLutLength(pi.dispId); ++cv) { double max = static_cast<double>( (1 << pi.disp->getPreLutBitDepth(pi.dispId)) - 1); double x = static_cast<double>(cv) / static_cast<double>(pi.disp->getPreLutLength(pi.dispId)-1); uint32_t val = static_cast<uint32_t>( 0.5 + max * pi.disp->evalTrcToLinear(x, calib.getColorSpaceInfo(), pi.dispId)); preLut[0].push_back(val); preLut[1].push_back(val); preLut[2].push_back(val); } // If we want, try and figure out Ro,Go,Bo that maintains // the neutral chromaticity. Rgb minRgb; minRgb.r = minRgb.g = minRgb.b = 0; for (uint32_t cv=0; cv<pi.disp->getPostLutLength(pi.dispId); ++cv) { double rgb[3]; double max = static_cast<double>( (1 << pi.disp->getPostLutBitDepth(pi.dispId)) - 1); double x = static_cast<double>(cv) / static_cast<double>(pi.disp->getPostLutLength(pi.dispId)-1); if (x > 1) x = 1; if (x < 0) x = 0; rgb[0] = max * pi.interp->catmullRomInverseInterp(x, rampR); rgb[1] = max * pi.interp->catmullRomInverseInterp(x, rampG); rgb[2] = max * pi.interp->catmullRomInverseInterp(x, rampB); if (cv == 0) { printf("postlut black goes to %f %f %f\n", rgb[0], rgb[1], rgb[2]); } for (int idx=0; idx<3; ++idx) { if (rgb[idx] < 0) rgb[idx] = 0; if (rgb[idx] > max) rgb[idx] = max; } postLut[0].push_back( static_cast<uint32_t>(rgb[0] + 0.5) ); postLut[1].push_back( static_cast<uint32_t>(rgb[1] + 0.5) ); postLut[2].push_back( static_cast<uint32_t>(rgb[2] + 0.5) ); } calib.setPreLutRed(preLut[0]); calib.setPreLutGreen(preLut[1]); calib.setPreLutBlue(preLut[2]); calib.setPostLutRed(postLut[0]); calib.setPostLutGreen(postLut[1]); calib.setPostLutBlue(postLut[2]); return true; } // ---------------------------------------- // bool Ookala::DreamColorCalib::computeGoalRgb( Color *color, const Yxy &red, const Yxy &green, const Yxy &blue, const Yxy &white, const Yxy &goalWhite, Rgb &rgb) { Npm npm; if (!color->computeNpm(red, green, blue, white, npm)) { return false; } rgb = color->cvtYxyToRgb(goalWhite, npm); return true; } // ---------------------------------------- // bool Ookala::DreamColorCalib::validate( PluginData &pi, DreamColorSpaceInfo target, PluginChain *chain) { Yxy actualWhite, actualRed, actualGreen, actualBlue; Yxy minWhite, maxWhite, minRed, maxRed, minGreen, maxGreen, minBlue, maxBlue; Npm panelNpm; std::map<double, double> grayRampR, grayRampG, grayRampB; setErrorString(""); // Figure out some limits for the color target we're trying to hit. minWhite = target.getWhite(); minRed = target.getRed(); minGreen = target.getGreen(); minBlue = target.getBlue(); maxWhite = target.getWhite(); maxRed = target.getRed(); maxGreen = target.getGreen(); maxBlue = target.getBlue(); minWhite.Y -= mWhiteToleranceMinus.Y; maxWhite.Y += mWhiteTolerancePlus.Y; minWhite.x -= mWhiteToleranceMinus.x; maxWhite.x += mWhiteTolerancePlus.x; minRed.x -= mRedToleranceMinus.x; maxRed.x += mRedTolerancePlus.x; minGreen.x -= mGreenToleranceMinus.x; maxGreen.x += mGreenTolerancePlus.x; minBlue.x -= mBlueToleranceMinus.x; maxBlue.x += mBlueTolerancePlus.x; minWhite.y -= mWhiteToleranceMinus.y; maxWhite.y += mWhiteTolerancePlus.y; minRed.y -= mRedToleranceMinus.y; maxRed.y += mRedTolerancePlus.y; minGreen.y -= mGreenToleranceMinus.y; maxGreen.y += mGreenTolerancePlus.y; minBlue.y -= mBlueToleranceMinus.y; maxBlue.y += mBlueTolerancePlus.y; // Turn on the pattern generator - take care to disable // it when we return in this method then. if (!pi.disp->setPatternGeneratorEnabled(true, target.getConnId())) { setErrorString("ERROR: Can't enable pattern generator."); return false; } if (!idle(pi.disp->patternGeneratorEnableTime(pi.dispId), chain)) { pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } if (!pi.disp->setPatternGeneratorColor(1023, 1023, 1023, pi.dispId)) { setErrorString("ERROR: Can't set pattern generator."); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } if (!idle(3, chain)) { pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } if (!pi.sensor->measureYxy(actualWhite, chain, pi.sensorId)) { setErrorString( std::string("Can't read sensor [white]: ") + pi.sensor->errorString()); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } if (!measurePrimaries(pi, chain, actualRed, actualGreen, actualBlue)) { pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } printf("Measured wht: %f %f %f\n", actualWhite.x, actualWhite.y, actualWhite.Y); printf("Measured red: %f %f\n", actualRed.x, actualRed.y); printf("Measured grn: %f %f\n", actualGreen.x, actualGreen.y); printf("Measured blu: %f %f\n", actualBlue.x, actualBlue.y); printf("\n"); printf("Target wht: %f %f %f\n", target.getWhite().x, target.getWhite().y, target.getWhite().Y); printf("Target red: %f %f\n", target.getRed().x, target.getRed().y); printf("Target grn: %f %f\n", target.getGreen().x, target.getGreen().y); printf("Target blu: %f %f\n", target.getBlue().x, target.getBlue().y); // Test against our target threshold if ((actualWhite.Y < minWhite.Y) || (actualWhite.Y > maxWhite.Y)) { setErrorString("WhitelLuminance out of range."); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } if ((actualWhite.x < minWhite.x) || (actualWhite.x > maxWhite.x) || (actualWhite.y < minWhite.y) || (actualWhite.y > maxWhite.y)) { setErrorString("White chromaticity out of range."); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } if ((actualRed.x < minRed.x) || (actualRed.x > maxRed.x) || (actualRed.y < minRed.y) || (actualRed.y > maxRed.y)) { setErrorString("Red chromaticity out of range."); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } if ((actualGreen.x < minGreen.x) || (actualGreen.x > maxGreen.x) || (actualGreen.y < minGreen.y) || (actualGreen.y > maxGreen.y)) { setErrorString("Green chromaticity out of range."); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } if ((actualBlue.x < minBlue.x) || (actualBlue.x > maxBlue.x) || (actualBlue.y < minBlue.y) || (actualBlue.y > maxBlue.y)) { setErrorString("Blue chromaticity out of range."); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } if (!pi.color->computeNpm(actualRed, actualGreen, actualBlue, actualWhite, panelNpm)) { setErrorString("Unable to compute native NPM."); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } printf("Actual white: %f %f %f\n", actualWhite.Y, actualWhite.x, actualWhite.y); // Drop a calibration record in the approprate spot so people // can track this later on DictItem *item = NULL; DreamColorCalibRecord *calibRec = NULL; //item = mRegistry->createDictItem("calibRecord"); item = mRegistry->createDictItem("DreamColorCalibRecord"); if (item) { std::vector<uint32_t> redLut, greenLut, blueLut; if (!pi.lut->get(redLut, greenLut, blueLut)) { setErrorString("Unable to retrieve luts."); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } calibRec = (DreamColorCalibRecord *)(item); if (calibRec) { DictHash *hash = NULL; Dict *chainDict = NULL; Dict *dstDict = NULL; std::vector<Plugin *> plugins = mRegistry->queryByName("DictHash"); if (!plugins.empty()) { hash = dynamic_cast<DictHash *>(plugins[0]); if (hash) { chainDict = hash->getDict(chain->getDictName()); if (chainDict) { StringDictItem *stringItem; stringItem = static_cast<StringDictItem *>( chainDict->get("DreamColorCalib::calibRecordDict")); if (stringItem) { dstDict = hash->newDict(stringItem->get()); } } } } // How do we get a meaningful device id? calibRec->setDeviceId("none"); calibRec->setCalibrationTime(time(NULL)); calibRec->setCalibrationPluginName("DreamColorCalib"); calibRec->setPreset(target.getPresetId()); calibRec->setPresetName(target.getName()); calibRec->setTargetWhite(target.getWhite()); calibRec->setTargetRed(target.getRed()); calibRec->setTargetGreen(target.getGreen()); calibRec->setTargetBlue(target.getBlue()); calibRec->setMeasuredWhite(actualWhite); calibRec->setMeasuredRed(actualRed); calibRec->setMeasuredGreen(actualGreen); calibRec->setMeasuredBlue(actualBlue); calibRec->setLut("red", redLut); calibRec->setLut("green", greenLut); calibRec->setLut("blue", blueLut); if (pi.disp) { uint32_t regValues[4]; if (pi.disp->getBacklightRegRaw(regValues[0], regValues[1], regValues[2], regValues[3], pi.dispId, chain)) { calibRec->setBrightnessReg(regValues[3]); } } if ((dstDict) && (target.getCalibRecordName() != std::string(""))) { dstDict->set(target.getCalibRecordName(), calibRec); dstDict->debug(); } } } // Turn off the pattern generator if (!pi.disp->setPatternGeneratorEnabled(false, pi.dispId)) { // If this happens, well, that sucks. I'm not sure we // can recover without power-cycling setErrorString("ERROR: Can't disable pattern generator."); return false; } if (!idle(pi.disp->patternGeneratorDisableTime(pi.dispId), chain)) { return false; } return true; } // ---------------------------------------- // // protected bool Ookala::DreamColorCalib::wasCancelled( PluginData &pi, PluginChain *chain, bool patternGenEnabled) { if (chain->wasCancelled()) { setErrorString("Execution cancelled."); if (patternGenEnabled) { pi.disp->setPatternGeneratorEnabled(false, pi.dispId); } return true; } return false; } // ------------------------------------- // // Periodically test if we've been cancelled or not. If so, // return false. // // protected bool Ookala::DreamColorCalib::idle(double seconds, PluginChain *chain) { uint32_t sleepUs = static_cast<uint32_t>( (seconds - floor(seconds)) * 1000000.0); #ifdef _WIN32 Sleep(sleepUs / 1000.0); #else usleep(sleepUs); #endif if (chain) { if (chain->wasCancelled()) { setErrorString("Execution cancelled."); return false; } } for (uint32_t i=0; i<static_cast<uint32_t>(floor(seconds)); ++i) { #ifdef _WIN32 Sleep(1000); #else sleep(1); #endif if (chain) { if (chain->wasCancelled()) { setErrorString("Execution cancelled."); return false; } } } if (chain) { if (chain->wasCancelled()) { setErrorString("Execution cancelled."); return false; } } return true; }
35.813853
153
0.54941
SchademanK
c523658548de1ac5bde7283a1cdcabe837a4ba7b
1,069
cpp
C++
hackerrank/algorithms/search/missing-numbers.cpp
maximg/comp-prog
3d7a3e936becb0bc25b890396fa2950ac072ffb8
[ "MIT" ]
null
null
null
hackerrank/algorithms/search/missing-numbers.cpp
maximg/comp-prog
3d7a3e936becb0bc25b890396fa2950ac072ffb8
[ "MIT" ]
null
null
null
hackerrank/algorithms/search/missing-numbers.cpp
maximg/comp-prog
3d7a3e936becb0bc25b890396fa2950ac072ffb8
[ "MIT" ]
null
null
null
// https://www.hackerrank.com/challenges/missing-numbers/problem #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; vector <int> missingNumbers(vector <int> arr, vector <int> brr) { vector<int> missing(100); int bmin{brr[0]}; for (auto x: brr) { ++missing[x % 100]; bmin = min(bmin, x); } for (auto x: arr) --missing[x % 100]; vector<int> result; for (int x = bmin; x < bmin + 100; ++x) { if (missing[x % 100] > 0) result.push_back(x); } return result; } int main() { int n; cin >> n; vector<int> arr(n); for(int arr_i = 0; arr_i < n; arr_i++){ cin >> arr[arr_i]; } int m; cin >> m; vector<int> brr(m); for(int brr_i = 0; brr_i < m; brr_i++){ cin >> brr[brr_i]; } vector <int> result = missingNumbers(arr, brr); for (ssize_t i = 0; i < result.size(); i++) { cout << result[i] << (i != result.size() - 1 ? " " : ""); } cout << endl; return 0; }
21.38
65
0.525725
maximg
c527ea2dc845956f912c85f6b9d7da344ff93f3b
3,333
cpp
C++
src/Graphics.cpp
HerrNamenlos123/BatteryEngine
bef5f1b81baf144176653a928c9e8ac138888b3a
[ "MIT" ]
null
null
null
src/Graphics.cpp
HerrNamenlos123/BatteryEngine
bef5f1b81baf144176653a928c9e8ac138888b3a
[ "MIT" ]
1
2021-10-07T09:59:58.000Z
2021-10-07T10:06:53.000Z
src/Graphics.cpp
HerrNamenlos123/BatteryEngine
bef5f1b81baf144176653a928c9e8ac138888b3a
[ "MIT" ]
null
null
null
#include "Battery/pch.h" #include "Battery/Graphics.h" // ImGui library #include "imgui/imgui.h" #include "imgui/imgui_internal.h" #include "imgui.h" #include "imgui_impl_allegro5.h" namespace Battery { namespace Graphics { glm::vec3 __fillcolor = { 255, 255, 255 }; glm::vec3 __strokecolor = { 0, 0, 0 }; double __thickness = 3; bool __fillenabled = true; bool __strokeenabled = true; enum class LINECAP __linecap = LINECAP::ROUND; enum class LINEJOIN __linejoin = LINEJOIN::ROUND; void DrawBackground(glm::vec3 color) { al_clear_to_color(ConvertAllegroColor(color)); } void DrawBackground(glm::vec4 color) { al_clear_to_color(ConvertAllegroColor(color)); } void Fill(glm::vec3 color) { __fillcolor = color; __fillenabled = true; } void Stroke(glm::vec3 color, double thickness) { __strokecolor = color; __thickness = thickness; __strokeenabled = true; } void NoFill() { __fillenabled = false; } void NoStroke() { __strokeenabled = false; } void UseLineCap(enum class LINECAP linecap) { __linecap = linecap; } void UseLineJoin(enum class LINEJOIN linejoin) { __linejoin = linejoin; } void DrawLine(glm::vec2 p1, glm::vec2 p2) { if (__strokeenabled) { al_draw_line(p1.x, p1.y, p2.x, p2.y, ConvertAllegroColor(__strokecolor), static_cast<float>(__thickness)); } } void DrawTriangle(glm::vec2 p1, glm::vec2 p2, double thickness, glm::vec3 color) { al_draw_line(p1.x, p1.y, p2.x, p2.y, ConvertAllegroColor(color), static_cast<float>(thickness)); } void DrawFilledTriangle(glm::vec2 p1, glm::vec2 p2, double thickness, glm::vec3 color) { al_draw_line(p1.x, p1.y, p2.x, p2.y, ConvertAllegroColor(color), static_cast<float>(thickness)); } void DrawRectangle(glm::vec2 p1, glm::vec2 p2, double thickness, glm::vec3 color) { al_draw_line(p1.x, p1.y, p2.x, p2.y, ConvertAllegroColor(color), static_cast<float>(thickness)); } void DrawFilledRectangle(glm::vec2 p1, glm::vec2 p2, double thickness, glm::vec3 color) { al_draw_line(p1.x, p1.y, p2.x, p2.y, ConvertAllegroColor(color), static_cast<float>(thickness)); } void DrawRoundedRectangle(glm::vec2 p1, glm::vec2 p2, double thickness, glm::vec3 color) { al_draw_line(p1.x, p1.y, p2.x, p2.y, ConvertAllegroColor(color), static_cast<float>(thickness)); } void DrawFilledRoundedRectangle(glm::vec2 p1, glm::vec2 p2, double thickness, glm::vec3 color) { al_draw_line(p1.x, p1.y, p2.x, p2.y, ConvertAllegroColor(color), static_cast<float>(thickness)); } void DrawCircle(glm::vec2 p1, glm::vec2 p2, double thickness, glm::vec3 color) { al_draw_line(p1.x, p1.y, p2.x, p2.y, ConvertAllegroColor(color), static_cast<float>(thickness)); } void DrawFilledCircle(glm::vec2 p1, glm::vec2 p2, double thickness, glm::vec3 color) { al_draw_line(p1.x, p1.y, p2.x, p2.y, ConvertAllegroColor(color), static_cast<float>(thickness)); } ALLEGRO_COLOR ConvertAllegroColor(glm::vec3 color) { return al_map_rgb(color.r, color.g, color.b); } ALLEGRO_COLOR ConvertAllegroColor(glm::vec4 color) { return al_map_rgba(color.r, color.g, color.b, color.a); } glm::vec4 ConvertAllegroColor(ALLEGRO_COLOR color) { unsigned char r, g, b, a; al_unmap_rgba(color, &r, &g, &b, &a); return glm::vec4(r, g, b, a); } } }
28.008403
110
0.69667
HerrNamenlos123
c52aa1f923212c0b4ae0d12329313cd1edf83658
1,163
cpp
C++
AIC/AIC'20 - Level 2 Training Contests/Contest #3/B.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
3
2020-11-01T06:31:30.000Z
2022-02-21T20:37:51.000Z
AIC/AIC'20 - Level 2 Training Contests/Contest #3/B.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
null
null
null
AIC/AIC'20 - Level 2 Training Contests/Contest #3/B.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
1
2021-05-05T18:56:31.000Z
2021-05-05T18:56:31.000Z
//https://vjudge.net/contest/416541#problem/B #include <bits/stdc++.h> using namespace std; #define F first #define S second typedef long long ll; typedef long double ld; ll mod = 1e9 + 7; ll bs (vector<pair<ll, ll>> &v, ll f) { ll l = 0, r = v.size () - 1, ans = 0; while (l <= r) { ll mid = l + (r - l) / 2; if (v[mid].F <= f) l = mid + 1, ans = v[mid].S; else r = mid - 1; } return ans; } void solve () { ll n, q; cin >> n >> q; map<ll, ll> a; for (ll i = 0; i < n; ++i) { ll d, h, m, r; cin >> d >> h >> m >> r; ll start = (d * 60 * 60) + (h * 60) + m; ll end = start + (r * 60 * 60); a[start]++, a[end]--; } vector<pair<ll, ll>> dp; for (auto& x : a) dp.push_back (make_pair (x.F, x.S)); for (ll i = 1; i < dp.size (); ++i) dp[i].S += dp[i - 1].S; while (q--) { ll d, h, m; cin >> d >> h >> m; ll f = (d * 60 * 60) + (h * 60) + m; cout << bs (dp, f) << "\n"; } } int main () { ios_base::sync_with_stdio (0); cin.tie (0); cout.tie (0); ll t; cin >> t; while (t--) solve (); }
21.943396
63
0.426483
MaGnsio
c5346eaff5201f731e266b53b16c2b0dd1d97d8d
688
cpp
C++
src/Pipeline/TimedWorkWrapper_Test.cpp
rcstilborn/SecMon
f750d9c421dac1c5a795384ff8f7b7a29a0aece9
[ "MIT" ]
2
2021-12-17T17:35:07.000Z
2022-01-11T12:38:00.000Z
src/Pipeline/TimedWorkWrapper_Test.cpp
rcstilborn/SecMon
f750d9c421dac1c5a795384ff8f7b7a29a0aece9
[ "MIT" ]
null
null
null
src/Pipeline/TimedWorkWrapper_Test.cpp
rcstilborn/SecMon
f750d9c421dac1c5a795384ff8f7b7a29a0aece9
[ "MIT" ]
2
2018-01-15T06:10:07.000Z
2021-07-08T19:40:49.000Z
/* * TimedWorkWrapper_Test.cpp * * Created on: Aug 27, 2017 * Author: Richard * * Copyright 2017 Richard Stilborn * Licensed under the MIT License */ #include "TimedWorkWrapper.h" #include <gtest/gtest.h> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <memory> void ttw_test_function(const int i) { if (i < 0) return; } TEST(TimedWorkWrapperConstruct, Success) { boost::asio::io_service io_service; std::shared_ptr<pipeline::TimeStatsQueue> tsq(new pipeline::TimeStatsQueue()); try { pipeline::TimedWorkWrapper<const int> tww(io_service, boost::bind(ttw_test_function, 1), 11, tsq); } catch (const char* msg) { FAIL() << msg; } }
21.5
102
0.688953
rcstilborn
c534fb6ca70c053d8e069d69de9822e139d0a52d
4,442
cpp
C++
Axis.Capsicum/foundation/computing/GPUManager.cpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
2
2021-07-23T08:49:54.000Z
2021-07-29T22:07:30.000Z
Axis.Capsicum/foundation/computing/GPUManager.cpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
Axis.Capsicum/foundation/computing/GPUManager.cpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
#include "GPUManager.hpp" #include <cuda_runtime.h> #include <cuda.h> #include <vector> namespace afc = axis::foundation::computing; #define ERR_CHECK(x) {cudaError_t errId = x; if (errId != CUDA_SUCCESS) throw errId;} #define AXIS_MIN_CUDA_COMPUTE_MAJOR_VERSION 2 #define AXIS_MIN_CUDA_COMPUTE_MINOR_VERSION 0 namespace { /** * Returns if, for a given device, the capabilities required by this * application are present. * * @param gpuProp The GPU properties descriptor. * * @return true if it is a compatible device, false otherwise. **/ inline bool IsCompatibleDevice(const cudaDeviceProp& gpuProp) { bool versionCompatible = ((gpuProp.major == AXIS_MIN_CUDA_COMPUTE_MAJOR_VERSION && gpuProp.minor >= AXIS_MIN_CUDA_COMPUTE_MINOR_VERSION) || (gpuProp.major > AXIS_MIN_CUDA_COMPUTE_MAJOR_VERSION)); bool deviceAvailable = gpuProp.computeMode != cudaComputeMode::cudaComputeModeProhibited; return (versionCompatible && deviceAvailable); } } afc::GPUManager::GPUManager( void ) { gpuCount_ = 0; realGpuIndex_ = nullptr; gpuCapabilities_ = nullptr; } afc::GPUManager::~GPUManager( void ) { if (realGpuIndex_) delete [] realGpuIndex_; if (gpuCapabilities_) delete [] gpuCapabilities_; } void afc::GPUManager::Rescan( void ) { std::lock_guard<std::mutex> guard(mutex_); PopulateGPU(); for (int i = 0; i < gpuCount_; i++) { int gpuIndex = realGpuIndex_[i]; gpuCapabilities_[i] = ReadGPUCapability(gpuIndex); } } int afc::GPUManager::GetAvailableGPUCount( void ) const { std::lock_guard<std::mutex> guard(mutex_); return gpuCount_; } afc::GPUCapability afc::GPUManager::GetGPUCapabilities( int gpuIndex ) const { return gpuCapabilities_[gpuIndex]; } void afc::GPUManager::PopulateGPU( void ) { int totalGpuCount = 0; std::vector<int> indexes; try { // scan for available devices cudaError_t errId = cudaGetDeviceCount(&totalGpuCount); if (errId == cudaErrorInsufficientDriver || errId == cudaErrorNoDevice) { // there are no compatible GPUs in the system totalGpuCount = 0; } for (int i = 0; i < totalGpuCount; i++) { cudaDeviceProp gpuProp; ERR_CHECK(cudaGetDeviceProperties(&gpuProp, i)); if (IsCompatibleDevice(gpuProp)) { indexes.push_back(i); } } } catch (int&) { // an error occurred // TODO: warn it } // add all gathered devices gpuCount_ = (int)indexes.size(); if (realGpuIndex_) delete [] realGpuIndex_; if (gpuCapabilities_) delete [] gpuCapabilities_; realGpuIndex_ = new int[gpuCount_]; gpuCapabilities_ = new GPUCapability[gpuCount_]; for (int i = 0; i < gpuCount_; i++) { realGpuIndex_[i] = indexes[i]; } } afc::GPUCapability afc::GPUManager::ReadGPUCapability( int index ) { try { cudaDeviceProp gpuProp; ERR_CHECK(cudaGetDeviceProperties(&gpuProp, index)); String devName; StringEncoding::AssignFromASCII(gpuProp.name, devName); afc::GPUCapability caps(index); caps.Name() = devName; caps.GlobalMemorySize() = gpuProp.totalGlobalMem; caps.ConstantMemorySize() = gpuProp.totalConstMem; caps.MaxSharedMemoryPerBlock() = gpuProp.sharedMemPerBlock; caps.PCIDeviceId() = gpuProp.pciDeviceID; caps.PCIBusId() = gpuProp.pciBusID; caps.PCIDomainId() = gpuProp.pciDomainID; caps.MaxThreadPerMultiprocessor() = gpuProp.maxThreadsPerMultiProcessor; caps.MaxThreadPerBlock() = gpuProp.maxThreadsPerBlock; caps.MaxThreadDimX() = gpuProp.maxThreadsDim[0]; caps.MaxThreadDimY() = gpuProp.maxThreadsDim[1]; caps.MaxThreadDimZ() = gpuProp.maxThreadsDim[2]; caps.MaxGridDimX() = gpuProp.maxGridSize[0]; caps.MaxGridDimY() = gpuProp.maxGridSize[1]; caps.MaxGridDimZ() = gpuProp.maxGridSize[2]; caps.MaxAsynchronousOperationCount() = gpuProp.asyncEngineCount; caps.IsWatchdogTimerEnabled() = (gpuProp.kernelExecTimeoutEnabled != 0); caps.IsTeslaComputeClusterEnabled() = (gpuProp.tccDriver != 0); caps.IsUnifiedAddressEnabled() = (gpuProp.unifiedAddressing != 0); caps.IsECCEnabled() = (gpuProp.ECCEnabled != 0); caps.IsDiscreteDevice() = (gpuProp.integrated == 0); caps.MaxThreadsInGPU() = (gpuProp.maxGridSize[0]*gpuProp.maxGridSize[1]*gpuProp.maxGridSize[2]*gpuProp.maxThreadsPerBlock); return caps; } catch (int&) { // an error occurred calling CUDA runtime functions return GPUCapability(index); } }
30.634483
127
0.708915
renato-yuzup
c53744556267aefd9647f1eb957ceca53b9cf48b
13,529
cpp
C++
lib/sck/server.cpp
TheMarlboroMan/listener_service
955b952a9c36d4a1ba3704551a9b1ac1d3dd2fb8
[ "MIT" ]
null
null
null
lib/sck/server.cpp
TheMarlboroMan/listener_service
955b952a9c36d4a1ba3704551a9b1ac1d3dd2fb8
[ "MIT" ]
null
null
null
lib/sck/server.cpp
TheMarlboroMan/listener_service
955b952a9c36d4a1ba3704551a9b1ac1d3dd2fb8
[ "MIT" ]
null
null
null
#include <sck/server.h> #include <sck/exception.h> #include <lm/sentry.h> #include <cstring> //Memset. #include <arpa/inet.h> //inet_ntop. #include <signal.h> //Memset. #include <sys/un.h> //Local sockets... #include <iostream> /* struct addrinfo { int ai_flags; // AI_PASSIVE, AI_CANONNAME, etc. int ai_family; // AF_INET, AF_INET6, AF_UNSPEC int ai_socktype; // SOCK_STREAM, SOCK_DGRAM int ai_protocol; // use 0 for "any" size_t ai_addrlen; // size of ai_addr in bytes struct sockaddr *ai_addr; // struct sockaddr_in or _in6 char *ai_canonname; // full canonical hostname struct addrinfo *ai_next; // linked list, next node }; struct sockaddr { unsigned short sa_family; // address family, AF_xxx char sa_data[14]; // 14 bytes of protocol address }; struct sockaddr_in { short int sin_family; // Address family, AF_INET unsigned short int sin_port; // Port number struct in_addr sin_addr; // Internet address unsigned char sin_zero[8]; // Same size as struct sockaddr }; */ using namespace sck; server::server(const server_config& _sc, lm::logger * _log) : //TODO: Why don't just keep the sc instance and refer to it????? ssl_wrapper(_sc.use_ssl_tls ? new openssl_wrapper(_sc.ssl_tls_cert_path, _sc.ssl_tls_key_path, _log) : nullptr), reader{_sc.blocksize, ssl_wrapper.get()}, config(_sc), log(_log), security_thread_count{0} { } server::~server() { if(log) { lm::log(*log, lm::lvl::info)<<"Cleaning up clients..."<<std::endl; } for(int i=0; i<=in_sockets.max_descriptor; i++) { if(clients.count(i)) { disconnect_client(clients.at(i)); } } ssl_wrapper.reset(nullptr); if(server_config::type::sock_unix==config.socktype) { unlink(config.unix_sock_path.c_str()); } if(log) { lm::log(*log, lm::lvl::info)<<"Cleanup completed..."<<std::endl; } } bool server::is_secure() const { return nullptr!=ssl_wrapper; } /* From man getaddrinfo: If the AI_PASSIVE flag is specified in hints.ai_flags, and node is NULL, then the returned socket addresses will be suitable for bind(2)ing a socket that will accept(2) connections. The returned socket address will contain the "wildcard address" (INADDR_ANY for IPv4 addresses, IN6ADDR_ANY_INIT for IPv6 address). The wildcard address is used by applications (typically servers) that intend to accept connections on any of the hosts's network addresses. If node is not NULL, then the AI_PASSIVE flag is ignored. If the AI_PASSIVE flag is not set in hints.ai_flags, then the returned socket addresses will be suitable for use with connect(2), sendto(2), or sendmsg(2). If node is NULL, then the network address will be set to the loopback interface address (INADDR_LOOPBACK for IPv4 addresses, IN6ADDR_LOOPBACK_INIT for IPv6 address); this is used by applications that intend to communicate with peers running on the same host. */ void server::start() { switch(config.socktype) { case server_config::type::sock_unix: setup_unix(); break; case server_config::type::sock_inet: setup_inet(); break; } if(::listen(file_descriptor, config.backlog)==-1) { throw std::runtime_error("Could not set the server to listen"); } in_sockets.max_descriptor=file_descriptor > in_sockets.max_descriptor ? file_descriptor : in_sockets.max_descriptor; FD_ZERO(&in_sockets.set); FD_SET(file_descriptor, &in_sockets.set); if(file_descriptor==-1) { throw std::runtime_error("Cannot run if server is not started"); } loop(); } void server::setup_inet() { //Fill up the hints... addrinfo hints; memset(&hints, 0, sizeof hints); hints.ai_family=AF_UNSPEC; hints.ai_socktype=SOCK_STREAM; hints.ai_flags=AI_PASSIVE; //Get the address info. addrinfo *servinfo=nullptr; //TODO: Specify the IP in which we are listening... //We could use "127.0.0.1", it would not give us the wildcard 0.0.0.0. int getaddrinfo_res=getaddrinfo(nullptr, std::to_string(config.port).c_str(), &hints, &servinfo); if(getaddrinfo_res != 0) { throw std::runtime_error("Failed to get address info :"+std::string(gai_strerror(getaddrinfo_res))); } //Bind to the first good result. addrinfo *p=servinfo; while(nullptr!=p) { file_descriptor=socket(p->ai_family, p->ai_socktype, p->ai_protocol); if(-1!=file_descriptor) { //Force adress reuse, in case a previous process is still hogging the port. int optval=1; if(setsockopt(file_descriptor, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(int))==-1) { throw std::runtime_error("Unable to force address reuse"); } if(0==bind(file_descriptor, p->ai_addr, p->ai_addrlen)) { address=ip_from_addrinfo(*p); break; //Everything is ok... Break the loop!. } close(file_descriptor); } p=p->ai_next; } freeaddrinfo(servinfo); if(!p) { throw std::runtime_error("Could not bind socket! Perhaps the port is still in use?"); } if(log) { lm::log(*log, lm::lvl::info)<<"Inet server started on "<<address<<":"<<config.port<<" with FD "<<file_descriptor<<std::endl; } } void server::setup_unix() { file_descriptor=socket(AF_UNIX, SOCK_STREAM, 0); if(-1==file_descriptor) { throw std::runtime_error("Could not generate file descriptor for local socket"); } //Directly from the man pages. struct sockaddr_un my_addr; memset(&my_addr, 0, sizeof(struct sockaddr_un)); my_addr.sun_family=AF_UNIX; strncpy(my_addr.sun_path, config.unix_sock_path.c_str(), sizeof(my_addr.sun_path) - 1); if(bind(file_descriptor, (struct sockaddr *) &my_addr, sizeof(struct sockaddr_un)) == -1) { throw std::runtime_error("Could not bind local socket"); } if(log) { lm::log(*log, lm::lvl::info)<<"Unix server started on "<<config.unix_sock_path<<" with FD "<<file_descriptor<<std::endl; } } void server::stop() { running=false; if(security_thread_count) { if(log) { lm::log(*log, lm::lvl::info)<<"Dangling client security threads detected... waiting. "<<security_thread_count<<" threads remain..."<<std::endl; } std::this_thread::sleep_for(std::chrono::milliseconds(150)); } if(log) { lm::log(*log, lm::lvl::info)<<"Stopping server now. Will complete the current listening cycle."<<std::endl; } } void server::loop() { fd_set copy_in; //timeval timeout{0, 100000}; //Struct of 0.1 seconds. timeval timeout{1, 0}; //Struct of 1 seconds. Select will exit once anything is ready, regardless of the timeout. if(log) { lm::log(*log, lm::lvl::info)<<"Starting to listen now"<<std::endl; } running=true; while(running) { try { copy_in=in_sockets.set; //Swap... select may change its values!. timeout.tv_sec=5; timeout.tv_usec=0; //select MAY write on these values and cause us to hog CPU. int select_res=select(in_sockets.max_descriptor+1, &copy_in, nullptr, nullptr, &timeout); if(select_res==-1) { throw std::runtime_error("Select failed!"); } if(select_res > 0) { //TODO: This happens to be reading in stdin and out too :D. for(int i=0; i<=in_sockets.max_descriptor; i++) { if(FD_ISSET(i, &copy_in)) { if(i==file_descriptor) { //New connection on listener file_descriptor. handle_new_connection(); } else { //New data on client file descriptor. handle_client_data(clients.at(i)); } } } } } catch(std::exception &e) { if(log) { lm::log(*log, lm::lvl::info)<<"Listener thread caused an exception: "<<e.what()<<std::endl; } } } if(log) { lm::log(*log, lm::lvl::info)<<"Listening stopped"<<std::endl; } if(nullptr!=logic) { logic->handle_server_shutdown(); } } void server::handle_new_connection() { sockaddr_in client_address; socklen_t l=sizeof(client_address); int client_descriptor=accept(file_descriptor, (sockaddr *) &client_address, &l); if(client_descriptor==-1) { throw std::runtime_error("Failed on accept for new connection"); } clients.insert( { client_descriptor, connected_client( client_descriptor, server_config::type::sock_unix==config.socktype ? "LOCAL" : ip_from_sockaddr_in(client_address) ) } ); FD_SET(client_descriptor, &in_sockets.set); in_sockets.max_descriptor=client_descriptor > in_sockets.max_descriptor ? client_descriptor : in_sockets.max_descriptor; auto& client=clients.at(client_descriptor); std::thread client_security_thread(&sck::server::set_client_security, this, std::ref(client)); client_security_thread.detach(); if(log) { lm::log(*log, lm::lvl::info)<<"Client "<<client.descriptor<<" from "<<client.ip<<" status: "<<client.get_readable_status()<<std::endl; } if(logic) { logic->handle_new_connection(client); } } void server::set_client_security(connected_client& _client) { if(log) { lm::log(*log, lm::lvl::info)<<"Starting thread to determine client " <<_client.descriptor<<":"<<_client.ip <<" security level, max timeout of " <<config.ssl_set_security_seconds<<"sec and " <<config.ssl_set_security_milliseconds<<"ms"<<std::endl; } security_thread_count_guard guard(security_thread_count); //A timeout is be used to try and see if the client says something. //In the case of SSL/TLS connections the client will speak right away to //negotiate the handshake and everything will work out, but not secure //clients will stay silent, hence this timeout. struct timeval tv; tv.tv_sec=config.ssl_set_security_seconds; tv.tv_usec=config.ssl_set_security_milliseconds; setsockopt(_client.descriptor, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv); char head=0; auto recvres=recv(_client.descriptor, &head, 1, MSG_PEEK); //Of course, let us reset the timeout. tv.tv_sec=0; setsockopt(_client.descriptor, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv); //The client did not speak, we just know it is not secure. if(-1==recvres) { if(log) { lm::log(*log, lm::lvl::info)<<"Client " <<_client.descriptor<<":"<<_client.ip <<" is deemed not to use TLS by timeout"<<std::endl; } secure_client(_client, false); return; } try { //22 means start of SSL/TLS handshake. if(22==head) { //Secure clients connecting to non-secure servers are rejected. if(!is_secure()) { throw incompatible_client_exception(); } if(log) { lm::log(*log, lm::lvl::info)<<"Client " <<_client.descriptor<<":"<<_client.ip <<" uses TLS"<<std::endl; } secure_client(_client, true); ssl_wrapper->accept(_client.descriptor); } else { //A client with no secure capabilities spoke before the timeout... if(log) { lm::log(*log, lm::lvl::info)<<"Client " <<_client.descriptor<<":"<<_client.ip <<" is deemed not to use TLS by invalid handshake sequence"<<std::endl; } secure_client(_client, false); } } catch(incompatible_client_exception& e) { if(log) { lm::log(*log, lm::lvl::info)<<"Client "<<_client.descriptor<<" from "<<_client.ip<<" rejected, uses SSL/TLS when server cannot and will be disconnected"<<std::endl; } disconnect_client(_client); } catch(openssl_exception &e) { if(log) { lm::log(*log, lm::lvl::info)<<"Client "<<_client.descriptor<<" from "<<_client.ip<<" caused SSL/TLS exception and will be disconnected: "<<e.what()<<std::endl; } disconnect_client(_client); } } void server::secure_client(connected_client& _client, bool _secure) { if(_secure) { _client.set_secure(); } else { _client.set_not_secure(); } if(logic) { logic->handle_client_security(_client, _secure); } } void server::handle_client_data(connected_client& _client) { //Clients that haven't been validated yet should have their messages //ignored. try { std::string message=reader.read(_client); if(logic) { logic->handle_client_data(message, _client); } } catch(read_exception& e) { if(log) { lm::log(*log, lm::lvl::info)<<"Client "<<_client.descriptor<<" read failure: "<<e.what()<<std::endl; } if(logic) { logic->handle_exception(e, _client); } } catch(client_disconnected_exception& e) { if(log) { lm::log(*log, lm::lvl::info)<<"Client "<<_client.descriptor<<" disconnected on client side..."<<std::endl; } if(logic) { logic->handle_exception(e, _client); } } } void server::disconnect_client(const sck::connected_client& _cl) { int client_key=_cl.descriptor; if(!clients.count(client_key)) { throw std::runtime_error("Attempted to disconnect invalid client"); } if(logic) { logic->handle_dissconection(clients.at(client_key)); } //Well, the key is actually the file descriptor, but that could change. int client_fd=clients.at(client_key).descriptor; close(client_fd); FD_CLR(client_fd, &in_sockets.set); clients.erase(client_key); if(log) { lm::log(*log, lm::lvl::info) << "Client " << client_fd << " disconnected" << std::endl; } } void server::set_logic(logic_interface& _li) { logic=&_li; } client_writer server::create_writer() { return client_writer(ssl_wrapper.get()); } //TODO: Suckage: fix the calling point and pass the ai_addr damn it... std::string sck::ip_from_addrinfo(const addrinfo& p) { //gethostname... char ip[INET6_ADDRSTRLEN]; inet_ntop(p.ai_family, &(reinterpret_cast<sockaddr_in*>(p.ai_addr))->sin_addr, ip, sizeof ip); return std::string(ip); } std::string sck::ip_from_sockaddr_in(const sockaddr_in& p) { //getpeername... char ip[INET6_ADDRSTRLEN]; inet_ntop(p.sin_family, &(p.sin_addr), ip, sizeof ip); return std::string(ip); }
27.058
167
0.688151
TheMarlboroMan
c53e306b453a4b49d262e15673de0b6d7baca7c2
1,589
hpp
C++
engine/src/engine/input/InputManager.hpp
CaptureTheBanana/CaptureTheBanana
1398bedc80608e502c87b880c5b57d272236f229
[ "MIT" ]
1
2018-08-14T05:45:29.000Z
2018-08-14T05:45:29.000Z
engine/src/engine/input/InputManager.hpp
CaptureTheBanana/CaptureTheBanana
1398bedc80608e502c87b880c5b57d272236f229
[ "MIT" ]
null
null
null
engine/src/engine/input/InputManager.hpp
CaptureTheBanana/CaptureTheBanana
1398bedc80608e502c87b880c5b57d272236f229
[ "MIT" ]
null
null
null
// This file is part of CaptureTheBanana++. // // Copyright (c) 2018 the CaptureTheBanana++ contributors (see CONTRIBUTORS.md) // This file is licensed under the MIT license; see LICENSE file in the root of this // project for details. #ifndef ENGINE_KEYBOARDMANAGER_HPP #define ENGINE_KEYBOARDMANAGER_HPP #include <string> #include <vector> namespace ctb { namespace parser { class GameConfig; } namespace engine { class Input; class Keyboard; /// Class that handles user input class InputManager { public: InputManager(parser::GameConfig* config); virtual ~InputManager(); bool update(); /// Check, if the keyboard is in the inputs bool hasKeyboard() const { return m_keyboard != 0 && !m_addKeyboard; } /// Return the keyboard pointer. May be null! Keyboard* getKeyboard() const { return m_keyboard; } /// Returns a list of input devices std::vector<Input*>& getInputs() { return m_inputs; } /// Add a keyboard to the inputs void addKeyboard(); /// Remove the keyboard from the inputs void removeKeyboard(); private: /// Initialize all inputs found on execution void setupDefaultInputs(const std::string& controllerMapFile); /// A flag that indicates, if m_keyboard should be added to m_inputs after /// the iteration over m_inputs is done. bool m_addKeyboard; /// A Vector of all registered inputs std::vector<Input*> m_inputs; /// To control the keyboard in m_inputs Keyboard* m_keyboard; }; } // namespace engine } // namespace ctb #endif // ENGINE_KEYBOARDMANAGER_HPP
24.446154
84
0.702329
CaptureTheBanana
c543bf36206b1938e768f1f7dd2e8d1c2d5e72cc
17,816
cpp
C++
bwchart/common/sysinfo.cpp
udonyang/scr-benchmark
ed81d74a9348b6813750007d45f236aaf5cf4ea4
[ "MIT" ]
null
null
null
bwchart/common/sysinfo.cpp
udonyang/scr-benchmark
ed81d74a9348b6813750007d45f236aaf5cf4ea4
[ "MIT" ]
null
null
null
bwchart/common/sysinfo.cpp
udonyang/scr-benchmark
ed81d74a9348b6813750007d45f236aaf5cf4ea4
[ "MIT" ]
null
null
null
// #include "stdafx.h" #include <windows.h> #include <wincon.h> #include <stdlib.h> #include <stdio.h> #include <io.h> #include <time.h> #include "sysinfo.h" static char MACP[17+1]; static char MAC[12+1]; static int nMACSearched = 0; static int gnCodingMethod = 0; static char ipconfig[32]="bwrecorder.dta"; #include<Iprtrmib.h> #include<Iphlpapi.h> //------------------------------------------------------------------------------------ static const char *_GetAdapterMAC(bool bPrettyPrint) { // get adapter info IP_ADAPTER_INFO *pInfo; IP_ADAPTER_INFO AdapterInfo[8]; ULONG size=sizeof(AdapterInfo); DWORD err = GetAdaptersInfo(&AdapterInfo[0], &size); pInfo = err == 0 ? &AdapterInfo[0] : 0; //char msg[255]; //sprintf(msg,"%lu need=%lu oneis=%lu",err,size,sizeof(AdapterInfo[0])); //if(err!=0) ::MessageBox(0,msg,"error",MB_OK); //else ::MessageBox(0,msg,"ok",MB_OK); // read all adapters info searching for the right one int i=0; int pref[8]; int maxpref=-999,maxidx=-1; memset(pref,0,sizeof(pref)); while(pInfo!=0) { // build MAC sprintf(MAC,"%02X%02X%02X%02X%02X%02X", pInfo->Address[0], pInfo->Address[1], pInfo->Address[2], pInfo->Address[3], pInfo->Address[4], pInfo->Address[5]); // count zeros in address int zeros=0; for(int j=0;j<6;j++) if(pInfo->Address[j]==0) zeros++; if(zeros>=3) pref[i]-=10; // compare to "no adapter" value if(strcmp(MAC,"444553540000")==0) pref[i]-=5; // check ip const char *pIP = &pInfo->IpAddressList.IpAddress.String[0]; if(atoi(pIP)!=0 && atoi(pIP)!=255) pref[i]++; // update max if(pref[i]>maxpref) {maxpref=pref[i]; maxidx=i;} //strcpy(msg,pInfo->AdapterName); //strcat(msg,"\r\n"); //strcat(msg,pIP); //strcat(msg,"\r\n"); //strcat(msg,MAC); //::MessageBox(0,msg,"info",MB_OK); // try next adapter pInfo = pInfo->Next; i++; } if(maxidx>=0) { // if we have a valid ip address pInfo = &AdapterInfo[maxidx]; // return MAC sprintf(MACP,"%02X-%02X-%02X-%02X-%02X-%02X", pInfo->Address[0], pInfo->Address[1], pInfo->Address[2], pInfo->Address[3], pInfo->Address[4], pInfo->Address[5]); sprintf(MAC,"%02X%02X%02X%02X%02X%02X", pInfo->Address[0], pInfo->Address[1], pInfo->Address[2], pInfo->Address[3], pInfo->Address[4], pInfo->Address[5]); return bPrettyPrint?MACP:MAC; } return 0; } //------------------------------------------------------------------------------------ // set file name for ipconfig results void NumericCoding::SetIpConfigFileName(const char *file) { strcpy(ipconfig,file); } //------------------------------------------------------------------------------------ // launch a different process static int _StartProcess(const char *pszExe, const char *pszCmdLine) { #ifndef ISMAGIC LOG.Print(LOG_DEBUG1,"_StartProcess(%s,%s)",pszExe,pszCmdLine); #endif int nvErr=-1; char *pszTmpCmdLine; STARTUPINFO si; PROCESS_INFORMATION pi; // init structures ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; // make a tmp copy of the command line because CreateProcess will modify it pszTmpCmdLine = new char[(strlen(pszExe)+ (pszCmdLine!=0 ? strlen(pszCmdLine) : 0) + 4)]; if(pszTmpCmdLine == 0) return -1; strcpy(pszTmpCmdLine,pszExe); if(pszCmdLine!=0) strcat(pszTmpCmdLine," "); if(pszCmdLine!=0) strcat(pszTmpCmdLine,pszCmdLine); // start process if(CreateProcess(NULL,pszTmpCmdLine,NULL,NULL,FALSE,0,NULL,NULL,&si,&pi)) { // Close process and thread handles. CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); nvErr=0; } else { nvErr=GetLastError(); #ifndef ISMAGIC LOG.Print(LOG_DEBUG1,"CreateProcess error %lu",GetLastError()); #endif } // delete temporary command line if(pszTmpCmdLine!=0) delete []pszTmpCmdLine; return nvErr; } //------------------------------------------------------------------------------------ #define VERS_UNKNOWN 0 #define VERS_WINNT 1 #define VERS_WIN98 2 #define VERS_WIN95 3 #define VERS_WIN31 4 static int SystemVersion() { OSVERSIONINFOEX osvi; BOOL bOsVersionInfoEx; // Try calling GetVersionEx using the OSVERSIONINFOEX structure, // If that fails, try using the OSVERSIONINFO structure. ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if((bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi))==0) { // If OSVERSIONINFOEX doesn't work, try OSVERSIONINFO. osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO); if (! GetVersionEx ( (OSVERSIONINFO *) &osvi) ) return VERS_UNKNOWN; } switch (osvi.dwPlatformId) { case VER_PLATFORM_WIN32_NT: return VERS_WINNT; case VER_PLATFORM_WIN32_WINDOWS: if ((osvi.dwMajorVersion > 4) || ((osvi.dwMajorVersion == 4) && (osvi.dwMinorVersion > 0))) return VERS_WIN98; else return VERS_WIN95; case VER_PLATFORM_WIN32s: return VERS_WIN31; } return VERS_UNKNOWN; } //------------------------------------------------------------------------------------ // dump file will be located in same directory than executable static const char *DumpFileName() { static char DumpFile[255+1]; if ( GetModuleFileName( NULL, DumpFile, 255 ) != 0) { char *p=strrchr(DumpFile,'\\'); if(p!=0) p[1]=0; strcat(DumpFile,ipconfig); } return DumpFile; } //------------------------------------------------------------------------------------ const char *GetMACAddressUsingIPCONFIG(bool bPrettyPrint) { #ifndef ISMAGIC LOG.Print(LOG_DEBUG1,"GetMACAddressUsingIPCONFIG"); #endif // try to make sure dump file does not already exist #ifndef ISMAGIC LOG.Print(LOG_DEBUG1,"pre-remove dump file"); #endif const char *dump = DumpFileName(); remove(dump); if(access(dump,00)==0 && access(dump,06)!=0) { // if it does, maybe someone is trying to force the MAC address // so we simulate failure #ifndef ISMAGIC LOG.Print(LOG_ERROR,"Dump file is write protected"); #endif return bPrettyPrint?MACP:MAC; } // execute ipconfig in a hidden command window char cmdParam[255]; sprintf(cmdParam,"/C ipconfig /all > \"%s\"",dump); const char *cmdexe = (SystemVersion()==VERS_WINNT) ? "cmd.exe":"command.com"; _StartProcess(cmdexe, cmdParam); // open result file FILE * fp = 0; for(int i=0; i<3; i++) { // we try multiple times fp = fopen(dump,"rb"); #ifndef ISMAGIC LOG.Print(LOG_DEBUG1,"fp=%x",fp); #endif if(fp!=0) break; Sleep(1000); } if(fp==0) { #ifndef ISMAGIC LOG.Print(LOG_DEBUG1,"cant open dump file"); #endif goto Exit; } for(i=0; i<3; i++) { // read content fseek(fp,SEEK_END,0); int size = ftell(fp); if(size>0) break; Sleep(1000); } fseek(fp,SEEK_SET,0); // read content char szBuf[4096+1]; int read; read=fread(szBuf,1,sizeof(szBuf)-1,fp); szBuf[read]=0; // close file fclose(fp); // browse physical addresses char *pCur; pCur = szBuf; while(true) { // search for physical address char *p=strstr(pCur,"Physical Address"); if(p==0) p=strstr(pCur,"Adresse physique"); if(p==0) goto Exit; // if found #ifndef ISMAGIC LOG.Print(LOG_DEBUG1,"found Physical Address"); #endif // skip title while(*p!=':' && *p!=0) p++; if(*p==0) goto Exit; p++; // skip blanks while(*p==' ') p++; if(*p==0) goto Exit; //extract MAC address strncpy(MACP,p,17); MACP[17]=0; #ifndef ISMAGIC LOG.Print(LOG_DEBUG1,"Extracted MAC %s",MACP); #endif // remove dash if needed if(!bPrettyPrint) { // pair 1 MAC[0]=MACP[0]; MAC[1]=MACP[1]; // pair 2 MAC[2]=MACP[3]; MAC[3]=MACP[4]; // pair 3 MAC[4]=MACP[6]; MAC[5]=MACP[7]; // pair 4 MAC[6]=MACP[9]; MAC[7]=MACP[10]; // pair 5 MAC[8]=MACP[12]; MAC[9]=MACP[13]; // pair 6 MAC[10]=MACP[15]; MAC[11]=MACP[16]; MAC[12]=0; } // count zeros for(int i=0, zeros=0; i<6; i++) { int val; sscanf(&MACP[i*3],"%x",&val); if(val==0) zeros++; } // do we have a reasonable amount of zeros? if(zeros<=3) break; // if not, keep searching pCur = p; } Exit: #ifndef ISMAGIC LOG.Print(LOG_DEBUG1,"remove dump file"); #endif remove(dump); return bPrettyPrint?MACP:MAC; } //------------------------------------------------------------------------------------ static const char *__GetMACAddress(bool bPrettyPrint) { //#ifndef ISMAGIC //LOG.Print(LOG_DEBUG1,"GetMACAddress"); //#endif if(nMACSearched>1) return bPrettyPrint?MACP:MAC; nMACSearched++; strcpy(MACP,"00-00-00-00-00-00"); strcpy(MAC,"000000000000"); // get adapter info const char *macapi = _GetAdapterMAC(bPrettyPrint); if(macapi!=0) return macapi; return GetMACAddressUsingIPCONFIG(bPrettyPrint); } //------------------------------------------------------------------------------------ const char *GetMACAddress(bool bPrettyPrint) { //try once const char *mac = __GetMACAddress(bPrettyPrint); // if mac is empty if(strcmp(MAC,"000000000000")==0) { //wait a bit and try again Sleep(1000); mac = __GetMACAddress(bPrettyPrint); } else nMACSearched++; return mac; } //------------------------------------------------------------------------------------ // convert an hexadecimal letter into a digit between 0 and 15 #define VALX(ch) ((ch>='0' && ch<='9') ? (int)ch-(int)'0' : 10 + (int)ch - (int)'A') // build a magic code from: // the user name: XXXXXXXXXXX // the shop name: YYYYYYYYYYY // and the MAC : xx-xx-xx-xx-xx-xx or xxxxxxxxxxxx // Magic code is a 24 letter string. We create one unsigned word for the user name, // and the shop, and 3 unsigned words for the MAC // // return true if we builded a valid code, false if the input was wrong or MAC empty // static bool BuildCode(const char *user, const char *shop, const char *MAC, char *code) { if(user==0 || user[0]==0) return false; if(shop==0 || shop[0]==0) return false; // for newer codings we change the last long and use more of the MAC address if(stricmp(shop,"labmusic")!=0 && stricmp(user,"netcast")!=0) gnCodingMethod = 1; else gnCodingMethod = 0; // get MAC char szMAC[12+1]; if(MAC!=0) { if(MAC[2]=='-') { szMAC[0]=MAC[0]; szMAC[1]=MAC[1]; szMAC[2]=MAC[3]; szMAC[3]=MAC[4]; szMAC[4]=MAC[6]; szMAC[5]=MAC[7]; szMAC[6]=MAC[9]; szMAC[7]=MAC[10]; szMAC[8]=MAC[12]; szMAC[9]=MAC[13]; szMAC[10]=MAC[15]; szMAC[11]=MAC[16]; } else strncpy(szMAC,MAC,12); szMAC[12]=0; } else { strcpy(szMAC,GetMACAddress(false)); } if(szMAC[0]==0) return false; #ifndef ISMAGIC static int once=0; if(!once) LOG.Print(LOG_DEBUG1,"BuildCode u=[%s] s=[%s] m=[%s]",user,shop,szMAC); once=1; #endif // use last digits of MAC to build an unsigned long unsigned long ul1 = VALX(szMAC[0]); ul1 <<= 4; ul1 += VALX(szMAC[7]); ul1 <<= 4; ul1 += VALX(szMAC[5]); ul1 <<= 4; ul1 += VALX(szMAC[3]); ul1 <<= 4; ul1 += VALX(szMAC[10]); ul1 <<= 4; ul1 += VALX(szMAC[2]); ul1 <<= 4; ul1 += VALX(szMAC[6]); ul1 <<= 4; ul1 += VALX(szMAC[1]); // use last digits of MAC to build an unsigned long unsigned long ul2 = VALX(szMAC[11]); ul2 <<= 4; ul2 += VALX(szMAC[9]); ul2 <<= 4; ul2 += VALX(szMAC[4]); ul2 <<= 4; ul2 += VALX(szMAC[8]); ul2 <<= 4; ul2 += VALX(user[0]); ul2 <<= 4; ul2 += VALX(shop[0]); ul2 <<= 4; ul2 += VALX(user[1]); ul2 <<= 4; ul2 += VALX(shop[1]); // use letters of user and shop to build an unsigned long unsigned long val1=0UL; for(int i=0;i<(int)strlen(user); i++, val1+=(unsigned long)toupper(user[i]), val1<<=1); unsigned long val2=0UL; for(i=0;i<(int)strlen(shop); i++, val2+=(unsigned long)toupper(shop[i]), val2<<=1); unsigned long ul3 = (val1<<16) + (val2%0x00FF); // for newer codings we change the last long and use more of the MAC address if(gnCodingMethod==1) { unsigned short word = (unsigned short)(VALX(szMAC[2])); word <<= 4; word = (unsigned short)(word + (unsigned short)(VALX(szMAC[9]))); word <<= 4; word = (unsigned short)(word + (unsigned short)(VALX(szMAC[10]))); word <<= 4; word = (unsigned short)(word + (unsigned short)(VALX(szMAC[11]))); ul3 &= 0xFFFF0000; ul3 += word; } //#ifndef ISMAGIC //LOG.Print(LOG_DEBUG1,"ul1=%lu ul2=%lu ul3=%lu",ul1,ul2,ul3); //#endif // create some noise ul1+= ul3; ul2-= ul3; //#ifndef ISMAGIC //LOG.Print(LOG_DEBUG1,"ul1=%lu ul2=%lu ul3=%lu",ul1,ul2,ul3); //#endif // convert longs to strings NumericCoding::CodeNumeric(ul1, code); NumericCoding::CodeNumeric(ul2, code+8); NumericCoding::CodeNumeric(ul3, code+16); code[24]=0; return true; } //------------------------------------------------------------------------------------ // return 0 if ok int ComputeCodeCRC(int crc, const char *user, const char *shop, const char *code) { int res=0; CString strUser = AfxGetApp()->GetProfileString("LOGIN","USER","NETCAST"); if(user==0) user = strUser; CString strShop = AfxGetApp()->GetProfileString("LOGIN","SHOP","LABMUSIC"); if(shop==0) shop = strShop; CString AllCode; CString strCode = AfxGetApp()->GetProfileString("LOGIN","CODE1",""); AllCode=AllCode+strCode.Left(4); strCode = AfxGetApp()->GetProfileString("LOGIN","CODE2",""); AllCode=AllCode+strCode.Left(4); strCode = AfxGetApp()->GetProfileString("LOGIN","CODE3",""); AllCode=AllCode+strCode.Left(4); strCode = AfxGetApp()->GetProfileString("LOGIN","CODE4",""); AllCode=AllCode+strCode.Left(4); strCode = AfxGetApp()->GetProfileString("LOGIN","CODE5",""); AllCode=AllCode+strCode.Left(4); strCode = AfxGetApp()->GetProfileString("LOGIN","CODE6",""); AllCode=AllCode+strCode.Left(4); if(code==0) code = AllCode; //#ifndef ISMAGIC //LOG.Print(LOG_DEBUG1,"current code [%s]",(const char*)AllCode); //#endif // build magic code char magic[24+1]; if(!BuildCode(user, shop, 0, magic)) res += 4; //#ifndef ISMAGIC //LOG.Print(LOG_DEBUG1,"magic code [%s]",magic); //#endif // compare with the one entered by user res += strcmp(code,magic); return res==0 ? res+crc : res+crc%8; } //------------------------------------------------------------------------------------ bool BuildMagicCode(const char *user, const char *shop, const char *MAC, char *code) { return BuildCode(user, shop, MAC, code); } //------------------------------------------------------------------------------------ // !! THOSE 2 ALPHABETS (STRINGS) MUST NOT SHARE ANY LETTER !! const char *NumericCoding::m_gszNull[2] = { "ZA9M", "4AO0" }; const char *NumericCoding::m_gszAlphabet[2] = { "RSTUFGHVXY86BCW012KL7NOPQ34DEIJ5", "VX3MDEIJ5RS91Y86BCWQ2KL7NZPTUFGH" }; // Coding: pszNumeric is a 8 char string. For each 5 bits, we pick a char from the // 2^5=32 letters alphabet and place it in the string. We add an 8th char with a checksum. // For the value 0, we use a different alphabet and place random chars and a random crc. // void NumericCoding::CodeNumeric( unsigned long dwNumeric, char *pszNumeric) { unsigned long dwOffset = 0; unsigned long dwID; unsigned long dwValBase32; int i,nChecksum=0; // is it a null player ID? if( dwNumeric == 0) { //null player ID are coded with a different alphabet srand(GetTickCount()); for(i=0; i<7; i++) pszNumeric[i]=m_gszNull[gnCodingMethod][rand()%(strlen(m_gszNull[gnCodingMethod]))]; sprintf(&pszNumeric[7],"%d",rand()%2000); } else { // normal player ID dwID = dwNumeric; for(i=0; i<7; i++) { dwValBase32 = dwID&0x1F; dwID >>= 5; pszNumeric[i]=m_gszAlphabet[gnCodingMethod][(dwOffset+dwValBase32)%32]; nChecksum += (int)i*pszNumeric[i]; dwOffset += i; } sprintf(&pszNumeric[7],"%d",nChecksum); } } //------------------------------------------------------------------------------------ // Decoding: returns true if the player ID is valid // /* bool NumericCoding::bDecodeNumeric( unsigned long *pdwNumeric, const char *pszNumeric) { unsigned long dwOffset = 0; unsigned long dwID; unsigned long dwValBase32; int i,nChecksum=0; bool bValid=true; // is it long enough? if(strlen(pszNumeric)<8) bValid=false; // does it belong to one of our alphabets? bool bAllNull=true; bool bAllNonNull=true; for(i=0; i<7; i++) { if(strchr(m_gszNull,pszNumeric[i])==0) bAllNull=false; if(strchr(m_gszAlphabet,pszNumeric[i])==0) bAllNonNull=false; } if(!bAllNull && !bAllNonNull) bValid=false; if(bAllNull && bAllNonNull) bValid=false; // if it is not a null value dwID = 0; if(!bAllNull) { for(i=0, dwOffset=0; i<7; i++) {dwOffset += i;} for(i=0; i<7 && bValid; i++) { char *p=strchr(m_gszAlphabet,pszNumeric[7-i-1]); if(p==0) {bValid=false; break;} dwValBase32 = (unsigned long)(p-&m_gszAlphabet[0]); dwOffset -= 7-i-1; nChecksum += (7-i-1)*(int)pszNumeric[7-i-1]; dwValBase32 = (dwValBase32+32-dwOffset)%32; dwID <<= 5; dwID += dwValBase32; } if(nChecksum!=atoi(&pszNumeric[7])) bValid=false; } *pdwNumeric = dwID; if(!bValid) { // INVALID PLAYER ID ASSERT(false); *pdwNumeric=0; } return bValid; } */ //------------------------------------------------------------------------------------
25.933042
106
0.584082
udonyang
c546ecb9d78c548501323f1c49a45f0ae83a872f
3,550
cpp
C++
MineCloneProject/src/MCP/Renderer/Shader/Shader.cpp
didimojuni/MineClone
68efadc775c324d64f61094b7bbeb3855d2df901
[ "Apache-2.0" ]
3
2019-12-07T03:57:55.000Z
2021-01-26T15:40:19.000Z
MineCloneProject/src/MCP/Renderer/Shader/Shader.cpp
dindii/MineClone
68efadc775c324d64f61094b7bbeb3855d2df901
[ "Apache-2.0" ]
null
null
null
MineCloneProject/src/MCP/Renderer/Shader/Shader.cpp
dindii/MineClone
68efadc775c324d64f61094b7bbeb3855d2df901
[ "Apache-2.0" ]
null
null
null
#include "mcpch.h" #include "Shader.h" #include <glad/glad.h> #include "MCP/Utils/Logger.h" #include <fstream> #include <sstream> namespace MC { Shader::Shader(const std::string& vertexSource, const std::string& fragmentSource) { Init(vertexSource, fragmentSource); } void Shader::Init(const std::string& vertexSource, const std::string& fragmentSource) { ParseShaderFiles(vertexSource, fragmentSource); } void Shader::ParseShaderFiles(const std::string& vertexShaderPath, const std::string& fragmentShaderPath) { std::ifstream vertexShader, fragmentShader; vertexShader.exceptions(std::ifstream::failbit | std::ifstream::badbit); fragmentShader.exceptions(std::ifstream::failbit | std::ifstream::badbit); vertexShader.open(vertexShaderPath); fragmentShader.open(fragmentShaderPath); if(vertexShader && fragmentShader) { std::stringstream vertexShaderStream, fragmentShaderStream; vertexShaderStream << vertexShader.rdbuf(); fragmentShaderStream << fragmentShader.rdbuf(); vertexShader.close(); fragmentShader.close(); CreateShader(vertexShaderStream.str(), fragmentShaderStream.str()); } else { MC_LOG_ERROR("ERROR READING SHADER FILES!"); } } void Shader::CreateShader(const std::string& vertexShaderSource, const std::string& fragmentShaderSource) { unsigned int program = glCreateProgram(); unsigned int vs = CompileShader(GL_VERTEX_SHADER, vertexShaderSource); unsigned int fs = CompileShader(GL_FRAGMENT_SHADER, fragmentShaderSource); glAttachShader(program, vs); glAttachShader(program, fs); glLinkProgram(program); glValidateProgram(program); //@TODO: DETTACH m_RendererID = program; glDeleteShader(vs); glDeleteShader(fs); } unsigned int Shader::CompileShader(unsigned int type, const std::string& source) { unsigned int shaderId = glCreateShader(type); const char* src = source.c_str(); glShaderSource(shaderId, 1, &src, nullptr); glCompileShader(shaderId); int compileResult; glGetShaderiv(shaderId, GL_COMPILE_STATUS, &compileResult); if (!compileResult) { int length; glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &length); char* message = new char[length]; glGetShaderInfoLog(shaderId, length, &length, message); if (type == GL_FRAGMENT_SHADER) MC_LOG_ERROR("Failed to compile Fragment Shader: ", message); else if (type == GL_VERTEX_SHADER) MC_LOG_ERROR("Failed to compile Vertex Shader: ", message); else if (type == GL_GEOMETRY_SHADER) MC_LOG_ERROR("Failed to compile Geometry Shader: ", message); glDeleteShader(shaderId); delete[] message; return 0; } return shaderId; } Shader::~Shader() { glDeleteProgram(m_RendererID); } void Shader::Bind() { glUseProgram(m_RendererID); } void Shader::UnBind() { glUseProgram(0); } void Shader::UploadUniformMat4(const std::string& name, const mat4& mat) { GLint location = glGetUniformLocation(m_RendererID, name.c_str()); //@TODO: Cache those locations glUniformMatrix4fv(location, 1, GL_FALSE, &mat.elements[0]); } void Shader::UploadUniformFloat4(const std::string& name, const vec4& mat) { GLint location = glGetUniformLocation(m_RendererID, name.c_str()); //@TODO: Cache those locations glUniform4f(location, mat.x, mat.y, mat.z, mat.w); } void Shader::UploadIntArray(const std::string& name, int* data, uint32_t count) { GLint location = glGetUniformLocation(m_RendererID, name.c_str()); //@TODO: Cache those locations glUniform1iv(location, count, data); } }
25.177305
106
0.729577
didimojuni
c5474079ac031b8a30e3f6e686c2ba4e14a8c971
415
hpp
C++
phantom/include/phantom/inputs/linux_input.hpp
karanvivekbhargava/phantom
35accd85cbbfd793b9c2988af27b6cf3a8d0c76f
[ "Apache-2.0" ]
null
null
null
phantom/include/phantom/inputs/linux_input.hpp
karanvivekbhargava/phantom
35accd85cbbfd793b9c2988af27b6cf3a8d0c76f
[ "Apache-2.0" ]
null
null
null
phantom/include/phantom/inputs/linux_input.hpp
karanvivekbhargava/phantom
35accd85cbbfd793b9c2988af27b6cf3a8d0c76f
[ "Apache-2.0" ]
null
null
null
#pragma once #include "GLFW/glfw3.h" #include "phantom/application.hpp" #include "phantom/inputs/input.hpp" namespace Phantom { class LinuxInput : public Input { protected: virtual bool IsKeyPressedImpl(int32_t keycode) override; virtual bool IsMouseButtonPressedImpl(int32_t button) override; virtual std::pair<float32_t, float32_t> GetMousePositionImpl() override; }; }
23.055556
80
0.720482
karanvivekbhargava
c5476e04f7ae4d07121f07ea3a27412a9942cac8
8,453
hpp
C++
src/client/headers/client/sqf/camera.hpp
TheWillard/intercept
7bd96f4b0cec66f5ef1f3cbef7c4abe35e4f8fda
[ "MIT" ]
166
2016-02-11T09:21:26.000Z
2022-01-01T10:34:38.000Z
src/client/headers/client/sqf/camera.hpp
TheWillard/intercept
7bd96f4b0cec66f5ef1f3cbef7c4abe35e4f8fda
[ "MIT" ]
104
2016-02-10T14:34:27.000Z
2022-03-26T18:03:47.000Z
src/client/headers/client/sqf/camera.hpp
TheWillard/intercept
7bd96f4b0cec66f5ef1f3cbef7c4abe35e4f8fda
[ "MIT" ]
85
2016-02-11T23:14:23.000Z
2022-03-18T05:03:09.000Z
/*! @file @author Verox (verox.averre@gmail.com) @author Nou (korewananda@gmail.com) @author Glowbal (thomasskooi@live.nl) @author Dedmen (dedmen@dedmen.de) @brief Camera related Function wrappers. https://github.com/NouberNou/intercept */ #pragma once #include "shared/client_types.hpp" using namespace intercept::types; namespace intercept { namespace sqf { struct rv_apperture_params { float current_aperture{}; //Current aperture float approx_aperture{}; //Engine estimated aperture for the scene float approx_luminance{}; //Engine estimated luminance float min_aperture{}; //Minimal custom aperture{}; see setApertureNew float std_aperture{}; //Standard custom aperture{}; see setApertureNew float max_aperture{}; //Maximal custom aperture {}; see setApertureNew float custom_lumi{}; //Custom luminance{}; see setApertureNew float light_intensity{}; //Blinding intensity of the light bool forced{}; //Whether aperture was forced by setAperture bool custom_forced{}; //Whether custom values were forced rv_apperture_params(const game_value &gv_) : current_aperture(gv_[0]), forced(gv_[1]), approx_aperture(gv_[2]), approx_luminance(gv_[3]), min_aperture(gv_[4]), std_aperture(gv_[5]), max_aperture(gv_[6]), custom_lumi(gv_[7]), custom_forced(gv_[8]), light_intensity(gv_[9]) {} }; /* potential namespace: camera */ void add_cam_shake(float power_, float duration_, float frequency_); void reset_cam_shake(); void enable_cam_shake(bool value_); /* potential namespace: camera */ bool cam_committed(const object &camera_); void cam_destroy(const object &camera_); bool cam_preloaded(const object &camera_); object cam_target(const object &camera_); void cam_use_nvg(bool use_nvg_); void camera_effect_enable_hud(bool enable_hud_); float camera_interest(const object &entity_); void cam_constuction_set_params(const object &camera_, const vector3 &position_, float radius, float max_above_land_); object cam_create(sqf_string_const_ref type_, const vector3 &position_); void camera_effect(const object &camera_, sqf_string_const_ref name_, sqf_string_const_ref position_); void camera_effect(const object &camera_, sqf_string_const_ref name_, sqf_string_const_ref position_, sqf_string_const_ref rtt_); void cam_prepare_focus(const object &camera_, float distance_, float blur_); void cam_prepare_fov_range(const object &camera_, float min_, float max_); void cam_prepare_pos(const object &camera_, const vector3 &position_); void cam_prepare_rel_pos(const object &camera_, const vector3 &relative_position_); void cam_prepare_target(const object &camera_, const object &target_); void cam_prepare_target(const object &camera_, const vector3 &target_); // Broken command cam_set_dir void cam_set_focus(const object &camera_, float distance_, float blur_); void cam_set_fov_range(const object &camera_, float min_, float max_); void cam_set_pos(const object &camera_, const vector3 &position_); void cam_set_relative_pos(const object &camera_, const vector3 &relative_position_); void cam_set_target(const object &camera_, const object &target_); void cam_set_target(const object &camera_, const vector3 &target_); void cam_command(const object &value0_, sqf_string_const_ref value1_); void cam_commit(const object &value0_, float value1_); void cam_commit_prepared(const object &value0_, float value1_); void cam_preload(const object &value0_, float value1_); void cam_prepare_bank(const object &value0_, float value1_); void cam_prepare_dir(const object &value0_, float value1_); void cam_prepare_dive(const object &value0_, float value1_); void cam_prepare_fov(const object &value0_, float value1_); void cam_set_bank(const object &value0_, float value1_); void cam_set_dive(const object &value0_, float value1_); void cam_set_fov(const object &value0_, float value1_); enum class thermal_modes { white_hot = 0, black_hot = 1, lightgreen_hot = 2, ///< Light Green Hot / Darker Green cold black_hot_green_cold = 3, ///< Black Hot / Darker Green cold red_hot = 4, ///< Light Red Hot / Darker Red Cold black_hot_red_cold = 5, ///< Black Hot / Darker Red Cold white_hot_red_cold = 6, ///< White Hot.Darker Red Cold thermal = 7 ///< Shade of Red and Green, Bodies are white }; void set_cam_use_ti(thermal_modes mode_, bool value1_); void set_aperture(float value_); void set_aperture_new(float min_, float std_, float max_, float std_lum_); void set_cam_shake_def_params(float power_, float duration_, float freq_, float min_speed_, float min_mass_, float caliber_coef_hit_, float vehicle_coef_); void set_cam_shake_params(float pos_coef_, float vert_coef_, float horz_coef_, float bank_coef_, bool interpolate_); bool preload_camera(const vector3 &pos_); void set_default_camera(const vector3 &pos_, const vector3 &dir_); vector3 get_camera_view_direction(const object &obj_); void switch_camera(const object &value0_, sqf_string_const_ref value1_); void set_camera_interest(const object &value0_, float value1_); sqf_return_string camera_view(); //postprocessing effects struct rv_pp_effect { std::string name; float priority; operator game_value() { return game_value(std::vector<game_value>({name, priority})); } operator game_value() const { return game_value(std::vector<game_value>({name, priority})); } }; float pp_effect_create(sqf_string_const_ref name_, const float &priority_); std::vector<float> pp_effect_create(const std::vector<rv_pp_effect> &effects_); bool pp_effect_committed(sqf_string_const_ref value_); bool pp_effect_committed(float value_); void pp_effect_destroy(float value_); bool pp_effect_enabled(float value_); bool pp_effect_enabled(sqf_string_const_ref value_); void pp_effect_commit(float value0_, sqf_string_const_ref value1_); void pp_effect_enable(bool value0_, sqf_string_const_ref value1_); void pp_effect_enable(float value0_, bool value1_); void pp_effect_force_in_nvg(float value0_, bool value1_); void pp_effect_destroy(std::vector<float> effect_handles_); //#TODO: Replace &settings_ with the right pp_effect_parameters void pp_effect_adjust(std::variant<sqf_string_const_ref_wrapper, std::reference_wrapper<int>> effect_, const game_value &settings_); void pp_effect_commit(std::variant<std::reference_wrapper<const std::vector<int>>, std::reference_wrapper<int>> effect_, const float &duration_); void pp_effect_enable(const std::vector<int> &effets_, bool enable_); struct rv_camera_target { bool is_tracking; vector3 target_position; object target_object; }; vector3 get_pilot_camera_direction(const object &object_); vector3 get_pilot_camera_position(const object &object_); vector3 get_pilot_camera_rotation(const object &object_); rv_camera_target get_pilot_camera_target(const object &object_); bool has_pilot_camera(const object &object_); void cam_set_dir(const object &camera_, const vector3 &direction_); rv_apperture_params aperture_params(); } // namespace sqf } // namespace intercept
51.230303
164
0.653969
TheWillard
c55010c9b7c513f7fd8ab4e172072e12a9a4f3fd
7,704
cpp
C++
dp/rix/gl/src/SamplerStateGL.cpp
asuessenbach/pipeline
2e49968cc3b9948a57f7ee6c4cc3258925c92ab2
[ "BSD-3-Clause" ]
217
2015-01-06T09:26:53.000Z
2022-03-23T14:03:18.000Z
dp/rix/gl/src/SamplerStateGL.cpp
asuessenbach/pipeline
2e49968cc3b9948a57f7ee6c4cc3258925c92ab2
[ "BSD-3-Clause" ]
10
2015-01-25T12:42:05.000Z
2017-11-28T16:10:16.000Z
dp/rix/gl/src/SamplerStateGL.cpp
asuessenbach/pipeline
2e49968cc3b9948a57f7ee6c4cc3258925c92ab2
[ "BSD-3-Clause" ]
44
2015-01-13T01:19:41.000Z
2022-02-21T21:35:08.000Z
// Copyright (c) 2011-2016, 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 ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <cstring> #include <dp/rix/gl/inc/SamplerStateGL.h> #include <dp/rix/gl/inc/DataTypeConversionGL.h> namespace dp { namespace rix { namespace gl { using namespace dp::rix::core; SamplerStateGL::SamplerStateGL() { m_borderColorDataType = SamplerBorderColorDataType::FLOAT; m_borderColor.f[0] = 0.0f; m_borderColor.f[1] = 0.0f; m_borderColor.f[2] = 0.0f; m_borderColor.f[3] = 0.0f; m_minFilterModeGL = GL_NEAREST; m_magFilterModeGL = GL_NEAREST; m_wrapSModeGL = GL_CLAMP_TO_EDGE; m_wrapTModeGL = GL_CLAMP_TO_EDGE; m_wrapRModeGL = GL_CLAMP_TO_EDGE; m_minLOD = -1000.0f; m_maxLOD = 1000.0f; m_LODBias = 0.0f; m_compareModeGL = GL_NONE; m_compareFuncGL = GL_LEQUAL; m_maxAnisotropy = 1.0f; #if RIX_GL_SAMPLEROBJECT_SUPPORT glGenSamplers( 1, &m_id ); assert( m_id && "Couldn't create OpenGL sampler object" ); updateSamplerObject(); #endif } SamplerStateGL::~SamplerStateGL() { #if RIX_GL_SAMPLEROBJECT_SUPPORT if( m_id ) { glDeleteSamplers( 1, &m_id ); } #else // nothing to clean up #endif } SamplerStateHandle SamplerStateGL::create( const SamplerStateData& samplerStateData ) { SamplerStateGLHandle samplerStateGL = new SamplerStateGL; switch( samplerStateData.getSamplerStateDataType() ) { case dp::rix::core::SamplerStateDataType::COMMON: { assert( dynamic_cast<const dp::rix::core::SamplerStateDataCommon*>(&samplerStateData) ); const SamplerStateDataCommon& samplerStateDataCommon = static_cast<const SamplerStateDataCommon&>(samplerStateData); samplerStateGL->m_minFilterModeGL = getGLFilterMode( samplerStateDataCommon.m_minFilterMode ); samplerStateGL->m_magFilterModeGL = getGLFilterMode( samplerStateDataCommon.m_magFilterMode ); samplerStateGL->m_wrapSModeGL = getGLWrapMode( samplerStateDataCommon.m_wrapSMode ); samplerStateGL->m_wrapTModeGL = getGLWrapMode( samplerStateDataCommon.m_wrapTMode ); samplerStateGL->m_wrapRModeGL = getGLWrapMode( samplerStateDataCommon.m_wrapRMode ); samplerStateGL->m_compareModeGL = getGLCompareMode( samplerStateDataCommon.m_compareMode ); } break; case dp::rix::core::SamplerStateDataType::NATIVE: { assert( dynamic_cast<const SamplerStateDataGL*>(&samplerStateData) ); const SamplerStateDataGL& samplerStateDataGL = static_cast<const SamplerStateDataGL&>(samplerStateData); samplerStateGL->m_borderColorDataType = samplerStateDataGL.m_borderColorDataType; // either this or a switch case copying all data one by one memcpy( &samplerStateGL->m_borderColor, &samplerStateDataGL.m_borderColor, sizeof(samplerStateGL->m_borderColor ) ); samplerStateGL->m_minFilterModeGL = samplerStateDataGL.m_minFilterModeGL; samplerStateGL->m_magFilterModeGL = samplerStateDataGL.m_magFilterModeGL; samplerStateGL->m_wrapSModeGL = samplerStateDataGL.m_wrapSModeGL; samplerStateGL->m_wrapTModeGL = samplerStateDataGL.m_wrapTModeGL; samplerStateGL->m_wrapRModeGL = samplerStateDataGL.m_wrapRModeGL; samplerStateGL->m_minLOD = samplerStateDataGL.m_minLOD; samplerStateGL->m_maxLOD = samplerStateDataGL.m_maxLOD; samplerStateGL->m_LODBias = samplerStateDataGL.m_LODBias; samplerStateGL->m_compareModeGL = samplerStateDataGL.m_compareModeGL; samplerStateGL->m_compareFuncGL = samplerStateDataGL.m_compareFuncGL; samplerStateGL->m_maxAnisotropy = samplerStateDataGL.m_maxAnisotropy; } break; default: { assert( !"unsupported sampler state data type" ); delete samplerStateGL; return nullptr; } break; } #if RIX_GL_SAMPLEROBJECT_SUPPORT samplerStateGL->updateSamplerObject(); #endif return handleCast<SamplerState>(samplerStateGL); } #if RIX_GL_SAMPLEROBJECT_SUPPORT void SamplerStateGL::updateSamplerObject() { switch( m_borderColorDataType ) { case SamplerBorderColorDataType::FLOAT: glSamplerParameterfv( m_id, GL_TEXTURE_BORDER_COLOR, m_borderColor.f ); break; case SamplerBorderColorDataType::UINT: glSamplerParameterIuiv( m_id, GL_TEXTURE_BORDER_COLOR, m_borderColor.ui ); break; case SamplerBorderColorDataType::INT: glSamplerParameterIiv( m_id, GL_TEXTURE_BORDER_COLOR, m_borderColor.i ); break; default: assert( !"unknown sampler border color data type" ); break; } glSamplerParameteri( m_id, GL_TEXTURE_MIN_FILTER, m_minFilterModeGL ); glSamplerParameteri( m_id, GL_TEXTURE_MAG_FILTER, m_magFilterModeGL ); glSamplerParameteri( m_id, GL_TEXTURE_WRAP_S, m_wrapSModeGL ); glSamplerParameteri( m_id, GL_TEXTURE_WRAP_T, m_wrapTModeGL ); glSamplerParameteri( m_id, GL_TEXTURE_WRAP_R, m_wrapRModeGL ); glSamplerParameterf( m_id, GL_TEXTURE_MIN_LOD, m_minLOD ); glSamplerParameterf( m_id, GL_TEXTURE_MAX_LOD, m_maxLOD ); glSamplerParameterf( m_id, GL_TEXTURE_LOD_BIAS, m_LODBias ); glSamplerParameteri( m_id, GL_TEXTURE_COMPARE_MODE, m_compareModeGL ); glSamplerParameteri( m_id, GL_TEXTURE_COMPARE_FUNC, m_compareFuncGL ); glSamplerParameterf( m_id, GL_TEXTURE_MAX_ANISOTROPY_EXT, m_maxAnisotropy ); } #endif } // namespace gl } // namespace rix } // namespace dp
42.098361
129
0.670042
asuessenbach
c5533ca349bab1fc8faf4fe99ac9d68e54830ce6
3,444
cpp
C++
Src/GeometryShop/AMReX_IFData.cpp
malvarado27/Amrex
8d5c7a37695e7dc899386bfd1f6ac28221984976
[ "BSD-3-Clause-LBNL" ]
1
2021-05-20T13:04:05.000Z
2021-05-20T13:04:05.000Z
Src/GeometryShop/AMReX_IFData.cpp
malvarado27/Amrex
8d5c7a37695e7dc899386bfd1f6ac28221984976
[ "BSD-3-Clause-LBNL" ]
null
null
null
Src/GeometryShop/AMReX_IFData.cpp
malvarado27/Amrex
8d5c7a37695e7dc899386bfd1f6ac28221984976
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include <iostream> #include <iomanip> #include "AMReX_NormalDerivative.H" #include "AMReX_IFData.H" //leave to default faulse. Moving the coords works better //but makes for weird convergence tests bool LocalCoordMoveSwitch::s_turnOffMoveLocalCoords = true; // empty constructor (dim == 1) IFData<1>::IFData() { } IFData<1>::IFData(const IFData<1>& a_IFData) :m_cornerSigns (a_IFData.m_cornerSigns), m_intersection (a_IFData.m_intersection), m_globalCoord (a_IFData.m_globalCoord), m_cellCenterCoord(a_IFData.m_cellCenterCoord), m_parentCoord (a_IFData.m_parentCoord), m_allVerticesIn (a_IFData.m_allVerticesIn), m_allVerticesOut (a_IFData.m_allVerticesOut), m_allVerticesOn (a_IFData.m_allVerticesOn), m_badNormal (a_IFData.m_badNormal) { } // Constructor from the implicit function IFData<1>::IFData(const IFData<2> & a_2DIFData, const int & a_maxOrder, const int & a_idir, const int & a_hilo) :m_globalCoord(a_2DIFData.m_globalCoord,a_idir), m_cellCenterCoord(a_2DIFData.m_cellCenterCoord,a_idir), m_parentCoord(a_2DIFData.m_localCoord,a_idir) { // we want the edge on the a_hilo side of the square with normal in the // a_idir direction IFData<2>localInfo = a_2DIFData; // This 2D edgeIndex locates the 1D edge in the edgeIntersection map IndexTM<int,2>twoDEdge; twoDEdge[0] = (a_idir + 1)%2; twoDEdge[1] = a_hilo; m_intersection = LARGEREALVAL; if (localInfo.m_intersections.find(twoDEdge) != localInfo.m_intersections.end()) { m_intersection = localInfo.m_intersections[twoDEdge]; } // This 2D vertex locates the hi and lo ends of the 1D segment in the // cornerSigns map IndexTM<int,2>loPt2D; loPt2D[(a_idir + 1)%2] = 0; loPt2D[a_idir] = a_hilo; IndexTM<int,2>hiPt2D; hiPt2D[(a_idir+ 1)%2] = 1; hiPt2D[a_idir] = a_hilo; if (localInfo.m_cornerSigns.find(loPt2D) != localInfo.m_cornerSigns.end()) { m_cornerSigns[0] = localInfo.m_cornerSigns[loPt2D]; } else { amrex::Abort("Lo endpoint not in Map"); } if (localInfo.m_cornerSigns.find(hiPt2D) != localInfo.m_cornerSigns.end()) { m_cornerSigns[1] = localInfo.m_cornerSigns[hiPt2D]; } else { amrex::Abort("Hi endpoint not in Map"); } // set bools m_allVerticesIn = true; m_allVerticesOut = true; m_allVerticesOn = true; if (m_cornerSigns[0] != ON || m_cornerSigns[1] != ON) { m_allVerticesOn = false; } if (m_cornerSigns[0] == IN || m_cornerSigns[1] == IN) { m_allVerticesOut = false; } if (m_cornerSigns[0] == OUT || m_cornerSigns[1] == OUT) { m_allVerticesIn = false; } //there is no normal in one dimension. However, if m_badNormal = true at a lower dimension, then the higher dimension refines. m_badNormal = false; } // Destructor (dim == 1) IFData<1>::~IFData() { } // equals operator void IFData<1>::operator=(const IFData & a_IFData) { if (this != &a_IFData) { m_cornerSigns = a_IFData.m_cornerSigns; m_intersection = a_IFData.m_intersection; m_globalCoord = a_IFData.m_globalCoord; m_cellCenterCoord = a_IFData.m_cellCenterCoord; m_parentCoord = a_IFData.m_parentCoord; m_allVerticesIn = a_IFData.m_allVerticesIn; m_allVerticesOut = a_IFData.m_allVerticesOut; m_allVerticesOn = a_IFData.m_allVerticesOn; m_badNormal = a_IFData.m_badNormal; } }
26.90625
128
0.692218
malvarado27
c5557bc89b09fff49b0d2ce31d46af36e4e256e6
12,844
cpp
C++
test/function/string_functions_test.cpp
aaron-tian/peloton
2406b763b91d9cee2a5d9f4dee01c761b476cef6
[ "Apache-2.0" ]
3
2018-01-08T01:06:17.000Z
2019-06-17T23:14:36.000Z
test/function/string_functions_test.cpp
aaron-tian/peloton
2406b763b91d9cee2a5d9f4dee01c761b476cef6
[ "Apache-2.0" ]
1
2020-04-30T09:54:37.000Z
2020-04-30T09:54:37.000Z
test/function/string_functions_test.cpp
aaron-tian/peloton
2406b763b91d9cee2a5d9f4dee01c761b476cef6
[ "Apache-2.0" ]
3
2018-02-25T23:30:33.000Z
2018-04-08T10:11:42.000Z
//===----------------------------------------------------------------------===// // // Peloton // // string_functions_test.cpp // // Identification: test/expression/string_functions_test.cpp // // Copyright (c) 2015-2018, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <set> #include <string> #include <vector> #include "common/harness.h" #include "executor/executor_context.h" #include "function/string_functions.h" #include "function/old_engine_string_functions.h" using ::testing::NotNull; using ::testing::Return; namespace peloton { namespace test { class StringFunctionsTests : public PelotonTest { public: StringFunctionsTests() : test_ctx_(nullptr) {} executor::ExecutorContext &GetExecutorContext() { return test_ctx_; } private: executor::ExecutorContext test_ctx_; }; TEST_F(StringFunctionsTests, LikeTest) { //-------------- match ---------------- // std::string s1 = "forbes \\avenue"; // "forbes \avenue" std::string p1 = "%b_s \\\\avenue"; // "%b_s \\avenue" EXPECT_TRUE(function::StringFunctions::Like( GetExecutorContext(), s1.c_str(), s1.size(), p1.c_str(), p1.size())); std::string s2 = "for%bes avenue%"; // "for%bes avenue%" std::string p2 = "for%bes a_enue\\%"; // "for%bes a_enue%" EXPECT_TRUE(function::StringFunctions::Like( GetExecutorContext(), s2.c_str(), s2.size(), p2.c_str(), p2.size())); std::string s3 = "Allison"; // "Allison" std::string p3 = "%lison"; // "%lison" EXPECT_TRUE(function::StringFunctions::Like( GetExecutorContext(), s3.c_str(), s3.size(), p3.c_str(), p3.size())); //----------Exact Match------------// std::string s5 = "Allison"; // "Allison" std::string p5 = "Allison"; // "Allison" EXPECT_TRUE(function::StringFunctions::Like( GetExecutorContext(), s5.c_str(), s5.size(), p5.c_str(), p5.size())); //----------Exact Match------------// std::string s6 = "Allison"; // "Allison" std::string p6 = "A%llison"; // "A%llison" EXPECT_TRUE(function::StringFunctions::Like( GetExecutorContext(), s6.c_str(), s6.size(), p6.c_str(), p6.size())); //-------------- not match ----------------// std::string s4 = "forbes avenue"; // "forbes avenue" std::string p4 = "f_bes avenue"; // "f_bes avenue" EXPECT_FALSE(function::StringFunctions::Like( GetExecutorContext(), s4.c_str(), s4.size(), p4.c_str(), p4.size())); } TEST_F(StringFunctionsTests, AsciiTest) { const char column_char = 'A'; for (int i = 0; i < 52; i++) { auto expected = static_cast<uint32_t>(column_char + i); std::ostringstream os; os << static_cast<char>(expected); std::vector<type::Value> args = { type::ValueFactory::GetVarcharValue(os.str())}; auto result = function::OldEngineStringFunctions::Ascii(args); EXPECT_FALSE(result.IsNull()); EXPECT_EQ(expected, result.GetAs<int>()); } // NULL CHECK std::vector<type::Value> args = { type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR)}; auto result = function::OldEngineStringFunctions::Ascii(args); EXPECT_TRUE(result.IsNull()); } TEST_F(StringFunctionsTests, ChrTest) { const char column_char = 'A'; for (int i = 0; i < 52; i++) { int char_int = (int)column_char + i; std::ostringstream os; os << static_cast<char>(char_int); std::string expected = os.str(); std::vector<type::Value> args = { type::ValueFactory::GetIntegerValue(char_int)}; auto result = function::OldEngineStringFunctions::Chr(args); EXPECT_FALSE(result.IsNull()); EXPECT_EQ(expected, result.ToString()); } // NULL CHECK std::vector<type::Value> args = { type::ValueFactory::GetNullValueByType(type::TypeId::INTEGER)}; auto result = function::OldEngineStringFunctions::Chr(args); EXPECT_TRUE(result.IsNull()); } TEST_F(StringFunctionsTests, SubstrTest) { std::vector<std::string> words = {"Fuck", "yo", "couch"}; std::ostringstream os; for (auto w : words) { os << w; } int from = words[0].size() + 1; int len = words[1].size(); const std::string expected = words[1]; std::vector<type::Value> args = { type::ValueFactory::GetVarcharValue(os.str()), type::ValueFactory::GetIntegerValue(from), type::ValueFactory::GetIntegerValue(len), }; auto result = function::OldEngineStringFunctions::Substr(args); EXPECT_FALSE(result.IsNull()); EXPECT_EQ(expected, result.ToString()); // Use NULL for every argument and make sure that it always returns NULL. for (int i = 0; i < 3; i++) { std::vector<type::Value> nullargs = { type::ValueFactory::GetVarcharValue("aaa"), type::ValueFactory::GetVarcharValue("bbb"), type::ValueFactory::GetVarcharValue("ccc"), }; nullargs[i] = type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); auto result = function::OldEngineStringFunctions::Substr(nullargs); EXPECT_TRUE(result.IsNull()); } } TEST_F(StringFunctionsTests, CharLengthTest) { const std::string str = "A"; for (int i = 0; i < 100; i++) { std::string input = StringUtil::Repeat(str, i); std::vector<type::Value> args = { type::ValueFactory::GetVarcharValue(input)}; auto result = function::OldEngineStringFunctions::CharLength(args); EXPECT_FALSE(result.IsNull()); EXPECT_EQ(i, result.GetAs<int>()); } // NULL CHECK std::vector<type::Value> args = { type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR)}; auto result = function::OldEngineStringFunctions::CharLength(args); EXPECT_TRUE(result.IsNull()); } TEST_F(StringFunctionsTests, RepeatTest) { const std::string str = "A"; for (int i = 0; i < 100; i++) { std::string expected = StringUtil::Repeat(str, i); EXPECT_EQ(i, expected.size()); std::vector<type::Value> args = {type::ValueFactory::GetVarcharValue(str), type::ValueFactory::GetIntegerValue(i)}; auto result = function::OldEngineStringFunctions::Repeat(args); EXPECT_FALSE(result.IsNull()); EXPECT_EQ(expected, result.ToString()); } // NULL CHECK std::vector<type::Value> args = { type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR), type::ValueFactory::GetVarcharValue(str), }; auto result = function::OldEngineStringFunctions::Repeat(args); EXPECT_TRUE(result.IsNull()); } TEST_F(StringFunctionsTests, ReplaceTest) { const std::string origChar = "A"; const std::string replaceChar = "X"; const std::string prefix = "**PAVLO**"; for (int i = 0; i < 100; i++) { std::string expected = prefix + StringUtil::Repeat(origChar, i); EXPECT_EQ(i + prefix.size(), expected.size()); std::string input = prefix + StringUtil::Repeat(replaceChar, i); EXPECT_EQ(i + prefix.size(), expected.size()); std::vector<type::Value> args = { type::ValueFactory::GetVarcharValue(input), type::ValueFactory::GetVarcharValue(replaceChar), type::ValueFactory::GetVarcharValue(origChar)}; auto result = function::OldEngineStringFunctions::Replace(args); EXPECT_FALSE(result.IsNull()); EXPECT_EQ(expected, result.ToString()); } // Use NULL for every argument and make sure that it always returns NULL. for (int i = 0; i < 3; i++) { std::vector<type::Value> args = { type::ValueFactory::GetVarcharValue("aaa"), type::ValueFactory::GetVarcharValue("bbb"), type::ValueFactory::GetVarcharValue("ccc"), }; args[i] = type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); auto result = function::OldEngineStringFunctions::Replace(args); EXPECT_TRUE(result.IsNull()); } } TEST_F(StringFunctionsTests, LTrimTest) { const std::string message = "This is a string with spaces"; const std::string spaces = " "; const std::string origStr = spaces + message + spaces; const std::string expected = message + spaces; std::vector<type::Value> args = {type::ValueFactory::GetVarcharValue(origStr), type::ValueFactory::GetVarcharValue(" ")}; auto result = function::OldEngineStringFunctions::LTrim(args); EXPECT_FALSE(result.IsNull()); EXPECT_EQ(expected, result.ToString()); // Use NULL for every argument and make sure that it always returns NULL. for (int i = 0; i < 2; i++) { std::vector<type::Value> nullargs = { type::ValueFactory::GetVarcharValue("aaa"), type::ValueFactory::GetVarcharValue("bbb"), }; nullargs[i] = type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); auto result = function::OldEngineStringFunctions::LTrim(nullargs); EXPECT_TRUE(result.IsNull()); } } TEST_F(StringFunctionsTests, RTrimTest) { const std::string message = "This is a string with spaces"; const std::string spaces = " "; const std::string origStr = spaces + message + spaces; const std::string expected = spaces + message; std::vector<type::Value> args = {type::ValueFactory::GetVarcharValue(origStr), type::ValueFactory::GetVarcharValue(" ")}; auto result = function::OldEngineStringFunctions::RTrim(args); EXPECT_FALSE(result.IsNull()); EXPECT_EQ(expected, result.ToString()); // Use NULL for every argument and make sure that it always returns NULL. for (int i = 0; i < 2; i++) { std::vector<type::Value> nullargs = { type::ValueFactory::GetVarcharValue("aaa"), type::ValueFactory::GetVarcharValue("bbb"), }; nullargs[i] = type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); auto result = function::OldEngineStringFunctions::RTrim(nullargs); EXPECT_TRUE(result.IsNull()); } } TEST_F(StringFunctionsTests, BTrimTest) { const std::string message = "This is a string with spaces"; const std::string spaces = " "; const std::string origStr = spaces + message + spaces; const std::string expected = message; std::vector<type::Value> args = {type::ValueFactory::GetVarcharValue(origStr), type::ValueFactory::GetVarcharValue(" ")}; auto result = function::OldEngineStringFunctions::BTrim(args); EXPECT_FALSE(result.IsNull()); EXPECT_EQ(expected, result.ToString()); result = function::OldEngineStringFunctions::Trim( {type::ValueFactory::GetVarcharValue(origStr)}); EXPECT_FALSE(result.IsNull()); EXPECT_EQ(expected, result.ToString()); // Use NULL for every argument and make sure that it always returns NULL. for (int i = 0; i < 2; i++) { std::vector<type::Value> nullargs = { type::ValueFactory::GetVarcharValue("aaa"), type::ValueFactory::GetVarcharValue("bbb"), }; nullargs[i] = type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); auto result = function::OldEngineStringFunctions::BTrim(nullargs); EXPECT_TRUE(result.IsNull()); } } TEST_F(StringFunctionsTests, LengthTest) { const char column_char = 'A'; int expected = 1; std::string str = ""; for (int i = 0; i < 52; i++) { str += (char)(column_char + i); expected++; std::vector<type::Value> args = {type::ValueFactory::GetVarcharValue(str)}; auto result = function::OldEngineStringFunctions::Length(args); EXPECT_FALSE(result.IsNull()); EXPECT_EQ(expected, result.GetAs<int>()); } // NULL CHECK std::vector<type::Value> args = { type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR)}; auto result = function::OldEngineStringFunctions::Length(args); EXPECT_TRUE(result.IsNull()); } TEST_F(StringFunctionsTests, CodegenSubstrTest) { const std::string message = "1234567"; int from = 1; int len = 5; std::string expected = message.substr(from - 1, len); auto res = function::StringFunctions::Substr( GetExecutorContext(), message.c_str(), message.length(), from, len); EXPECT_EQ(len + 1, res.length); EXPECT_EQ(expected, std::string(res.str, len)); from = 7; len = 1; expected = message.substr(from - 1, len); res = function::StringFunctions::Substr(GetExecutorContext(), message.c_str(), message.length(), from, len); EXPECT_EQ(len + 1, res.length); EXPECT_EQ(expected, std::string(res.str, len)); from = -2; len = 4; expected = message.substr(0, 1); res = function::StringFunctions::Substr(GetExecutorContext(), message.c_str(), message.length(), from, len); EXPECT_EQ(2, res.length); EXPECT_EQ(expected, std::string(res.str, 1)); from = -2; len = 2; expected = ""; res = function::StringFunctions::Substr(GetExecutorContext(), message.c_str(), message.length(), from, len); EXPECT_EQ(0, res.length); EXPECT_EQ(nullptr, res.str); } } // namespace test } // namespace peloton
36.282486
80
0.645905
aaron-tian
c557875997d78542cb0593c52ceed50ff6fef5f2
372
cpp
C++
BOJ/1699.cpp
ReinforceIII/Algorithm
355f6e19f8deb6a76f82f5283d7c1987acd699a6
[ "MIT" ]
null
null
null
BOJ/1699.cpp
ReinforceIII/Algorithm
355f6e19f8deb6a76f82f5283d7c1987acd699a6
[ "MIT" ]
null
null
null
BOJ/1699.cpp
ReinforceIII/Algorithm
355f6e19f8deb6a76f82f5283d7c1987acd699a6
[ "MIT" ]
null
null
null
/* 1699 제곱수의 합 */ #include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { int n; cin>>n; vector<int> number(n+1); vector<int> memo(n+1); for(int i=1; i<=n; i++) { memo[i] = i; for(int j=1; j*j<=i; j++) { if(memo[i] > memo[i-j*j] + 1) memo[i] = memo[i-j*j] + 1; } } cout<<memo[n]; return 0; }
17.714286
64
0.510753
ReinforceIII
c55fffd11d11540757b91a2786112889d990257e
2,084
cpp
C++
liupeng/src/main/java/liupeng/Ch2_HDFS/liveMedia/H264VideoFileSink.cpp
jayfans3/example
6982e33d760dd8e4d94de40c81ae733434bf3f1b
[ "BSD-2-Clause" ]
null
null
null
liupeng/src/main/java/liupeng/Ch2_HDFS/liveMedia/H264VideoFileSink.cpp
jayfans3/example
6982e33d760dd8e4d94de40c81ae733434bf3f1b
[ "BSD-2-Clause" ]
null
null
null
liupeng/src/main/java/liupeng/Ch2_HDFS/liveMedia/H264VideoFileSink.cpp
jayfans3/example
6982e33d760dd8e4d94de40c81ae733434bf3f1b
[ "BSD-2-Clause" ]
null
null
null
#include "H264VideoFileSink.hh" #include "OutputFile.hh" #include "H264VideoRTPSource.hh" ////////// H264VideoFileSink ////////// H264VideoFileSink::H264VideoFileSink(UsageEnvironment& env, FILE* fid,char const* sPropParameterSetsStr,unsigned bufferSize, char const* perFrameFileNamePrefix) : FileSink(env, fid, bufferSize, perFrameFileNamePrefix),fSPropParameterSetsStr(sPropParameterSetsStr), fHaveWrittenFirstFrame(False) { } H264VideoFileSink::~H264VideoFileSink() { } H264VideoFileSink*H264VideoFileSink::createNew(UsageEnvironment& env, char const* fileName, char const* sPropParameterSetsStr, unsigned bufferSize, Boolean oneFilePerFrame) { do { FILE* fid; char const* perFrameFileNamePrefix; if (oneFilePerFrame) { // Create the fid for each frame fid = NULL; perFrameFileNamePrefix = fileName; } else { // Normal case: create the fid once fid = OpenOutputFile(env, fileName); if (fid == NULL) break; perFrameFileNamePrefix = NULL; } return new H264VideoFileSink(env, fid, sPropParameterSetsStr, bufferSize, perFrameFileNamePrefix); } while (0); return NULL; } void H264VideoFileSink::afterGettingFrame1(unsigned frameSize, struct timeval presentationTime) { unsigned char const start_code[4] = {0x00, 0x00, 0x00, 0x01}; if (!fHaveWrittenFirstFrame) { // If we have PPS/SPS NAL units encoded in a "sprop parameter string", prepend these to the file: unsigned numSPropRecords; SPropRecord* sPropRecords = parseSPropParameterSets(fSPropParameterSetsStr, numSPropRecords); for (unsigned i = 0; i < numSPropRecords; ++i) { addData(start_code, 4, presentationTime); addData(sPropRecords[i].sPropBytes, sPropRecords[i].sPropLength, presentationTime); } delete[] sPropRecords; fHaveWrittenFirstFrame = True; // for next time } //Write the input data to the file, with the start code in front: addData(start_code, 4, presentationTime); //Call the parent class to complete the normal file write with the input data: FileSink::afterGettingFrame1(frameSize, presentationTime); }
32.061538
160
0.74904
jayfans3
c56ddedb6dc095f70df3d91e1b1a86922bcba0fe
2,252
hpp
C++
src/ReteVisualSerialization.hpp
sempr-tk/sempr-gui
ba96dca6945122a157f61fec9e41f4aa6060e3b2
[ "BSD-3-Clause" ]
null
null
null
src/ReteVisualSerialization.hpp
sempr-tk/sempr-gui
ba96dca6945122a157f61fec9e41f4aa6060e3b2
[ "BSD-3-Clause" ]
null
null
null
src/ReteVisualSerialization.hpp
sempr-tk/sempr-gui
ba96dca6945122a157f61fec9e41f4aa6060e3b2
[ "BSD-3-Clause" ]
null
null
null
#ifndef SEMPR_GUI_RETEVISUALSERIALIZATION_HPP_ #define SEMPR_GUI_RETEVISUALSERIALIZATION_HPP_ #include <cereal/cereal.hpp> #include <cereal/types/set.hpp> #include <rete-core/NodeVisitor.hpp> #include <string> #include <set> /* This file provides a few classes to help with creating and transmitting a visual representation of a rete network. Some helper structs for the basic representation, which can be created through the use of a node visitor which traverses the graph. These can be serialized to send them over the network. */ namespace sempr { namespace gui { struct Node { enum Type { CONDITION, MEMORY, PRODUCTION }; Type type; std::string id; std::string label; bool operator < (const Node& other) const; template <class Archive> void serialize(Archive& ar) { ar( cereal::make_nvp<Archive>("id", id), cereal::make_nvp<Archive>("label", label), cereal::make_nvp<Archive>("type", type) ); } }; struct Edge { std::string from; std::string to; bool operator < (const Edge& other) const; template <class Archive> void serialize(Archive& ar) { ar( cereal::make_nvp<Archive>("from", from), cereal::make_nvp<Archive>("to", to) ); } }; struct Graph { std::set<Node> nodes; std::set<Edge> edges; template <class Archive> void serialize(Archive& ar) { ar( cereal::make_nvp<Archive>("nodes", nodes), cereal::make_nvp<Archive>("edges", edges) ); } }; class CreateVisualGraphVisitor : public rete::NodeVisitor { Graph graph_; // a set of already visited nodes, to not visit them twice std::set<std::string> visited_; void addNode(Node::Type type, const std::string& id, const std::string& label); void addEdge(const std::string& from, const std::string& to); public: void visit(rete::AlphaNode*) override; void visit(rete::AlphaMemory*) override; void visit(rete::BetaNode*) override; void visit(rete::BetaMemory*) override; void visit(rete::BetaBetaNode*) override; void visit(rete::ProductionNode*) override; Graph graph() const; }; }} #endif /* include guard: SEMPR_GUI_RETEVISUALSERIALIZATION_HPP_ */
24.747253
83
0.666963
sempr-tk
c570bfb70284d78d42c5c150e462cd6efd27988e
24,468
cpp
C++
Daniel2.Benchmark/Daniel2.Benchmark.cpp
Cinegy/Cinecoder.Samples
28a567b52ee599307bf797f6420dbb1e54c918e5
[ "Apache-2.0" ]
17
2018-04-06T07:51:30.000Z
2022-03-21T13:38:50.000Z
Daniel2.Benchmark/Daniel2.Benchmark.cpp
Cinegy/Cinecoder.Samples
28a567b52ee599307bf797f6420dbb1e54c918e5
[ "Apache-2.0" ]
9
2019-02-22T10:00:03.000Z
2020-12-11T03:27:46.000Z
Daniel2.Benchmark/Daniel2.Benchmark.cpp
Cinegy/Cinecoder.Samples
28a567b52ee599307bf797f6420dbb1e54c918e5
[ "Apache-2.0" ]
4
2018-06-05T12:37:47.000Z
2020-07-28T08:31:21.000Z
#define _CRT_SECURE_NO_WARNINGS #ifdef _WIN32 #include <windows.h> #include <atlbase.h> #endif #include <stdio.h> #include <stdlib.h> #include <thread> #include <chrono> using namespace std::chrono; using namespace std::chrono_literals; #include "cpu_load_meter.h" #include "../common/cuda_dyn/cuda_dyn_load.h" #include <Cinecoder_h.h> #include <Cinecoder_i.c> #ifdef _WIN32 #include "Cinecoder.Plugin.GpuCodecs.h" #include "Cinecoder.Plugin.GpuCodecs_i.c" #endif #include "cinecoder_errors.h" #include "../common/cinecoder_license_string.h" #include "../common/cinecoder_error_handler.h" #include "../common/com_ptr.h" #include "../common/c_unknown.h" #include "../common/conio.h" LONG g_target_bitrate = 0; bool g_CudaEnabled = false; // variables used for encoder/decoder latency calculation static decltype(system_clock::now()) g_EncoderTimeFirstFrameIn, g_EncoderTimeFirstFrameOut; static decltype(system_clock::now()) g_DecoderTimeFirstFrameIn, g_DecoderTimeFirstFrameOut; // Memory types used in benchmark enum MemType { MEM_SYSTEM, MEM_PINNED, MEM_GPU }; MemType g_mem_type = MEM_SYSTEM; void* mem_alloc(MemType type, size_t size, int device = 0) { if(type == MEM_SYSTEM) { #ifdef _WIN32 BYTE *ptr = (BYTE*)VirtualAlloc(NULL, size + 2*4096, MEM_COMMIT, PAGE_READWRITE); ptr += 4096 - (size & 4095); DWORD oldf; VirtualProtect(ptr + size, 4096, PAGE_NOACCESS, &oldf); return ptr; #elif defined(__APPLE__) return (LPBYTE)malloc(size); #elif defined(__ANDROID__) void *ptr = nullptr; posix_memalign(&ptr, 4096, size); return ptr; #else return (LPBYTE)aligned_alloc(4096, size); #endif } if(!g_CudaEnabled) return fprintf(stderr, "CUDA is disabled\n"), nullptr; if(type == MEM_PINNED) { void *ptr = nullptr; auto err = cudaMallocHost(&ptr, size); if(err) fprintf(stderr, "CUDA error %d\n", err); return ptr; } if(type == MEM_GPU) { printf("Using CUDA GPU memory: %zd byte(s) on Device %d\n", size, device); int old_device; auto err = cudaGetDevice(&old_device); if(err) return fprintf(stderr, "cudaGetDevice() error %d\n", err), nullptr; if(device != old_device && (err = cudaSetDevice(device)) != 0) return fprintf(stderr, "cudaSetDevice(%d) error %d\n", device, err), nullptr; void *ptr = nullptr; err = cudaMalloc(&ptr, size); if(err) return fprintf(stderr, "CUDA error %d\n", err), nullptr; cudaSetDevice(old_device); return ptr; } return nullptr; } #include "file_writer.h" #include "dummy_consumer.h" //----------------------------------------------------------------------------- CC_COLOR_FMT ParseColorFmt(const char *s) //----------------------------------------------------------------------------- { if(0 == strcmp(s, "YUY2")) return CCF_YUY2; if(0 == strcmp(s, "V210")) return CCF_V210; if(0 == strcmp(s, "Y216")) return CCF_Y216; if(0 == strcmp(s, "RGBA")) return CCF_RGBA; if(0 == strcmp(s, "RGBX")) return CCF_RGBX; if(0 == strcmp(s, "NV12")) return CCF_NV12; if(0 == strcmp(s, "NULL")) return CCF_UNKNOWN; return (CC_COLOR_FMT)-1; } //----------------------------------------------------------------------------- int main(int argc, char* argv[]) //----------------------------------------------------------------------------- { g_CudaEnabled = __InitCUDA() == 0; if(argc < 5) { puts("Usage: intra_encoder <codec> <profile.xml> <rawtype> <input_file.raw> [/outfile=<output_file.bin>] [/outfmt=<rawtype>] [/outscale=#] [/fps=#] [/device=#]"); puts("Where the <codec> is one of the following:"); puts("\t'D2' -- Daniel2 CPU codec test"); if(g_CudaEnabled) { puts("\t'D2CUDA' -- Daniel2 CUDA codec test, data is copying from GPU into CPU pinned memory"); puts("\t'D2CUDAGPU' -- Daniel2 CUDA codec test, data is copying from GPU into GPU global memory"); puts("\t'D2CUDANP' -- Daniel2 CUDA codec test, data is copying from GPU into CPU NOT-pinned memory (bad case test)"); } #ifndef __aarch64__ puts("\t'AVCI' -- AVC-Intra CPU codec test"); #endif #ifdef _WIN32 puts("\t'H264_NV' -- H264 NVidia GPU codec test (requires GPU codec plugin)"); puts("\t'HEVC_NV' -- HEVC NVidia GPU codec test (requires GPU codec plugin)"); puts("\t'H264_IMDK' -- H264 Intel QuickSync codec test (requires GPU codec plugin)"); puts("\t'HEVC_IMDK' -- HEVC Intel QuickSync codec test (requires GPU codec plugin)"); puts("\t'H264_IMDK_SW' -- H264 Intel QuickSync codec test (requires GPU codec plugin)"); puts("\t'HEVC_IMDK_SW' -- HEVC Intel QuickSync codec test (requires GPU codec plugin)"); puts("\t'MPEG' -- MPEG s/w encoder"); puts("\t'H264' -- H264 s/w encoder"); #endif puts("\n <rawtype> can be 'YUY2','V210','V216','RGBA' or 'NULL'"); return 1; } CC_VERSION_INFO version = Cinecoder_GetVersion(); printf("Cinecoder version %d.%02d.%02d\n", version.VersionHi, version.VersionLo, version.EditionNo); Cinecoder_SetErrorHandler(new C_CinecoderErrorHandler()); CLSID clsidEnc = {}, clsidDec = {}; const char *strEncName = 0; bool bForceGetFrameOnDecode = false; bool bLoadGpuCodecsPlugin = false; if(0 == strcmp(argv[1], "AVCI")) { clsidEnc = CLSID_CC_AVCIntraEncoder; clsidDec = CLSID_CC_AVCIntraDecoder2; strEncName = "AVC-Intra"; } if(0 == strcmp(argv[1], "D2")) { clsidEnc = CLSID_CC_DanielVideoEncoder; clsidDec = CLSID_CC_DanielVideoDecoder; strEncName = "Daniel2"; bForceGetFrameOnDecode = true; } if(g_CudaEnabled && 0 == strcmp(argv[1], "D2CUDA")) { clsidEnc = CLSID_CC_DanielVideoEncoder_CUDA; clsidDec = CLSID_CC_DanielVideoDecoder_CUDA; strEncName = "Daniel2_CUDA"; g_mem_type = MEM_PINNED; bForceGetFrameOnDecode = true; } if(g_CudaEnabled && 0 == strcmp(argv[1], "D2CUDANP")) { clsidEnc = CLSID_CC_DanielVideoEncoder_CUDA; clsidDec = CLSID_CC_DanielVideoDecoder_CUDA; strEncName = "Daniel2_CUDA (NOT PINNED MEMORY!!)"; //g_mem_type = MEM_PINNED; bForceGetFrameOnDecode = true; } if(g_CudaEnabled && 0 == strcmp(argv[1], "D2CUDAGPU")) { clsidEnc = CLSID_CC_DanielVideoEncoder_CUDA; clsidDec = CLSID_CC_DanielVideoDecoder_CUDA; strEncName = "Daniel2_CUDA (GPU-GPU mode)"; g_mem_type = MEM_GPU; } #ifdef _WIN32 if(0 == strcmp(argv[1], "H264_NV")) { clsidEnc = CLSID_CC_H264VideoEncoder_NV; clsidDec = CLSID_CC_H264VideoDecoder_NV; strEncName = "NVidia H264"; bLoadGpuCodecsPlugin = true; } if(0 == strcmp(argv[1], "H264_NV_GPU")) { clsidEnc = CLSID_CC_H264VideoEncoder_NV; clsidDec = CLSID_CC_H264VideoDecoder_NV; strEncName = "NVidia H264"; bLoadGpuCodecsPlugin = true; g_mem_type = MEM_GPU; } if(0 == strcmp(argv[1], "HEVC_NV")) { clsidEnc = CLSID_CC_HEVCVideoEncoder_NV; clsidDec = CLSID_CC_HEVCVideoDecoder_NV; strEncName = "NVidia HEVC"; bLoadGpuCodecsPlugin = true; } if(0 == strcmp(argv[1], "HEVC_NV_GPU")) { clsidEnc = CLSID_CC_HEVCVideoEncoder_NV; clsidDec = CLSID_CC_HEVCVideoDecoder_NV; strEncName = "NVidia HEVC"; g_mem_type = MEM_GPU; bLoadGpuCodecsPlugin = true; } if(0 == strcmp(argv[1], "H264_IMDK")) { clsidEnc = CLSID_CC_H264VideoEncoder_IMDK; clsidDec = CLSID_CC_H264VideoDecoder_IMDK; strEncName = "Intel QuickSync H264"; bLoadGpuCodecsPlugin = true; } if(0 == strcmp(argv[1], "HEVC_IMDK")) { clsidEnc = CLSID_CC_HEVCVideoEncoder_IMDK; clsidDec = CLSID_CC_HEVCVideoDecoder_IMDK; strEncName = "Intel QuickSync HEVC"; bLoadGpuCodecsPlugin = true; } if(0 == strcmp(argv[1], "H264_IMDK_SW")) { clsidEnc = CLSID_CC_H264VideoEncoder_IMDK_SW; clsidDec = CLSID_CC_H264VideoDecoder_IMDK_SW; strEncName = "Intel QuickSync H264 (SOFTWARE)"; bLoadGpuCodecsPlugin = true; } if(0 == strcmp(argv[1], "HEVC_IMDK_SW")) { clsidEnc = CLSID_CC_HEVCVideoEncoder_IMDK_SW; clsidDec = CLSID_CC_HEVCVideoDecoder_IMDK_SW; strEncName = "Intel QuickSync HEVC (SOFTWARE)"; bLoadGpuCodecsPlugin = true; } if(0 == strcmp(argv[1], "H264")) { clsidEnc = CLSID_CC_H264VideoEncoder; clsidDec = CLSID_CC_H264VideoDecoder; strEncName = "H264"; } if(0 == strcmp(argv[1], "MPEG")) { clsidEnc = CLSID_CC_MpegVideoEncoder; clsidDec = CLSID_CC_MpegVideoDecoder; strEncName = "MPEG"; } #endif if(!strEncName) return fprintf(stderr, "Unknown encoder type '%s'\n", argv[1]), -1; FILE *profile = fopen(argv[2], "rt"); if(profile == NULL) return fprintf(stderr, "Can't open the profile %s\n", argv[2]), -2; const char *strInputFormat = argv[3], *strOutputFormat = argv[3]; CC_COLOR_FMT cFormat = ParseColorFmt(strInputFormat); if(cFormat == (CC_COLOR_FMT)-1) return fprintf(stderr, "Unknown raw data type '%s'\n", argv[3]), -3; FILE *inpf = fopen(argv[4], "rb"); if(inpf == NULL) return fprintf(stderr, "Can't open the file %s", argv[4]), -4; FILE *outf = NULL; CC_COLOR_FMT cOutputFormat = cFormat; int DecoderScale = 0; double TargetFps = 0; int EncDeviceID = -2, DecDeviceID = -2; int NumThreads = 0; for(int i = 5; i < argc; i++) { if(0 == strncmp(argv[i], "/outfile=", 9)) { outf = fopen(argv[i] + 9, "wb"); if(outf == NULL) return fprintf(stderr, "Can't create the file %s", argv[i] + 9), -i; } else if(0 == strncmp(argv[i], "/outfmt=", 8)) { cOutputFormat = ParseColorFmt(strOutputFormat = argv[i] + 8); if(cOutputFormat == (CC_COLOR_FMT)-1) return fprintf(stderr, "Unknown output raw data type '%s'\n", argv[i]), -i; } else if(0 == strncmp(argv[i], "/outscale=", 10)) { DecoderScale = atoi(argv[i] + 10); } else if(0 == strncmp(argv[i], "/fps=", 5)) { TargetFps = atof(argv[i] + 5); } else if(0 == strncmp(argv[i], "/device=", 8)) { EncDeviceID = atoi(argv[i] + 8); } else if(0 == strncmp(argv[i], "/device2=", 9)) { DecDeviceID = atoi(argv[i] + 9); } else if(0 == strncmp(argv[i], "/numthreads=", 12)) { NumThreads = atoi(argv[i] + 12); } else return fprintf(stderr, "Unknown switch '%s'\n", argv[i]), -i; } // cudaSetDeviceFlags(cudaDeviceMapHost); HRESULT hr = S_OK; com_ptr<ICC_ClassFactory> pFactory; hr = Cinecoder_CreateClassFactory(&pFactory); if(FAILED(hr)) return hr; hr = pFactory->AssignLicense(COMPANYNAME,LICENSEKEY); if(FAILED(hr)) return fprintf(stderr, "Incorrect license"), hr; #ifdef _WIN32 const char *gpu_plugin_name = "Cinecoder.Plugin.GpuCodecs.dll"; if(bLoadGpuCodecsPlugin && FAILED(hr = pFactory->LoadPlugin(CComBSTR(gpu_plugin_name)))) return fprintf(stderr, "Error loading '%s'", gpu_plugin_name), hr; #endif char profile_text[4096] = { 0 }; if (fread(profile_text, 1, sizeof(profile_text), profile) < 0) return fprintf(stderr, "Profile reading error"), -1; #ifdef _WIN32 CComBSTR pProfile = profile_text; #else auto pProfile = profile_text; #endif com_ptr<ICC_VideoEncoder> pEncoder; _fseeki64(inpf, 0, SEEK_SET); hr = pFactory->CreateInstance(clsidEnc, IID_ICC_VideoEncoder, (IUnknown**)&pEncoder); if(FAILED(hr)) return hr; if(NumThreads > 0) { fprintf(stderr, "Setting up specified number of threads = %d for the encoder: ", NumThreads); com_ptr<ICC_ThreadsCountProp> pTCP; if(FAILED(hr = pEncoder->QueryInterface(IID_ICC_ThreadsCountProp, (void**)&pTCP))) fprintf(stderr, "NAK. No ICC_ThreadsCountProp interface found\n"); else if(FAILED(hr = pTCP->put_ThreadsCount(NumThreads))) return fprintf(stderr, "FAILED\n"), hr; fprintf(stderr, "OK\n"); } com_ptr<ICC_DeviceIDProp> pDevId; pEncoder->QueryInterface(IID_ICC_DeviceIDProp, (void**)&pDevId); if(EncDeviceID >= -1) { if(pDevId) { printf("Encoder has ICC_DeviceIDProp interface.\n"); if(EncDeviceID >= -1) { if(FAILED(hr = pDevId->put_DeviceID(EncDeviceID))) return fprintf(stderr, "Failed to assign DeviceId=%d to the encoder", EncDeviceID), hr; } } else { printf("Encoder has no ICC_DeviceIDProp interface. Using default device (unknown)\n"); } } hr = pEncoder->InitByXml(pProfile); if(FAILED(hr)) return hr; if(EncDeviceID < -1) { if(pDevId) { if(FAILED(hr = pDevId->get_DeviceID(&EncDeviceID))) return fprintf(stderr, "Failed to get DeviceId from the encoder"), hr; } else EncDeviceID = 0; } if(EncDeviceID >= -1) printf("Encoder device id = %d\n", EncDeviceID); CC_AMOUNT concur_level = 0; com_ptr<ICC_ConcurrencyLevelProp> pConcur; if(S_OK == pEncoder->QueryInterface(IID_ICC_ConcurrencyLevelProp, (void**)&pConcur)) { printf("Encoder has ICC_ConcurrencyLevelProp interface.\n"); if(FAILED(hr = pConcur->get_ConcurrencyLevel(&concur_level))) return fprintf(stderr, "Failed to get ConcurrencyLevel from the encoder"), hr; printf("Encoder concurrency level = %d\n", concur_level); } CC_VIDEO_FRAME_DESCR vpar = { cFormat }; printf("Encoder: %s\n", strEncName); printf("Footage: type=%s filename=%s\n", argv[3], argv[4]); printf("Profile: %s\n%s\n", argv[2], profile_text); com_ptr<ICC_VideoStreamInfo> pVideoInfo; if(FAILED(hr = pEncoder->GetVideoStreamInfo(&pVideoInfo))) return fprintf(stderr, "Failed to get video stream info the encoder: code=%08x", hr), hr; CC_SIZE frame_size = {}; pVideoInfo->get_FrameSize(&frame_size); DWORD frame_pitch = 0, dec_frame_pitch = 0; if(FAILED(hr = pEncoder->GetStride(cFormat, &frame_pitch))) return fprintf(stderr, "Failed to get frame pitch from the encoder: code=%08x", hr), hr; if(cOutputFormat == CCF_UNKNOWN) dec_frame_pitch = frame_pitch; else if(FAILED(hr = pEncoder->GetStride(cOutputFormat, &dec_frame_pitch))) return fprintf(stderr, "Failed to get frame pitch for the decoder: code=%08x", hr), hr; //__declspec(align(32)) static BYTE buffer[]; size_t uncompressed_frame_size = size_t(frame_pitch) * frame_size.cy; printf("Frame size: %dx%d, pitch=%d, bytes=%zd\n", frame_size.cx, frame_size.cy, frame_pitch, uncompressed_frame_size); BYTE *read_buffer = (BYTE*)mem_alloc(MEM_SYSTEM, uncompressed_frame_size); if(!read_buffer) return fprintf(stderr, "buffer allocation error for %zd byte(s)", uncompressed_frame_size), E_OUTOFMEMORY; else printf("Compressed buffer address : 0x%p\n", read_buffer); std::vector<BYTE*> source_frames; int max_num_frames_in_loop = 32; for(int i = 0; i < max_num_frames_in_loop; i++) { size_t read_size = fread(read_buffer, 1, uncompressed_frame_size, inpf); if(read_size < uncompressed_frame_size) break; BYTE *buf = (BYTE*)mem_alloc(g_mem_type, uncompressed_frame_size, EncDeviceID); if(!buf) return fprintf(stderr, "buffer allocation error for %zd byte(s)", uncompressed_frame_size), E_OUTOFMEMORY; else printf("Uncompressed buffer address: 0x%p, format: %s, size: %zd byte(s)\n", buf, strInputFormat, uncompressed_frame_size); if(g_mem_type == MEM_GPU) cudaMemcpy(buf, read_buffer, uncompressed_frame_size, cudaMemcpyHostToDevice); else memcpy(buf, read_buffer, uncompressed_frame_size); source_frames.push_back(buf); } C_FileWriter *pFileWriter = new C_FileWriter(outf, true, source_frames.size()); hr = pEncoder->put_OutputCallback(static_cast<ICC_ByteStreamCallback*>(pFileWriter)); if(FAILED(hr)) return hr; com_ptr<ICC_VideoConsumerExtAsync> pEncAsync = 0; pEncoder->QueryInterface(IID_ICC_VideoConsumerExtAsync, (void**)&pEncAsync); CpuLoadMeter cpuLoadMeter; auto t00 = system_clock::now(); int frame_count = 0, total_frame_count = 0; auto t0 = t00; auto coded_size0 = pFileWriter->GetTotalBytesWritten(); g_EncoderTimeFirstFrameIn = t00; printf("Performing encoding loop, press ESC to break\n"); int max_frames = 0x7fffffff; int update_mask = 0x07; for(int frame_no = 0; frame_no < max_frames; frame_no++) { size_t idx = frame_no % (source_frames.size()*2-1); if(idx >= source_frames.size()) idx = source_frames.size()*2 - idx - 1; if(pEncAsync) hr = pEncAsync->AddScaleFrameAsync(source_frames[idx], (DWORD)uncompressed_frame_size, &vpar, pEncAsync); else hr = pEncoder->AddFrame(vpar.cFormat, source_frames[idx], (DWORD)uncompressed_frame_size); if(FAILED(hr)) { pEncoder = NULL; return hr; } if(TargetFps > 0) { auto t1 = system_clock::now(); auto Treal = duration_cast<milliseconds>(t1 - t0).count(); auto Tideal = (int)(frame_count * 1000 / TargetFps); if (Tideal > Treal + 1) std::this_thread::sleep_for(milliseconds{ Tideal - Treal }); } if((frame_count & update_mask) == update_mask) { auto t1 = system_clock::now(); auto dT = duration<double>(t1 - t0).count(); auto coded_size = pFileWriter->GetTotalBytesWritten(); fprintf(stderr, " %d, %.3f fps, in %.3f GB/s, out %.3f Mbps, CPU load: %.1f%% \r", frame_no, frame_count / dT, uncompressed_frame_size / 1E9 * frame_count / dT, (coded_size - coded_size0) * 8 / 1E6 / dT, cpuLoadMeter.GetLoad()); t0 = t1; frame_count = 0; coded_size0 = coded_size; if(dT < 0.5) { update_mask = (update_mask<<1) | 1; } else while(dT > 2 && update_mask > 1) { update_mask = (update_mask>>1) | 1; dT /= 2; } } frame_count++; total_frame_count++; if(_kbhit() && _getch() == 27) break; } hr = pEncoder->Done(CC_TRUE); if(FAILED(hr)) return hr; auto t1 = system_clock::now(); pEncoder = NULL; puts("\nDone.\n"); auto dT = duration<double>(t1 - t00).count(); printf("Average performance = %.3f fps (%.1f ms/f), avg data rate = %.3f GB/s\n", total_frame_count / dT, dT * 1000 / total_frame_count, uncompressed_frame_size / 1E9 * total_frame_count / dT); auto time_ms = std::chrono::duration_cast<std::chrono::milliseconds>(g_EncoderTimeFirstFrameOut - g_EncoderTimeFirstFrameIn); printf("Encoder latency = %d ms\n", (int)time_ms.count()); fclose(inpf); if(outf) fclose(outf); // decoder test ================================================================== fprintf(stderr, "\n------------------------------------------------------------\nEntering decoder test loop...\n"); com_ptr<ICC_VideoDecoder> pDecoder; hr = pFactory->CreateInstance(clsidDec, IID_ICC_VideoDecoder, (IUnknown**)&pDecoder); if(FAILED(hr)) return hr; if(NumThreads > 0) { fprintf(stderr, "Setting up specified number of threads = %d for the decoder: ", NumThreads); com_ptr<ICC_ThreadsCountProp> pTCP; if(FAILED(hr = pEncoder->QueryInterface(IID_ICC_ThreadsCountProp, (void**)&pTCP))) fprintf(stderr, "NAK. No ICC_ThreadsCountProp interface found\n"); else if(FAILED(hr = pTCP->put_ThreadsCount(NumThreads))) return fprintf(stderr, "FAILED\n"), hr; fprintf(stderr, "OK\n"); } if(DecDeviceID < -1 && EncDeviceID >= -1) DecDeviceID = EncDeviceID; if(DecDeviceID >= -1 && S_OK == pDecoder->QueryInterface(IID_ICC_DeviceIDProp, (void**)&pDevId)) { printf("Decoder has ICC_DeviceIDProp interface.\n"); if(FAILED(hr = pDevId->put_DeviceID(DecDeviceID))) return fprintf(stderr, "Failed to assign DeviceId %d to the decoder", DecDeviceID), hr; printf("Decoder device id = %d\n", DecDeviceID); } if(concur_level != 0 && S_OK == pDecoder->QueryInterface(IID_ICC_ConcurrencyLevelProp, (void**)&pConcur)) { printf("Decoder has ICC_ConcurrencyLevelProp interface.\n"); if(FAILED(hr = pConcur->put_ConcurrencyLevel(concur_level))) return fprintf(stderr, "Failed to assign ConcurrencyLevel %d to the decoder", concur_level), hr; } hr = pDecoder->Init(); if(FAILED(hr)) return hr; if(pConcur) { if(FAILED(hr = pConcur->get_ConcurrencyLevel(&concur_level))) return fprintf(stderr, "Failed to get ConcurrencyLevel from the decoder"), hr; printf("Decoder concurrency level = %d\n", concur_level); } if(!bForceGetFrameOnDecode) cFormat = CCF_UNKNOWN; uncompressed_frame_size = size_t(dec_frame_pitch) * frame_size.cy; BYTE *dec_buf = (BYTE*)mem_alloc(g_mem_type, uncompressed_frame_size, DecDeviceID); if(!dec_buf) return fprintf(stderr, "buffer allocation error for %zd byte(s)", uncompressed_frame_size), E_OUTOFMEMORY; else printf("Uncompressed buffer address: 0x%p, format: %s, size: %zd byte(s)\n", dec_buf, strOutputFormat, uncompressed_frame_size); com_ptr<ICC_VideoQualityMeter> pPsnrCalc; if(cOutputFormat == cFormat && g_mem_type != MEM_GPU) { if(FAILED(hr = pFactory->CreateInstance(CLSID_CC_VideoQualityMeter, IID_ICC_VideoQualityMeter, (IUnknown**)&pPsnrCalc))) fprintf(stdout, "Can't create VideoQualityMeter, error=%xh, PSNR calculation is disabled\n", hr); } else { fprintf(stdout, "PSNR calculation is disabled due to %s\n", cOutputFormat != cFormat ? "color format mismatch" : "GPU memory"); } hr = pDecoder->put_OutputCallback(new C_DummyWriter(cOutputFormat, dec_buf, (int)uncompressed_frame_size, pPsnrCalc, source_frames[0])); if(FAILED(hr)) return hr; com_ptr<ICC_ProcessDataPolicyProp> pPDP; if(SUCCEEDED(pDecoder->QueryInterface(IID_ICC_ProcessDataPolicyProp, (void**)&pPDP))) pPDP->put_ProcessDataPolicy(CC_PDP_PARSED_DATA); com_ptr<ICC_DanielVideoDecoder_CUDA> pCudaDec; if(SUCCEEDED(pDecoder->QueryInterface(IID_ICC_DanielVideoDecoder_CUDA, (void**)&pCudaDec))) pCudaDec->put_TargetColorFormat(cOutputFormat); t00 = t0 = system_clock::now(); g_DecoderTimeFirstFrameIn = t00; frame_count = total_frame_count = 0; printf("Performing decoding loop, press ESC to break\n"); printf("coded sequence length = %zd\n", pFileWriter->GetCodedSequenceLength()); for(int i = 0; i < pFileWriter->GetCodedSequenceLength(); i++) printf(" %zd", pFileWriter->GetCodedFrame(i).second); puts(""); update_mask = 0x07; int key_pressed = 0; int warm_up_frames = 4; coded_size0 = 0; long long coded_size = 0; if(int num_coded_frames = (int)pFileWriter->GetCodedSequenceLength()) for(int frame_no = 0; frame_no < max_frames; frame_no++) { auto codedFrame = pFileWriter->GetCodedFrame(frame_no % num_coded_frames); hr = pDecoder->ProcessData(codedFrame.first, (DWORD)codedFrame.second); if(FAILED(hr)) { pDecoder = NULL; return hr; } coded_size += codedFrame.second; if(TargetFps > 0) { auto t1 = system_clock::now(); auto Treal = duration_cast<milliseconds>(t1 - t0).count(); auto Tideal = (int)(frame_count * 1000 / TargetFps); if(Tideal > Treal + 1) std::this_thread::sleep_for(milliseconds{Tideal - Treal}); } if(warm_up_frames > 0) { if(--warm_up_frames > 0) continue; t00 = t0 = system_clock::now(); } if((frame_count & update_mask) == update_mask) { auto t1 = system_clock::now(); auto dT = duration<double>(t1 - t0).count(); if(dT < 0.5) update_mask = (update_mask<<1) | 1; else if(dT > 2) update_mask = (update_mask>>1) | 1; fprintf(stderr, " %d, %.3f fps, in %.3f Mbps, out %.3f GB/s, CPU load: %.1f%% \r", frame_no, frame_count / dT, (coded_size - coded_size0) * 8 / 1E6 / dT, uncompressed_frame_size / 1E9 * frame_count / dT, cpuLoadMeter.GetLoad()); t0 = t1; coded_size0 = coded_size; frame_count = 0; } frame_count++; total_frame_count++; if(_kbhit() && _getch() == 27) break; } hr = pDecoder->Done(CC_TRUE); if(FAILED(hr)) return hr; t1 = system_clock::now(); pDecoder = NULL; puts("\nDone.\n"); dT = duration<double>(t1 - t00).count(); printf("Average performance = %.3f fps (%.1f ms/f), avg data rate = %.3f GB/s\n", total_frame_count / dT, dT * 1000 / total_frame_count, uncompressed_frame_size / 1E9 * total_frame_count / dT); time_ms = std::chrono::duration_cast<std::chrono::milliseconds>(g_DecoderTimeFirstFrameOut - g_DecoderTimeFirstFrameIn); printf("Decoder latency = %d ms\n", (int)time_ms.count()); return 0; }
30.932996
166
0.65506
Cinegy
c57320827df3d63551e6259d6cedb1a413afc4c6
71
cpp
C++
test/data/pkg_config_use/program.cpp
thomasrockhu/bfg9000
1cd1226eab9bed2fc2ec6acccf7864fdcf2ed31a
[ "BSD-3-Clause" ]
72
2015-06-23T02:35:13.000Z
2021-12-08T01:47:40.000Z
test/data/pkg_config_use/program.cpp
thomasrockhu/bfg9000
1cd1226eab9bed2fc2ec6acccf7864fdcf2ed31a
[ "BSD-3-Clause" ]
139
2015-03-01T18:48:17.000Z
2021-06-18T15:45:14.000Z
test/data/pkg_config_use/program.cpp
thomasrockhu/bfg9000
1cd1226eab9bed2fc2ec6acccf7864fdcf2ed31a
[ "BSD-3-Clause" ]
19
2015-12-23T21:24:33.000Z
2022-01-06T04:04:41.000Z
#include <hello.hpp> int main() { hello::say_hello(); return 0; }
10.142857
21
0.605634
thomasrockhu
c57601efe76fd07101ca62475a552334f32818e2
1,774
cpp
C++
tests/memRdRspFunc/src_pers/PersF2_src.cpp
TonyBrewer/OpenHT
63898397de4d303ba514d88b621cc91367ffe2a6
[ "BSD-3-Clause" ]
13
2015-02-26T22:46:18.000Z
2020-03-24T11:53:06.000Z
tests/memRdRspFunc/src_pers/PersF2_src.cpp
PacificBiosciences/OpenHT
63898397de4d303ba514d88b621cc91367ffe2a6
[ "BSD-3-Clause" ]
5
2016-02-25T17:08:19.000Z
2018-01-20T15:24:36.000Z
tests/memRdRspFunc/src_pers/PersF2_src.cpp
TonyBrewer/OpenHT
63898397de4d303ba514d88b621cc91367ffe2a6
[ "BSD-3-Clause" ]
12
2015-04-13T21:39:54.000Z
2021-01-15T01:00:13.000Z
#include "Ht.h" #include "PersF2.h" void CPersF2::PersF2() { if (PR1_htValid) { switch (PR1_htInst) { case F2_ENTRY: { if (ReadMemBusy()) { HtRetry(); break; } S_rslt64 = 0; ReadMem_func64(PR1_addr, 0x15, 256); ReadMemPause(F2_RD32); break; } case F2_RD32: { if (ReadMemBusy()) { HtRetry(); break; } HtAssert(SR_rslt64 == 9574400, 0); S_rslt32 = 0; ReadMem_func32(PR1_addr + 256 * 8, 0x75, 64); ReadMemPause(F2_RD16); break; } case F2_RD16: { if (ReadMemBusy()) { HtRetry(); break; } HtAssert(SR_rslt32 == 341376, 0); ReadMem_func16(PR1_addr, 0x9); ReadMemPause(F2_RD64DLY); break; } case F2_RD64DLY: { if (ReadMemBusy()) { HtRetry(); break; } S_rslt64Dly = 0; ReadMem_func64Dly(PR1_addr, 0x19, 32); ReadMemPause(F2_RETURN); break; } case F2_RETURN: { if (SendReturnBusy_f2()) { HtRetry(); break; } HtAssert(SR_rslt64Dly == 71424, 0); SendReturn_f2(); break; } default: assert(0); } } T1_rdRspData = 0; S_rslt64Dly += T11_rdRspData; } void CPersF2::ReadMemResp_func64(ht_uint8 rdRspElemIdx, ht_uint5 ht_noload rdRspInfo, uint64_t rdRspData) { S_rslt64 += (uint64_t)(rdRspData * rdRspElemIdx); } void CPersF2::ReadMemResp_func32(ht_uint6 rdRspElemIdx, ht_uint7 ht_noload rdRspInfo, uint32_t rdRspData) { S_rslt32 += (uint32_t)(rdRspData * rdRspElemIdx); } void CPersF2::ReadMemResp_func16(ht_uint4 ht_noload rdRspInfo, int16_t ht_noload rdRspData) { HtAssert(rdRspData == 123, 0); HtAssert(rdRspInfo == 9, 0); } void CPersF2::ReadMemResp_func64Dly(ht_uint5 rdRspElemIdx, ht_uint5 ht_noload rdRspInfo, uint64_t rdRspData) { T1_rdRspData = (uint64_t)(rdRspData * rdRspElemIdx); }
16.735849
108
0.658399
TonyBrewer