hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
cd3e21da419656a66613a4a983e2edf4d5aa3f9d
6,313
cpp
C++
third_party/WebKit/Source/modules/webgl/WebGLGetBufferSubDataAsync.cpp
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
third_party/WebKit/Source/modules/webgl/WebGLGetBufferSubDataAsync.cpp
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
third_party/WebKit/Source/modules/webgl/WebGLGetBufferSubDataAsync.cpp
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2016 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 "modules/webgl/WebGLGetBufferSubDataAsync.h" #include "core/dom/DOMException.h" #include "gpu/GLES2/gl2extchromium.h" #include "gpu/command_buffer/client/gles2_interface.h" #include "modules/webgl/WebGL2RenderingContextBase.h" namespace blink { WebGLGetBufferSubDataAsync::WebGLGetBufferSubDataAsync( WebGLRenderingContextBase* context) : WebGLExtension(context) {} WebGLExtensionName WebGLGetBufferSubDataAsync::name() const { return WebGLGetBufferSubDataAsyncName; } WebGLGetBufferSubDataAsync* WebGLGetBufferSubDataAsync::create( WebGLRenderingContextBase* context) { return new WebGLGetBufferSubDataAsync(context); } bool WebGLGetBufferSubDataAsync::supported(WebGLRenderingContextBase* context) { return true; } const char* WebGLGetBufferSubDataAsync::extensionName() { return "WEBGL_get_buffer_sub_data_async"; } ScriptPromise WebGLGetBufferSubDataAsync::getBufferSubDataAsync( ScriptState* scriptState, GLenum target, GLintptr srcByteOffset, DOMArrayBufferView* dstData, GLuint dstOffset, GLuint length) { ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState); ScriptPromise promise = resolver->promise(); WebGLExtensionScopedContext scoped(this); if (scoped.isLost()) { DOMException* exception = DOMException::create(InvalidStateError, "context lost"); resolver->reject(exception); return promise; } WebGL2RenderingContextBase* context = nullptr; { WebGLRenderingContextBase* contextBase = scoped.context(); DCHECK_GE(contextBase->version(), 2u); context = static_cast<WebGL2RenderingContextBase*>(contextBase); } WebGLBuffer* sourceBuffer = nullptr; void* destinationDataPtr = nullptr; long long destinationByteLength = 0; const char* message = context->validateGetBufferSubData( __FUNCTION__, target, srcByteOffset, dstData, dstOffset, length, &sourceBuffer, &destinationDataPtr, &destinationByteLength); if (message) { // If there was a GL error, it was already synthesized in // validateGetBufferSubData, so it's not done here. DOMException* exception = DOMException::create(InvalidStateError, message); resolver->reject(exception); return promise; } message = context->validateGetBufferSubDataBounds( __FUNCTION__, sourceBuffer, srcByteOffset, destinationByteLength); if (message) { // If there was a GL error, it was already synthesized in // validateGetBufferSubDataBounds, so it's not done here. DOMException* exception = DOMException::create(InvalidStateError, message); resolver->reject(exception); return promise; } // If the length of the copy is zero, this is a no-op. if (!destinationByteLength) { resolver->resolve(dstData); return promise; } GLuint queryID; context->contextGL()->GenQueriesEXT(1, &queryID); context->contextGL()->BeginQueryEXT(GL_COMMANDS_ISSUED_CHROMIUM, queryID); void* mappedData = context->contextGL()->GetBufferSubDataAsyncCHROMIUM( target, srcByteOffset, destinationByteLength); context->contextGL()->EndQueryEXT(GL_COMMANDS_ISSUED_CHROMIUM); if (!mappedData) { DOMException* exception = DOMException::create(InvalidStateError, "Out of memory"); resolver->reject(exception); return promise; } auto callbackObject = new WebGLGetBufferSubDataAsyncCallback( context, resolver, mappedData, queryID, dstData, destinationDataPtr, destinationByteLength); context->registerGetBufferSubDataAsyncCallback(callbackObject); auto callback = WTF::bind(&WebGLGetBufferSubDataAsyncCallback::resolve, wrapPersistent(callbackObject)); context->drawingBuffer()->contextProvider()->signalQuery( queryID, convertToBaseCallback(std::move(callback))); return promise; } WebGLGetBufferSubDataAsyncCallback::WebGLGetBufferSubDataAsyncCallback( WebGL2RenderingContextBase* context, ScriptPromiseResolver* promiseResolver, void* shmReadbackResultData, GLuint commandsIssuedQueryID, DOMArrayBufferView* destinationArrayBufferView, void* destinationDataPtr, long long destinationByteLength) : m_context(context), m_promiseResolver(promiseResolver), m_shmReadbackResultData(shmReadbackResultData), m_commandsIssuedQueryID(commandsIssuedQueryID), m_destinationArrayBufferView(destinationArrayBufferView), m_destinationDataPtr(destinationDataPtr), m_destinationByteLength(destinationByteLength) { DCHECK(shmReadbackResultData); DCHECK(destinationDataPtr); } void WebGLGetBufferSubDataAsyncCallback::destroy() { DCHECK(m_shmReadbackResultData); m_context->contextGL()->FreeSharedMemory(m_shmReadbackResultData); m_shmReadbackResultData = nullptr; DOMException* exception = DOMException::create(InvalidStateError, "Context lost or destroyed"); m_promiseResolver->reject(exception); } void WebGLGetBufferSubDataAsyncCallback::resolve() { if (!m_context || !m_shmReadbackResultData) { DOMException* exception = DOMException::create(InvalidStateError, "Context lost or destroyed"); m_promiseResolver->reject(exception); return; } if (m_destinationArrayBufferView->buffer()->isNeutered()) { DOMException* exception = DOMException::create( InvalidStateError, "ArrayBufferView became invalid asynchronously"); m_promiseResolver->reject(exception); return; } memcpy(m_destinationDataPtr, m_shmReadbackResultData, m_destinationByteLength); // TODO(kainino): What would happen if the DOM was suspended when the // promise became resolved? Could another JS task happen between the memcpy // and the promise resolution task, which would see the wrong data? m_promiseResolver->resolve(m_destinationArrayBufferView); m_context->contextGL()->DeleteQueriesEXT(1, &m_commandsIssuedQueryID); this->destroy(); m_context->unregisterGetBufferSubDataAsyncCallback(this); } DEFINE_TRACE(WebGLGetBufferSubDataAsyncCallback) { visitor->trace(m_context); visitor->trace(m_promiseResolver); visitor->trace(m_destinationArrayBufferView); } } // namespace blink
36.074286
80
0.764296
google-ar
cd3f00cb62b7a82c5cb412716f0521d99dcd853d
25,577
cc
C++
base/allocator/allocator_shim_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
base/allocator/allocator_shim_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
base/allocator/allocator_shim_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2016 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/allocator/allocator_shim.h" #include <stdlib.h> #include <string.h> #include <atomic> #include <iomanip> #include <memory> #include <new> #include <sstream> #include <vector> #include "base/allocator/buildflags.h" #include "base/allocator/partition_allocator/partition_alloc.h" #include "base/memory/page_size.h" #include "base/synchronization/waitable_event.h" #include "base/threading/platform_thread.h" #include "base/threading/thread_local.h" #include "build/build_config.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_WIN) #include <malloc.h> #include <windows.h> #elif defined(OS_APPLE) #include <malloc/malloc.h> #include "base/allocator/allocator_interception_mac.h" #include "base/mac/mac_util.h" #include "third_party/apple_apsl/malloc.h" #else #include <malloc.h> #endif #if !defined(OS_WIN) #include <unistd.h> #endif #if defined(LIBC_GLIBC) extern "C" void* __libc_memalign(size_t align, size_t s); #endif namespace base { namespace allocator { namespace { using testing::_; using testing::MockFunction; // Special sentinel values used for testing GetSizeEstimate() interception. const char kTestSizeEstimateData[] = "test_value"; constexpr void* kTestSizeEstimateAddress = (void*)kTestSizeEstimateData; constexpr size_t kTestSizeEstimate = 1234; class AllocatorShimTest : public testing::Test { public: AllocatorShimTest() : testing::Test() {} static size_t Hash(const void* ptr) { return reinterpret_cast<uintptr_t>(ptr) % MaxSizeTracked(); } static void* MockAlloc(const AllocatorDispatch* self, size_t size, void* context) { if (instance_ && size < MaxSizeTracked()) ++(instance_->allocs_intercepted_by_size[size]); return self->next->alloc_function(self->next, size, context); } static void* MockAllocUnchecked(const AllocatorDispatch* self, size_t size, void* context) { if (instance_ && size < MaxSizeTracked()) ++(instance_->allocs_intercepted_by_size[size]); return self->next->alloc_unchecked_function(self->next, size, context); } static void* MockAllocZeroInit(const AllocatorDispatch* self, size_t n, size_t size, void* context) { const size_t real_size = n * size; if (instance_ && real_size < MaxSizeTracked()) ++(instance_->zero_allocs_intercepted_by_size[real_size]); return self->next->alloc_zero_initialized_function(self->next, n, size, context); } static void* MockAllocAligned(const AllocatorDispatch* self, size_t alignment, size_t size, void* context) { if (instance_) { if (size < MaxSizeTracked()) ++(instance_->aligned_allocs_intercepted_by_size[size]); if (alignment < MaxSizeTracked()) ++(instance_->aligned_allocs_intercepted_by_alignment[alignment]); } return self->next->alloc_aligned_function(self->next, alignment, size, context); } static void* MockRealloc(const AllocatorDispatch* self, void* address, size_t size, void* context) { if (instance_) { // Size 0xFEED a special sentinel for the NewHandlerConcurrency test. // Hitting it for the first time will cause a failure, causing the // invocation of the std::new_handler. if (size == 0xFEED) { if (!instance_->did_fail_realloc_0xfeed_once->Get()) { instance_->did_fail_realloc_0xfeed_once->Set(true); return nullptr; } return address; } if (size < MaxSizeTracked()) ++(instance_->reallocs_intercepted_by_size[size]); ++instance_->reallocs_intercepted_by_addr[Hash(address)]; } return self->next->realloc_function(self->next, address, size, context); } static void MockFree(const AllocatorDispatch* self, void* address, void* context) { if (instance_) { ++instance_->frees_intercepted_by_addr[Hash(address)]; } self->next->free_function(self->next, address, context); } static size_t MockGetSizeEstimate(const AllocatorDispatch* self, void* address, void* context) { // Special testing values for GetSizeEstimate() interception. if (address == kTestSizeEstimateAddress) return kTestSizeEstimate; return self->next->get_size_estimate_function(self->next, address, context); } static unsigned MockBatchMalloc(const AllocatorDispatch* self, size_t size, void** results, unsigned num_requested, void* context) { if (instance_) { instance_->batch_mallocs_intercepted_by_size[size] = instance_->batch_mallocs_intercepted_by_size[size] + num_requested; } return self->next->batch_malloc_function(self->next, size, results, num_requested, context); } static void MockBatchFree(const AllocatorDispatch* self, void** to_be_freed, unsigned num_to_be_freed, void* context) { if (instance_) { for (unsigned i = 0; i < num_to_be_freed; ++i) { ++instance_->batch_frees_intercepted_by_addr[Hash(to_be_freed[i])]; } } self->next->batch_free_function(self->next, to_be_freed, num_to_be_freed, context); } static void MockFreeDefiniteSize(const AllocatorDispatch* self, void* ptr, size_t size, void* context) { if (instance_) { ++instance_->frees_intercepted_by_addr[Hash(ptr)]; ++instance_->free_definite_sizes_intercepted_by_size[size]; } self->next->free_definite_size_function(self->next, ptr, size, context); } static void* MockAlignedMalloc(const AllocatorDispatch* self, size_t size, size_t alignment, void* context) { if (instance_ && size < MaxSizeTracked()) { ++instance_->aligned_mallocs_intercepted_by_size[size]; } return self->next->aligned_malloc_function(self->next, size, alignment, context); } static void* MockAlignedRealloc(const AllocatorDispatch* self, void* address, size_t size, size_t alignment, void* context) { if (instance_) { if (size < MaxSizeTracked()) ++instance_->aligned_reallocs_intercepted_by_size[size]; ++instance_->aligned_reallocs_intercepted_by_addr[Hash(address)]; } return self->next->aligned_realloc_function(self->next, address, size, alignment, context); } static void MockAlignedFree(const AllocatorDispatch* self, void* address, void* context) { if (instance_) { ++instance_->aligned_frees_intercepted_by_addr[Hash(address)]; } self->next->aligned_free_function(self->next, address, context); } static void NewHandler() { if (!instance_) return; instance_->num_new_handler_calls.fetch_add(1, std::memory_order_relaxed); } int32_t GetNumberOfNewHandlerCalls() { return instance_->num_new_handler_calls.load(std::memory_order_acquire); } void SetUp() override { allocs_intercepted_by_size.resize(MaxSizeTracked()); zero_allocs_intercepted_by_size.resize(MaxSizeTracked()); aligned_allocs_intercepted_by_size.resize(MaxSizeTracked()); aligned_allocs_intercepted_by_alignment.resize(MaxSizeTracked()); reallocs_intercepted_by_size.resize(MaxSizeTracked()); reallocs_intercepted_by_addr.resize(MaxSizeTracked()); frees_intercepted_by_addr.resize(MaxSizeTracked()); batch_mallocs_intercepted_by_size.resize(MaxSizeTracked()); batch_frees_intercepted_by_addr.resize(MaxSizeTracked()); free_definite_sizes_intercepted_by_size.resize(MaxSizeTracked()); aligned_mallocs_intercepted_by_size.resize(MaxSizeTracked()); aligned_reallocs_intercepted_by_size.resize(MaxSizeTracked()); aligned_reallocs_intercepted_by_addr.resize(MaxSizeTracked()); aligned_frees_intercepted_by_addr.resize(MaxSizeTracked()); did_fail_realloc_0xfeed_once = std::make_unique<ThreadLocalBoolean>(); num_new_handler_calls.store(0, std::memory_order_release); instance_ = this; #if defined(OS_APPLE) InitializeAllocatorShim(); #endif } void TearDown() override { instance_ = nullptr; #if defined(OS_APPLE) UninterceptMallocZonesForTesting(); #endif } static size_t MaxSizeTracked() { #if defined(OS_IOS) // TODO(crbug.com/1077271): 64-bit iOS uses a page size that is larger than // SystemPageSize(), causing this test to make larger allocations, relative // to SystemPageSize(). return 6 * base::SystemPageSize(); #else return 2 * base::SystemPageSize(); #endif } protected: std::vector<size_t> allocs_intercepted_by_size; std::vector<size_t> zero_allocs_intercepted_by_size; std::vector<size_t> aligned_allocs_intercepted_by_size; std::vector<size_t> aligned_allocs_intercepted_by_alignment; std::vector<size_t> reallocs_intercepted_by_size; std::vector<size_t> reallocs_intercepted_by_addr; std::vector<size_t> frees_intercepted_by_addr; std::vector<size_t> batch_mallocs_intercepted_by_size; std::vector<size_t> batch_frees_intercepted_by_addr; std::vector<size_t> free_definite_sizes_intercepted_by_size; std::vector<size_t> aligned_mallocs_intercepted_by_size; std::vector<size_t> aligned_reallocs_intercepted_by_size; std::vector<size_t> aligned_reallocs_intercepted_by_addr; std::vector<size_t> aligned_frees_intercepted_by_addr; std::unique_ptr<ThreadLocalBoolean> did_fail_realloc_0xfeed_once; std::atomic<uint32_t> num_new_handler_calls; private: static AllocatorShimTest* instance_; }; struct TestStruct1 { uint32_t ignored; uint8_t ignored_2; }; struct TestStruct2 { uint64_t ignored; uint8_t ignored_3; }; class ThreadDelegateForNewHandlerTest : public PlatformThread::Delegate { public: explicit ThreadDelegateForNewHandlerTest(WaitableEvent* event) : event_(event) {} void ThreadMain() override { event_->Wait(); void* temp = malloc(1); void* res = realloc(temp, 0xFEED); EXPECT_EQ(temp, res); } private: WaitableEvent* event_; }; AllocatorShimTest* AllocatorShimTest::instance_ = nullptr; AllocatorDispatch g_mock_dispatch = { &AllocatorShimTest::MockAlloc, /* alloc_function */ &AllocatorShimTest::MockAllocUnchecked, /* alloc_unchecked_function */ &AllocatorShimTest::MockAllocZeroInit, /* alloc_zero_initialized_function */ &AllocatorShimTest::MockAllocAligned, /* alloc_aligned_function */ &AllocatorShimTest::MockRealloc, /* realloc_function */ &AllocatorShimTest::MockFree, /* free_function */ &AllocatorShimTest::MockGetSizeEstimate, /* get_size_estimate_function */ &AllocatorShimTest::MockBatchMalloc, /* batch_malloc_function */ &AllocatorShimTest::MockBatchFree, /* batch_free_function */ &AllocatorShimTest::MockFreeDefiniteSize, /* free_definite_size_function */ &AllocatorShimTest::MockAlignedMalloc, /* aligned_malloc_function */ &AllocatorShimTest::MockAlignedRealloc, /* aligned_realloc_function */ &AllocatorShimTest::MockAlignedFree, /* aligned_free_function */ nullptr, /* next */ }; TEST_F(AllocatorShimTest, InterceptLibcSymbols) { InsertAllocatorDispatch(&g_mock_dispatch); void* alloc_ptr = malloc(19); ASSERT_NE(nullptr, alloc_ptr); ASSERT_GE(allocs_intercepted_by_size[19], 1u); void* zero_alloc_ptr = calloc(2, 23); ASSERT_NE(nullptr, zero_alloc_ptr); ASSERT_GE(zero_allocs_intercepted_by_size[2 * 23], 1u); #if !defined(OS_WIN) void* posix_memalign_ptr = nullptr; int res = posix_memalign(&posix_memalign_ptr, 256, 59); ASSERT_EQ(0, res); ASSERT_NE(nullptr, posix_memalign_ptr); ASSERT_EQ(0u, reinterpret_cast<uintptr_t>(posix_memalign_ptr) % 256); ASSERT_GE(aligned_allocs_intercepted_by_alignment[256], 1u); ASSERT_GE(aligned_allocs_intercepted_by_size[59], 1u); // (p)valloc() are not defined on Android. pvalloc() is a GNU extension, // valloc() is not in POSIX. #if !defined(OS_ANDROID) const size_t kPageSize = base::GetPageSize(); void* valloc_ptr = valloc(61); ASSERT_NE(nullptr, valloc_ptr); ASSERT_EQ(0u, reinterpret_cast<uintptr_t>(valloc_ptr) % kPageSize); ASSERT_GE(aligned_allocs_intercepted_by_alignment[kPageSize], 1u); ASSERT_GE(aligned_allocs_intercepted_by_size[61], 1u); #endif // !defined(OS_ANDROID) #endif // !OS_WIN #if !defined(OS_WIN) && !defined(OS_APPLE) void* memalign_ptr = memalign(128, 53); ASSERT_NE(nullptr, memalign_ptr); ASSERT_EQ(0u, reinterpret_cast<uintptr_t>(memalign_ptr) % 128); ASSERT_GE(aligned_allocs_intercepted_by_alignment[128], 1u); ASSERT_GE(aligned_allocs_intercepted_by_size[53], 1u); #if defined(OS_POSIX) && !defined(OS_ANDROID) void* pvalloc_ptr = pvalloc(67); ASSERT_NE(nullptr, pvalloc_ptr); ASSERT_EQ(0u, reinterpret_cast<uintptr_t>(pvalloc_ptr) % kPageSize); ASSERT_GE(aligned_allocs_intercepted_by_alignment[kPageSize], 1u); // pvalloc rounds the size up to the next page. ASSERT_GE(aligned_allocs_intercepted_by_size[kPageSize], 1u); #endif // defined(OS_POSIX) && !defined(OS_ANDROID) #endif // !OS_WIN && !OS_APPLE // See allocator_shim_override_glibc_weak_symbols.h for why we intercept // internal libc symbols. #if defined(LIBC_GLIBC) && \ (BUILDFLAG(USE_TCMALLOC) || BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)) void* libc_memalign_ptr = __libc_memalign(512, 56); ASSERT_NE(nullptr, memalign_ptr); ASSERT_EQ(0u, reinterpret_cast<uintptr_t>(libc_memalign_ptr) % 512); ASSERT_GE(aligned_allocs_intercepted_by_alignment[512], 1u); ASSERT_GE(aligned_allocs_intercepted_by_size[56], 1u); #endif char* realloc_ptr = static_cast<char*>(malloc(10)); strcpy(realloc_ptr, "foobar"); void* old_realloc_ptr = realloc_ptr; realloc_ptr = static_cast<char*>(realloc(realloc_ptr, 73)); ASSERT_GE(reallocs_intercepted_by_size[73], 1u); ASSERT_GE(reallocs_intercepted_by_addr[Hash(old_realloc_ptr)], 1u); ASSERT_EQ(0, strcmp(realloc_ptr, "foobar")); free(alloc_ptr); ASSERT_GE(frees_intercepted_by_addr[Hash(alloc_ptr)], 1u); free(zero_alloc_ptr); ASSERT_GE(frees_intercepted_by_addr[Hash(zero_alloc_ptr)], 1u); #if !defined(OS_WIN) && !defined(OS_APPLE) free(memalign_ptr); ASSERT_GE(frees_intercepted_by_addr[Hash(memalign_ptr)], 1u); #if defined(OS_POSIX) && !defined(OS_ANDROID) free(pvalloc_ptr); ASSERT_GE(frees_intercepted_by_addr[Hash(pvalloc_ptr)], 1u); #endif // defined(OS_POSIX) && !defined(OS_ANDROID) #endif // !OS_WIN && !OS_APPLE #if !defined(OS_WIN) free(posix_memalign_ptr); ASSERT_GE(frees_intercepted_by_addr[Hash(posix_memalign_ptr)], 1u); #if !defined(OS_ANDROID) free(valloc_ptr); ASSERT_GE(frees_intercepted_by_addr[Hash(valloc_ptr)], 1u); #endif // !defined(OS_ANDROID) #endif // !OS_WIN #if defined(LIBC_GLIBC) && \ (BUILDFLAG(USE_TCMALLOC) || BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)) free(libc_memalign_ptr); ASSERT_GE(frees_intercepted_by_addr[Hash(memalign_ptr)], 1u); #endif free(realloc_ptr); ASSERT_GE(frees_intercepted_by_addr[Hash(realloc_ptr)], 1u); RemoveAllocatorDispatchForTesting(&g_mock_dispatch); void* non_hooked_ptr = malloc(4095); ASSERT_NE(nullptr, non_hooked_ptr); ASSERT_EQ(0u, allocs_intercepted_by_size[4095]); free(non_hooked_ptr); } // PartitionAlloc-Everywhere does not support batch_malloc / batch_free. #if defined(OS_APPLE) && !BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) TEST_F(AllocatorShimTest, InterceptLibcSymbolsBatchMallocFree) { InsertAllocatorDispatch(&g_mock_dispatch); unsigned count = 13; std::vector<void*> results; results.resize(count); unsigned result_count = malloc_zone_batch_malloc(malloc_default_zone(), 99, results.data(), count); ASSERT_EQ(count, result_count); // TODO(erikchen): On macOS 10.12+, batch_malloc in the default zone may // forward to another zone, which we've also shimmed, resulting in // MockBatchMalloc getting called twice as often as we'd expect. This // re-entrancy into the allocator shim is a bug that needs to be fixed. // https://crbug.com/693237. // ASSERT_EQ(count, batch_mallocs_intercepted_by_size[99]); std::vector<void*> results_copy(results); malloc_zone_batch_free(malloc_default_zone(), results.data(), count); for (void* result : results_copy) { ASSERT_GE(batch_frees_intercepted_by_addr[Hash(result)], 1u); } RemoveAllocatorDispatchForTesting(&g_mock_dispatch); } TEST_F(AllocatorShimTest, InterceptLibcSymbolsFreeDefiniteSize) { InsertAllocatorDispatch(&g_mock_dispatch); void* alloc_ptr = malloc(19); ASSERT_NE(nullptr, alloc_ptr); ASSERT_GE(allocs_intercepted_by_size[19], 1u); ChromeMallocZone* default_zone = reinterpret_cast<ChromeMallocZone*>(malloc_default_zone()); default_zone->free_definite_size(malloc_default_zone(), alloc_ptr, 19); ASSERT_GE(free_definite_sizes_intercepted_by_size[19], 1u); RemoveAllocatorDispatchForTesting(&g_mock_dispatch); } #endif // defined(OS_APPLE) && !BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) #if defined(OS_WIN) TEST_F(AllocatorShimTest, InterceptUcrtAlignedAllocationSymbols) { InsertAllocatorDispatch(&g_mock_dispatch); constexpr size_t kAlignment = 32; void* alloc_ptr = _aligned_malloc(123, kAlignment); EXPECT_GE(aligned_mallocs_intercepted_by_size[123], 1u); void* new_alloc_ptr = _aligned_realloc(alloc_ptr, 1234, kAlignment); EXPECT_GE(aligned_reallocs_intercepted_by_size[1234], 1u); EXPECT_GE(aligned_reallocs_intercepted_by_addr[Hash(alloc_ptr)], 1u); _aligned_free(new_alloc_ptr); EXPECT_GE(aligned_frees_intercepted_by_addr[Hash(new_alloc_ptr)], 1u); RemoveAllocatorDispatchForTesting(&g_mock_dispatch); } TEST_F(AllocatorShimTest, AlignedReallocSizeZeroFrees) { void* alloc_ptr = _aligned_malloc(123, 16); CHECK(alloc_ptr); alloc_ptr = _aligned_realloc(alloc_ptr, 0, 16); CHECK(!alloc_ptr); } #endif // defined(OS_WIN) TEST_F(AllocatorShimTest, InterceptCppSymbols) { InsertAllocatorDispatch(&g_mock_dispatch); TestStruct1* new_ptr = new TestStruct1; ASSERT_NE(nullptr, new_ptr); ASSERT_GE(allocs_intercepted_by_size[sizeof(TestStruct1)], 1u); TestStruct1* new_array_ptr = new TestStruct1[3]; ASSERT_NE(nullptr, new_array_ptr); ASSERT_GE(allocs_intercepted_by_size[sizeof(TestStruct1) * 3], 1u); TestStruct2* new_nt_ptr = new (std::nothrow) TestStruct2; ASSERT_NE(nullptr, new_nt_ptr); ASSERT_GE(allocs_intercepted_by_size[sizeof(TestStruct2)], 1u); TestStruct2* new_array_nt_ptr = new TestStruct2[3]; ASSERT_NE(nullptr, new_array_nt_ptr); ASSERT_GE(allocs_intercepted_by_size[sizeof(TestStruct2) * 3], 1u); delete new_ptr; ASSERT_GE(frees_intercepted_by_addr[Hash(new_ptr)], 1u); delete[] new_array_ptr; ASSERT_GE(frees_intercepted_by_addr[Hash(new_array_ptr)], 1u); delete new_nt_ptr; ASSERT_GE(frees_intercepted_by_addr[Hash(new_nt_ptr)], 1u); delete[] new_array_nt_ptr; ASSERT_GE(frees_intercepted_by_addr[Hash(new_array_nt_ptr)], 1u); RemoveAllocatorDispatchForTesting(&g_mock_dispatch); } // PartitionAlloc disallows large allocations to avoid errors with int // overflows. #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) struct TooLarge { char padding1[1UL << 31]; int padding2; }; TEST_F(AllocatorShimTest, NewNoThrowTooLarge) { char* too_large_array = new (std::nothrow) char[(1UL << 31) + 100]; EXPECT_EQ(nullptr, too_large_array); TooLarge* too_large_struct = new (std::nothrow) TooLarge; EXPECT_EQ(nullptr, too_large_struct); } #endif // This test exercises the case of concurrent OOM failure, which would end up // invoking std::new_handler concurrently. This is to cover the CallNewHandler() // paths of allocator_shim.cc and smoke-test its thread safey. // The test creates kNumThreads threads. Each of them mallocs some memory, and // then does a realloc(<new memory>, 0xFEED). // The shim intercepts such realloc and makes it fail only once on each thread. // We expect to see excactly kNumThreads invocations of the new_handler. TEST_F(AllocatorShimTest, NewHandlerConcurrency) { const int kNumThreads = 32; PlatformThreadHandle threads[kNumThreads]; // The WaitableEvent here is used to attempt to trigger all the threads at // the same time, after they have been initialized. WaitableEvent event(WaitableEvent::ResetPolicy::MANUAL, WaitableEvent::InitialState::NOT_SIGNALED); ThreadDelegateForNewHandlerTest mock_thread_main(&event); for (int i = 0; i < kNumThreads; ++i) PlatformThread::Create(0, &mock_thread_main, &threads[i]); std::set_new_handler(&AllocatorShimTest::NewHandler); SetCallNewHandlerOnMallocFailure(true); // It's going to fail on realloc(). InsertAllocatorDispatch(&g_mock_dispatch); event.Signal(); for (int i = 0; i < kNumThreads; ++i) PlatformThread::Join(threads[i]); RemoveAllocatorDispatchForTesting(&g_mock_dispatch); ASSERT_EQ(kNumThreads, GetNumberOfNewHandlerCalls()); } #if defined(OS_WIN) TEST_F(AllocatorShimTest, ShimReplacesCRTHeapWhenEnabled) { ASSERT_EQ(::GetProcessHeap(), reinterpret_cast<HANDLE>(_get_heap_handle())); } #endif // defined(OS_WIN) #if defined(OS_WIN) static size_t GetUsableSize(void* ptr) { return _msize(ptr); } #elif defined(OS_APPLE) static size_t GetUsableSize(void* ptr) { return malloc_size(ptr); } #elif defined(OS_LINUX) || defined(OS_CHROMEOS) static size_t GetUsableSize(void* ptr) { return malloc_usable_size(ptr); } #else #define NO_MALLOC_SIZE #endif #if !defined(NO_MALLOC_SIZE) TEST_F(AllocatorShimTest, ShimReplacesMallocSizeWhenEnabled) { InsertAllocatorDispatch(&g_mock_dispatch); EXPECT_EQ(GetUsableSize(kTestSizeEstimateAddress), kTestSizeEstimate); RemoveAllocatorDispatchForTesting(&g_mock_dispatch); } TEST_F(AllocatorShimTest, ShimDoesntChangeMallocSizeWhenEnabled) { void* alloc = malloc(16); size_t sz = GetUsableSize(alloc); EXPECT_GE(sz, 16U); InsertAllocatorDispatch(&g_mock_dispatch); EXPECT_EQ(GetUsableSize(alloc), sz); RemoveAllocatorDispatchForTesting(&g_mock_dispatch); free(alloc); } #endif // !defined(NO_MALLOC_SIZE) #if defined(OS_ANDROID) TEST_F(AllocatorShimTest, InterceptCLibraryFunctions) { auto total_counts = [](const std::vector<size_t>& counts) { size_t total = 0; for (const auto count : counts) total += count; return total; }; size_t counts_before; size_t counts_after = total_counts(allocs_intercepted_by_size); void* ptr; InsertAllocatorDispatch(&g_mock_dispatch); // <stdlib.h> counts_before = counts_after; ptr = realpath(".", nullptr); EXPECT_NE(nullptr, ptr); free(ptr); counts_after = total_counts(allocs_intercepted_by_size); EXPECT_GT(counts_after, counts_before); // <string.h> counts_before = counts_after; ptr = strdup("hello, world"); EXPECT_NE(nullptr, ptr); free(ptr); counts_after = total_counts(allocs_intercepted_by_size); EXPECT_GT(counts_after, counts_before); counts_before = counts_after; ptr = strndup("hello, world", 5); EXPECT_NE(nullptr, ptr); free(ptr); counts_after = total_counts(allocs_intercepted_by_size); EXPECT_GT(counts_after, counts_before); // <unistd.h> counts_before = counts_after; ptr = getcwd(nullptr, 0); EXPECT_NE(nullptr, ptr); free(ptr); counts_after = total_counts(allocs_intercepted_by_size); EXPECT_GT(counts_after, counts_before); // Calls vasprintf() indirectly, see below. counts_before = counts_after; std::stringstream stream; stream << std::setprecision(1) << std::showpoint << std::fixed << 1.e38; EXPECT_GT(stream.str().size(), 30u); counts_after = total_counts(allocs_intercepted_by_size); EXPECT_GT(counts_after, counts_before); RemoveAllocatorDispatchForTesting(&g_mock_dispatch); } #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) // Non-regression test for crbug.com/1166558. TEST_F(AllocatorShimTest, InterceptVasprintf) { // Printing a float which expands to >=30 characters calls vasprintf() in // libc, which we should intercept. std::stringstream stream; stream << std::setprecision(1) << std::showpoint << std::fixed << 1.e38; EXPECT_GT(stream.str().size(), 30u); // Should not crash. } #endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) #endif // defined(OS_ANDROID) } // namespace } // namespace allocator } // namespace base
35.573018
80
0.7097
zealoussnow
cd3f5062455731485bb70b6490078cd95515799e
72
hh
C++
RAVL2/MSVC/include/Ravl/Image/GaussConvolve.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/MSVC/include/Ravl/Image/GaussConvolve.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/MSVC/include/Ravl/Image/GaussConvolve.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
#include "../.././Image/Processing/Filters/Convolve/GaussConvolve.hh"
18
69
0.722222
isuhao
cd40158fa587ea149d6323d39ce5d36b66d36005
440
hpp
C++
tests/gt_os/inc/mocks/window-enumerator.mock.hpp
my-repositories/GameTrainer
fd307e0bd6e0ef74e8b3195ad6394c71e2fac555
[ "MIT" ]
3
2018-10-11T13:37:42.000Z
2021-03-23T21:54:02.000Z
tests/gt_os/inc/mocks/window-enumerator.mock.hpp
my-repositories/GameTrainer
fd307e0bd6e0ef74e8b3195ad6394c71e2fac555
[ "MIT" ]
null
null
null
tests/gt_os/inc/mocks/window-enumerator.mock.hpp
my-repositories/GameTrainer
fd307e0bd6e0ef74e8b3195ad6394c71e2fac555
[ "MIT" ]
null
null
null
#ifndef GAMETRAINER_WINDOW_ENUMERATOR_MOCK_HPP #define GAMETRAINER_WINDOW_ENUMERATOR_MOCK_HPP #include <gt_os/window-enumerator.i.hpp> class WindowEnumeratorMock : public gt::os::IWindowEnumerator { public: MOCK_METHOD1(setTitle, gt::os::IWindowEnumerator*(const std::string&)); MOCK_METHOD0(enumerate, gt::os::IWindowEnumerator*()); MOCK_CONST_METHOD0(getWindow, HWND()); }; #endif // GAMETRAINER_WINDOW_ENUMERATOR_MOCK_HPP
31.428571
75
0.793182
my-repositories
cd440ea0da86750b6ce74621bc985f77a210e6b2
2,553
cpp
C++
Lib/Ziran/CS/DataStructure/KdTree.cpp
NTForked/ziran2019
35742ac3ab1ae42cf2bbe8761fd7c8e630a638c4
[ "MIT" ]
73
2019-11-06T13:33:46.000Z
2020-05-06T15:54:50.000Z
Lib/Ziran/CS/DataStructure/KdTree.cpp
NTForked/ziran2019
35742ac3ab1ae42cf2bbe8761fd7c8e630a638c4
[ "MIT" ]
6
2020-06-24T21:19:33.000Z
2021-12-15T19:37:53.000Z
Lib/Ziran/CS/DataStructure/KdTree.cpp
NTForked/ziran2019
35742ac3ab1ae42cf2bbe8761fd7c8e630a638c4
[ "MIT" ]
17
2019-11-07T07:15:45.000Z
2020-05-06T10:40:39.000Z
#include "KdTree.h" namespace ZIRAN { /** add an eigenvec point to the tree */ template <int dim> template <class TV_IN> void KdTree<dim>::addPoint(const int i, const TV_IN& new_p) { TV p; for (int i = 0; i < dim; i++) p(i) = (double)(new_p(i)); tree.insert(KdTreeHelper<dim>(i, p)); } template <int dim> void KdTree<dim>::optimize() { tree.optimise(); } /** find the closest point to p in the tree */ template <int dim> template <class TV_IN, class T_IN> void KdTree<dim>::findNearest(const TV_IN& new_p, int& id, TV_IN& pos, T_IN& distance) { TV p; for (int i = 0; i < dim; i++) p(i) = (double)(new_p(i)); auto found = tree.find_nearest(KdTreeHelper<dim>(-1, p)); id = found.first->id; for (int i = 0; i < dim; i++) pos(i) = (T_IN)((found.first->pos)(i)); distance = (T_IN)found.second; } /** erase point erase_p from the tree */ template <int dim> template <class TV_IN> void KdTree<dim>::erasePoint(const int i, const TV_IN& erase_p) { TV p; for (int i = 0; i < dim; i++) p(i) = (double)(erase_p(i)); tree.erase(KdTreeHelper<dim>(i, p)); } template class KdTree<2>; template class KdTree<3>; template void KdTree<2>::addPoint<Eigen::Matrix<float, 2, 1, 0, 2, 1>>(int, Eigen::Matrix<float, 2, 1, 0, 2, 1> const&); template void KdTree<2>::addPoint<Eigen::Matrix<double, 2, 1, 0, 2, 1>>(int, Eigen::Matrix<double, 2, 1, 0, 2, 1> const&); template void KdTree<2>::findNearest<Eigen::Matrix<float, 2, 1, 0, 2, 1>, float>(Eigen::Matrix<float, 2, 1, 0, 2, 1> const&, int&, Eigen::Matrix<float, 2, 1, 0, 2, 1>&, float&); template void KdTree<2>::findNearest<Eigen::Matrix<double, 2, 1, 0, 2, 1>, double>(Eigen::Matrix<double, 2, 1, 0, 2, 1> const&, int&, Eigen::Matrix<double, 2, 1, 0, 2, 1>&, double&); template void KdTree<3>::addPoint<Eigen::Matrix<double, 3, 1, 0, 3, 1>>(int, Eigen::Matrix<double, 3, 1, 0, 3, 1> const&); template void KdTree<3>::addPoint<Eigen::Matrix<float, 3, 1, 0, 3, 1>>(int, Eigen::Matrix<float, 3, 1, 0, 3, 1> const&); template void KdTree<3>::erasePoint<Eigen::Matrix<double, 3, 1, 0, 3, 1>>(int, Eigen::Matrix<double, 3, 1, 0, 3, 1> const&); template void KdTree<3>::findNearest<Eigen::Matrix<double, 3, 1, 0, 3, 1>, double>(Eigen::Matrix<double, 3, 1, 0, 3, 1> const&, int&, Eigen::Matrix<double, 3, 1, 0, 3, 1>&, double&); template void KdTree<3>::findNearest<Eigen::Matrix<float, 3, 1, 0, 3, 1>, float>(Eigen::Matrix<float, 3, 1, 0, 3, 1> const&, int&, Eigen::Matrix<float, 3, 1, 0, 3, 1>&, float&); } // namespace ZIRAN
39.276923
182
0.620447
NTForked
cd44485256c8664d140b4cc445f59264c2e94353
11,768
hxx
C++
include/geombd/CRTP/DJointBase.hxx
garechav/geombd_crtp
c723c0cda841728fcb34fbad634f166e3237d9d9
[ "MIT" ]
1
2021-12-20T23:11:23.000Z
2021-12-20T23:11:23.000Z
include/geombd/CRTP/DJointBase.hxx
garechav/geombd_crtp
c723c0cda841728fcb34fbad634f166e3237d9d9
[ "MIT" ]
null
null
null
include/geombd/CRTP/DJointBase.hxx
garechav/geombd_crtp
c723c0cda841728fcb34fbad634f166e3237d9d9
[ "MIT" ]
null
null
null
/** * \file include/geombd/CRTP/DJointBase.hxx * \author Alvaro Paz, Gustavo Arechavaleta * \version 1.0 * \date 2021 * * Class to implement the CRTP base (interface) * Copyright (c) 2021 Cinvestav * This library is distributed under the MIT License. */ #ifdef EIGEN_VECTORIZE #endif #ifndef GEOMBD_JOINT_BASE_DIFFERENTIATION_CRTP_HXX #define GEOMBD_JOINT_BASE_DIFFERENTIATION_CRTP_HXX //! Include Eigen Library //!--------------------------------------------------------------------------------!// #define EIGEN_NO_DEBUG #define EIGEN_MPL2_ONLY #define EIGEN_UNROLLING_LIMIT 30 #include "Eigen/Core" //#include "Eigen/../unsupported/Eigen/KroneckerProduct" //!--------------------------------------------------------------------------------!// namespace geo { //! Joint Type Base //!------------------------------------------------------------------------------!// template<typename Derived> struct D_CRTPInterface{ public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW //! Recurring Pattern for the Forward Kinematics. template<typename ScalarType, typename Vector3Type, typename Matrix3Type> EIGEN_ALWAYS_INLINE void D_FwdKin(const ScalarType & qi, const Eigen::MatrixBase<Vector3Type> & S_, typename Eigen::MatrixBase<Matrix3Type> & R) { static_cast<Derived*>(this)->runD_FK(qi, S_, R); // static_cast<Derived&>(*this).runD_FK(qi, S_, R); } //! Recurring Pattern for Twist, C bias and P bias at root. template<typename ScalarType, typename Vector3Type, typename Vector6Type, typename Matrix6Type, typename D_Vector6Type> EIGEN_ALWAYS_INLINE void D_TCP_root(const ScalarType & vi, const Eigen::MatrixBase<Vector3Type> & S_, Eigen::MatrixBase<Vector6Type> & S_i, Eigen::MatrixBase<Vector6Type> & p_, const Eigen::MatrixBase<Matrix6Type> & M_, Eigen::MatrixBase<D_Vector6Type> & D_dq_p_) { static_cast<Derived*>(this)->runD_TCP_root(vi, S_, S_i, p_.derived(), M_.derived(), D_dq_p_.derived()); } //! Recurring Pattern for Twist, C bias and P bias. template<typename ScalarType, typename Matrix3Type, typename Matrix6Type, typename Vector3Type, typename Vector6Type, typename D_Vector6Type> EIGEN_ALWAYS_INLINE void D_TwCbPb(bool zeroFlag, const ScalarType & vi, const Eigen::MatrixBase<Vector3Type> & S_, const Eigen::MatrixBase<Matrix3Type> & R_, const Eigen::MatrixBase<Vector3Type> & P_, const Eigen::MatrixBase<Vector6Type> & S_l, const Eigen::MatrixBase<Matrix6Type> & M_, Eigen::MatrixBase<Vector6Type> & S_i, Eigen::MatrixBase<Vector6Type> & c_, Eigen::MatrixBase<Vector6Type> & p_, Eigen::MatrixBase<D_Vector6Type> & D_q_V_, Eigen::MatrixBase<D_Vector6Type> & D_dq_V_, const Eigen::MatrixBase<D_Vector6Type> & D_q_Vj_, const Eigen::MatrixBase<D_Vector6Type> & D_dq_Vj_, Eigen::MatrixBase<D_Vector6Type> & D_q_c_, Eigen::MatrixBase<D_Vector6Type> & D_dq_c_, Eigen::MatrixBase<D_Vector6Type> & D_q_p_, Eigen::MatrixBase<D_Vector6Type> & D_dq_p_) { static_cast<Derived*>(this)->runD_TwCbPb(zeroFlag, vi, S_.derived(), R_.derived(), P_.derived(), S_l.derived(), M_.derived(), S_i.derived(), c_.derived(), p_.derived(), D_q_V_.derived(), D_dq_V_.derived(), D_q_Vj_.derived(), D_dq_Vj_.derived(), D_q_c_.derived(), D_dq_c_.derived(), D_q_p_.derived(), D_dq_p_.derived()); } //! Recurring pattern for inertial expressions at leaf. template<typename ScalarType, typename Vector3Type, typename Matrix3Type, typename Vector6Type, typename Matrix6Type, typename RowVectorXType, typename D_Vector6Type, typename D_Matrix6Type> EIGEN_ALWAYS_INLINE void D_InertiaLeaf(ScalarType & u, ScalarType & iD, const ScalarType tau, const Eigen::MatrixBase<Vector3Type> & S_, Eigen::MatrixBase<Vector6Type> & U_, Eigen::MatrixBase<Vector6Type> & c_, Eigen::MatrixBase<Vector6Type> & P_a_, Eigen::MatrixBase<Matrix6Type> & M_a_, Eigen::MatrixBase<Vector6Type> & P_A_, Eigen::MatrixBase<Matrix6Type> & M_A_, bool P_z, Eigen::MatrixBase<Vector3Type> & P_, Eigen::MatrixBase<Matrix3Type> & R_, Eigen::MatrixBase<Vector6Type> & P_Aj_, Eigen::MatrixBase<Matrix6Type> & M_Aj_, Eigen::MatrixBase<D_Matrix6Type> & D_M_Aj_, Eigen::MatrixBase<RowVectorXType> & D_q_u_, Eigen::MatrixBase<RowVectorXType> & D_dq_u_, Eigen::MatrixBase<D_Vector6Type> & D_q_p_, Eigen::MatrixBase<D_Vector6Type> & D_dq_p_, Eigen::MatrixBase<D_Vector6Type> & D_q_Pa_, Eigen::MatrixBase<D_Vector6Type> & D_dq_Pa_, Eigen::MatrixBase<D_Vector6Type> & D_q_PA_, Eigen::MatrixBase<D_Vector6Type> & D_dq_PA_, Eigen::MatrixBase<D_Vector6Type> & D_q_PAj_, Eigen::MatrixBase<D_Vector6Type> & D_dq_PAj_, Eigen::MatrixBase<D_Vector6Type> & D_q_c_, Eigen::MatrixBase<D_Vector6Type> & D_dq_c_) { static_cast<Derived*>(this)->runD_InertiaLeaf(u, iD, tau, S_, U_, c_, P_a_, M_a_, P_A_, M_A_, P_z, P_, R_, P_Aj_, M_Aj_, D_M_Aj_, D_q_u_, D_dq_u_, D_q_p_, D_dq_p_, D_q_Pa_, D_dq_Pa_, D_q_PA_, D_dq_PA_, D_q_PAj_, D_dq_PAj_, D_q_c_, D_dq_c_); } //! Recurring pattern for inertial expressions. template<typename ScalarType, typename Vector6iType, typename Vector3Type, typename Matrix3Type, typename Vector6Type, typename Matrix6Type, typename VectorXType, typename RowVectorXType, typename D_Vector6Type, typename D_Matrix6Type> EIGEN_ALWAYS_INLINE void D_Inertial(bool rootFlag, Eigen::MatrixBase<Vector6iType> & indexVec, ScalarType & u, ScalarType & iD, const ScalarType tau, const Eigen::MatrixBase<Vector3Type> & S_, Eigen::MatrixBase<Vector6Type> & U_, Eigen::MatrixBase<Vector6Type> & c_, Eigen::MatrixBase<Vector6Type> & P_a_, Eigen::MatrixBase<Matrix6Type> & M_a_, Eigen::MatrixBase<Vector6Type> & P_A_, Eigen::MatrixBase<Matrix6Type> & M_A_, bool P_z, Eigen::MatrixBase<Vector3Type> & P_, Eigen::MatrixBase<Matrix3Type> & R_, Eigen::MatrixBase<Vector6Type> & P_Aj_, Eigen::MatrixBase<Matrix6Type> & M_Aj_, Eigen::MatrixBase<D_Vector6Type> & D_U_h_, Eigen::MatrixBase<VectorXType> & D_U_v_, Eigen::MatrixBase<RowVectorXType> & D_invD_, Eigen::MatrixBase<D_Matrix6Type> & D_M_A_, Eigen::MatrixBase<D_Matrix6Type> & D_M_Aj_, Eigen::MatrixBase<RowVectorXType> & D_q_u_, Eigen::MatrixBase<RowVectorXType> & D_dq_u_, Eigen::MatrixBase<D_Vector6Type> & D_q_Pa_, Eigen::MatrixBase<D_Vector6Type> & D_dq_Pa_, Eigen::MatrixBase<D_Vector6Type> & D_q_PA_, Eigen::MatrixBase<D_Vector6Type> & D_dq_PA_, Eigen::MatrixBase<D_Vector6Type> & D_q_PAj_, Eigen::MatrixBase<D_Vector6Type> & D_dq_PAj_, Eigen::MatrixBase<D_Vector6Type> & D_q_c_, Eigen::MatrixBase<D_Vector6Type> & D_dq_c_) { static_cast<Derived*>(this)->runD_Inertial(rootFlag, indexVec, u, iD, tau, S_, U_, c_, P_a_, M_a_, P_A_, M_A_, P_z, P_, R_, P_Aj_, M_Aj_, D_U_h_, D_U_v_, D_invD_, D_M_A_, D_M_Aj_, D_q_u_, D_dq_u_, D_q_Pa_, D_dq_Pa_, D_q_PA_, D_dq_PA_, D_q_PAj_, D_dq_PAj_, D_q_c_, D_dq_c_); } //! Recurring pattern for acceleration expression at root. template<typename ScalarType, typename Vector3Type, typename Matrix3Type, typename Vector6Type, typename D_Vector6Type, typename RowVectorXType, typename MatrixXType> EIGEN_ALWAYS_INLINE void D_AccelRoot(ScalarType u, ScalarType iD, ScalarType* ddq, const Eigen::MatrixBase<Vector3Type> & S, const Eigen::MatrixBase<Vector3Type> & P_r, const Eigen::MatrixBase<Matrix3Type> & R_r, const Eigen::MatrixBase<Vector6Type> & U_r, Eigen::MatrixBase<Vector6Type> & Acc_i_r, Eigen::MatrixBase<D_Vector6Type> & D_U_h_, Eigen::MatrixBase<RowVectorXType> & D_invD_, Eigen::MatrixBase<RowVectorXType> & D_q_u_, Eigen::MatrixBase<RowVectorXType> & D_dq_u_, Eigen::MatrixBase<D_Vector6Type> & D_q_A_, Eigen::MatrixBase<D_Vector6Type> & D_dq_A_, Eigen::MatrixBase<MatrixXType> & D_ddq_) { static_cast<Derived*>(this)->runD_AccelRoot(u, iD, ddq, S, P_r, R_r, U_r, Acc_i_r, D_U_h_, D_invD_, D_q_u_, D_dq_u_, D_q_A_, D_dq_A_, D_ddq_); } //! Recurring pattern for acceleration expression. template<typename ScalarType, typename IndexType, typename Vector3Type, typename Matrix3Type, typename Vector6Type, typename D_Vector6Type, typename RowVectorXType, typename MatrixXType> EIGEN_ALWAYS_INLINE void D_Accel(IndexType ID, bool zeroFlag, ScalarType u, ScalarType iD, ScalarType* ddq, const Eigen::MatrixBase<Vector3Type> & S, const Eigen::MatrixBase<Vector3Type> & P_, const Eigen::MatrixBase<Matrix3Type> & R_, const Eigen::MatrixBase<Vector6Type> & c_, const Eigen::MatrixBase<Vector6Type> & U_, Eigen::MatrixBase<Vector6Type> & A_, const Eigen::MatrixBase<Vector6Type> & Aj_, bool isLeaf, std::vector< IndexType >* Pre_, std::vector< IndexType >* Suc_, std::vector< IndexType >* PreSuc_, Eigen::MatrixBase<D_Vector6Type> & D_U_h_, Eigen::MatrixBase<RowVectorXType> & D_invD_, Eigen::MatrixBase<MatrixXType> & D_ddq_, Eigen::MatrixBase<RowVectorXType> & D_q_u_, Eigen::MatrixBase<RowVectorXType> & D_dq_u_, Eigen::MatrixBase<D_Vector6Type> & D_q_c_, Eigen::MatrixBase<D_Vector6Type> & D_dq_c_, Eigen::MatrixBase<D_Vector6Type> & D_q_A_, Eigen::MatrixBase<D_Vector6Type> & D_dq_A_, Eigen::MatrixBase<D_Vector6Type> & D_q_Aj_, Eigen::MatrixBase<D_Vector6Type> & D_dq_Aj_) { static_cast<Derived*>(this)->runD_Accel(ID, zeroFlag, u, iD, ddq, S, P_, R_, c_, U_, A_, Aj_, isLeaf, Pre_, Suc_, PreSuc_, D_U_h_, D_invD_, D_ddq_, D_q_u_, D_dq_u_, D_q_c_, D_dq_c_, D_q_A_, D_dq_A_, D_q_Aj_, D_dq_Aj_); } }; } #include "DJointDerived/DJointDerived.hpp" #include "DJointDerived/DVisitors.hxx" #endif // GEOMBD_JOINT_BASE_DIFFERENTIATION_CRTP_HXX
48.829876
145
0.592284
garechav
cd49d18ca8c7e4a4656f848822b82592e20fe15b
9,167
cxx
C++
panda/src/display/parasiteBuffer.cxx
kestred/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
3
2018-03-09T12:07:29.000Z
2021-02-25T06:50:25.000Z
panda/src/display/parasiteBuffer.cxx
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
panda/src/display/parasiteBuffer.cxx
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
// Filename: parasiteBuffer.cxx // Created by: drose (27Feb04) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #include "parasiteBuffer.h" #include "texture.h" TypeHandle ParasiteBuffer::_type_handle; //////////////////////////////////////////////////////////////////// // Function: ParasiteBuffer::Constructor // Access: Public // Description: Normally, the ParasiteBuffer constructor is not // called directly; these are created instead via the // GraphicsEngine::make_parasite() function. //////////////////////////////////////////////////////////////////// ParasiteBuffer:: ParasiteBuffer(GraphicsOutput *host, const string &name, int x_size, int y_size, int flags) : GraphicsOutput(host->get_engine(), host->get_pipe(), name, host->get_fb_properties(), WindowProperties::size(x_size, y_size), flags, host->get_gsg(), host, false) { #ifdef DO_MEMORY_USAGE MemoryUsage::update_type(this, this); #endif if (display_cat.is_debug()) { display_cat.debug() << "Creating new parasite buffer " << get_name() << " on " << _host->get_name() << "\n"; } _creation_flags = flags; if (flags & GraphicsPipe::BF_size_track_host) { _size = host->get_size(); } else { _size.set(x_size, y_size); } _has_size = true; _overlay_display_region->compute_pixels(_size.get_x(), _size.get_y()); _is_valid = true; set_inverted(host->get_gsg()->get_copy_texture_inverted()); } //////////////////////////////////////////////////////////////////// // Function: ParasiteBuffer::Destructor // Access: Published, Virtual // Description: //////////////////////////////////////////////////////////////////// ParasiteBuffer:: ~ParasiteBuffer() { _is_valid = false; } //////////////////////////////////////////////////////////////////// // Function: ParasiteBuffer::is_active // Access: Published, Virtual // Description: Returns true if the window is ready to be rendered // into, false otherwise. //////////////////////////////////////////////////////////////////// bool ParasiteBuffer:: is_active() const { return GraphicsOutput::is_active() && _host->is_active(); } //////////////////////////////////////////////////////////////////// // Function: ParasiteBuffer::set_size // Access: Public, Virtual // Description: This is called by the GraphicsEngine to request that // the buffer resize itself. Although calls to get the // size will return the new value, much of the actual // resizing work doesn't take place until the next // begin_frame. Not all buffers are resizeable. //////////////////////////////////////////////////////////////////// void ParasiteBuffer:: set_size(int x, int y) { if ((_creation_flags & GraphicsPipe::BF_resizeable) == 0) { nassert_raise("Cannot resize buffer unless it is created with BF_resizeable flag"); return; } set_size_and_recalc(x, y); } //////////////////////////////////////////////////////////////////// // Function: ParasiteBuffer::set_size_and_recalc // Access: Public // Description: //////////////////////////////////////////////////////////////////// void ParasiteBuffer:: set_size_and_recalc(int x, int y) { if (!(_creation_flags & GraphicsPipe::BF_size_track_host)) { if (_creation_flags & GraphicsPipe::BF_size_power_2) { x = Texture::down_to_power_2(x); y = Texture::down_to_power_2(y); } if (_creation_flags & GraphicsPipe::BF_size_square) { x = y = min(x, y); } } GraphicsOutput::set_size_and_recalc(x, y); } //////////////////////////////////////////////////////////////////// // Function: ParasiteBuffer::flip_ready // Access: Public, Virtual // Description: Returns true if a frame has been rendered and needs // to be flipped, false otherwise. //////////////////////////////////////////////////////////////////// bool ParasiteBuffer:: flip_ready() const { nassertr(_host != NULL, false); return _host->flip_ready(); } //////////////////////////////////////////////////////////////////// // Function: ParasiteBuffer::begin_flip // Access: Public, Virtual // Description: This function will be called within the draw thread // after end_frame() has been called on all windows, to // initiate the exchange of the front and back buffers. // // This should instruct the window to prepare for the // flip at the next video sync, but it should not wait. // // We have the two separate functions, begin_flip() and // end_flip(), to make it easier to flip all of the // windows at the same time. //////////////////////////////////////////////////////////////////// void ParasiteBuffer:: begin_flip() { nassertv(_host != NULL); _host->begin_flip(); } //////////////////////////////////////////////////////////////////// // Function: ParasiteBuffer::ready_flip // Access: Public, Virtual // Description: This function will be called within the draw thread // after end_frame() has been called on all windows, to // initiate the exchange of the front and back buffers. // // This should instruct the window to prepare for the // flip when it is command but not actually flip // //////////////////////////////////////////////////////////////////// void ParasiteBuffer:: ready_flip() { nassertv(_host != NULL); _host->ready_flip(); } //////////////////////////////////////////////////////////////////// // Function: ParasiteBuffer::end_flip // Access: Public, Virtual // Description: This function will be called within the draw thread // after begin_flip() has been called on all windows, to // finish the exchange of the front and back buffers. // // This should cause the window to wait for the flip, if // necessary. //////////////////////////////////////////////////////////////////// void ParasiteBuffer:: end_flip() { nassertv(_host != NULL); _host->end_flip(); _flip_ready = false; } //////////////////////////////////////////////////////////////////// // Function: ParasiteBuffer::begin_frame // Access: Public, Virtual // Description: This function will be called within the draw thread // before beginning rendering for a given frame. It // should do whatever setup is required, and return true // if the frame should be rendered, or false if it // should be skipped. //////////////////////////////////////////////////////////////////// bool ParasiteBuffer:: begin_frame(FrameMode mode, Thread *current_thread) { begin_frame_spam(mode); if (!_host->begin_frame(FM_parasite, current_thread)) { return false; } if (_creation_flags & GraphicsPipe::BF_size_track_host) { if (_host->get_size() != _size) { set_size_and_recalc(_host->get_x_size(), _host->get_y_size()); } } else { if (_host->get_x_size() < get_x_size() || _host->get_y_size() < get_y_size()) { set_size_and_recalc(min(get_x_size(), _host->get_x_size()), min(get_y_size(), _host->get_y_size())); } } clear_cube_map_selection(); return true; } //////////////////////////////////////////////////////////////////// // Function: ParasiteBuffer::end_frame // Access: Public, Virtual // Description: This function will be called within the draw thread // after rendering is completed for a given frame. It // should do whatever finalization is required. //////////////////////////////////////////////////////////////////// void ParasiteBuffer:: end_frame(FrameMode mode, Thread *current_thread) { end_frame_spam(mode); nassertv(_gsg != (GraphicsStateGuardian *)NULL); _host->end_frame(FM_parasite, current_thread); if (mode == FM_refresh) { return; } if (mode == FM_render) { promote_to_copy_texture(); copy_to_textures(); clear_cube_map_selection(); } } //////////////////////////////////////////////////////////////////// // Function: ParasiteBuffer::get_host // Access: Public, Virtual // Description: This is normally called only from within // make_texture_buffer(). When called on a // ParasiteBuffer, it returns the host of that buffer; // but when called on some other buffer, it returns the // buffer itself. //////////////////////////////////////////////////////////////////// GraphicsOutput *ParasiteBuffer:: get_host() { return _host; }
35.393822
87
0.522417
kestred
cd49f7c4a184424639af62ff5022ff61a394ae59
963
cpp
C++
0071 Simplify Path/solution.cpp
Aden-Tao/LeetCode
c34019520b5808c4251cb76f69ca2befa820401d
[ "MIT" ]
1
2019-12-19T04:13:15.000Z
2019-12-19T04:13:15.000Z
0071 Simplify Path/solution.cpp
Aden-Tao/LeetCode
c34019520b5808c4251cb76f69ca2befa820401d
[ "MIT" ]
null
null
null
0071 Simplify Path/solution.cpp
Aden-Tao/LeetCode
c34019520b5808c4251cb76f69ca2befa820401d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; class Solution { public: string simplifyPath(string path) { if (path.back() != '/') path += '/'; string res, s; for (auto &c : path) { if (res.empty()) res += c; else if (c == '/') { if (s == "..") { if (res.size() > 1) { res.pop_back(); while (res.back() != '/') res.pop_back(); } } else if (s != "" && s != ".") { res += s + '/'; } s = ""; } else { s += c; } } if (res.size() > 1) res.pop_back(); return res; } }; int main(){ assert(Solution().simplifyPath("/home//foo/") == "/home/foo"); return 0; }
22.928571
66
0.298027
Aden-Tao
cd4d1bae880e0dda4505079c61cb2fd611e8eda9
1,010
cpp
C++
src/Standard/FirstPersonCameraController.cpp
HyperionDH/Tristeon
8475df94b9dbd4e3b4cc82b89c6d4bab45acef29
[ "MIT" ]
38
2017-12-04T10:48:28.000Z
2018-05-11T09:59:41.000Z
src/Standard/FirstPersonCameraController.cpp
Tristeon/Tristeon3D
8475df94b9dbd4e3b4cc82b89c6d4bab45acef29
[ "MIT" ]
9
2017-12-04T09:58:55.000Z
2018-02-05T00:06:41.000Z
src/Standard/FirstPersonCameraController.cpp
Tristeon/Tristeon3D
8475df94b9dbd4e3b4cc82b89c6d4bab45acef29
[ "MIT" ]
3
2018-01-10T13:39:12.000Z
2018-03-17T20:53:22.000Z
#include "FirstPersonCameraController.h" #include "Core/Transform.h" #include "Misc/Hardware/Mouse.h" #include "Misc/Hardware/Time.h" #include "XPlatform/typename.h" namespace Tristeon { namespace Standard { DerivedRegister<FirstPersonCameraController> FirstPersonCameraController::reg; nlohmann::json FirstPersonCameraController::serialize() { nlohmann::json j; j["typeID"] = TRISTEON_TYPENAME(FirstPersonCameraController); j["sensitivity"] = sensitivity; return j; } void FirstPersonCameraController::deserialize(nlohmann::json json) { sensitivity = json["sensitivity"]; } void FirstPersonCameraController::start() { } void FirstPersonCameraController::update() { float const x = Misc::Mouse::getMouseDelta().x * sensitivity * Misc::Time::getDeltaTime(); float const y = Misc::Mouse::getMouseDelta().y * sensitivity * Misc::Time::getDeltaTime(); xRot -= y; yRot -= x; transform.get()->rotation = Math::Quaternion::euler(xRot, yRot, 0); } } }
24.634146
93
0.715842
HyperionDH
cd4ef064954ebd7a87d517796eeeb6d2b4f350f8
3,496
hpp
C++
include/bit/stl/utilities/detail/compiler_traits/platform/win32.hpp
bitwizeshift/bit-stl
cec555fbda2ea1b6e126fa719637dde8d3f2ddd3
[ "MIT" ]
6
2017-03-29T07:20:30.000Z
2021-12-28T20:17:33.000Z
include/bit/stl/utilities/detail/compiler_traits/platform/win32.hpp
bitwizeshift/bit-stl
cec555fbda2ea1b6e126fa719637dde8d3f2ddd3
[ "MIT" ]
6
2017-10-11T02:26:07.000Z
2018-04-16T03:09:48.000Z
include/bit/stl/utilities/detail/compiler_traits/platform/win32.hpp
bitwizeshift/bit-stl
cec555fbda2ea1b6e126fa719637dde8d3f2ddd3
[ "MIT" ]
1
2018-08-27T15:03:47.000Z
2018-08-27T15:03:47.000Z
/***************************************************************************** * \file * \brief This header detects features for Windows platforms * * \note This is an internal header file, included by other library headers. * Do not attempt to use it directly. *****************************************************************************/ /* The MIT License (MIT) Bit Standard Template Library. https://github.com/bitwizeshift/bit-stl Copyright (c) 2018 Matthew Rodusek Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef BIT_STL_UTILITIES_DETAIL_COMPILER_TRAITS_PLATFORM_WIN32_HPP #define BIT_STL_UTILITIES_DETAIL_COMPILER_TRAITS_PLATFORM_WIN32_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) //----------------------------------------------------------------------------- // Platform Detection //----------------------------------------------------------------------------- #define BIT_PLATFORM_WINDOWS 1 #if defined(__MINGW32__) || defined(__MINGW64__) # include <_mingw.h> // Include for version information # define BIT_PLATFORM_MINGW 1 #endif #if defined(_WIN64) # define BIT_PLATFORM_WIN64 1 # define BIT_PLATFORM_STRING "Windows (64-bit)" #else # define BIT_PLATFORM_WIN32 1 # define BIT_PLATFORM_STRING "Windows (32-bit)" #endif //----------------------------------------------------------------------------- // Platform Specifics Detection //----------------------------------------------------------------------------- // MinGW has some added headers not present in MSVC #if defined(__MINGW32__) && ((__MINGW32_MAJOR_VERSION > 2) || ((__MINGW32_MAJOR_VERSION == 2) && (__MINGW32_MINOR_VERSION >= 0))) # ifndef BIT_PLATFORM_HAS_STDINT_H # define BIT_PLATFORM_HAS_STDINT_H 1 # endif # ifndef BIT_PLATFORM_HAS_DIRENT_H # define BIT_PLATFORM_HAS_DIRENT_H 1 # endif # ifndef BIT_PLATFORM_HAS_UNISTD_H # define BIT_PLATFORM_HAS_UNISTD_H 1 # endif #endif // Mingw configuration specific #if !defined(BIT_PLATFORM_HAS_PTHREADS) # define BIT_PLATFORM_HAS_WINTHREADS 1 #endif #define BIT_PLATFORM_HAS_WINSOCKS 1 #define BIT_PLATFORM_HAS_ALIGNED_MALLOC 1 #define BIT_PLATFORM_HAS_ALIGNED_OFFSET_MALLOC 1 // Determine API from defined compiler args #ifdef BIT_USE_VULKAN_API # define VK_USE_PLATFORM_WIN32_KHR 1 #elif !defined(BIT_USE_OGL_API) # define BIT_USE_OGL_API 1 #endif #endif /* BIT_STL_UTILITIES_DETAIL_COMPILER_TRAITS_PLATFORM_WIN32_HPP */
36.416667
129
0.674485
bitwizeshift
cd50047445a9ddb20977d511d916509d3572e306
2,590
cc
C++
RecoTracker/ConversionSeedGenerators/plugins/CombinedHitPairGeneratorForPhotonConversion.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
13
2015-11-30T15:49:45.000Z
2022-02-08T16:11:30.000Z
RecoTracker/ConversionSeedGenerators/plugins/CombinedHitPairGeneratorForPhotonConversion.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
640
2015-02-11T18:55:47.000Z
2022-03-31T14:12:23.000Z
RecoTracker/ConversionSeedGenerators/plugins/CombinedHitPairGeneratorForPhotonConversion.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
51
2015-08-11T21:01:40.000Z
2022-03-30T07:31:34.000Z
#include "CombinedHitPairGeneratorForPhotonConversion.h" #include <memory> #include "DataFormats/Common/interface/Handle.h" #include "FWCore/Framework/interface/ConsumesCollector.h" #include "FWCore/Framework/interface/Event.h" #include "HitPairGeneratorFromLayerPairForPhotonConversion.h" #include "FWCore/Utilities/interface/RunningAverage.h" namespace { edm::RunningAverage localRA; } CombinedHitPairGeneratorForPhotonConversion::CombinedHitPairGeneratorForPhotonConversion(const edm::ParameterSet& cfg, edm::ConsumesCollector& iC) : theSeedingLayerToken(iC.consumes<SeedingLayerSetsHits>(cfg.getParameter<edm::InputTag>("SeedingLayers"))) { theMaxElement = cfg.getParameter<unsigned int>("maxElement"); maxHitPairsPerTrackAndGenerator = cfg.getParameter<unsigned int>("maxHitPairsPerTrackAndGenerator"); theGenerator = std::make_unique<HitPairGeneratorFromLayerPairForPhotonConversion>( 0, 1, &theLayerCache, 0, maxHitPairsPerTrackAndGenerator); } const OrderedHitPairs& CombinedHitPairGeneratorForPhotonConversion::run(const ConversionRegion& convRegion, const TrackingRegion& region, const edm::Event& ev, const edm::EventSetup& es) { if (thePairs.capacity() == 0) thePairs.reserve(localRA.upper()); thePairs.clear(); hitPairs(convRegion, region, thePairs, ev, es); return thePairs; } void CombinedHitPairGeneratorForPhotonConversion::hitPairs(const ConversionRegion& convRegion, const TrackingRegion& region, OrderedHitPairs& result, const edm::Event& ev, const edm::EventSetup& es) { edm::Handle<SeedingLayerSetsHits> hlayers; ev.getByToken(theSeedingLayerToken, hlayers); const SeedingLayerSetsHits& layers = *hlayers; assert(layers.numberOfLayersInSet() == 2); for (SeedingLayerSetsHits::LayerSetIndex i = 0; i < layers.size(); ++i) { theGenerator->hitPairs(convRegion, region, result, layers[i], ev, es); } } void CombinedHitPairGeneratorForPhotonConversion::clearCache() { theLayerCache.clear(); localRA.update(thePairs.size()); thePairs.clear(); thePairs.shrink_to_fit(); }
46.25
118
0.62471
ckamtsikis
cd514616c26370ef50c18d6a6d50839b7315a62d
29,991
cc
C++
research/syntaxnet/syntaxnet/char_properties.cc
zcdzcdzcd/models
a31b526a7617a152a138a865b5689bf5b59f655d
[ "Apache-2.0" ]
3,326
2018-01-26T22:42:25.000Z
2022-02-16T13:16:39.000Z
research/syntaxnet/syntaxnet/char_properties.cc
zcdzcdzcd/models
a31b526a7617a152a138a865b5689bf5b59f655d
[ "Apache-2.0" ]
150
2017-08-28T14:59:36.000Z
2022-03-11T23:21:35.000Z
research/syntaxnet/syntaxnet/char_properties.cc
zcdzcdzcd/models
a31b526a7617a152a138a865b5689bf5b59f655d
[ "Apache-2.0" ]
1,474
2018-02-01T04:33:18.000Z
2022-03-08T07:02:20.000Z
/* Copyright 2016 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // char_properties.cc - define is_X() tests for various character properties // // See char_properties.h for how to write a character property. // // References for the char sets below: // // . http://www.unicode.org/Public/UNIDATA/PropList.txt // // Large (but not exhaustive) list of Unicode chars and their "properties" // (e.g., the property "Pi" = an initial quote punctuation char). // // . http://www.unicode.org/Public/UNIDATA/PropertyValueAliases.txt // // Defines the list of properties, such as "Pi", used in the above list. // // . http://www.unipad.org/unimap/index.php?param_char=XXXX&page=detail // // Gives detail about a particular character code. // XXXX is a 4-hex-digit Unicode character code. // // . http://www.unicode.org/Public/UNIDATA/UCD.html // // General reference for Unicode characters. // #include "syntaxnet/char_properties.h" #include <ctype.h> // for ispunct, isspace #include <memory> #include <utility> #include <vector> // for vector #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/strings/stringprintf.h" #include "third_party/utf/utf.h" // for runetochar, ::UTFmax, Rune #include "util/utf8/unilib.h" // for IsValidCodepoint, etc #include "util/utf8/unilib_utf8_utils.h" //============================================================ // CharPropertyImplementation // // A CharPropertyImplementation stores a set of Unicode characters, // encoded in UTF-8, as a trie. The trie is represented as a vector // of nodes. Each node is a 256-element array that specifies what to // do with one byte of the UTF-8 sequence. Each element n of a node // is one of: // n = 0, indicating that the Property is not true of any // character whose UTF-8 encoding includes this byte at // this position // n = -1, indicating that the Property is true for the UTF-8 sequence // that ends with this byte. // n > 0, indicating the index of the row that describes the // remaining bytes in the UTF-8 sequence. // // The only operation that needs to be fast is HoldsFor, which tests // whether a character has a given property. We use each byte of the // character's UTF-8 encoding to index into a row. If the value is 0, // then the property is not true for the character. (We might discover // this even before getting to the end of the sequence.) If the value // is -1, then the property is true for this character. Otherwise, // the value is the index of another row, which we index using the next // byte in the sequence, and so on. The design of UTF-8 prevents // ambiguities here; no prefix of a UTF-8 sequence is a valid UTF-8 // sequence. // // While it is possible to implement an iterator for this representation, // it is much easier to use set<char32> for this purpose. In fact, we // would use that as the entire representation, were it not for concerns // that HoldsFor might be slower. namespace syntaxnet { struct CharPropertyImplementation { unordered_set<char32> chars; std::vector<std::vector<int> > rows; CharPropertyImplementation() { rows.reserve(10); rows.resize(1); rows[0].resize(256, 0); } void AddChar(char *buf, int len) { int n = 0; // row index for (int i = 0; i < len; ++i) { int ch = reinterpret_cast<unsigned char *>(buf)[i]; int m = rows[n][ch]; if (m > 0) { CHECK_LT(i, len - 1) << " : " << (i + 1) << "-byte UTF-8 sequence " << "(" << tensorflow::str_util::CEscape(string(buf, i + 1)) << ")" << " is prefix of previously-seen UTF-8 sequence(s)"; n = m; } else if (i == len - 1) { rows[n][ch] = -1; } else { CHECK_EQ(m, 0) << " : UTF-8 sequence is extension of previously-seen " << (i + 1) << "-byte UTF-8 sequence " << "(" << tensorflow::str_util::CEscape(string(buf, i + 1)) << ")"; int a = rows.size(); rows.resize(a + 1); rows[a].resize(256, 0); rows[n][ch] = a; n = a; } } } bool HoldsFor(const char *buf) const { const unsigned char *bytes = reinterpret_cast<const unsigned char *>(buf); // Lookup each byte of the UTF-8 sequence, starting in row 0. int n = rows[0][*bytes]; if (n == 0) return false; if (n == -1) return true; // If the value is not 0 or -1, then it is the index of the row for the // second byte in the sequence. n = rows[n][*++bytes]; if (n == 0) return false; if (n == -1) return true; n = rows[n][*++bytes]; // Likewise for the third byte. if (n == 0) return false; if (n == -1) return true; n = rows[n][*++bytes]; // Likewise for the fourth byte. if (n == 0) return false; // Since there can be at most 4 bytes in the sequence, n must be -1. return true; // Implementation note: it is possible (and perhaps clearer) to write this // code as a loop, "for (int i = 0; i < 4; ++i) ...", but the TestHoldsFor // benchmark results indicate that doing so produces slower code for // anything other than short 7-bit ASCII strings (< 512 bytes). This is // mysterious, since the compiler unrolls the loop, producing code that // is almost the same as what we have here, except for the shortcut on // the 4th byte. } }; //============================================================ // CharProperty - a property that holds for selected Unicode chars // CharProperty::CharProperty(const char *name, const int *unicodes, int num_unicodes) : name_(name), impl_(new CharPropertyImplementation) { // Initialize CharProperty to its char set. AddCharSpec(unicodes, num_unicodes); } CharProperty::CharProperty(const char *name, CharPropertyInitializer *init_fn) : name_(name), impl_(new CharPropertyImplementation) { (*init_fn)(this); } CharProperty::~CharProperty() { delete impl_; } void CharProperty::AddChar(int c) { CheckUnicodeVal(c); impl_->chars.insert(c); char buf[UTFmax]; Rune r = c; int len = runetochar(buf, &r); impl_->AddChar(buf, len); } void CharProperty::AddCharRange(int c1, int c2) { for (int c = c1; c <= c2; ++c) { AddChar(c); } } void CharProperty::AddAsciiPredicate(AsciiPredicate *pred) { for (int c = 0; c < 256; ++c) { if ((*pred)(c)) { AddChar(c); } } } void CharProperty::AddCharProperty(const char *propname) { const CharProperty *prop = CharProperty::Lookup(propname); CHECK(prop != nullptr) << ": unknown char property \"" << propname << "\" in " << name_; int c = -1; while ((c = prop->NextElementAfter(c)) >= 0) { AddChar(c); } } void CharProperty::AddCharSpec(const int *unicodes, int num_unicodes) { for (int i = 0; i < num_unicodes; ++i) { if (i + 3 < num_unicodes && unicodes[i] == kPreUnicodeRange && unicodes[i + 3] == kPostUnicodeRange) { // Range of unicode values int lower = unicodes[i + 1]; int upper = unicodes[i + 2]; i += 3; // i will be incremented once more at top of loop CHECK(lower <= upper) << ": invalid char range in " << name_ << ": [" << UnicodeToString(lower) << ", " << UnicodeToString(upper) << "]"; AddCharRange(lower, upper); } else { AddChar(unicodes[i]); } } } bool CharProperty::HoldsFor(int c) const { if (!UniLib::IsValidCodepoint(c)) return false; char buf[UTFmax]; Rune r = c; runetochar(buf, &r); return impl_->HoldsFor(buf); } bool CharProperty::HoldsFor(const char *str, int len) const { // UniLib::IsUTF8ValidCodepoint also checks for structural validity. return len > 0 && UniLib::IsUTF8ValidCodepoint(StringPiece(str, len)) && impl_->HoldsFor(str); } // Return -1 or the smallest Unicode char greater than c for which // the CharProperty holds. Expects c == -1 or HoldsFor(c). int CharProperty::NextElementAfter(int c) const { DCHECK(c == -1 || HoldsFor(c)); unordered_set<char32>::const_iterator end = impl_->chars.end(); if (c < 0) { unordered_set<char32>::const_iterator it = impl_->chars.begin(); if (it == end) return -1; return *it; } char32 r = c; unordered_set<char32>::const_iterator it = impl_->chars.find(r); if (it == end) return -1; it++; if (it == end) return -1; return *it; } REGISTER_SYNTAXNET_CLASS_REGISTRY("char property wrapper", CharPropertyWrapper); const CharProperty *CharProperty::Lookup(const char *subclass) { // Create a CharPropertyWrapper object and delete it. We only care about // the CharProperty it provides. std::unique_ptr<CharPropertyWrapper> wrapper( CharPropertyWrapper::Create(subclass)); if (wrapper == nullptr) { LOG(ERROR) << "CharPropertyWrapper not found for subclass: " << "\"" << subclass << "\""; return nullptr; } return wrapper->GetCharProperty(); } // Check that a given Unicode value is in range. void CharProperty::CheckUnicodeVal(int c) const { CHECK(UniLib::IsValidCodepoint(c)) << "Unicode in " << name_ << " out of range: " << UnicodeToString(c); } // Converts a Unicode value to a string (for error messages). string CharProperty::UnicodeToString(int c) { const char *fmt; if (c < 0) { fmt = "%d"; // out-of-range } else if (c <= 0x7f) { fmt = "'%c'"; // ascii } else if (c <= 0xffff) { fmt = "0x%04X"; // 4 hex digits } else { fmt = "0x%X"; // also out-of-range } return tensorflow::strings::Printf(fmt, c); } //====================================================================== // Expression-level punctuation // // Punctuation that starts a sentence. DEFINE_CHAR_PROPERTY_AS_SET(start_sentence_punc, 0x00A1, // Spanish inverted exclamation mark 0x00BF, // Spanish inverted question mark ) // Punctuation that ends a sentence. // Based on: http://www.unicode.org/unicode/reports/tr29/#Sentence_Boundaries DEFINE_CHAR_PROPERTY_AS_SET(end_sentence_punc, '.', '!', '?', 0x055C, // Armenian exclamation mark 0x055E, // Armenian question mark 0x0589, // Armenian full stop 0x061F, // Arabic question mark 0x06D4, // Arabic full stop 0x0700, // Syriac end of paragraph 0x0701, // Syriac supralinear full stop 0x0702, // Syriac sublinear full stop RANGE(0x0964, 0x0965), // Devanagari danda..Devanagari double danda 0x1362, // Ethiopic full stop 0x1367, // Ethiopic question mark 0x1368, // Ethiopic paragraph separator 0x104A, // Myanmar sign little section 0x104B, // Myanmar sign section 0x166E, // Canadian syllabics full stop 0x17d4, // Khmer sign khan 0x1803, // Mongolian full stop 0x1809, // Mongolian Manchu full stop 0x1944, // Limbu exclamation mark 0x1945, // Limbu question mark 0x203C, // double exclamation mark 0x203D, // interrobang 0x2047, // double question mark 0x2048, // question exclamation mark 0x2049, // exclamation question mark 0x3002, // ideographic full stop 0x037E, // Greek question mark 0xFE52, // small full stop 0xFE56, // small question mark 0xFE57, // small exclamation mark 0xFF01, // fullwidth exclamation mark 0xFF0E, // fullwidth full stop 0xFF1F, // fullwidth question mark 0xFF61, // halfwidth ideographic full stop 0x2026, // ellipsis ) // Punctuation, such as parens, that opens a "nested expression" of text. DEFINE_CHAR_PROPERTY_AS_SET(open_expr_punc, '(', '[', '<', '{', 0x207D, // superscript left parenthesis 0x208D, // subscript left parenthesis 0x27E6, // mathematical left white square bracket 0x27E8, // mathematical left angle bracket 0x27EA, // mathematical left double angle bracket 0x2983, // left white curly bracket 0x2985, // left white parenthesis 0x2987, // Z notation left image bracket 0x2989, // Z notation left binding bracket 0x298B, // left square bracket with underbar 0x298D, // left square bracket with tick in top corner 0x298F, // left square bracket with tick in bottom corner 0x2991, // left angle bracket with dot 0x2993, // left arc less-than bracket 0x2995, // double left arc greater-than bracket 0x2997, // left black tortoise shell bracket 0x29D8, // left wiggly fence 0x29DA, // left double wiggly fence 0x29FC, // left-pointing curved angle bracket 0x3008, // CJK left angle bracket 0x300A, // CJK left double angle bracket 0x3010, // CJK left black lenticular bracket 0x3014, // CJK left tortoise shell bracket 0x3016, // CJK left white lenticular bracket 0x3018, // CJK left white tortoise shell bracket 0x301A, // CJK left white square bracket 0xFD3E, // Ornate left parenthesis 0xFE59, // small left parenthesis 0xFE5B, // small left curly bracket 0xFF08, // fullwidth left parenthesis 0xFF3B, // fullwidth left square bracket 0xFF5B, // fullwidth left curly bracket ) // Punctuation, such as parens, that closes a "nested expression" of text. DEFINE_CHAR_PROPERTY_AS_SET(close_expr_punc, ')', ']', '>', '}', 0x207E, // superscript right parenthesis 0x208E, // subscript right parenthesis 0x27E7, // mathematical right white square bracket 0x27E9, // mathematical right angle bracket 0x27EB, // mathematical right double angle bracket 0x2984, // right white curly bracket 0x2986, // right white parenthesis 0x2988, // Z notation right image bracket 0x298A, // Z notation right binding bracket 0x298C, // right square bracket with underbar 0x298E, // right square bracket with tick in top corner 0x2990, // right square bracket with tick in bottom corner 0x2992, // right angle bracket with dot 0x2994, // right arc greater-than bracket 0x2996, // double right arc less-than bracket 0x2998, // right black tortoise shell bracket 0x29D9, // right wiggly fence 0x29DB, // right double wiggly fence 0x29FD, // right-pointing curved angle bracket 0x3009, // CJK right angle bracket 0x300B, // CJK right double angle bracket 0x3011, // CJK right black lenticular bracket 0x3015, // CJK right tortoise shell bracket 0x3017, // CJK right white lenticular bracket 0x3019, // CJK right white tortoise shell bracket 0x301B, // CJK right white square bracket 0xFD3F, // Ornate right parenthesis 0xFE5A, // small right parenthesis 0xFE5C, // small right curly bracket 0xFF09, // fullwidth right parenthesis 0xFF3D, // fullwidth right square bracket 0xFF5D, // fullwidth right curly bracket ) // Chars that open a quotation. // Based on: http://www.unicode.org/uni2book/ch06.pdf DEFINE_CHAR_PROPERTY_AS_SET(open_quote, '"', '\'', '`', 0xFF07, // fullwidth apostrophe 0xFF02, // fullwidth quotation mark 0x2018, // left single quotation mark (English, others) 0x201C, // left double quotation mark (English, others) 0x201B, // single high-reveresed-9 quotation mark (PropList.txt) 0x201A, // single low-9 quotation mark (Czech, German, Slovak) 0x201E, // double low-9 quotation mark (Czech, German, Slovak) 0x201F, // double high-reversed-9 quotation mark (PropList.txt) 0x2019, // right single quotation mark (Danish, Finnish, Swedish, Norw.) 0x201D, // right double quotation mark (Danish, Finnish, Swedish, Norw.) 0x2039, // single left-pointing angle quotation mark (French, others) 0x00AB, // left-pointing double angle quotation mark (French, others) 0x203A, // single right-pointing angle quotation mark (Slovenian, others) 0x00BB, // right-pointing double angle quotation mark (Slovenian, others) 0x300C, // left corner bracket (East Asian languages) 0xFE41, // presentation form for vertical left corner bracket 0xFF62, // halfwidth left corner bracket (East Asian languages) 0x300E, // left white corner bracket (East Asian languages) 0xFE43, // presentation form for vertical left white corner bracket 0x301D, // reversed double prime quotation mark (East Asian langs, horiz.) ) // Chars that close a quotation. // Based on: http://www.unicode.org/uni2book/ch06.pdf DEFINE_CHAR_PROPERTY_AS_SET(close_quote, '\'', '"', '`', 0xFF07, // fullwidth apostrophe 0xFF02, // fullwidth quotation mark 0x2019, // right single quotation mark (English, others) 0x201D, // right double quotation mark (English, others) 0x2018, // left single quotation mark (Czech, German, Slovak) 0x201C, // left double quotation mark (Czech, German, Slovak) 0x203A, // single right-pointing angle quotation mark (French, others) 0x00BB, // right-pointing double angle quotation mark (French, others) 0x2039, // single left-pointing angle quotation mark (Slovenian, others) 0x00AB, // left-pointing double angle quotation mark (Slovenian, others) 0x300D, // right corner bracket (East Asian languages) 0xfe42, // presentation form for vertical right corner bracket 0xFF63, // halfwidth right corner bracket (East Asian languages) 0x300F, // right white corner bracket (East Asian languages) 0xfe44, // presentation form for vertical right white corner bracket 0x301F, // low double prime quotation mark (East Asian languages) 0x301E, // close double prime (East Asian languages written horizontally) ) // Punctuation chars that open an expression or a quotation. DEFINE_CHAR_PROPERTY(open_punc, prop) { prop->AddCharProperty("open_expr_punc"); prop->AddCharProperty("open_quote"); } // Punctuation chars that close an expression or a quotation. DEFINE_CHAR_PROPERTY(close_punc, prop) { prop->AddCharProperty("close_expr_punc"); prop->AddCharProperty("close_quote"); } // Punctuation chars that can come at the beginning of a sentence. DEFINE_CHAR_PROPERTY(leading_sentence_punc, prop) { prop->AddCharProperty("open_punc"); prop->AddCharProperty("start_sentence_punc"); } // Punctuation chars that can come at the end of a sentence. DEFINE_CHAR_PROPERTY(trailing_sentence_punc, prop) { prop->AddCharProperty("close_punc"); prop->AddCharProperty("end_sentence_punc"); } //====================================================================== // Special symbols // // Currency symbols. // From: http://www.unicode.org/charts/PDF/U20A0.pdf DEFINE_CHAR_PROPERTY_AS_SET(currency_symbol, '$', // 0x00A2, // cents (NB: typically FOLLOWS the amount) 0x00A3, // pounds and liras 0x00A4, // general currency sign 0x00A5, // yen or yuan 0x0192, // Dutch florin (latin small letter "f" with hook) 0x09F2, // Bengali rupee mark 0x09F3, // Bengali rupee sign 0x0AF1, // Guajarati rupee sign 0x0BF9, // Tamil rupee sign 0x0E3F, // Thai baht 0x17DB, // Khmer riel 0x20A0, // alternative euro sign 0x20A1, // Costa Rica, El Salvador (colon sign) 0x20A2, // Brazilian cruzeiro 0x20A3, // French Franc 0x20A4, // alternative lira sign 0x20A5, // mill sign (USA 1/10 cent) 0x20A6, // Nigerian Naira 0x20A7, // Spanish peseta 0x20A8, // Indian rupee 0x20A9, // Korean won 0x20AA, // Israeli new sheqel 0x20AB, // Vietnam dong 0x20AC, // euro sign 0x20AD, // Laotian kip 0x20AE, // Mongolian tugrik 0x20AF, // Greek drachma 0x20B0, // German penny 0x20B1, // Philippine peso (Mexican peso uses "$") 0x2133, // Old German mark (script capital M) 0xFDFC, // rial sign 0xFFE0, // fullwidth cents 0xFFE1, // fullwidth pounds 0xFFE5, // fullwidth Japanese yen 0xFFE6, // fullwidth Korean won ) // Chinese bookquotes. // They look like "<<" and ">>" except that they are single UTF8 chars // (U+300A, U+300B). These are used in chinese as special // punctuation, refering to the title of a book, an article, a movie, // etc. For example: "cellphone" means cellphone, but <<cellphone>> // means (exclusively) the movie. DEFINE_CHAR_PROPERTY_AS_SET(open_bookquote, 0x300A ) DEFINE_CHAR_PROPERTY_AS_SET(close_bookquote, 0x300B ) //====================================================================== // Token-level punctuation // // Token-prefix symbols, excluding currency symbols -- glom on // to following token (esp. if no space after) DEFINE_CHAR_PROPERTY_AS_SET(noncurrency_token_prefix_symbol, '#', 0x2116, // numero sign ("No") ) // Token-prefix symbols -- glom on to following token (esp. if no space after) DEFINE_CHAR_PROPERTY(token_prefix_symbol, prop) { prop->AddCharProperty("currency_symbol"); prop->AddCharProperty("noncurrency_token_prefix_symbol"); } // Token-suffix symbols -- glom on to preceding token (esp. if no space before) DEFINE_CHAR_PROPERTY_AS_SET(token_suffix_symbol, '%', 0x066A, // Arabic percent sign 0x2030, // per mille 0x2031, // per ten thousand 0x00A2, // cents sign 0x2125, // ounces sign 0x00AA, // feminine ordinal indicator (Spanish) 0x00BA, // masculine ordinal indicator (Spanish) 0x00B0, // degrees 0x2109, // degrees Fahrenheit 0x2103, // degrees Celsius 0x2126, // ohms 0x212A, // Kelvin 0x212B, // Angstroms ("A" with circle on top) 0x00A9, // copyright 0x2117, // sound recording copyright (circled "P") 0x2122, // trade mark 0x00AE, // registered trade mark 0x2120, // service mark 0x2106, // cada una ("c/a" == "each" in Spanish) 0x2020, // dagger (can be used for footnotes) 0x2021, // double dagger (can be used for footnotes) ) // Subscripts DEFINE_CHAR_PROPERTY_AS_SET(subscript_symbol, 0x2080, // subscript 0 0x2081, // subscript 1 0x2082, // subscript 2 0x2083, // subscript 3 0x2084, // subscript 4 0x2085, // subscript 5 0x2086, // subscript 6 0x2087, // subscript 7 0x2088, // subscript 8 0x2089, // subscript 9 0x208A, // subscript "+" 0x208B, // subscript "-" 0x208C, // subscript "=" 0x208D, // subscript "(" 0x208E, // subscript ")" ) // Superscripts DEFINE_CHAR_PROPERTY_AS_SET(superscript_symbol, 0x2070, // superscript 0 0x00B9, // superscript 1 0x00B2, // superscript 2 0x00B3, // superscript 3 0x2074, // superscript 4 0x2075, // superscript 5 0x2076, // superscript 6 0x2077, // superscript 7 0x2078, // superscript 8 0x2079, // superscript 9 0x2071, // superscript Latin small "i" 0x207A, // superscript "+" 0x207B, // superscript "-" 0x207C, // superscript "=" 0x207D, // superscript "(" 0x207E, // superscript ")" 0x207F, // superscript Latin small "n" ) //====================================================================== // General punctuation // // Connector punctuation // Code Pc from http://www.unicode.org/Public/UNIDATA/PropList.txt // NB: This list is not necessarily exhaustive. DEFINE_CHAR_PROPERTY_AS_SET(connector_punc, 0x30fb, // Katakana middle dot 0xff65, // halfwidth Katakana middle dot 0x2040, // character tie ) // Dashes // Code Pd from http://www.unicode.org/Public/UNIDATA/PropList.txt // NB: This list is not necessarily exhaustive. DEFINE_CHAR_PROPERTY_AS_SET(dash_punc, '-', '~', 0x058a, // Armenian hyphen 0x1806, // Mongolian todo soft hyphen RANGE(0x2010, 0x2015), // hyphen..horizontal bar 0x2053, // swung dash -- from Table 6-3 of Unicode book 0x207b, // superscript minus 0x208b, // subscript minus 0x2212, // minus sign 0x301c, // wave dash 0x3030, // wavy dash RANGE(0xfe31, 0xfe32), // presentation form for vertical em dash..en dash 0xfe58, // small em dash 0xfe63, // small hyphen-minus 0xff0d, // fullwidth hyphen-minus ) // Other punctuation // Code Po from http://www.unicode.org/Public/UNIDATA/UnicodeData.txt // NB: This list is not exhaustive. DEFINE_CHAR_PROPERTY_AS_SET(other_punc, ',', ':', ';', 0x00b7, // middle dot 0x0387, // Greek ano teleia 0x05c3, // Hebrew punctuation sof pasuq 0x060c, // Arabic comma 0x061b, // Arabic semicolon 0x066b, // Arabic decimal separator 0x066c, // Arabic thousands separator RANGE(0x0703, 0x70a), // Syriac contraction and others 0x070c, // Syric harklean metobelus 0x0e5a, // Thai character angkhankhu 0x0e5b, // Thai character khomut 0x0f08, // Tibetan mark sbrul shad RANGE(0x0f0d, 0x0f12), // Tibetan mark shad..Tibetan mark rgya gram shad 0x1361, // Ethiopic wordspace RANGE(0x1363, 0x1366), // other Ethiopic chars 0x166d, // Canadian syllabics chi sign RANGE(0x16eb, 0x16ed), // Runic single punctuation..Runic cross punctuation RANGE(0x17d5, 0x17d6), // Khmer sign camnuc pii huuh and other 0x17da, // Khmer sign koomut 0x1802, // Mongolian comma RANGE(0x1804, 0x1805), // Mongolian four dots and other 0x1808, // Mongolian manchu comma 0x3001, // ideographic comma RANGE(0xfe50, 0xfe51), // small comma and others RANGE(0xfe54, 0xfe55), // small semicolon and other 0xff0c, // fullwidth comma RANGE(0xff0e, 0xff0f), // fullwidth stop..fullwidth solidus RANGE(0xff1a, 0xff1b), // fullwidth colon..fullwidth semicolon 0xff64, // halfwidth ideographic comma 0x2016, // double vertical line RANGE(0x2032, 0x2034), // prime..triple prime 0xfe61, // small asterisk 0xfe68, // small reverse solidus 0xff3c, // fullwidth reverse solidus ) // All punctuation. // Code P from http://www.unicode.org/Public/UNIDATA/PropList.txt // NB: This list is not necessarily exhaustive. DEFINE_CHAR_PROPERTY(punctuation, prop) { prop->AddCharProperty("open_punc"); prop->AddCharProperty("close_punc"); prop->AddCharProperty("leading_sentence_punc"); prop->AddCharProperty("trailing_sentence_punc"); prop->AddCharProperty("connector_punc"); prop->AddCharProperty("dash_punc"); prop->AddCharProperty("other_punc"); prop->AddAsciiPredicate(&ispunct); } //====================================================================== // Separators // // Line separators // Code Zl from http://www.unicode.org/Public/UNIDATA/PropList.txt // NB: This list is not necessarily exhaustive. DEFINE_CHAR_PROPERTY_AS_SET(line_separator, 0x2028, // line separator ) // Paragraph separators // Code Zp from http://www.unicode.org/Public/UNIDATA/PropList.txt // NB: This list is not necessarily exhaustive. DEFINE_CHAR_PROPERTY_AS_SET(paragraph_separator, 0x2029, // paragraph separator ) // Space separators // Code Zs from http://www.unicode.org/Public/UNIDATA/PropList.txt // NB: This list is not necessarily exhaustive. DEFINE_CHAR_PROPERTY_AS_SET(space_separator, 0x0020, // space 0x00a0, // no-break space 0x1680, // Ogham space mark 0x180e, // Mongolian vowel separator RANGE(0x2000, 0x200a), // en quad..hair space 0x202f, // narrow no-break space 0x205f, // medium mathematical space 0x3000, // ideographic space // Google additions 0xe5e5, // "private" char used as space in Chinese ) // Separators -- all line, paragraph, and space separators. // Code Z from http://www.unicode.org/Public/UNIDATA/PropList.txt // NB: This list is not necessarily exhaustive. DEFINE_CHAR_PROPERTY(separator, prop) { prop->AddCharProperty("line_separator"); prop->AddCharProperty("paragraph_separator"); prop->AddCharProperty("space_separator"); prop->AddAsciiPredicate(&isspace); } //====================================================================== // Alphanumeric Characters // // Digits DEFINE_CHAR_PROPERTY_AS_SET(digit, RANGE('0', '9'), RANGE(0x0660, 0x0669), // Arabic-Indic digits RANGE(0x06F0, 0x06F9), // Eastern Arabic-Indic digits ) //====================================================================== // Japanese Katakana // DEFINE_CHAR_PROPERTY_AS_SET(katakana, 0x3099, // COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK 0x309A, // COMBINING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK 0x309B, // KATAKANA-HIRAGANA VOICED SOUND MARK 0x309C, // KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK RANGE(0x30A0, 0x30FF), // Fullwidth Katakana RANGE(0xFF65, 0xFF9F), // Halfwidth Katakana ) //====================================================================== // BiDi Directional Formatting Codes // // See http://www.unicode.org/reports/tr9/ for a description of Bidi // and http://www.unicode.org/charts/PDF/U2000.pdf for the character codes. DEFINE_CHAR_PROPERTY_AS_SET(directional_formatting_code, 0x200E, // LRM (Left-to-Right Mark) 0x200F, // RLM (Right-to-Left Mark) 0x202A, // LRE (Left-to-Right Embedding) 0x202B, // RLE (Right-to-Left Embedding) 0x202C, // PDF (Pop Directional Format) 0x202D, // LRO (Left-to-Right Override) 0x202E, // RLO (Right-to-Left Override) ) //====================================================================== // Special collections // // NB: This does not check for all punctuation and symbols in the // standard; just those listed in our code. See the definitions in // char_properties.cc DEFINE_CHAR_PROPERTY(punctuation_or_symbol, prop) { prop->AddCharProperty("punctuation"); prop->AddCharProperty("subscript_symbol"); prop->AddCharProperty("superscript_symbol"); prop->AddCharProperty("token_prefix_symbol"); prop->AddCharProperty("token_suffix_symbol"); } } // namespace syntaxnet
35.408501
80
0.661265
zcdzcdzcd
cd5175264eeaf261eed1956dba071251b8e5418c
3,924
cpp
C++
ParticleShooter/Polygon.cpp
fuzzwaz/ParticleShooter
9165f5142d797b223e73d145de80317b1fdababf
[ "Apache-2.0" ]
1
2021-09-10T00:44:09.000Z
2021-09-10T00:44:09.000Z
Fuzzy2D/Polygon.cpp
fuzzwaz/Fuzzy2D-Game-Engine
1258bb0268a5be5925ce31f7c7edbdcf87eb27c2
[ "Apache-2.0" ]
null
null
null
Fuzzy2D/Polygon.cpp
fuzzwaz/Fuzzy2D-Game-Engine
1258bb0268a5be5925ce31f7c7edbdcf87eb27c2
[ "Apache-2.0" ]
null
null
null
#include "Common.h" #include "Polygon.h" #include "Vector2.h" Polygon::Polygon() { _vertices.reset(new std::vector<Vector2>()); _perpendiculars.reset(new std::vector<Vector2>()); } void Polygon::operator=(const Polygon& source) { if (this == &source) return; _vertices->clear(); _perpendiculars->clear(); _vertices->insert(_vertices->end(), source._vertices->cbegin(), source._vertices->cend()); _perpendiculars->insert(_perpendiculars->end(), source._perpendiculars->cbegin(), source._perpendiculars->cend()); } void Polygon::AddVertexPoint(float x, float y) { AddVertexPoint(Vector2(x, y)); } void Polygon::AddVertexPoint(const Vector2& vertex) { _vertices->push_back(vertex); _numOfVertices++; _dirtyPerpendiculars = true; //New vertex means a new edge has been added. Perpendiculars need to be recalculated RecalculateCenterPoint(); } void Polygon::AddVertexPoint(const std::vector<Vector2>& vertices) { for (auto it = vertices.begin(); it != vertices.end(); it++) { AddVertexPoint(*it); } } /* Description: A getter which can trigger a Perpendicular recalculation if marked as dirty Returns: shared_ptr<vector<Vector2>> - Pointer to the cached perpendiculars for this Collider */ const std::shared_ptr<const std::vector<Vector2>> Polygon::GetPerpendiculars() const { if (_dirtyPerpendiculars) { RecalculatePerpendicularVectors(); } return _perpendiculars; } /* Description: Rotates each vertex point by "degrees" degrees clockwise. Sets the dirty flag for perpendiculars. Arguments: degrees - Clockwise rotatation */ void Polygon::Rotate(float degrees) { const float radians = CommonHelpers::DegToRad(degrees); for (int i = 0; i < _vertices->size(); i++) { float newX = (_vertices->at(i).x * cos(radians)) + (_vertices->at(i).y * sin(radians) * -1); float newY = (_vertices->at(i).x * sin(radians)) + (_vertices->at(i).y * cos(radians)); _vertices->at(i).x = newX; _vertices->at(i).y = newY; } if (degrees != 0) _dirtyPerpendiculars = true; } /* Description: Resets the current Perpendicular list. Goes through each edge in the polygon and calculates a clockwise perpendicular vector. Adds that vector to _perpendiculars. Clears the dirty flag */ void Polygon::RecalculatePerpendicularVectors() const { _perpendiculars->clear(); if (_vertices->size() >= 2) { for (int i = 0; i < _vertices->size() - 1; i++) { _perpendiculars->push_back(ClockwisePerpendicularVector(_vertices->at(i), _vertices->at(i + 1))); } //Wrap the last vertex to the first for the final polygon perpendicular _perpendiculars->push_back(ClockwisePerpendicularVector(_vertices->at(_vertices->size() - 1), _vertices->at(0))); } _dirtyPerpendiculars = false; } void Polygon::RecalculateCenterPoint() { float minX = INT_MAX, minY = INT_MAX; float maxX = INT_MIN, maxY = INT_MIN; for (int i = 0; i < _vertices->size(); i++) { Vector2 vertex(_vertices->at(i)); if (vertex.x < minX) minX = vertex.x; if (vertex.x > maxX) maxX = vertex.x; if (vertex.y < minY) minY = vertex.y; if (vertex.y > maxY) maxY = vertex.y; } Vector2 sizeVector(maxX - minX, maxY - minY); _center.x = (sizeVector.x / 2) + minX; _center.y = (sizeVector.y / 2) + minY; } Vector2 ClockwisePerpendicularVector(const Vector2& pointA, const Vector2& pointB) { const Vector2 clockwiseVector(pointB.x - pointA.x, pointB.y - pointA.y); return ClockwisePerpendicularVector(clockwiseVector); } Vector2 ClockwisePerpendicularVector(const Vector2& vector) { return Vector2(vector.y, -1 * vector.x); } Vector2 CounterClockwisePerpendicularVector(const Vector2& pointA, const Vector2& pointB) { const Vector2 counterClockwiseVector(pointB.x - pointA.x, pointB.y - pointA.y); return CounterClockwisePerpendicularVector(counterClockwiseVector); } Vector2 CounterClockwisePerpendicularVector(const Vector2& vector) { return Vector2(-1 * vector.y, vector.x); }
25.480519
115
0.717635
fuzzwaz
cd5192159d2d380d6bb84e44bfdf7fbeccf894f7
1,695
cc
C++
src/FractalStruct/force_at_particle.cc
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/FractalStruct/force_at_particle.cc
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/FractalStruct/force_at_particle.cc
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
#include "libs.hh" #include "classes.hh" #include "headers.hh" namespace FractalSpace { void force_at_particle(Group& group, Fractal& fractal,const bool& conserve) { fractal.timing(-1,8); ofstream& FileFractal=fractal.p_file->DUMPS; vector <double> dens(8); vector <double> weights(8); vector <double> pott(8); vector <double> f_x(8); vector <double> f_y(8); vector <double> f_z(8); vector <double> sum_pf(4); Group* p_group=&group; double d_x,d_y,d_z; vector <double> pos(3); double d_inv=pow(2.0,group.get_level()-fractal.get_level_max()); const double scale=(double)(fractal.get_grid_length()*Misc::pow(2,fractal.get_level_max())); // for(auto &p : group.list_points) { Point& point=*p; if(point.list_particles.empty()) continue; bool not_yet=true; for(auto &part : point.list_particles) { Particle& particle=*part; if(!particle.get_real_particle()) continue; if(particle.get_p_highest_level_group() != 0) { if(conserve || p_group == particle.get_p_highest_level_group()) { if(not_yet) { point.get_field_values(pott,f_x,f_y,f_z); not_yet=false; } // particle.get_pos(pos); point.get_deltas(pos,d_x,d_y,d_z,scale,d_inv); Misc::set_weights(weights,d_x,d_y,d_z); Misc::sum_prod<double>(0,7,1,sum_pf,weights,pott,f_x,f_y,f_z); particle.set_field_pf(sum_pf); if(sum_pf[0]*sum_pf[1]*sum_pf[2]*sum_pf[3] ==0.0) particle.dump(FileFractal,pott,f_x,f_y,f_z); } } else { particle.dump(FileFractal); particle.set_field_pf(0.0); } } } fractal.timing(1,8); } }
27.33871
97
0.632448
jmikeowen
cd5233f448b5bbb7254076384c8aafb1a319ddc0
2,195
cc
C++
chrome/browser/chromeos/login/easy_unlock/easy_unlock_user_login_flow.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/chromeos/login/easy_unlock/easy_unlock_user_login_flow.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/chromeos/login/easy_unlock/easy_unlock_user_login_flow.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_user_login_flow.h" #include "base/metrics/histogram_macros.h" #include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_service.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" namespace chromeos { EasyUnlockUserLoginFlow::EasyUnlockUserLoginFlow(const AccountId& account_id) : ExtendedUserFlow(account_id) {} EasyUnlockUserLoginFlow::~EasyUnlockUserLoginFlow() {} bool EasyUnlockUserLoginFlow::CanLockScreen() { return true; } bool EasyUnlockUserLoginFlow::CanStartArc() { return true; } bool EasyUnlockUserLoginFlow::ShouldLaunchBrowser() { return true; } bool EasyUnlockUserLoginFlow::ShouldSkipPostLoginScreens() { return false; } bool EasyUnlockUserLoginFlow::HandleLoginFailure(const AuthFailure& failure) { SmartLockMetricsRecorder::RecordAuthResultSignInFailure( SmartLockMetricsRecorder::SmartLockAuthResultFailureReason:: kUserControllerSignInFailure); UMA_HISTOGRAM_ENUMERATION( "SmartLock.AuthResult.SignIn.Failure.UserControllerAuth", failure.reason(), AuthFailure::FailureReason::NUM_FAILURE_REASONS); Profile* profile = ProfileHelper::GetSigninProfile(); EasyUnlockService* service = EasyUnlockService::Get(profile); if (!service) return false; service->HandleAuthFailure(account_id()); service->RecordEasySignInOutcome(account_id(), false); UnregisterFlowSoon(); return true; } void EasyUnlockUserLoginFlow::HandleLoginSuccess(const UserContext& context) { Profile* profile = ProfileHelper::GetSigninProfile(); EasyUnlockService* service = EasyUnlockService::Get(profile); if (!service) return; service->RecordEasySignInOutcome(account_id(), true); } void EasyUnlockUserLoginFlow::HandleOAuthTokenStatusChange( user_manager::User::OAuthTokenStatus status) {} void EasyUnlockUserLoginFlow::LaunchExtraSteps(Profile* profile) {} bool EasyUnlockUserLoginFlow::SupportsEarlyRestartToApplyFlags() { return true; } } // namespace chromeos
31.811594
82
0.7918
sarang-apps
cd547ac5c53ee63d3d283612a9009197499528ca
4,900
cpp
C++
icpc/2020-5-30/D.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
3
2018-08-30T09:43:20.000Z
2019-12-03T04:53:43.000Z
icpc/2020-5-30/D.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
null
null
null
icpc/2020-5-30/D.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
null
null
null
#include <cstdio> #include <cstring> #include <stack> #include <vector> #include <algorithm> #include <unordered_map> using namespace std; #define NMAX 200000 #define MEMSIZE 1800000 struct Pair { int u, v; bool operator==(const Pair &z) const { return u == z.u && v == z.v; } }; namespace std { template <> struct hash<Pair> { size_t operator()(const Pair &z) const { static hash<int> H; return H(z.u) ^ H(z.v); } }; } int n, m; vector<int> G[NMAX + 10], T[NMAX + 10]; bool marked[NMAX + 10]; int in[NMAX + 10], low[NMAX + 10], cur, cnt; void bcc(int u, int f = 0) { static stack<Pair> stk; in[u] = low[u] = ++cur; for (int v : G[u]) { if (v == f) f = 0; else if (in[v]) low[u] = min(low[u], in[v]); else { stk.push(Pair{u, v}); bcc(v, u); low[u] = min(low[u], low[v]); if (low[v] > in[u]) { T[u].push_back(v); T[v].push_back(u); stk.pop(); } else if (low[v] >= in[u]) { cnt++; int linked = 0, p = n + cnt; auto add = [p, &linked](int x) { if (!marked[x]) { marked[x] = true; T[p].push_back(x); T[x].push_back(p); linked++; } }; while (!stk.empty()) { Pair x = stk.top(); stk.pop(); add(x.u); add(x.v); if (x.u == u && x.v == v) break; } for (int v : T[p]) { marked[v] = false; } if (linked == 0) cnt--; } } } } struct Node { int sum; Node *lch, *rch; Node() { memset(this, 0, sizeof(Node)); } }; // Node mem[MEMSIZE]; // size_t mempos; // Node *allocate() { // auto r = mem + mempos; // mempos++; // memset(r, 0, sizeof(Node)); // return r; // } Node *single(int p, int xl, int xr) { // Node *x = allocate(); Node *x = new Node; x->sum = 1; Node *y = x; while (xl < xr) { int mi = (xl + xr) / 2; // Node *z = allocate(); Node *z = new Node; z->sum = 1; if (p <= mi) { y->lch = z; xr = mi; } else { y->rch = z; xl = mi + 1; } y = z; } return x; } Node *meld(Node *x, Node *y) { if (!x) return y; if (!y) return x; x->sum += y->sum; // assume disjoint x->lch = meld(x->lch, y->lch); x->rch = meld(x->rch, y->rch); delete y; return x; } void release(Node *x) { if (!x) return; release(x->lch); release(x->rch); delete x; } int maxp(Node *x, int xl, int xr) { // present if (xl == xr) return xl; int mi = (xl + xr) / 2; if (x->rch) return maxp(x->rch, mi + 1, xr); return maxp(x->lch, xl, mi); } int maxnp(Node *x, int xl, int xr) { // not present if (!x) return xr; int mi = (xl + xr) / 2; if (!x->rch || x->rch->sum < (xr - mi)) return maxnp(x->rch, mi + 1, xr); return maxnp(x->lch, xl, mi); } unordered_map<Pair, Pair> ans; Node *dfs(int u, int pa = 0) { Node *tr = NULL; for (int v : T[u]) if (v != pa) { auto t = dfs(v, u); tr = meld(tr, t); } tr = meld(tr, single(u, 1, n)); if (pa && pa <= n && u <= n) { Pair key = {u, pa}; if (key.u > key.v) swap(key.u, key.v); int mp = maxp(tr, 1, n); if (mp == n) mp = maxnp(tr, 1, n); ans[key] = {mp, mp + 1}; } return tr; } Pair key[NMAX + 10]; void initialize() { // mempos = 0; scanf("%d%d", &n, &m); memset(marked + 1, 0, 2 * n); memset(in + 1, 0, sizeof(int) * 2 * n); memset(low + 1, 0, sizeof(int) * 2 * n); cur = cnt = 0; for (int i = 1; i <= 2 * n; i++) { G[i].clear(); T[i].clear(); } ans.clear(); for (int i = 0; i < m; i++) { int u, v; scanf("%d%d", &u, &v); if (u > v) swap(u, v); key[i] = {u, v}; G[u].push_back(v); G[v].push_back(u); } bcc(1); auto t = dfs(1); release(t); for (int i = 0; i < m; i++) { auto it = ans.find(key[i]); if (it != ans.end()) printf("%d %d\n", it->second.u, it->second.v); else puts("0 0"); } } void _main() { initialize(); } int main() { int T; scanf("%d", &T); while (T--) { _main(); // fprintf(stderr, "mempos = %zu\n", mempos); } return 0; }
20.588235
58
0.391837
Riteme
cd54b296c3370bee409421ff58e93b1bb0ca1fc3
4,596
hpp
C++
include/realm/core/component.hpp
pyrbin/realm.hpp
e34b18ce1f5c39b080a9e70f675adf740490ff83
[ "MIT" ]
2
2020-03-01T18:15:27.000Z
2020-03-25T10:21:59.000Z
include/realm/core/component.hpp
pyrbin/realm.hpp
e34b18ce1f5c39b080a9e70f675adf740490ff83
[ "MIT" ]
null
null
null
include/realm/core/component.hpp
pyrbin/realm.hpp
e34b18ce1f5c39b080a9e70f675adf740490ff83
[ "MIT" ]
1
2020-03-25T10:22:00.000Z
2020-03-25T10:22:00.000Z
#pragma once #include <cstddef> #include <functional> #include <iostream> #include <vector> #include <realm/util/identifier.hpp> #include <realm/util/type_traits.hpp> namespace realm { /** * @brief Memory layout * Describes a particular layout of memory. Inspired by Rust's alloc::Layout. * @ref https://doc.rust-lang.org/std/alloc/struct.Layout.html */ struct memory_layout { const unsigned size{ 0 }; const unsigned align{ 0 }; constexpr memory_layout() = default; constexpr memory_layout(const unsigned size, const unsigned align) : size{ size } , align{ align } { /** * TODO: add some necessary checks, eg. align has to be power of 2 * see Rust impl. for examples */ } /** * Create a memory layout of a specified type * @tparam T * @return */ template<typename T> static constexpr memory_layout of() { return { sizeof(T), alignof(T) }; } /** * @brief Returns the amount of padding that has to be added to size to satisfy the * layouts alignment * @param size * @param align * @return Padding to insert */ static constexpr int align_up(const int size, const int align) noexcept { return (size + (align - 1)) & !(align - 1); } [[nodiscard]] constexpr int align_up(const int size) const noexcept { return align_up(size, align); } }; /** * @brief Component meta * Describes component metadata of a specified type. */ struct component_meta { const u64 hash{ 0 }; const u64 mask{ 0 }; constexpr component_meta() = default; constexpr component_meta(const u64 hash, const u64 mask) : hash{ hash } , mask{ mask } {}; /** * Create component meta of a type. * @tparam T * @return */ template<typename T> static constexpr internal::enable_if_component<T, component_meta> of() { return component_meta{ internal::identifier_hash_v<internal::pure_t<T>>, internal::identifier_mask_v<internal::pure_t<T>> }; } }; /** * @brief Component * Describes a component (metadata, memory layout & functions for construction and * destruction). */ struct component { using constructor_t = void(void*); const component_meta meta; const memory_layout layout; constructor_t* alloc{ nullptr }; constructor_t* destroy{ nullptr }; constexpr component() = default; constexpr component( component_meta meta, memory_layout layout, constructor_t* alloc, constructor_t* destroy) : meta{ meta } , layout{ layout } , alloc{ alloc } , destroy{ destroy } {} constexpr bool operator==(const component& other) const { return other.meta.hash == meta.hash; } /** * Create a component of a specified type * @tparam T * @return */ template<typename T> static constexpr internal::enable_if_component<T, component> of() { return { component_meta::of<T>(), memory_layout::of<T>(), [](void* ptr) { new (ptr) T{}; }, [](void* ptr) { static_cast<T*>(ptr)->~T(); } }; } }; /** * @brief Singleton component * Singleton component base class */ struct singleton_component { singleton_component() = default; singleton_component(component&& comp) : component_info{ comp } {}; virtual ~singleton_component() = default; const component component_info; }; /** * @brief Singleton instance * Stores a single component using a unique_ptr. * Currently used in world to store singleton components. * @tparam T */ template<typename T> struct singleton_instance final : singleton_component { explicit singleton_instance(T& t) : singleton_component{ component::of<T>() } , instance_{ std::unique_ptr<T>(std::move(t)) } {} template<typename... Args> explicit singleton_instance(Args&&... args) : singleton_component{ component::of<T>() } , instance_{ std::make_unique<T>(std::forward<Args>(args)...) } {} /** * Get the underlying component instance * @return Pointer to component instance */ T* get() { return static_cast<T*>(instance_.get()); } private: const std::unique_ptr<T> instance_; }; } // namespace realm /** * @cond TURN_OFF_DOXYGEN * Internal details not to be documented. */ namespace std { template<> struct hash<realm::component> { size_t operator()(const realm::component& c) const noexcept { return (hash<size_t>{}(c.meta.hash)); } }; } // namespace std
24.446809
100
0.629896
pyrbin
cd55cc5b68d628bbff6e9fd9ebbf86ee87d7c262
15,669
c++
C++
c++/src/capnp/schema-parser.c++
faizol/capnproto
be7a80b4add706ddaeb41689221146b86c3e0f5f
[ "MIT" ]
1
2022-03-23T23:49:55.000Z
2022-03-23T23:49:55.000Z
c++/src/capnp/schema-parser.c++
faizol/capnproto
be7a80b4add706ddaeb41689221146b86c3e0f5f
[ "MIT" ]
null
null
null
c++/src/capnp/schema-parser.c++
faizol/capnproto
be7a80b4add706ddaeb41689221146b86c3e0f5f
[ "MIT" ]
null
null
null
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include "schema-parser.h" #include "message.h" #include <capnp/compiler/compiler.h> #include <capnp/compiler/lexer.capnp.h> #include <capnp/compiler/lexer.h> #include <capnp/compiler/grammar.capnp.h> #include <capnp/compiler/parser.h> #include <unordered_map> #include <kj/mutex.h> #include <kj/vector.h> #include <kj/debug.h> #include <kj/io.h> #include <map> namespace capnp { namespace { template <typename T> size_t findLargestElementBefore(const kj::Vector<T>& vec, const T& key) { KJ_REQUIRE(vec.size() > 0 && vec[0] <= key); size_t lower = 0; size_t upper = vec.size(); while (upper - lower > 1) { size_t mid = (lower + upper) / 2; if (vec[mid] > key) { upper = mid; } else { lower = mid; } } return lower; } } // namespace // ======================================================================================= class SchemaParser::ModuleImpl final: public compiler::Module { public: ModuleImpl(const SchemaParser& parser, kj::Own<const SchemaFile>&& file) : parser(parser), file(kj::mv(file)) {} kj::StringPtr getSourceName() override { return file->getDisplayName(); } Orphan<compiler::ParsedFile> loadContent(Orphanage orphanage) override { kj::Array<const char> content = file->readContent(); lineBreaks.get([&](kj::SpaceFor<kj::Vector<uint>>& space) { auto vec = space.construct(content.size() / 40); vec->add(0); for (const char* pos = content.begin(); pos < content.end(); ++pos) { if (*pos == '\n') { vec->add(pos + 1 - content.begin()); } } return vec; }); MallocMessageBuilder lexedBuilder; auto statements = lexedBuilder.initRoot<compiler::LexedStatements>(); compiler::lex(content, statements, *this); auto parsed = orphanage.newOrphan<compiler::ParsedFile>(); compiler::parseFile(statements.getStatements(), parsed.get(), *this); return parsed; } kj::Maybe<Module&> importRelative(kj::StringPtr importPath) override { KJ_IF_MAYBE(importedFile, file->import(importPath)) { return parser.getModuleImpl(kj::mv(*importedFile)); } else { return nullptr; } } kj::Maybe<kj::Array<const byte>> embedRelative(kj::StringPtr embedPath) override { KJ_IF_MAYBE(importedFile, file->import(embedPath)) { return importedFile->get()->readContent().releaseAsBytes(); } else { return nullptr; } } void addError(uint32_t startByte, uint32_t endByte, kj::StringPtr message) override { auto& lines = lineBreaks.get( [](kj::SpaceFor<kj::Vector<uint>>& space) { KJ_FAIL_REQUIRE("Can't report errors until loadContent() is called."); return space.construct(); }); // TODO(someday): This counts tabs as single characters. Do we care? uint startLine = findLargestElementBefore(lines, startByte); uint startCol = startByte - lines[startLine]; uint endLine = findLargestElementBefore(lines, endByte); uint endCol = endByte - lines[endLine]; file->reportError( SchemaFile::SourcePos { startByte, startLine, startCol }, SchemaFile::SourcePos { endByte, endLine, endCol }, message); // We intentionally only set hadErrors true if reportError() didn't throw. parser.hadErrors = true; } bool hadErrors() override { return parser.hadErrors; } private: const SchemaParser& parser; kj::Own<const SchemaFile> file; kj::Lazy<kj::Vector<uint>> lineBreaks; // Byte offsets of the first byte in each source line. The first element is always zero. // Initialized the first time the module is loaded. }; // ======================================================================================= namespace { struct SchemaFileHash { inline bool operator()(const SchemaFile* f) const { return f->hashCode(); } }; struct SchemaFileEq { inline bool operator()(const SchemaFile* a, const SchemaFile* b) const { return *a == *b; } }; } // namespace struct SchemaParser::DiskFileCompat { // Stuff we only create if parseDiskFile() is ever called, in order to translate that call into // KJ filesystem API calls. kj::Own<kj::Filesystem> ownFs; kj::Filesystem& fs; struct ImportDir { kj::String pathStr; kj::Path path; kj::Own<const kj::ReadableDirectory> dir; }; std::map<kj::StringPtr, ImportDir> cachedImportDirs; std::map<std::pair<const kj::StringPtr*, size_t>, kj::Array<const kj::ReadableDirectory*>> cachedImportPaths; DiskFileCompat(): ownFs(kj::newDiskFilesystem()), fs(*ownFs) {} DiskFileCompat(kj::Filesystem& fs): fs(fs) {} }; struct SchemaParser::Impl { typedef std::unordered_map< const SchemaFile*, kj::Own<ModuleImpl>, SchemaFileHash, SchemaFileEq> FileMap; kj::MutexGuarded<FileMap> fileMap; compiler::Compiler compiler; kj::MutexGuarded<kj::Maybe<DiskFileCompat>> compat; }; SchemaParser::SchemaParser(): impl(kj::heap<Impl>()) {} SchemaParser::~SchemaParser() noexcept(false) {} ParsedSchema SchemaParser::parseFromDirectory( const kj::ReadableDirectory& baseDir, kj::Path path, kj::ArrayPtr<const kj::ReadableDirectory* const> importPath) const { return parseFile(SchemaFile::newFromDirectory(baseDir, kj::mv(path), importPath)); } ParsedSchema SchemaParser::parseDiskFile( kj::StringPtr displayName, kj::StringPtr diskPath, kj::ArrayPtr<const kj::StringPtr> importPath) const { auto lock = impl->compat.lockExclusive(); DiskFileCompat* compat; KJ_IF_MAYBE(c, *lock) { compat = c; } else { compat = &lock->emplace(); } auto& root = compat->fs.getRoot(); auto cwd = compat->fs.getCurrentPath(); const kj::ReadableDirectory* baseDir = &root; kj::Path path = cwd.evalNative(diskPath); kj::ArrayPtr<const kj::ReadableDirectory* const> translatedImportPath = nullptr; if (importPath.size() > 0) { auto importPathKey = std::make_pair(importPath.begin(), importPath.size()); auto& slot = compat->cachedImportPaths[importPathKey]; if (slot == nullptr) { slot = KJ_MAP(path, importPath) -> const kj::ReadableDirectory* { auto iter = compat->cachedImportDirs.find(path); if (iter != compat->cachedImportDirs.end()) { return iter->second.dir; } auto parsed = cwd.evalNative(path); kj::Own<const kj::ReadableDirectory> dir; KJ_IF_MAYBE(d, root.tryOpenSubdir(parsed)) { dir = kj::mv(*d); } else { // Ignore paths that don't exist. dir = kj::newInMemoryDirectory(kj::nullClock()); } const kj::ReadableDirectory* result = dir; kj::StringPtr pathRef = path; KJ_ASSERT(compat->cachedImportDirs.insert(std::make_pair(pathRef, DiskFileCompat::ImportDir { kj::str(path), kj::mv(parsed), kj::mv(dir) })).second); return result; }; } translatedImportPath = slot; // Check if `path` appears to be inside any of the import path directories. If so, adjust // to be relative to that directory rather than absolute. kj::Maybe<DiskFileCompat::ImportDir&> matchedImportDir; size_t bestMatchLength = 0; for (auto importDir: importPath) { auto iter = compat->cachedImportDirs.find(importDir); KJ_ASSERT(iter != compat->cachedImportDirs.end()); if (path.startsWith(iter->second.path)) { // Looks like we're trying to load a file from inside this import path. Treat the import // path as the base directory. if (iter->second.path.size() > bestMatchLength) { bestMatchLength = iter->second.path.size(); matchedImportDir = iter->second; } } } KJ_IF_MAYBE(match, matchedImportDir) { baseDir = match->dir; path = path.slice(match->path.size(), path.size()).clone(); } } return parseFile(SchemaFile::newFromDirectory( *baseDir, kj::mv(path), translatedImportPath, kj::str(displayName))); } void SchemaParser::setDiskFilesystem(kj::Filesystem& fs) { auto lock = impl->compat.lockExclusive(); KJ_REQUIRE(*lock == nullptr, "already called parseDiskFile() or setDiskFilesystem()"); lock->emplace(fs); } ParsedSchema SchemaParser::parseFile(kj::Own<SchemaFile>&& file) const { KJ_DEFER(impl->compiler.clearWorkspace()); uint64_t id = impl->compiler.add(getModuleImpl(kj::mv(file))).getId(); impl->compiler.eagerlyCompile(id, compiler::Compiler::NODE | compiler::Compiler::CHILDREN | compiler::Compiler::DEPENDENCIES | compiler::Compiler::DEPENDENCY_DEPENDENCIES); return ParsedSchema(impl->compiler.getLoader().get(id), *this); } kj::Maybe<schema::Node::SourceInfo::Reader> SchemaParser::getSourceInfo(Schema schema) const { return impl->compiler.getSourceInfo(schema.getProto().getId()); } SchemaParser::ModuleImpl& SchemaParser::getModuleImpl(kj::Own<SchemaFile>&& file) const { auto lock = impl->fileMap.lockExclusive(); auto insertResult = lock->insert(std::make_pair(file.get(), kj::Own<ModuleImpl>())); if (insertResult.second) { // This is a newly-inserted entry. Construct the ModuleImpl. insertResult.first->second = kj::heap<ModuleImpl>(*this, kj::mv(file)); } return *insertResult.first->second; } SchemaLoader& SchemaParser::getLoader() { return impl->compiler.getLoader(); } const SchemaLoader& SchemaParser::getLoader() const { return impl->compiler.getLoader(); } kj::Maybe<ParsedSchema> ParsedSchema::findNested(kj::StringPtr name) const { // TODO(someday): lookup() doesn't handle generics correctly. Use the ModuleScope/CompiledType // interface instead. We can also add an applybrand() method to ParsedSchema using those // interfaces, which would allow us to expose generics more explicitly to e.g. Python. return parser->impl->compiler.lookup(getProto().getId(), name).map( [this](uint64_t childId) { return ParsedSchema(parser->impl->compiler.getLoader().get(childId), *parser); }); } ParsedSchema ParsedSchema::getNested(kj::StringPtr nestedName) const { KJ_IF_MAYBE(nested, findNested(nestedName)) { return *nested; } else { KJ_FAIL_REQUIRE("no such nested declaration", getProto().getDisplayName(), nestedName); } } ParsedSchema::ParsedSchemaList ParsedSchema::getAllNested() const { return ParsedSchemaList(*this, getProto().getNestedNodes()); } schema::Node::SourceInfo::Reader ParsedSchema::getSourceInfo() const { return KJ_ASSERT_NONNULL(parser->getSourceInfo(*this)); } // ------------------------------------------------------------------- ParsedSchema ParsedSchema::ParsedSchemaList::operator[](uint index) const { return ParsedSchema( parent.parser->impl->compiler.getLoader().get(list[index].getId()), *parent.parser); } // ------------------------------------------------------------------- class SchemaFile::DiskSchemaFile final: public SchemaFile { public: DiskSchemaFile(const kj::ReadableDirectory& baseDir, kj::Path pathParam, kj::ArrayPtr<const kj::ReadableDirectory* const> importPath, kj::Own<const kj::ReadableFile> file, kj::Maybe<kj::String> displayNameOverride) : baseDir(baseDir), path(kj::mv(pathParam)), importPath(importPath), file(kj::mv(file)) { KJ_IF_MAYBE(dn, displayNameOverride) { displayName = kj::mv(*dn); displayNameOverridden = true; } else { displayName = path.toString(); displayNameOverridden = false; } } kj::StringPtr getDisplayName() const override { return displayName; } kj::Array<const char> readContent() const override { return file->mmap(0, file->stat().size).releaseAsChars(); } kj::Maybe<kj::Own<SchemaFile>> import(kj::StringPtr target) const override { if (target.startsWith("/")) { auto parsed = kj::Path::parse(target.slice(1)); for (auto candidate: importPath) { KJ_IF_MAYBE(newFile, candidate->tryOpenFile(parsed)) { return kj::implicitCast<kj::Own<SchemaFile>>(kj::heap<DiskSchemaFile>( *candidate, kj::mv(parsed), importPath, kj::mv(*newFile), nullptr)); } } return nullptr; } else { auto parsed = path.parent().eval(target); kj::Maybe<kj::String> displayNameOverride; if (displayNameOverridden) { // Try to create a consistent display name override for the imported file. This is for // backwards-compatibility only -- display names are only overridden when using the // deprecated parseDiskFile() interface. kj::runCatchingExceptions([&]() { displayNameOverride = kj::Path::parse(displayName).parent().eval(target).toString(); }); } KJ_IF_MAYBE(newFile, baseDir.tryOpenFile(parsed)) { return kj::implicitCast<kj::Own<SchemaFile>>(kj::heap<DiskSchemaFile>( baseDir, kj::mv(parsed), importPath, kj::mv(*newFile), kj::mv(displayNameOverride))); } else { return nullptr; } } } bool operator==(const SchemaFile& other) const override { auto& other2 = kj::downcast<const DiskSchemaFile>(other); return &baseDir == &other2.baseDir && path == other2.path; } bool operator!=(const SchemaFile& other) const override { return !operator==(other); } size_t hashCode() const override { // djb hash with xor // TODO(someday): Add hashing library to KJ. size_t result = reinterpret_cast<uintptr_t>(&baseDir); for (auto& part: path) { for (char c: part) { result = (result * 33) ^ c; } result = (result * 33) ^ '/'; } return result; } void reportError(SourcePos start, SourcePos end, kj::StringPtr message) const override { kj::getExceptionCallback().onRecoverableException(kj::Exception( kj::Exception::Type::FAILED, path.toString(), start.line, kj::heapString(message))); } private: const kj::ReadableDirectory& baseDir; kj::Path path; kj::ArrayPtr<const kj::ReadableDirectory* const> importPath; kj::Own<const kj::ReadableFile> file; kj::String displayName; bool displayNameOverridden; }; kj::Own<SchemaFile> SchemaFile::newFromDirectory( const kj::ReadableDirectory& baseDir, kj::Path path, kj::ArrayPtr<const kj::ReadableDirectory* const> importPath, kj::Maybe<kj::String> displayNameOverride) { return kj::heap<DiskSchemaFile>(baseDir, kj::mv(path), importPath, baseDir.openFile(path), kj::mv(displayNameOverride)); } } // namespace capnp
34.361842
97
0.664752
faizol
cd565ed49ea1c9e80360b98111311d6cb23f1b6e
9,716
cc
C++
SimPPS/PPSPixelDigiProducer/plugins/PPSPixelDigiProducer.cc
swiedenb/cmssw
f91490fd5861333c9be8b8a0ce74eb7816cb2d11
[ "Apache-2.0" ]
1
2019-12-19T13:43:44.000Z
2019-12-19T13:43:44.000Z
SimPPS/PPSPixelDigiProducer/plugins/PPSPixelDigiProducer.cc
swiedenb/cmssw
f91490fd5861333c9be8b8a0ce74eb7816cb2d11
[ "Apache-2.0" ]
7
2020-02-10T18:55:34.000Z
2022-01-16T20:08:44.000Z
SimPPS/PPSPixelDigiProducer/plugins/PPSPixelDigiProducer.cc
swiedenb/cmssw
f91490fd5861333c9be8b8a0ce74eb7816cb2d11
[ "Apache-2.0" ]
1
2020-11-06T14:49:52.000Z
2020-11-06T14:49:52.000Z
#ifndef SimPPS_PPSPixelDigiProducer_PPSPixelDigiProducer_h #define SimPPS_PPSPixelDigiProducer_PPSPixelDigiProducer_h // -*- C++ -*- // // Package: PPSPixelDigiProducer // Class: CTPPSPixelDigiProducer // /**\class CTPPSPixelDigiProducer PPSPixelDigiProducer.cc SimPPS/PPSPixelDigiProducer/plugins/PPSPixelDigiProducer.cc Description: <one line class summary> Implementation: <Notes on implementation> */ // // Original Author: F.Ferro // // system include files #include <memory> #include <vector> #include <map> #include <string> // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/stream/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/ParameterSet/interface/ParameterSetDescription.h" #include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h" // **** CTPPS #include "DataFormats/CTPPSDigi/interface/CTPPSPixelDigi.h" #include "DataFormats/CTPPSDigi/interface/CTPPSPixelDigiCollection.h" #include "SimPPS/PPSPixelDigiProducer/interface/RPixDetDigitizer.h" #include "SimDataFormats/CrossingFrame/interface/MixCollection.h" #include "DataFormats/Common/interface/DetSet.h" // DB #include "CondFormats/DataRecord/interface/CTPPSPixelDAQMappingRcd.h" #include "CondFormats/DataRecord/interface/CTPPSPixelAnalysisMaskRcd.h" #include "CondFormats/DataRecord/interface/CTPPSPixelGainCalibrationsRcd.h" #include "CondFormats/PPSObjects/interface/CTPPSPixelDAQMapping.h" #include "CondFormats/PPSObjects/interface/CTPPSPixelAnalysisMask.h" #include "CondFormats/PPSObjects/interface/CTPPSPixelGainCalibrations.h" // user include files #include "SimDataFormats/TrackingHit/interface/PSimHitContainer.h" #include "SimDataFormats/TrackingHit/interface/PSimHit.h" #include "SimDataFormats/CrossingFrame/interface/CrossingFrame.h" #include "SimDataFormats/CrossingFrame/interface/MixCollection.h" #include <cstdlib> // I need it for random numbers //needed for the geometry: #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/ESHandle.h" #include "DataFormats/Common/interface/DetSetVector.h" //Random Number #include "FWCore/ServiceRegistry/interface/Service.h" #include "FWCore/Utilities/interface/RandomNumberGenerator.h" #include "FWCore/Utilities/interface/Exception.h" #include "CLHEP/Random/RandomEngine.h" namespace CLHEP { class HepRandomEngine; } class CTPPSPixelDigiProducer : public edm::stream::EDProducer<> { public: explicit CTPPSPixelDigiProducer(const edm::ParameterSet&); ~CTPPSPixelDigiProducer() override; static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); private: void produce(edm::Event&, const edm::EventSetup&) override; // ----------member data --------------------------- std::vector<std::string> RPix_hit_containers_; typedef std::map<unsigned int, std::vector<PSimHit>> simhit_map; typedef simhit_map::iterator simhit_map_iterator; edm::ParameterSet conf_; std::map<uint32_t, std::unique_ptr<RPixDetDigitizer>> theAlgoMap; //DetId = uint32_t CLHEP::HepRandomEngine* rndEngine_ = nullptr; int verbosity_; edm::EDGetTokenT<CrossingFrame<PSimHit>> tokenCrossingFramePPSPixel; edm::ESGetToken<CTPPSPixelGainCalibrations, CTPPSPixelGainCalibrationsRcd> gainCalibESToken_; }; CTPPSPixelDigiProducer::CTPPSPixelDigiProducer(const edm::ParameterSet& conf) : conf_(conf), gainCalibESToken_(esConsumes()) { produces<edm::DetSetVector<CTPPSPixelDigi>>(); // register data to consume tokenCrossingFramePPSPixel = consumes<CrossingFrame<PSimHit>>(edm::InputTag("mix", "g4SimHitsCTPPSPixelHits")); RPix_hit_containers_.clear(); RPix_hit_containers_ = conf.getParameter<std::vector<std::string>>("ROUList"); verbosity_ = conf.getParameter<int>("RPixVerbosity"); } CTPPSPixelDigiProducer::~CTPPSPixelDigiProducer() {} void CTPPSPixelDigiProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; // all distances in [mm] // RPDigiProducer desc.add<std::vector<std::string>>("ROUList", {"CTPPSPixelHits"}); desc.add<int>("RPixVerbosity", 0); desc.add<bool>("CTPPSPixelDigiSimHitRelationsPersistence", false); // save links betweend digi, clusters and OSCAR/Geant4 hits // RPDetDigitizer desc.add<double>("RPixEquivalentNoiseCharge", 1000.0); desc.add<bool>("RPixNoNoise", false); // RPDisplacementGenerator desc.add<double>("RPixGeVPerElectron", 3.61e-09); desc.add<std::vector<double>>("RPixInterSmearing", {0.011}); desc.add<bool>("RPixLandauFluctuations", true); desc.add<int>("RPixChargeDivisions", 20); desc.add<double>("RPixDeltaProductionCut", 0.120425); // [MeV] // RPixChargeShare desc.add<std::string>("ChargeMapFile2E", "SimPPS/PPSPixelDigiProducer/data/PixelChargeMap.txt"); desc.add<std::string>("ChargeMapFile2E_2X", "SimPPS/PPSPixelDigiProducer/data/PixelChargeMap_2X.txt"); desc.add<std::string>("ChargeMapFile2E_2Y", "SimPPS/PPSPixelDigiProducer/data/PixelChargeMap_2Y.txt"); desc.add<std::string>("ChargeMapFile2E_2X2Y", "SimPPS/PPSPixelDigiProducer/data/PixelChargeMap_2X2Y.txt"); desc.add<double>( "RPixCoupling", 0.250); // fraction of the remaining charge going to the closer neighbour pixel. Value = 0.135, Value = 0.0 bypass the charge map and the charge sharing approach // RPixDummyROCSimulator desc.add<double>("RPixDummyROCThreshold", 1900.0); desc.add<double>("RPixDummyROCElectronPerADC", 135.0); // 210.0 to be verified desc.add<int>("VCaltoElectronGain", 50); // same values as in RPixDetClusterizer desc.add<int>("VCaltoElectronOffset", -411); // desc.add<bool>("doSingleCalibration", false); // desc.add<double>("RPixDeadPixelProbability", 0.001); desc.add<bool>("RPixDeadPixelSimulationOn", true); // CTPPSPixelSimTopology desc.add<double>("RPixActiveEdgeSmearing", 0.020); desc.add<double>("RPixActiveEdgePosition", 0.150); desc.add<std::string>("mixLabel", "mix"); desc.add<std::string>("InputCollection", "g4SimHitsCTPPSPixelHits"); descriptions.add("RPixDetDigitizer", desc); } // // member functions // // ------------ method called to produce the data ------------ void CTPPSPixelDigiProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { using namespace edm; if (!rndEngine_) { Service<RandomNumberGenerator> rng; if (!rng.isAvailable()) { throw cms::Exception("Configuration") << "This class requires the RandomNumberGeneratorService\n" "which is not present in the configuration file. You must add the service\n" "in the configuration file or remove the modules that require it."; } rndEngine_ = &(rng->getEngine(iEvent.streamID())); } // get calibration DB const auto& gainCalibration = iSetup.getData(gainCalibESToken_); // Step A: Get Inputs edm::Handle<CrossingFrame<PSimHit>> cf; iEvent.getByToken(tokenCrossingFramePPSPixel, cf); if (verbosity_) { edm::LogInfo("PPSPixelDigiProducer") << "\n\n=================== Starting SimHit access" << " ==================="; MixCollection<PSimHit> col{cf.product(), std::pair(-0, 0)}; edm::LogInfo("PPSPixelDigiProducer") << col; MixCollection<PSimHit>::iterator cfi; int count = 0; for (cfi = col.begin(); cfi != col.end(); cfi++) { edm::LogInfo("PPSPixelDigiProducer") << " Hit " << count << " has tof " << cfi->timeOfFlight() << " trackid " << cfi->trackId() << " bunchcr " << cfi.bunch() << " trigger " << cfi.getTrigger() << ", from EncodedEventId: " << cfi->eventId().bunchCrossing() << " " << cfi->eventId().event() << " bcr from MixCol " << cfi.bunch(); edm::LogInfo("PPSPixelDigiProducer") << " Hit: " << (*cfi) << " " << cfi->exitPoint(); count++; } } MixCollection<PSimHit> allRPixHits{cf.product(), std::pair(0, 0)}; if (verbosity_) edm::LogInfo("PPSPixelDigiProducer") << "Input MixCollection size = " << allRPixHits.size(); //Loop on PSimHit simhit_map SimHitMap; SimHitMap.clear(); MixCollection<PSimHit>::iterator isim; for (isim = allRPixHits.begin(); isim != allRPixHits.end(); ++isim) { SimHitMap[(*isim).detUnitId()].push_back((*isim)); } // Step B: LOOP on hits in event std::vector<edm::DetSet<CTPPSPixelDigi>> theDigiVector; theDigiVector.reserve(400); theDigiVector.clear(); for (simhit_map_iterator it = SimHitMap.begin(); it != SimHitMap.end(); ++it) { edm::DetSet<CTPPSPixelDigi> digi_collector(it->first); if (theAlgoMap.find(it->first) == theAlgoMap.end()) { theAlgoMap[it->first] = std::make_unique<RPixDetDigitizer>(conf_, *rndEngine_, it->first, iSetup); //a digitizer for eny detector } std::vector<int> input_links; std::vector<std::vector<std::pair<int, double>>> output_digi_links; // links to simhits theAlgoMap.at(it->first)->run( SimHitMap[it->first], input_links, digi_collector.data, output_digi_links, &gainCalibration); if (!digi_collector.data.empty()) { theDigiVector.push_back(digi_collector); } } std::unique_ptr<edm::DetSetVector<CTPPSPixelDigi>> digi_output(new edm::DetSetVector<CTPPSPixelDigi>(theDigiVector)); if (verbosity_) { edm::LogInfo("PPSPixelDigiProducer") << "digi_output->size()=" << digi_output->size(); } iEvent.put(std::move(digi_output)); } DEFINE_FWK_MODULE(CTPPSPixelDigiProducer); #endif
37.658915
168
0.72077
swiedenb
cd56e796cc589b6b6883bef7024befae8ab36dc6
251
cpp
C++
gps_kalman_filter/src/gps_kf_node.cpp
oaklandrobotics/ou_self_drive_ros
54e460e5c10780652310f31cded1f50d9467c8d7
[ "BSD-2-Clause" ]
2
2020-09-19T00:57:47.000Z
2020-09-19T03:55:57.000Z
gps_kalman_filter/src/gps_kf_node.cpp
oaklandrobotics/ou_self_drive_ros
54e460e5c10780652310f31cded1f50d9467c8d7
[ "BSD-2-Clause" ]
1
2019-03-23T16:27:11.000Z
2019-03-23T16:27:11.000Z
gps_kalman_filter/src/gps_kf_node.cpp
oaklandrobotics/ou_self_drive_ros
54e460e5c10780652310f31cded1f50d9467c8d7
[ "BSD-2-Clause" ]
2
2020-11-15T20:29:56.000Z
2021-09-12T00:02:14.000Z
#include <ros/ros.h> #include "GpsKalmanFilter.h" int main(int argc, char** argv) { ros::init(argc, argv, "gps_kalman_filter"); ros::NodeHandle n; ros::NodeHandle pn("~"); gps_kalman_filter::GpsKalmanFilter node(n, pn); ros::spin(); }
19.307692
49
0.661355
oaklandrobotics
cd56f95ad30452c0b347f00d65240e938b3ea8be
44,101
cxx
C++
sprokit/tests/sprokit/pipeline_util/test_pipe_bakery.cxx
neal-siekierski/kwiver
1c97ad72c8b6237cb4b9618665d042be16825005
[ "BSD-3-Clause" ]
null
null
null
sprokit/tests/sprokit/pipeline_util/test_pipe_bakery.cxx
neal-siekierski/kwiver
1c97ad72c8b6237cb4b9618665d042be16825005
[ "BSD-3-Clause" ]
null
null
null
sprokit/tests/sprokit/pipeline_util/test_pipe_bakery.cxx
neal-siekierski/kwiver
1c97ad72c8b6237cb4b9618665d042be16825005
[ "BSD-3-Clause" ]
null
null
null
/*ckwg +29 * Copyright 2012-2018 by Kitware, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither name of Kitware, Inc. nor the names of any contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS 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 <test_common.h> #include <sprokit/pipeline_util/pipeline_builder.h> #include <sprokit/pipeline_util/pipe_bakery.h> #include <sprokit/pipeline_util/pipe_bakery_exception.h> #include <sprokit/pipeline_util/load_pipe_exception.h> #include <sprokit/pipeline/pipeline.h> #include <sprokit/pipeline/process_cluster.h> #include <sprokit/pipeline/process_factory.h> #include <sprokit/pipeline/scheduler.h> #include <sprokit/pipeline/scheduler_factory.h> #include <kwiversys/SystemTools.hxx> #include <exception> #include <iostream> #include <fstream> #include <sstream> #include <string> #include <memory> #include <cstdlib> #define TEST_ARGS (kwiver::vital::path_t const& pipe_file) DECLARE_TEST_MAP(); /// \todo Add tests for clusters without ports or processes. static std::string const pipe_ext = ".pipe"; int main( int argc, char* argv[] ) { CHECK_ARGS( 2 ); std::string const testname = argv[1]; kwiver::vital::path_t const pipe_dir = argv[2]; kwiver::vital::path_t const pipe_file = pipe_dir + "/" + testname + pipe_ext; RUN_TEST( testname, pipe_file ); } // ---------------------------------------------------------------------------- sprokit::pipe_blocks load_pipe_blocks_from_file( kwiver::vital::path_t const& pipe_file ) { sprokit::pipeline_builder builder; builder.load_pipeline( pipe_file ); return builder.pipeline_blocks(); } // ---------------------------------------------------------------------------- sprokit::cluster_blocks load_cluster_blocks_from_file( kwiver::vital::path_t const& pipe_file ) { sprokit::pipeline_builder builder; builder.load_pipeline( pipe_file ); return builder.cluster_blocks(); } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_block ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "myvalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration was not correct: Expected: " << expected << " Received: " << myvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_block_block ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); { const auto mykey = kwiver::vital::config_block_key_t( "myblock:foo:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "myvalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration was not correct: Expected: " << expected << " Received: " << myvalue ); } } { const auto mykey = kwiver::vital::config_block_key_t( "myblock:foo:oldkey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "oldvalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration was not correct: Expected: " << expected << " Received: " << myvalue ); } } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_block_relativepath ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:otherkey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const std::string cwd = kwiversys::SystemTools::GetFilenamePath( pipe_file ); const auto expected = cwd + "/" + "value"; if ( myvalue != expected ) { TEST_ERROR( "Configuration was not correct: Expected: " << expected << " Received: " << myvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_block_long_block ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:foo:a:b:c:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "myvalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration was not correct: Expected: " << expected << " Received: " << myvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_block_nested_block ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:foo:bar:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "myvalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration was not correct: Expected: " << expected << " Received: " << myvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_block_notalnum ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "my_block:my-key" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "myvalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration was not correct: Expected: " << expected << " Received: " << myvalue ); } const auto myotherkey = kwiver::vital::config_block_key_t( "my-block:my_key" ); const auto myothervalue = conf->get_value< kwiver::vital::config_block_value_t > ( myotherkey ); const auto otherexpected = kwiver::vital::config_block_value_t( "myothervalue" ); if ( myothervalue != otherexpected ) { TEST_ERROR( "Configuration was not correct: Expected: " << otherexpected << " Received: " << myothervalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_value_spaces ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "my value with spaces" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration was not correct: Expected: " << expected << " Received: " << myvalue ); } const auto mytabkey = kwiver::vital::config_block_key_t( "myblock:mytabs" ); const auto mytabvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mytabkey ); const auto tabexpected = kwiver::vital::config_block_value_t( "my value with tabs"); if ( mytabvalue != tabexpected ) { TEST_ERROR( "Configuration was not correct: Expected: " << tabexpected << " Received: " << mytabvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_overrides ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "myothervalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration was not overridden: Expected: " << expected << " Received: " << myvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_read_only ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const config = sprokit::extract_configuration( blocks ); const auto rokey = kwiver::vital::config_block_key_t( "myblock:mykey" ); if ( ! config->is_read_only( rokey ) ) { TEST_ERROR( "The configuration value was not marked as read only" ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_not_a_flag ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); EXPECT_EXCEPTION( sprokit::unrecognized_config_flag_exception, sprokit::extract_configuration( blocks ), "using an unknown flag" ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_read_only_override ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); EXPECT_EXCEPTION( kwiver::vital::set_on_read_only_value_exception, sprokit::extract_configuration( blocks ), "setting a read-only value" ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_append_ro ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "myvalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration value was not appended: Expected: " << expected << " Received: " << myvalue ); } if ( ! conf->is_read_only( mykey ) ) { TEST_ERROR( "The configuration value was not marked as read only" ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_append_provided ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "myvalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration value was not appended: Expected: " << expected << " Received: " << myvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_append_provided_ro ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "myvalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration value was not appended: Expected: " << expected << " Received: " << myvalue ); } if ( ! conf->is_read_only( mykey ) ) { TEST_ERROR( "The configuration value was not marked as read only" ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_append_comma ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "myvalue,othervalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration value was not appended with a comma separator: Expected: " << expected << " Received: " << myvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_append_space_empty ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "othervalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration value was created with a space separator: Expected: " << expected << " Received: " << myvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_append_path ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); kwiver::vital::path_t const expected = kwiver::vital::path_t( "myvalue" ) + "/" + kwiver::vital::path_t( "othervalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration value was not appended with a path separator: Expected: " << expected << " Received: " << myvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_dotted_key ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:dotted.key" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "value" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration was not read properly: Expected: " << expected << " Received: " << myvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_dotted_nested_key ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:dotted:nested.key:subkey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "value" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration was not read properly: Expected: " << expected << " Received: " << myvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_provider_conf ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myotherblock:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "myvalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration was not overridden: Expected: " << expected << " Received: " << myvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_provider_conf_dep ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); EXPECT_EXCEPTION( sprokit::provider_error_exception, sprokit::extract_configuration( blocks ), "Referencing config key not defined yet" ); } // ------------------------------------------------------------------ TEST_PROPERTY( ENVIRONMENT, TEST_ENV = expected ) IMPLEMENT_TEST( config_provider_env ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const config = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:myenv" ); const auto value = config->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "expected" ); if ( value != expected ) { TEST_ERROR( "Environment was not read properly: Expected: " << expected << " Received: " << value ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_provider_read_only ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const config = sprokit::extract_configuration( blocks ); const auto rokey = kwiver::vital::config_block_key_t( "myblock:mykey" ); if ( ! config->is_read_only( rokey ) ) { TEST_ERROR( "The configuration value was not marked as read only" ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_provider_read_only_override ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); EXPECT_EXCEPTION( kwiver::vital::set_on_read_only_value_exception, sprokit::extract_configuration( blocks ), "setting a read-only provided value" ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( pipeline_multiplier ) { kwiver::vital::plugin_manager::instance().load_all_plugins(); sprokit::pipeline_builder builder; builder.load_pipeline( pipe_file ); sprokit::pipeline_t const pipeline = builder.pipeline(); if ( ! pipeline ) { TEST_ERROR( "A pipeline was not created" ); return; } pipeline->process_by_name( "gen_numbers1" ); pipeline->process_by_name( "gen_numbers2" ); pipeline->process_by_name( "multiply" ); pipeline->process_by_name( "print" ); /// \todo Verify the connections are done properly. } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_multiplier ) { kwiver::vital::plugin_manager::instance().load_all_plugins(); sprokit::pipeline_builder builder; builder.load_cluster( pipe_file ); sprokit::cluster_info_t const info = builder.cluster_info(); const auto ctor = info->ctor; const auto config = kwiver::vital::config_block::empty_config(); std::stringstream str; str << int(30); config->set_value( "factor", str.str() ); sprokit::process_t const proc = ctor( config ); sprokit::process_cluster_t const cluster = std::dynamic_pointer_cast< sprokit::process_cluster > ( proc ); if ( ! cluster ) { TEST_ERROR( "A cluster was not created" ); return; } /// \todo Verify the configuration. /// \todo Verify the input mapping. /// \todo Verify the output mapping. /// \todo Verify the connections are done properly. } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_missing_cluster ) { (void)pipe_file; sprokit::cluster_blocks blocks; sprokit::process_pipe_block const pipe_block = sprokit::process_pipe_block(); sprokit::cluster_block const block = pipe_block; blocks.push_back( block ); EXPECT_EXCEPTION( sprokit::missing_cluster_block_exception, sprokit::bake_cluster_blocks( blocks ), "baking a set of cluster blocks without a cluster" ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_missing_processes ) { sprokit::cluster_blocks const blocks = load_cluster_blocks_from_file( pipe_file ); EXPECT_EXCEPTION( sprokit::cluster_without_processes_exception, sprokit::bake_cluster_blocks( blocks ), "baking a cluster without processes" ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_missing_ports ) { sprokit::cluster_blocks const blocks = load_cluster_blocks_from_file( pipe_file ); EXPECT_EXCEPTION( sprokit::cluster_without_ports_exception, sprokit::bake_cluster_blocks( blocks ), "baking a cluster without ports" ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_multiple_cluster ) { (void)pipe_file; sprokit::cluster_blocks blocks; sprokit::cluster_pipe_block const cluster_pipe_block = sprokit::cluster_pipe_block(); sprokit::cluster_block const cluster_block = cluster_pipe_block; blocks.push_back( cluster_block ); blocks.push_back( cluster_block ); EXPECT_EXCEPTION( sprokit::multiple_cluster_blocks_exception, sprokit::bake_cluster_blocks( blocks ), "baking a set of cluster blocks without multiple clusters" ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_duplicate_input ) { sprokit::cluster_blocks const blocks = load_cluster_blocks_from_file( pipe_file ); kwiver::vital::plugin_manager::instance().load_all_plugins(); EXPECT_EXCEPTION( sprokit::duplicate_cluster_input_port_exception, sprokit::bake_cluster_blocks( blocks ), "baking a cluster with duplicate input ports" ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_duplicate_output ) { sprokit::cluster_blocks const blocks = load_cluster_blocks_from_file( pipe_file ); kwiver::vital::plugin_manager::instance().load_all_plugins(); EXPECT_EXCEPTION( sprokit::duplicate_cluster_output_port_exception, sprokit::bake_cluster_blocks( blocks ), "baking a cluster with duplicate output ports" ); } static void test_cluster( sprokit::process_t const& cluster, std::string const& path ); // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_configuration_default ) { sprokit::cluster_blocks const blocks = load_cluster_blocks_from_file( pipe_file ); kwiver::vital::plugin_manager::instance().load_all_plugins(); sprokit::cluster_info_t const info = sprokit::bake_cluster_blocks( blocks ); const auto ctor = info->ctor; const auto config = kwiver::vital::config_block::empty_config(); sprokit::process_t const cluster = ctor( config ); std::string const output_path = "test-pipe_bakery-configuration_default.txt"; test_cluster( cluster, output_path ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_configuration_provide ) { sprokit::cluster_blocks const blocks = load_cluster_blocks_from_file( pipe_file ); kwiver::vital::plugin_manager::instance().load_all_plugins(); sprokit::cluster_info_t const info = sprokit::bake_cluster_blocks( blocks ); const auto ctor = info->ctor; const auto config = kwiver::vital::config_block::empty_config(); sprokit::process_t const cluster = ctor( config ); std::string const output_path = "test-pipe_bakery-configuration_provide.txt"; test_cluster( cluster, output_path ); } static sprokit::process_cluster_t setup_map_config_cluster( sprokit::process::name_t const& name, kwiver::vital::path_t const& pipe_file ); // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_map_config ) { /// \todo This test is poorly designed in that it tests for mapping by /// leveraging the fact that only mapped configuration get pushed through when /// reconfiguring a cluster. sprokit::process::name_t const cluster_name = sprokit::process::name_t( "cluster" ); sprokit::process_cluster_t const cluster = setup_map_config_cluster( cluster_name, pipe_file ); if ( ! cluster ) { TEST_ERROR( "A cluster was not created" ); return; } sprokit::pipeline_t const pipeline = std::make_shared< sprokit::pipeline > ( kwiver::vital::config_block::empty_config() ); pipeline->add_process( cluster ); pipeline->setup_pipeline(); const auto new_conf = kwiver::vital::config_block::empty_config(); const auto key = kwiver::vital::config_block_key_t( "tunable" ); const auto tuned_value = kwiver::vital::config_block_key_t( "expected" ); new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + key, tuned_value ); pipeline->reconfigure( new_conf ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_map_config_tunable ) { sprokit::process::name_t const cluster_name = sprokit::process::name_t( "cluster" ); sprokit::process_cluster_t const cluster = setup_map_config_cluster( cluster_name, pipe_file ); if ( ! cluster ) { TEST_ERROR( "A cluster was not created" ); return; } sprokit::pipeline_t const pipeline = std::make_shared< sprokit::pipeline > ( kwiver::vital::config_block::empty_config() ); pipeline->add_process( cluster ); pipeline->setup_pipeline(); const auto new_conf = kwiver::vital::config_block::empty_config(); const auto key = kwiver::vital::config_block_key_t( "tunable" ); const auto tuned_value = kwiver::vital::config_block_key_t( "expected" ); new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + key, tuned_value ); pipeline->reconfigure( new_conf ); } #if 0 // disable incomplete tests //+ Need to mangle the macro name so the CMake tooling does not //+ register these tests even though they are not active //------------------------------------------------------------------ DONT_IMPLEMENT_TEST( cluster_map_config_redirect ) { sprokit::process::name_t const cluster_name = sprokit::process::name_t( "cluster" ); sprokit::process_cluster_t const cluster = setup_map_config_cluster( cluster_name, pipe_file ); if ( ! cluster ) { TEST_ERROR( "A cluster was not created" ); return; } sprokit::pipeline_t const pipeline = std::make_shared< sprokit::pipeline > ( kwiver::vital::config_block::empty_config() ); pipeline->add_process( cluster ); pipeline->setup_pipeline(); const auto new_conf = kwiver::vital::config_block::empty_config(); const auto key = kwiver::vital::config_block_key_t( "tunable" ); const auto tuned_value = kwiver::vital::config_block_key_t( "expected" ); new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + key, tuned_value ); sprokit::process::name_t const proc_name = sprokit::process::name_t( "expect" ); const auto new_key = kwiver::vital::config_block_key_t( "new_key" ); // Fill a block so that the expect process gets reconfigured to do its check; // if the block for it is empty, the check won't happen. new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + proc_name + kwiver::vital::config_block::block_sep + new_key, tuned_value ); pipeline->reconfigure( new_conf ); } // ------------------------------------------------------------------ DONT_IMPLEMENT_TEST( cluster_map_config_modified ) { sprokit::process::name_t const cluster_name = sprokit::process::name_t( "cluster" ); sprokit::process_cluster_t const cluster = setup_map_config_cluster( cluster_name, pipe_file ); if ( ! cluster ) { TEST_ERROR( "A cluster was not created" ); return; } sprokit::pipeline_t const pipeline = std::make_shared< sprokit::pipeline > ( kwiver::vital::config_block::empty_config() ); pipeline->add_process( cluster ); pipeline->setup_pipeline(); const auto new_conf = kwiver::vital::config_block::empty_config(); const auto key = kwiver::vital::config_block_key_t( "tunable" ); const auto tuned_value = kwiver::vital::config_block_key_t( "expected" ); new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + key, tuned_value ); sprokit::process::name_t const proc_name = sprokit::process::name_t( "expect" ); const auto new_key = kwiver::vital::config_block_key_t( "new_key" ); // Fill a block so that the expect process gets reconfigured to do its check; // if the block for it is empty, the check won't happen. new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + proc_name + kwiver::vital::config_block::block_sep + new_key, tuned_value ); pipeline->reconfigure( new_conf ); } #endif // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_map_config_not_read_only ) { sprokit::process::name_t const cluster_name = sprokit::process::name_t( "cluster" ); sprokit::process_cluster_t const cluster = setup_map_config_cluster( cluster_name, pipe_file ); if ( ! cluster ) { TEST_ERROR( "A cluster was not created" ); return; } sprokit::pipeline_t const pipeline = std::make_shared< sprokit::pipeline > ( kwiver::vital::config_block::empty_config() ); pipeline->add_process( cluster ); pipeline->setup_pipeline(); const auto new_conf = kwiver::vital::config_block::empty_config(); const auto key = kwiver::vital::config_block_key_t( "tunable" ); const auto tuned_value = kwiver::vital::config_block_key_t( "unexpected" ); new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + key, tuned_value ); sprokit::process::name_t const proc_name = sprokit::process::name_t( "expect" ); const auto new_key = kwiver::vital::config_block_key_t( "new_key" ); // Fill a block so that the expect process gets reconfigured to do its check; // if the block for it is empty, the check won't happen. new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + proc_name + kwiver::vital::config_block::block_sep + new_key, tuned_value ); pipeline->reconfigure( new_conf ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_map_config_only_provided ) { sprokit::process::name_t const cluster_name = sprokit::process::name_t( "cluster" ); sprokit::process_cluster_t const cluster = setup_map_config_cluster( cluster_name, pipe_file ); if ( ! cluster ) { TEST_ERROR( "A cluster was not created" ); return; } sprokit::pipeline_t const pipeline = std::make_shared< sprokit::pipeline > ( kwiver::vital::config_block::empty_config() ); pipeline->add_process( cluster ); pipeline->setup_pipeline(); const auto new_conf = kwiver::vital::config_block::empty_config(); const auto key = kwiver::vital::config_block_key_t( "tunable" ); const auto tuned_value = kwiver::vital::config_block_key_t( "unexpected" ); new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + key, tuned_value ); sprokit::process::name_t const proc_name = sprokit::process::name_t( "expect" ); const auto new_key = kwiver::vital::config_block_key_t( "new_key" ); // Fill a block so that the expect process gets reconfigured to do its check; // if the block for it is empty, the check won't happen. new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + proc_name + kwiver::vital::config_block::block_sep + new_key, tuned_value ); pipeline->reconfigure( new_conf ); } // ------------------------------------------------------------------ TEST_PROPERTY( ENVIRONMENT, TEST_ENV = expected ) IMPLEMENT_TEST( cluster_map_config_only_conf_provided ) { sprokit::process::name_t const cluster_name = sprokit::process::name_t( "cluster" ); sprokit::process_cluster_t const cluster = setup_map_config_cluster( cluster_name, pipe_file ); if ( ! cluster ) { TEST_ERROR( "A cluster was not created" ); return; } sprokit::pipeline_t const pipeline = std::make_shared< sprokit::pipeline > ( kwiver::vital::config_block::empty_config() ); pipeline->add_process( cluster ); pipeline->setup_pipeline(); const auto new_conf = kwiver::vital::config_block::empty_config(); const auto key = kwiver::vital::config_block_key_t( "tunable" ); const auto tuned_value = kwiver::vital::config_block_key_t( "unexpected" ); new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + key, tuned_value ); sprokit::process::name_t const proc_name = sprokit::process::name_t( "expect" ); const auto new_key = kwiver::vital::config_block_key_t( "new_key" ); // Fill a block so that the expect process gets reconfigured to do its check; // if the block for it is empty, the check won't happen. new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + proc_name + kwiver::vital::config_block::block_sep + new_key, tuned_value ); pipeline->reconfigure( new_conf ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_map_config_to_non_process ) { /// \todo This test is poorly designed because there's no check that / the /// mapping wasn't actually created. sprokit::process::name_t const cluster_name = sprokit::process::name_t( "cluster" ); sprokit::process_cluster_t const cluster = setup_map_config_cluster( cluster_name, pipe_file ); if ( ! cluster ) { TEST_ERROR( "A cluster was not created" ); return; } sprokit::pipeline_t const pipeline = std::make_shared< sprokit::pipeline > ( kwiver::vital::config_block::empty_config() ); pipeline->add_process( cluster ); pipeline->setup_pipeline(); const auto new_conf = kwiver::vital::config_block::empty_config(); const auto key = kwiver::vital::config_block_key_t( "tunable" ); const auto tuned_value = kwiver::vital::config_block_key_t( "expected" ); new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + key, tuned_value ); sprokit::process::name_t const proc_name = sprokit::process::name_t( "expect" ); const auto new_key = kwiver::vital::config_block_key_t( "new_key" ); // Fill a block so that the expect process gets reconfigured to do its check; // if the block for it is empty, the check won't happen. new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + proc_name + kwiver::vital::config_block::block_sep + new_key, tuned_value ); pipeline->reconfigure( new_conf ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_map_config_not_from_cluster ) { sprokit::process::name_t const cluster_name = sprokit::process::name_t( "cluster" ); sprokit::process_cluster_t const cluster = setup_map_config_cluster( cluster_name, pipe_file ); if ( ! cluster ) { TEST_ERROR( "A cluster was not created" ); return; } sprokit::pipeline_t const pipeline = std::make_shared< sprokit::pipeline > ( kwiver::vital::config_block::empty_config() ); pipeline->add_process( cluster ); pipeline->setup_pipeline(); const auto new_conf = kwiver::vital::config_block::empty_config(); const auto proc_name = sprokit::process::name_t( "expect" ); const auto new_key = kwiver::vital::config_block_key_t( "new_key" ); const auto tuned_value = kwiver::vital::config_block_key_t( "expected" ); // Fill a block so that the expect process gets reconfigured to do its check; // if the block for it is empty, the check won't happen. new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + proc_name + kwiver::vital::config_block::block_sep + new_key, tuned_value ); pipeline->reconfigure( new_conf ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_override_mapped ) { sprokit::process::name_t const cluster_name = sprokit::process::name_t( "cluster" ); const auto conf = kwiver::vital::config_block::empty_config(); const auto proc_name = sprokit::process::name_t( "expect" ); const auto key = kwiver::vital::config_block_key_t( "tunable" ); const auto full_key = proc_name + kwiver::vital::config_block::block_sep + key; const auto value = kwiver::vital::config_block_value_t( "unexpected" ); // The problem here is that the expect:tunable parameter is meant to be mapped // with the map_config call within the cluster. Due to the implementation, // the lines which cause the linking are removed, so if we try to sneak in an // invalid parameter, we should get an error about overriding a read-only // variable. conf->set_value( full_key, value ); sprokit::cluster_blocks const blocks = load_cluster_blocks_from_file( pipe_file ); kwiver::vital::plugin_manager::instance().load_all_plugins(); sprokit::cluster_info_t const info = sprokit::bake_cluster_blocks( blocks ); const auto ctor = info->ctor; EXPECT_EXCEPTION( kwiver::vital::set_on_read_only_value_exception, ctor( conf ), "manually setting a parameter which is mapped in a cluster" ); } static sprokit::process_t create_process( sprokit::process::type_t const& type, sprokit::process::name_t const& name, kwiver::vital::config_block_sptr config = kwiver::vital::config_block::empty_config() ); static sprokit::pipeline_t create_pipeline(); // ------------------------------------------------------------------ void test_cluster( sprokit::process_t const& cluster, std::string const& path ) { sprokit::process::type_t const proc_typeu = sprokit::process::type_t( "numbers" ); sprokit::process::type_t const proc_typet = sprokit::process::type_t( "print_number" ); sprokit::process::name_t const proc_nameu = sprokit::process::name_t( "upstream" ); sprokit::process::name_t const proc_named = cluster->name(); sprokit::process::name_t const proc_namet = sprokit::process::name_t( "terminal" ); int32_t const start_value = 10; int32_t const end_value = 20; { const auto configu = kwiver::vital::config_block::empty_config(); const auto start_key = kwiver::vital::config_block_key_t( "start" ); const auto end_key = kwiver::vital::config_block_key_t( "end" ); std::stringstream str; str << start_value; const auto start_num = str.str(); str.clear(); str << end_value; const auto end_num = str.str(); configu->set_value( start_key, start_num ); configu->set_value( end_key, end_num ); const auto configt = kwiver::vital::config_block::empty_config(); const auto output_key = kwiver::vital::config_block_key_t( "output" ); const auto output_value = kwiver::vital::config_block_value_t( path ); configt->set_value( output_key, output_value ); sprokit::process_t const processu = create_process( proc_typeu, proc_nameu, configu ); sprokit::process_t const processt = create_process( proc_typet, proc_namet, configt ); sprokit::pipeline_t const pipeline = create_pipeline(); pipeline->add_process( processu ); pipeline->add_process( cluster ); pipeline->add_process( processt ); const auto port_nameu = sprokit::process::port_t( "number" ); const auto port_namedi = sprokit::process::port_t( "factor" ); const auto port_namedo = sprokit::process::port_t( "product" ); const auto port_namet = sprokit::process::port_t( "number" ); pipeline->connect( proc_nameu, port_nameu, proc_named, port_namedi ); pipeline->connect( proc_named, port_namedo, proc_namet, port_namet ); pipeline->setup_pipeline(); sprokit::scheduler_t const scheduler = sprokit::create_scheduler( sprokit::scheduler_factory::default_type, pipeline ); scheduler->start(); scheduler->wait(); } std::ifstream fin( path.c_str() ); if ( ! fin.good() ) { TEST_ERROR( "Could not open the output file" ); } std::string line; // From the input cluster. static const int32_t factor = 20; for ( int32_t i = start_value; i < end_value; ++i ) { if ( ! std::getline( fin, line ) ) { TEST_ERROR( "Failed to read a line from the file" ); } std::stringstream str; str << ( i * factor ); if ( kwiver::vital::config_block_value_t( line ) != str.str() ) { TEST_ERROR( "Did not get expected value: Expected: " << (i * factor) << " Received: " << line ); } } if ( std::getline( fin, line ) ) { TEST_ERROR( "More results than expected in the file" ); } if ( ! fin.eof() ) { TEST_ERROR( "Not at end of file" ); } } // test_cluster sprokit::process_t create_process( sprokit::process::type_t const& type, sprokit::process::name_t const& name, kwiver::vital::config_block_sptr config ) { static bool const modules_loaded = ( kwiver::vital::plugin_manager::instance().load_all_plugins(), true ); (void)modules_loaded; return sprokit::create_process( type, name, config ); } sprokit::pipeline_t create_pipeline() { return std::make_shared< sprokit::pipeline > (); } sprokit::process_cluster_t setup_map_config_cluster( sprokit::process::name_t const& name, kwiver::vital::path_t const& pipe_file ) { sprokit::cluster_blocks const blocks = load_cluster_blocks_from_file( pipe_file ); kwiver::vital::plugin_manager::instance().load_all_plugins(); sprokit::cluster_info_t const info = sprokit::bake_cluster_blocks( blocks ); const auto ctor = info->ctor; const auto config = kwiver::vital::config_block::empty_config(); config->set_value( sprokit::process::config_name, name ); sprokit::process_t const proc = ctor( config ); sprokit::process_cluster_t const cluster = std::dynamic_pointer_cast< sprokit::process_cluster > ( proc ); return cluster; }
35.854472
140
0.657581
neal-siekierski
cd58bcd6eb02b7c3b11c24a2cae39ed0b353711b
4,558
cpp
C++
src/3rdparty/pythonqt/generator/parser/rpp/preprocessor.cpp
aliakseis/FVD
8d549834fcf9e8fdd5ebecdcaf9410074876b2ed
[ "MIT" ]
null
null
null
src/3rdparty/pythonqt/generator/parser/rpp/preprocessor.cpp
aliakseis/FVD
8d549834fcf9e8fdd5ebecdcaf9410074876b2ed
[ "MIT" ]
null
null
null
src/3rdparty/pythonqt/generator/parser/rpp/preprocessor.cpp
aliakseis/FVD
8d549834fcf9e8fdd5ebecdcaf9410074876b2ed
[ "MIT" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Script Generator project on Qt Labs. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "preprocessor.h" #include <string> // register callback for include hooks static void includeFileHook(const std::string &, const std::string &, FILE *); #define PP_HOOK_ON_FILE_INCLUDED(A, B, C) includeFileHook(A, B, C) #include "pp.h" using namespace rpp; #include <QtCore/QtCore> class PreprocessorPrivate { public: QByteArray result; pp_environment env; QStringList includePaths; void initPP(pp &proc) { foreach(QString path, includePaths) proc.push_include_path(path.toStdString()); } }; QHash<QString, QStringList> includedFiles; void includeFileHook(const std::string &fileName, const std::string &filePath, FILE *) { includedFiles[QString::fromStdString(fileName)].append(QString::fromStdString(filePath)); } Preprocessor::Preprocessor() { d = new PreprocessorPrivate; includedFiles.clear(); } Preprocessor::~Preprocessor() { delete d; } void Preprocessor::processFile(const QString &fileName) { pp proc(d->env); d->initPP(proc); d->result.reserve(d->result.size() + 20 * 1024); d->result += "# 1 \"" + fileName.toLatin1() + "\"\n"; // ### REMOVE ME proc.file(fileName.toLocal8Bit().constData(), std::back_inserter(d->result)); } void Preprocessor::processString(const QByteArray &str) { pp proc(d->env); d->initPP(proc); proc(str.begin(), str.end(), std::back_inserter(d->result)); } QByteArray Preprocessor::result() const { return d->result; } void Preprocessor::addIncludePaths(const QStringList &includePaths) { d->includePaths += includePaths; } QStringList Preprocessor::macroNames() const { QStringList macros; pp_environment::const_iterator it = d->env.first_macro(); while (it != d->env.last_macro()) { const pp_macro *m = *it; macros += QString::fromLatin1(m->name->begin(), m->name->size()); ++it; } return macros; } QList<Preprocessor::MacroItem> Preprocessor::macros() const { QList<MacroItem> items; pp_environment::const_iterator it = d->env.first_macro(); while (it != d->env.last_macro()) { const pp_macro *m = *it; MacroItem item; item.name = QString::fromLatin1(m->name->begin(), m->name->size()); item.definition = QString::fromLatin1(m->definition->begin(), m->definition->size()); for (size_t i = 0; i < m->formals.size(); ++i) { item.parameters += QString::fromLatin1(m->formals[i]->begin(), m->formals[i]->size()); } item.isFunctionLike = m->function_like; #ifdef PP_WITH_MACRO_POSITION item.fileName = QString::fromLatin1(m->file->begin(), m->file->size()); #endif items += item; ++it; } return items; } /* int main() { Preprocessor pp; QStringList paths; paths << "/usr/include"; pp.addIncludePaths(paths); pp.processFile("pp-configuration"); pp.processFile("/usr/include/stdio.h"); qDebug() << pp.result(); return 0; } */
25.751412
93
0.64129
aliakseis
cd5905a4ef373352261cfb942ce39d9da755dec8
659
cpp
C++
torch/csrc/lazy/python/init.cpp
ljhOfGithub/pytorch
c568f7b16f2a98d72ff5b7c6c6161b67b2c27514
[ "Intel" ]
2
2022-02-14T13:56:03.000Z
2022-02-14T13:56:05.000Z
torch/csrc/lazy/python/init.cpp
ljhOfGithub/pytorch
c568f7b16f2a98d72ff5b7c6c6161b67b2c27514
[ "Intel" ]
1
2019-07-23T15:23:32.000Z
2019-07-23T15:32:23.000Z
torch/csrc/lazy/python/init.cpp
ljhOfGithub/pytorch
c568f7b16f2a98d72ff5b7c6c6161b67b2c27514
[ "Intel" ]
2
2019-07-23T14:37:31.000Z
2019-07-23T14:47:13.000Z
#include <torch/csrc/lazy/python/init.h> #include <torch/csrc/lazy/core/debug_util.h> #include <torch/csrc/lazy/python/python_util.h> namespace torch { namespace lazy { void initLazyBindings(PyObject* /* module */){ #ifndef USE_DEPLOY // When libtorch_python is loaded, we register the python frame getter // otherwise, debug util simply omits python frames // TODO(whc) can we make this work inside torch deploy interpreter? // it doesn't work as-is, possibly becuase GetPythonFrames resolves to external // cpython rather than embedded cpython GetPythonFramesFunction() = GetPythonFrames; #endif } } // namespace lazy } // namespace torch
29.954545
81
0.754173
ljhOfGithub
cd59fa9054e04fee861bc5998147190383fed43a
5,384
cpp
C++
B2G/gecko/content/events/src/nsDOMNotifyAudioAvailableEvent.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/content/events/src/nsDOMNotifyAudioAvailableEvent.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/content/events/src/nsDOMNotifyAudioAvailableEvent.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim:set ts=2 sw=2 sts=2 et cindent: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "nsError.h" #include "nsDOMNotifyAudioAvailableEvent.h" #include "nsDOMClassInfoID.h" // DOMCI_DATA, NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO #include "nsContentUtils.h" // NS_DROP_JS_OBJECTS #include "jsfriendapi.h" nsDOMNotifyAudioAvailableEvent::nsDOMNotifyAudioAvailableEvent(nsPresContext* aPresContext, nsEvent* aEvent, uint32_t aEventType, float* aFrameBuffer, uint32_t aFrameBufferLength, float aTime) : nsDOMEvent(aPresContext, aEvent), mFrameBuffer(aFrameBuffer), mFrameBufferLength(aFrameBufferLength), mTime(aTime), mCachedArray(nullptr), mAllowAudioData(false) { MOZ_COUNT_CTOR(nsDOMNotifyAudioAvailableEvent); if (mEvent) { mEvent->message = aEventType; } } DOMCI_DATA(NotifyAudioAvailableEvent, nsDOMNotifyAudioAvailableEvent) NS_IMPL_CYCLE_COLLECTION_CLASS(nsDOMNotifyAudioAvailableEvent) NS_IMPL_ADDREF_INHERITED(nsDOMNotifyAudioAvailableEvent, nsDOMEvent) NS_IMPL_RELEASE_INHERITED(nsDOMNotifyAudioAvailableEvent, nsDOMEvent) NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(nsDOMNotifyAudioAvailableEvent, nsDOMEvent) if (tmp->mCachedArray) { tmp->mCachedArray = nullptr; NS_DROP_JS_OBJECTS(tmp, nsDOMNotifyAudioAvailableEvent); } NS_IMPL_CYCLE_COLLECTION_UNLINK_END NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsDOMNotifyAudioAvailableEvent, nsDOMEvent) NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(nsDOMNotifyAudioAvailableEvent) NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mCachedArray) NS_IMPL_CYCLE_COLLECTION_TRACE_END NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(nsDOMNotifyAudioAvailableEvent) NS_INTERFACE_MAP_ENTRY(nsIDOMNotifyAudioAvailableEvent) NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(NotifyAudioAvailableEvent) NS_INTERFACE_MAP_END_INHERITING(nsDOMEvent) nsDOMNotifyAudioAvailableEvent::~nsDOMNotifyAudioAvailableEvent() { MOZ_COUNT_DTOR(nsDOMNotifyAudioAvailableEvent); if (mCachedArray) { mCachedArray = nullptr; NS_DROP_JS_OBJECTS(this, nsDOMNotifyAudioAvailableEvent); } } NS_IMETHODIMP nsDOMNotifyAudioAvailableEvent::GetFrameBuffer(JSContext* aCx, jsval* aResult) { if (!mAllowAudioData) { // Media is not same-origin, don't allow the data out. return NS_ERROR_DOM_SECURITY_ERR; } if (mCachedArray) { *aResult = OBJECT_TO_JSVAL(mCachedArray); return NS_OK; } // Cache this array so we don't recreate on next call. NS_HOLD_JS_OBJECTS(this, nsDOMNotifyAudioAvailableEvent); mCachedArray = JS_NewFloat32Array(aCx, mFrameBufferLength); if (!mCachedArray) { NS_DROP_JS_OBJECTS(this, nsDOMNotifyAudioAvailableEvent); return NS_ERROR_FAILURE; } memcpy(JS_GetFloat32ArrayData(mCachedArray, aCx), mFrameBuffer.get(), mFrameBufferLength * sizeof(float)); *aResult = OBJECT_TO_JSVAL(mCachedArray); return NS_OK; } NS_IMETHODIMP nsDOMNotifyAudioAvailableEvent::GetTime(float *aRetVal) { *aRetVal = mTime; return NS_OK; } NS_IMETHODIMP nsDOMNotifyAudioAvailableEvent::InitAudioAvailableEvent(const nsAString& aType, bool aCanBubble, bool aCancelable, float* aFrameBuffer, uint32_t aFrameBufferLength, float aTime, bool aAllowAudioData) { // Auto manage the memory which stores the frame buffer. This ensures // that if we exit due to some error, the memory will be freed. Otherwise, // the framebuffer's memory will be freed when this event is destroyed. nsAutoArrayPtr<float> frameBuffer(aFrameBuffer); nsresult rv = nsDOMEvent::InitEvent(aType, aCanBubble, aCancelable); NS_ENSURE_SUCCESS(rv, rv); mFrameBuffer = frameBuffer.forget(); mFrameBufferLength = aFrameBufferLength; mTime = aTime; mAllowAudioData = aAllowAudioData; return NS_OK; } nsresult NS_NewDOMAudioAvailableEvent(nsIDOMEvent** aInstancePtrResult, nsPresContext* aPresContext, nsEvent *aEvent, uint32_t aEventType, float* aFrameBuffer, uint32_t aFrameBufferLength, float aTime) { nsDOMNotifyAudioAvailableEvent* it = new nsDOMNotifyAudioAvailableEvent(aPresContext, aEvent, aEventType, aFrameBuffer, aFrameBufferLength, aTime); return CallQueryInterface(it, aInstancePtrResult); }
39.014493
108
0.670134
wilebeast
cd5b3fd49836834a174cc6548e2045163fc7744e
4,738
hpp
C++
src/main/cpp/Balau/Dev/Assert.hpp
borasoftware/balau
8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14
[ "Apache-2.0" ]
6
2018-12-30T15:09:26.000Z
2020-04-20T09:27:59.000Z
src/main/cpp/Balau/Dev/Assert.hpp
borasoftware/balau
8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14
[ "Apache-2.0" ]
null
null
null
src/main/cpp/Balau/Dev/Assert.hpp
borasoftware/balau
8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14
[ "Apache-2.0" ]
2
2019-11-12T08:07:16.000Z
2019-11-29T11:19:47.000Z
// @formatter:off // // Balau core C++ library // // Copyright (C) 2008 Bora Software (contact@borasoftware.com) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /// /// @file Assert.hpp /// /// Assertion utilities for development purposes. /// #ifndef COM_BORA_SOFTWARE__BALAU_DEV__ASSERT #define COM_BORA_SOFTWARE__BALAU_DEV__ASSERT #include <boost/core/ignore_unused.hpp> #include <string> #ifdef BALAU_ENABLE_STACKTRACES #include <boost/stacktrace.hpp> #endif #include <iostream> #include <sstream> namespace Balau { /// /// An assertion class for development purposes. /// class Assert { /// /// Abort after logging the message. /// public: static void fail(const char * fatalMessage) { performAssertion(false, fatalMessage, "Fail called"); } /////////////////////////////////////////////////////////////////////////// /// /// If the bug test assertion fails, abort after logging the message supplied by the function. /// public: template <typename StringFunctionT> static void assertion(bool test, StringFunctionT function) { performAssertion(test, function, "Bug found"); } /// /// If the bug test assertion fails, abort after logging the message. /// public: static void assertion(bool test, const char * fatalMessage) { performAssertion(test, fatalMessage, "Bug found"); } /// /// Abort if the bug test fails. /// public: static void assertion(bool test) { performAssertion(test, "", "Bug found"); } /// /// If the bug test assertion predicate function fails, abort after logging the message supplied by the function. /// public: template <typename TestFunctionT, typename StringFunctionT> static void assertion(TestFunctionT test, StringFunctionT function) { performAssertion(test, function, "Bug found"); } /// /// If the bug test assertion predicate function fails, abort after logging the message. /// public: template <typename TestFunctionT> static void assertion(TestFunctionT test, const char * fatalMessage) { performAssertion(test, fatalMessage, "Bug found"); } /// /// Abort if the bug test assertion predicate function fails. /// public: template <typename TestFunctionT> static void assertion(TestFunctionT test) { performAssertion(test, "", "Bug found"); } /////////////////////////////////////////////////////////////////////////// private: template <typename FunctionT> static void performAssertion(bool test, FunctionT function, const char * testType) { boost::ignore_unused(test); boost::ignore_unused(function); boost::ignore_unused(testType); #ifdef BALAU_DEBUG if (!test) { const std::string message = function(); abortProcess(message.c_str(), testType); } #endif } private: template <typename TestT, typename FunctionT> static void performAssertion(TestT test, FunctionT function, const char * testType) { boost::ignore_unused(test); boost::ignore_unused(function); boost::ignore_unused(testType); #ifdef BALAU_DEBUG if (!test()) { const std::string message = function(); abortProcess(message.c_str(), testType); } #endif } private: static void performAssertion(bool test, const char * fatalMessage, const char * testType) { boost::ignore_unused(test); boost::ignore_unused(fatalMessage); boost::ignore_unused(testType); #ifdef BALAU_DEBUG if (!test) { abortProcess(fatalMessage, testType); } #endif } private: template <typename TestT> static void performAssertion(TestT test, const char * fatalMessage, const char * testType) { boost::ignore_unused(test); boost::ignore_unused(fatalMessage); boost::ignore_unused(testType); #ifdef BALAU_DEBUG if (!test()) { abortProcess(fatalMessage, testType); } #endif } private: static void abortProcess(const char * fatalMessage, const char * testType) { std::ostringstream str; if (fatalMessage != nullptr) { str << testType << ": " << fatalMessage << "\n"; } else { str << testType << "\n"; } #ifdef BALAU_ENABLE_STACKTRACES str << "Stack trace: " << boost::stacktrace::stacktrace() << "\n"; #endif str << "Program will abort now\n"; std::cerr << str.str(); abort(); } }; } // namespace Balau #endif // COM_BORA_SOFTWARE__BALAU_DEV__ASSERT
26.768362
114
0.689109
borasoftware
cd5b741d65503fdf30eed5b872d5ebc30ca2acd7
6,347
cpp
C++
soundlib/plugins/DigiBoosterEcho.cpp
ev3dev/libopenmpt
06d2c8b26a148dc6e87ccfe2ab4bcb82a55d6714
[ "BSD-3-Clause" ]
null
null
null
soundlib/plugins/DigiBoosterEcho.cpp
ev3dev/libopenmpt
06d2c8b26a148dc6e87ccfe2ab4bcb82a55d6714
[ "BSD-3-Clause" ]
null
null
null
soundlib/plugins/DigiBoosterEcho.cpp
ev3dev/libopenmpt
06d2c8b26a148dc6e87ccfe2ab4bcb82a55d6714
[ "BSD-3-Clause" ]
null
null
null
/* * DigiBoosterEcho.cpp * ------------------- * Purpose: Implementation of the DigiBooster Pro Echo DSP * Notes : (currently none) * Authors: OpenMPT Devs, based on original code by Grzegorz Kraszewski (BSD 2-clause) * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #include "stdafx.h" #ifndef NO_PLUGINS #include "../Sndfile.h" #include "DigiBoosterEcho.h" OPENMPT_NAMESPACE_BEGIN IMixPlugin* DigiBoosterEcho::Create(VSTPluginLib &factory, CSoundFile &sndFile, SNDMIXPLUGIN *mixStruct) //------------------------------------------------------------------------------------------------------ { return new (std::nothrow) DigiBoosterEcho(factory, sndFile, mixStruct); } DigiBoosterEcho::DigiBoosterEcho(VSTPluginLib &factory, CSoundFile &sndFile, SNDMIXPLUGIN *mixStruct) : IMixPlugin(factory, sndFile, mixStruct) , m_bufferSize(0) , m_writePos(0) , m_sampleRate(sndFile.GetSampleRate()) //--------------------------------------------------------------------------------------------------- { m_mixBuffer.Initialize(2, 2); InsertIntoFactoryList(); } void DigiBoosterEcho::Process(float *pOutL, float *pOutR, uint32 numFrames) //------------------------------------------------------------------------- { if(!m_bufferSize) return; const float *srcL = m_mixBuffer.GetInputBuffer(0), *srcR = m_mixBuffer.GetInputBuffer(1); float *outL = m_mixBuffer.GetOutputBuffer(0), *outR = m_mixBuffer.GetOutputBuffer(1); for(uint32 i = numFrames; i != 0; i--) { int readPos = m_writePos - m_delayTime; if(readPos < 0) readPos += m_bufferSize; float l = *srcL++, r = *srcR++; float lDelay = m_delayLine[readPos * 2], rDelay = m_delayLine[readPos * 2 + 1]; // Calculate the delay float al = l * m_NCrossNBack; al += r * m_PCrossNBack; al += lDelay * m_NCrossPBack; al += rDelay * m_PCrossPBack; float ar = r * m_NCrossNBack; ar += l * m_PCrossNBack; ar += rDelay * m_NCrossPBack; ar += lDelay * m_PCrossPBack; // Prevent denormals if(mpt::abs(al) < 1e-24f) al = 0.0f; if(mpt::abs(ar) < 1e-24f) ar = 0.0f; m_delayLine[m_writePos * 2] = al; m_delayLine[m_writePos * 2 + 1] = ar; m_writePos++; if(m_writePos == m_bufferSize) m_writePos = 0; // Output samples now *outL++ = (l * m_NMix + lDelay * m_PMix); *outR++ = (r * m_NMix + rDelay * m_PMix); } ProcessMixOps(pOutL, pOutR, m_mixBuffer.GetOutputBuffer(0), m_mixBuffer.GetOutputBuffer(1), numFrames); } void DigiBoosterEcho::SaveAllParameters() //--------------------------------------- { m_pMixStruct->defaultProgram = -1; if(m_pMixStruct->nPluginDataSize != sizeof(chunk) || m_pMixStruct->pPluginData == nullptr) { delete[] m_pMixStruct->pPluginData; m_pMixStruct->nPluginDataSize = sizeof(chunk); m_pMixStruct->pPluginData = new (std::nothrow) char[sizeof(chunk)]; } if(m_pMixStruct->pPluginData != nullptr) { memcpy(m_pMixStruct->pPluginData, &chunk, sizeof(chunk)); } } void DigiBoosterEcho::RestoreAllParameters(int32 program) //------------------------------------------------------- { if(m_pMixStruct->nPluginDataSize == sizeof(chunk) && !memcmp(m_pMixStruct->pPluginData, "Echo", 4)) { memcpy(&chunk, m_pMixStruct->pPluginData, sizeof(chunk)); } else { IMixPlugin::RestoreAllParameters(program); } RecalculateEchoParams(); } PlugParamValue DigiBoosterEcho::GetParameter(PlugParamIndex index) //---------------------------------------------------------------- { if(index < kEchoNumParameters) { return chunk.param[index] / 255.0f; } return 0; } void DigiBoosterEcho::SetParameter(PlugParamIndex index, PlugParamValue value) //---------------------------------------------------------------------------- { if(index < kEchoNumParameters) { chunk.param[index] = Util::Round<uint8>(value * 255.0f); RecalculateEchoParams(); } } void DigiBoosterEcho::Resume() //---------------------------- { m_isResumed = true; m_sampleRate = m_SndFile.GetSampleRate(); m_bufferSize = (m_sampleRate >> 1) + (m_sampleRate >> 6); RecalculateEchoParams(); try { m_delayLine.assign(m_bufferSize * 2, 0); } catch(MPTMemoryException) { m_bufferSize = 0; } m_writePos = 0; } #ifdef MODPLUG_TRACKER CString DigiBoosterEcho::GetParamName(PlugParamIndex param) //--------------------------------------------------------- { switch(param) { case kEchoDelay: return _T("Delay"); case kEchoFeedback: return _T("Feedback"); case kEchoMix: return _T("Wet / Dry Ratio"); case kEchoCross: return _T("Cross Echo"); } return CString(); } CString DigiBoosterEcho::GetParamLabel(PlugParamIndex param) //---------------------------------------------------------- { if(param == kEchoDelay) return _T("ms"); return CString(); } CString DigiBoosterEcho::GetParamDisplay(PlugParamIndex param) //------------------------------------------------------------ { CString s; if(param == kEchoMix) { int wet = (chunk.param[kEchoMix] * 100) / 255; s.Format(_T("%d%% / %d%%"), wet, 100 - wet); } else if(param < kEchoNumParameters) { int val = chunk.param[param]; if(param == kEchoDelay) val *= 2; s.Format(_T("%d"), val); } return s; } #endif // MODPLUG_TRACKER size_t DigiBoosterEcho::GetChunk(char *(&data), bool) //--------------------------------------------------- { data = reinterpret_cast<char *>(&chunk); return sizeof(chunk); } void DigiBoosterEcho::SetChunk(size_t size, char *data, bool) //----------------------------------------------------------- { if(size == sizeof(chunk) && !memcmp(data, "Echo", 4)) { memcpy(&chunk, data, size); RecalculateEchoParams(); } } void DigiBoosterEcho::RecalculateEchoParams() //------------------------------------------- { m_delayTime = (chunk.param[kEchoDelay] * m_sampleRate + 250) / 500; m_PMix = (chunk.param[kEchoMix]) * (1.0f / 256.0f); m_NMix = (256 - chunk.param[kEchoMix]) * (1.0f / 256.0f); m_PCrossPBack = (chunk.param[kEchoCross] * chunk.param[kEchoFeedback]) * (1.0f / 65536.0f); m_PCrossNBack = (chunk.param[kEchoCross] * (256 - chunk.param[kEchoFeedback])) * (1.0f / 65536.0f); m_NCrossPBack = ((chunk.param[kEchoCross] - 256) * chunk.param[kEchoFeedback]) * (1.0f / 65536.0f); m_NCrossNBack = ((chunk.param[kEchoCross] - 256) * (chunk.param[kEchoFeedback] - 256)) * (1.0f / 65536.0f); } OPENMPT_NAMESPACE_END #endif // NO_PLUGINS
26.668067
108
0.598393
ev3dev
cd5cd82914164fe87e414e025406662814b15a1b
2,913
cpp
C++
src/projects/scripts/run.cpp
AntonBankevich/DR
73450ad3b25f90a3c7747aaf17fe60d13d9692d3
[ "BSD-3-Clause" ]
3
2020-11-14T14:41:55.000Z
2020-12-12T07:05:51.000Z
src/projects/scripts/run.cpp
AntonBankevich/DR
73450ad3b25f90a3c7747aaf17fe60d13d9692d3
[ "BSD-3-Clause" ]
1
2022-02-01T11:16:31.000Z
2022-02-01T18:56:55.000Z
src/projects/scripts/run.cpp
AntonBankevich/DR
73450ad3b25f90a3c7747aaf17fe60d13d9692d3
[ "BSD-3-Clause" ]
null
null
null
#include <common/verify.hpp> #include <experimental/filesystem> #include <fstream> #include <unistd.h> #include <common/dir_utils.hpp> #include <common/string_utils.hpp> std::string getFirst(const std::experimental::filesystem::path &cfile) { std::string res; std::ifstream is; is.open(cfile); std::getline(is, res); is.close(); return std::move(res); } void removeFirst(const std::experimental::filesystem::path &cfile) { std::vector<std::string> contents; std::string next; std::ifstream is; is.open(cfile); while(std::getline(is, next)) { if(!next.empty()) { contents.emplace_back(next); } } is.close(); std::ofstream os; os.open(cfile); contents.erase(contents.begin()); for(std::string &line : contents) { os << line << "\n"; } os.close(); } void append(const std::experimental::filesystem::path &cfile, const std::string &next) { std::ofstream os; os.open(cfile, std::ios_base::app); os << next << "\n"; os.close(); } int main(int argc, char **argv) { VERIFY(argc == 3); std::experimental::filesystem::path cfile(argv[1]); std::experimental::filesystem::path dir(argv[2]); ensure_dir_existance(dir); ensure_dir_existance(dir / "logs"); std::experimental::filesystem::path log_path = dir/"log.txt"; size_t max = 0; for(const std::experimental::filesystem::path &p :std::experimental::filesystem::directory_iterator(dir / "logs")){ max = std::max<size_t>(max, std::stoull(p.filename())); } bool slept = false; #pragma clang diagnostic push #pragma ide diagnostic ignored "EndlessLoop" while(true) { std::string command = getFirst(cfile); if(command.empty()) { if(!slept) { std::cout << "No command. Sleeping." << std::endl; slept = true; } sleep(60); } else { slept = false; std::cout << "Running new command: " << command << std::endl; std::experimental::filesystem::path log(dir/"logs"/itos(max + 1)); std::cout << "Printing output to file " << log << std::endl; std::ofstream os; os.open(log_path, std::ios_base::app); os << (max + 1) << " started\n" << command << "\n"; os.close(); int res = system((command + " > " + log.string() + " 2>&1").c_str()); std::cout << "Finished running command: " << command << std::endl; std::cout << "Return code: " << res << "\n\n" << std::endl; std::ofstream os1; os1.open(log_path, std::ios_base::app); os1 << (max + 1) << " finished " << res << "\n\n"; os1.close(); max++; removeFirst(cfile); append(dir / "finished.txt", command); } } #pragma clang diagnostic pop }
33.482759
119
0.557501
AntonBankevich
cd6085a4c75c956e4f3511e5d4460f2db121b6ba
6,017
cc
C++
contrib/gcc-4.1/libstdc++-v3/src/ios.cc
masami256/dfly-3.0.2-bhyve
6f6c18db6fa90734135a2044769035eb82b821c1
[ "BSD-3-Clause" ]
3
2017-03-06T14:12:57.000Z
2019-11-23T09:35:10.000Z
contrib/gcc-4.1/libstdc++-v3/src/ios.cc
masami256/dfly-3.0.2-bhyve
6f6c18db6fa90734135a2044769035eb82b821c1
[ "BSD-3-Clause" ]
null
null
null
contrib/gcc-4.1/libstdc++-v3/src/ios.cc
masami256/dfly-3.0.2-bhyve
6f6c18db6fa90734135a2044769035eb82b821c1
[ "BSD-3-Clause" ]
null
null
null
// Iostreams base classes -*- C++ -*- // Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 // Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 2, 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 General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING. If not, write to the Free // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, // USA. // As a special exception, you may use this file as part of a free software // library without restriction. Specifically, if other files instantiate // templates or use macros or inline functions from this file, or you compile // this file and link it with other files to produce an executable, this // file does not by itself cause the resulting executable to be covered by // the GNU General Public License. This exception does not however // invalidate any other reasons why the executable file might be covered by // the GNU General Public License. // // ISO C++ 14882: 27.4 Iostreams base classes // #include <ios> #include <limits> #include <bits/atomicity.h> namespace std { // Definitions for static const members of ios_base. const ios_base::fmtflags ios_base::boolalpha; const ios_base::fmtflags ios_base::dec; const ios_base::fmtflags ios_base::fixed; const ios_base::fmtflags ios_base::hex; const ios_base::fmtflags ios_base::internal; const ios_base::fmtflags ios_base::left; const ios_base::fmtflags ios_base::oct; const ios_base::fmtflags ios_base::right; const ios_base::fmtflags ios_base::scientific; const ios_base::fmtflags ios_base::showbase; const ios_base::fmtflags ios_base::showpoint; const ios_base::fmtflags ios_base::showpos; const ios_base::fmtflags ios_base::skipws; const ios_base::fmtflags ios_base::unitbuf; const ios_base::fmtflags ios_base::uppercase; const ios_base::fmtflags ios_base::adjustfield; const ios_base::fmtflags ios_base::basefield; const ios_base::fmtflags ios_base::floatfield; const ios_base::iostate ios_base::badbit; const ios_base::iostate ios_base::eofbit; const ios_base::iostate ios_base::failbit; const ios_base::iostate ios_base::goodbit; const ios_base::openmode ios_base::app; const ios_base::openmode ios_base::ate; const ios_base::openmode ios_base::binary; const ios_base::openmode ios_base::in; const ios_base::openmode ios_base::out; const ios_base::openmode ios_base::trunc; const ios_base::seekdir ios_base::beg; const ios_base::seekdir ios_base::cur; const ios_base::seekdir ios_base::end; _Atomic_word ios_base::Init::_S_refcount; bool ios_base::Init::_S_synced_with_stdio = true; ios_base::ios_base() : _M_precision(), _M_width(), _M_flags(), _M_exception(), _M_streambuf_state(), _M_callbacks(0), _M_word_zero(), _M_word_size(_S_local_word_size), _M_word(_M_local_word), _M_ios_locale() { // Do nothing: basic_ios::init() does it. // NB: _M_callbacks and _M_word must be zero for non-initialized // ios_base to go through ~ios_base gracefully. } // 27.4.2.7 ios_base constructors/destructors ios_base::~ios_base() { _M_call_callbacks(erase_event); _M_dispose_callbacks(); if (_M_word != _M_local_word) { delete [] _M_word; _M_word = 0; } } // 27.4.2.5 ios_base storage functions int ios_base::xalloc() throw() { // Implementation note: Initialize top to zero to ensure that // initialization occurs before main() is started. static _Atomic_word _S_top = 0; return __gnu_cxx::__exchange_and_add(&_S_top, 1) + 4; } void ios_base::register_callback(event_callback __fn, int __index) { _M_callbacks = new _Callback_list(__fn, __index, _M_callbacks); } // 27.4.2.5 iword/pword storage ios_base::_Words& ios_base::_M_grow_words(int __ix, bool __iword) { // Precondition: _M_word_size <= __ix int __newsize = _S_local_word_size; _Words* __words = _M_local_word; if (__ix > _S_local_word_size - 1) { if (__ix < numeric_limits<int>::max()) { __newsize = __ix + 1; try { __words = new _Words[__newsize]; } catch (...) { _M_streambuf_state |= badbit; if (_M_streambuf_state & _M_exception) __throw_ios_failure(__N("ios_base::_M_grow_words " "allocation failed")); if (__iword) _M_word_zero._M_iword = 0; else _M_word_zero._M_pword = 0; return _M_word_zero; } for (int __i = 0; __i < _M_word_size; __i++) __words[__i] = _M_word[__i]; if (_M_word && _M_word != _M_local_word) { delete [] _M_word; _M_word = 0; } } else { _M_streambuf_state |= badbit; if (_M_streambuf_state & _M_exception) __throw_ios_failure(__N("ios_base::_M_grow_words is not valid")); if (__iword) _M_word_zero._M_iword = 0; else _M_word_zero._M_pword = 0; return _M_word_zero; } } _M_word = __words; _M_word_size = __newsize; return _M_word[__ix]; } void ios_base::_M_call_callbacks(event __e) throw() { _Callback_list* __p = _M_callbacks; while (__p) { try { (*__p->_M_fn) (__e, *this, __p->_M_index); } catch (...) { } __p = __p->_M_next; } } void ios_base::_M_dispose_callbacks(void) { _Callback_list* __p = _M_callbacks; while (__p && __p->_M_remove_reference() == 0) { _Callback_list* __next = __p->_M_next; delete __p; __p = __next; } _M_callbacks = 0; } } // namespace std
30.85641
79
0.69769
masami256
cd6135ffe5611c062dd725a7d1803a1549aa1639
605
hpp
C++
willow/include/popart/popx/op/reducesumsquarex.hpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
61
2020-07-06T17:11:46.000Z
2022-03-12T14:42:51.000Z
willow/include/popart/popx/op/reducesumsquarex.hpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
1
2021-02-25T01:30:29.000Z
2021-11-09T11:13:14.000Z
willow/include/popart/popx/op/reducesumsquarex.hpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
6
2020-07-15T12:33:13.000Z
2021-11-07T06:55:00.000Z
// Copyright (c) 2018 Graphcore Ltd. All rights reserved. #ifndef GUARD_NEURALNET_REDUCESUMSQUAREX_HPP #define GUARD_NEURALNET_REDUCESUMSQUAREX_HPP #include <popart/names.hpp> #include <popart/popx/popopx.hpp> namespace popart { namespace popx { class ReduceSumSquareOpx : public PopOpx { public: ReduceSumSquareOpx(Op *, Devicex *); void grow(snap::program::Sequence &) const override; }; class ReduceSumSquareGradOpx : public PopOpx { public: ReduceSumSquareGradOpx(Op *, Devicex *); void grow(snap::program::Sequence &) const override; }; } // namespace popx } // namespace popart #endif
22.407407
57
0.758678
gglin001
cd62b9eb823200cbe57965f55ecc0ad90ba578ba
405
hpp
C++
src/TextFile.hpp
oleksandrkozlov/touch-typing
e38f315fa979ab66539c0a6a47796b5e6cabe0a2
[ "MIT" ]
1
2020-10-10T14:04:15.000Z
2020-10-10T14:04:15.000Z
src/TextFile.hpp
oleksandrkozlov/touch-typing
e38f315fa979ab66539c0a6a47796b5e6cabe0a2
[ "MIT" ]
37
2020-04-19T12:37:03.000Z
2021-06-06T09:33:37.000Z
src/TextFile.hpp
oleksandrkozlov/touch-typing
e38f315fa979ab66539c0a6a47796b5e6cabe0a2
[ "MIT" ]
null
null
null
#ifndef TOUCH_TYPING_TEXT_FILER_HPP #define TOUCH_TYPING_TEXT_FILER_HPP #include <filesystem> #include <string> namespace touch_typing { class TextFile { public: explicit TextFile(const std::filesystem::path& filename); [[nodiscard]] auto asString() const noexcept -> const std::string&; private: std::string m_text; }; } // namespace touch_typing #endif // TOUCH_TYPING_TEXT_FILER_HPP
18.409091
71
0.753086
oleksandrkozlov
cd661369a54ab9c8aa3fdc9d51347c4ab770b7e6
3,534
hpp
C++
include/eve/module/bessel/detail/kernel_bessel_i.hpp
HadrienG2/eve
3afdcfb524f88c0b88df9b54e25bbb9b33f518ec
[ "MIT" ]
null
null
null
include/eve/module/bessel/detail/kernel_bessel_i.hpp
HadrienG2/eve
3afdcfb524f88c0b88df9b54e25bbb9b33f518ec
[ "MIT" ]
null
null
null
include/eve/module/bessel/detail/kernel_bessel_i.hpp
HadrienG2/eve
3afdcfb524f88c0b88df9b54e25bbb9b33f518ec
[ "MIT" ]
null
null
null
//================================================================================================== /** EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #pragma once #include <eve/module/core.hpp> #include <eve/module/math.hpp> #include <eve/module/bessel/regular/cyl_bessel_i0.hpp> #include <eve/module/bessel/regular/cyl_bessel_i1.hpp> #include <eve/module/bessel/detail/kernel_bessel_ik.hpp> #include <eve/module/bessel/detail/kernel_bessel_ij_small.hpp> ///////////////////////////////////////////////////////////////////////////////// // These routines are detail of the computation of modifiesd cylindrical bessel // fnctions of the first kind. . // They are not meant to be called directly, as their validities depends on // n and x ranges values which are not tested on entry. // The inspiration is from boost math ///////////////////////////////////////////////////////////////////////////////// namespace eve::detail { ///////////////////////////////////////////////////////////////////////// // bessel_i template<floating_real_value T> EVE_FORCEINLINE auto kernel_bessel_i (T n, T x) noexcept { auto br_small = [](auto n, auto x) { return bessel_i_small_z_series(n, x); }; auto br_medium = [](auto n, auto x) { auto [in, ipn, kn, kpn] = kernel_bessel_ik(n, x); return in; }; auto br_half = [](auto x) { if(eve::any(x >= maxlog(as(x)))) { auto ex = eve::exp(x/2); return ex*(ex*rsqrt(x*twopi(as(x)))); } else return rsqrt(x*pio_2(as(x)))*sinh(x); }; if constexpr(scalar_value<T>) { if (is_ngez(x)) return nan(as(x)); if (is_eqz(x)) return (n == 0) ? one(as(x)) : zero(as(x)); if (x == inf(as(x))) return inf(as(x)); if (n == T(0.5)) return br_half(x); //cyl_bessel_i order 0.5 if (n == 0) return cyl_bessel_i0(x); //cyl_bessel_i0(x); if (n == 1) return cyl_bessel_i1(x); //cyl_bessel_i1(x); if (x*4 < n) return br_small(n, x); // serie return br_medium(n, x); // general } else { auto r = nan(as(x)); auto isinfx = x == inf(as(x)); r = if_else(isinfx, inf(as(x)), allbits); x = if_else(isinfx, mone, x); auto iseqzx = is_eqz(x); auto iseqzn = is_eqz(n); if (eve::any(iseqzx)) { r = if_else(iseqzx, if_else(iseqzn, zero, one(as(x))), r); } if (eve::any(iseqzn)) { r = if_else(iseqzn, cyl_bessel_i0(x), r); } auto iseq1n = n == one(as(n)); if (eve::any(iseq1n)) { r = if_else(n == one(as(n)), cyl_bessel_i1(x), r); } auto notdone = is_gez(x) && !(iseqzn || iseq1n) ; x = if_else(notdone, x, allbits); if( eve::any(notdone) ) { notdone = next_interval(br_half, notdone, n == T(0.5), r, x); if( eve::any(notdone) ) { if( eve::any(notdone) ) { notdone = last_interval(br_medium, notdone, r, n, x); } } } return r; } } }
34.647059
101
0.44652
HadrienG2
cd6814ea4fe461770f5a10fa91ae225fab1ccbf8
13,619
hpp
C++
src/include/tdap/Limiter.hpp
emmef/speakerman
ea2352c6291b015375056120280640f50fd084e1
[ "Apache-2.0" ]
2
2016-05-02T07:52:31.000Z
2020-02-15T16:03:05.000Z
src/include/tdap/Limiter.hpp
emmef/speakerman
ea2352c6291b015375056120280640f50fd084e1
[ "Apache-2.0" ]
3
2016-09-08T22:56:12.000Z
2022-03-06T10:47:35.000Z
src/include/tdap/Limiter.hpp
emmef/speakerman
ea2352c6291b015375056120280640f50fd084e1
[ "Apache-2.0" ]
1
2022-03-05T21:38:39.000Z
2022-03-05T21:38:39.000Z
#ifndef TDAP_M_LIMITER_HPP #define TDAP_M_LIMITER_HPP /* * tdap/Limiter.hpp * * Added by michel on 2020-02-09 * Copyright (C) 2015-2020 Michel Fleur. * Source https://github.com/emmef/speakerman * Email speakerman@emmef.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <algorithm> #include <tdap/Followers.hpp> namespace tdap { template <typename T> class Limiter { public: virtual void setPredictionAndThreshold(size_t prediction, T threshold, T sampleRate) = 0; virtual size_t latency() const noexcept = 0; virtual T getGain(T sample) noexcept = 0; virtual ~Limiter() = default; }; template <typename T> class CheapLimiter : public Limiter<T> { IntegrationCoefficients<T> release_; IntegrationCoefficients<T> attack_; T hold_ = 0; T integrated1_ = 0; T integrated2_ = 0; T threshold_ = 1.0; T adjustedPeakFactor_ = 1.0; size_t holdCount_ = 0; bool inRelease = false; size_t latency_ = 0; static constexpr double predictionFactor = 0.30; public: void setPredictionAndThreshold(size_t prediction, T threshold, T sampleRate) override { double release = sampleRate * 0.04; double thresholdFactor = 1.0 - exp(-1.0 / predictionFactor); latency_ = prediction; attack_.setCharacteristicSamples(predictionFactor * prediction); release_.setCharacteristicSamples(release * M_SQRT1_2); threshold_ = threshold; integrated1_ = integrated2_ = threshold_; adjustedPeakFactor_ = 1.0 / thresholdFactor; } size_t latency() const noexcept override { return latency_; } T getGain(T sample) noexcept override { T peak = std::max(sample, threshold_); if (peak >= hold_) { hold_ = peak * adjustedPeakFactor_; holdCount_ = latency_ + 1; integrated1_ += attack_.inputMultiplier() * (hold_ - integrated1_); integrated2_ = integrated1_; } else if (holdCount_) { holdCount_--; integrated1_ += attack_.inputMultiplier() * (hold_ - integrated1_); integrated2_ = integrated1_; } else { hold_ = peak; integrated1_ += release_.inputMultiplier() * (hold_ - integrated1_); integrated2_ += release_.inputMultiplier() * (integrated1_ - integrated2_); } return threshold_ / integrated2_; } }; template <typename T> class FastLookAheadLimiter : public Limiter<T> { FastSmoothHoldFollower<T> follower; public: void setPredictionAndThreshold(size_t prediction, T threshold, T sampleRate) override { T predictionSeconds = 1.0 * prediction / sampleRate; follower.setPredictionAndThreshold( predictionSeconds, threshold, sampleRate, std::clamp(predictionSeconds * 5, 0.003, 0.02), threshold); } size_t latency() const noexcept override { return follower.latency(); } T getGain(T sample) noexcept override { return follower.getGain(sample); } }; template <typename T> class ZeroPredictionHardAttackLimiter : public Limiter<T> { IntegrationCoefficients<T> release_; T integrated1_ = 0; T integrated2_ = 0; T threshold_ = 1.0; static constexpr double predictionFactor = 0.30; public: void setPredictionAndThreshold(size_t prediction, T threshold, T sampleRate) override { size_t release = Floats::clamp(prediction * 8, sampleRate * 0.010, sampleRate * 0.020); release_.setCharacteristicSamples(release * M_SQRT1_2); threshold_ = threshold; integrated1_ = integrated2_ = threshold_; std::cout << "HARD no prediction limiter" << std::endl; } size_t latency() const noexcept override { return 0; } T getGain(T sample) noexcept override { T peak = std::max(sample, threshold_); if (peak >= integrated1_) { integrated2_ = integrated1_ = peak; } else { integrated1_ += release_.inputMultiplier() * (peak - integrated1_); integrated2_ += release_.inputMultiplier() * (integrated1_ - integrated2_); } return threshold_ / integrated2_; } }; template <typename T> class TriangularLimiter : public Limiter<T> { static constexpr double ATTACK_SMOOTHFACTOR = 0.1; static constexpr double RELEASE_SMOOTHFACTOR = 0.3; static constexpr double TOTAL_TIME_FACTOR = 1.0 + ATTACK_SMOOTHFACTOR; static constexpr double ADJUST_THRESHOLD = 0.99999; TriangularFollower<T> follower_; IntegrationCoefficients<T> release_; T integrated_ = 0; T adjustedThreshold_; size_t latency_ = 0; public: TriangularLimiter() : follower_(1000) {} void setPredictionAndThreshold(size_t prediction, T threshold, T sampleRate) override { size_t attack = prediction; latency_ = prediction; size_t release = Floats::clamp(prediction * 8, sampleRate * 0.010, sampleRate * 0.020); adjustedThreshold_ = threshold * ADJUST_THRESHOLD; follower_.setTimeConstantAndSamples(attack, release, adjustedThreshold_); release_.setCharacteristicSamples(release * RELEASE_SMOOTHFACTOR); integrated_ = adjustedThreshold_; std::cout << "TriangularLimiter" << std::endl; } size_t latency() const noexcept override { return latency_; } T getGain(T input) noexcept override { T followed = follower_.follow(input); T integrationFactor; if (followed > integrated_) { integrationFactor = 1.0; // attack_.inputMultiplier(); } else { integrationFactor = release_.inputMultiplier(); } integrated_ += integrationFactor * (followed - integrated_); return adjustedThreshold_ / integrated_; } }; template <typename sample_t> class PredictiveSmoothEnvelopeLimiter { Array<sample_t> attack_envelope_; Array<sample_t> release_envelope_; Array<sample_t> peaks_; sample_t threshold_; sample_t smoothness_; sample_t current_peak_; size_t release_count_; size_t current_sample; size_t attack_samples_; size_t release_samples_; static void create_smooth_semi_exponential_envelope(sample_t *envelope, const size_t length, size_t periods) { const sample_t periodExponent = exp(-1.0 * periods); size_t i; for (i = 0; i < length; i++) { envelope[i] = limiter_envelope_value(i, length, periods, periodExponent); } } template <typename... A> static void create_smooth_semi_exponential_envelope( ArrayTraits<sample_t, A...> envelope, const size_t length, size_t periods) { create_smooth_semi_exponential_envelope(envelope + 0, length, periods); } static inline double limiter_envelope_value(const size_t i, const size_t length, const double periods, const double periodExponent) { const double angle = M_PI * (i + 1) / length; const double ePower = 0.5 * periods * (cos(angle) - 1.0); const double envelope = (exp(ePower) - periodExponent) / (1.0 - periodExponent); return envelope; } void generate_envelopes_reset(bool recalculate_attack_envelope = true, bool recalculate_release_envelope = true) { if (recalculate_attack_envelope) { PredictiveSmoothEnvelopeLimiter::create_smooth_semi_exponential_envelope( attack_envelope_ + 0, attack_samples_, smoothness_); } if (recalculate_release_envelope) { PredictiveSmoothEnvelopeLimiter::create_smooth_semi_exponential_envelope( release_envelope_ + 0, release_samples_, smoothness_); } release_count_ = 0; current_peak_ = 0; current_sample = 0; } inline const sample_t getAmpAndMoveToNextSample(const sample_t newValue) { const sample_t pk = peaks_[current_sample]; peaks_[current_sample] = newValue; current_sample = (current_sample + attack_samples_ - 1) % attack_samples_; const sample_t threshold = threshold_; return threshold / (threshold + pk); } public: PredictiveSmoothEnvelopeLimiter(sample_t threshold, sample_t smoothness, const size_t max_attack_samples, const size_t max_release_samples) : threshold_(threshold), smoothness_(smoothness), attack_envelope_(max_attack_samples), release_envelope_(max_release_samples), peaks_(max_attack_samples), release_count_(0), current_peak_(0), current_sample(0), attack_samples_(max_attack_samples), release_samples_(max_release_samples) { generate_envelopes_reset(); } bool reconfigure(size_t attack_samples, size_t release_samples, sample_t threshold, sample_t smoothness) { if (attack_samples == 0 || attack_samples > attack_envelope_.capacity()) { return false; } if (release_samples == 0 || release_samples > release_envelope_.capacity()) { return false; } sample_t new_threshold = Value<sample_t>::force_between(threshold, 0.01, 1); sample_t new_smoothness = Value<sample_t>::force_between(smoothness, 1, 4); bool recalculate_attack_envelope = attack_samples != attack_samples_ || new_smoothness != smoothness_; bool recalculate_release_envelope = release_samples != release_samples_ || new_smoothness != smoothness_; attack_samples_ = attack_samples; release_samples_ = release_samples; threshold_ = threshold; smoothness_ = smoothness; generate_envelopes_reset(recalculate_attack_envelope, recalculate_release_envelope); return true; } bool set_smoothness(sample_t smoothness) { return reconfigure(attack_samples_, release_samples_, threshold_, smoothness); } bool set_attack_samples(size_t samples) { return reconfigure(samples, release_samples_, threshold_, smoothness_); } bool set_release_samples(size_t samples) { return reconfigure(attack_samples_, samples, threshold_, smoothness_); } bool set_threshold(double threshold) { return reconfigure(attack_samples_, release_samples_, threshold, smoothness_); } const sample_t limiter_submit_peak_return_amplification(sample_t samplePeakValue) { static int cnt = 0; const size_t prediction = attack_envelope_.size(); const sample_t relativeValue = samplePeakValue - threshold_; const int withinReleasePeriod = release_count_ < release_envelope_.size(); const sample_t releaseCurveValue = withinReleasePeriod ? current_peak_ * release_envelope_[release_count_] : 0.0; if (relativeValue < releaseCurveValue) { /* * The signal is below either the threshold_ or the projected release * curve of the last highest peak. We can just "follow" the release curve. */ if (withinReleasePeriod) { release_count_++; } cnt++; return getAmpAndMoveToNextSample(releaseCurveValue); } /** * Alas! We can forget about the last peak. * We will have alter the prediction values so that the current, * new peak, will be "predicted". */ release_count_ = 0; current_peak_ = relativeValue; /** * We will try to project the default attack-predicition curve, * (which is the relativeValue (peak) with the nicely smooth * attackEnvelope) into the "future". * As soon as this projection hits (is not greater than) a previously * predicted value, we proceed to the next step. */ const size_t max_t = attack_samples_ - 1; size_t tClash; // the hitting point size_t t; for (tClash = 0, t = current_sample; tClash < prediction; tClash++) { t = t < max_t ? t + 1 : 0; const sample_t existingValue = peaks_[t]; const sample_t projectedValue = attack_envelope_[tClash] * relativeValue; if (projectedValue <= existingValue) { break; } } /** * We have a clash. We will now blend the peak with the * previously predicted curve, using the attackEnvelope * as blend-factor. If tClash is smaller than the complete * prediction-length, the attackEnvelope will be compressed * to fit exactly up to that clash point. * Due to the properties of the attackEnvelope it can be * mathematically proven that the newly produced curve is * always larger than the previous one in the clash range and * will blend smoothly with the existing curve. */ size_t i; for (i = 0, t = current_sample; i < tClash; i++) { t = t < max_t ? t + 1 : 0; // get the compressed attack_envelope_ value const sample_t blendFactor = attack_envelope_[i * (prediction - 1) / tClash]; // blend the peak value with the previously calculated peak peaks_[t] = relativeValue * blendFactor + (1.0 - blendFactor) * peaks_[t]; } return getAmpAndMoveToNextSample(relativeValue); } }; } // namespace tdap #endif // TDAP_M_LIMITER_HPP
35.010283
80
0.677289
emmef
cd68929d6cfcef605b9da503ac4e87f494cd9ead
1,295
cpp
C++
grid_map_filters/src/DeletionFilter.cpp
saikrn112/grid_map
f64a471c6fc9059a7db7e3327ff94a65f862d95c
[ "BSD-3-Clause" ]
2
2019-04-18T01:26:21.000Z
2021-07-14T01:23:05.000Z
grid_map_filters/src/DeletionFilter.cpp
saikrn112/grid_map
f64a471c6fc9059a7db7e3327ff94a65f862d95c
[ "BSD-3-Clause" ]
null
null
null
grid_map_filters/src/DeletionFilter.cpp
saikrn112/grid_map
f64a471c6fc9059a7db7e3327ff94a65f862d95c
[ "BSD-3-Clause" ]
8
2018-02-20T17:33:33.000Z
2021-07-18T20:48:36.000Z
/* * DeletionFilter.cpp * * Created on: Mar 19, 2015 * Author: Martin Wermelinger, Peter Fankhauser * Institute: ETH Zurich, Autonomous Systems Lab */ #include "grid_map_filters/DeletionFilter.hpp" #include <grid_map_core/GridMap.hpp> #include <pluginlib/class_list_macros.h> using namespace filters; namespace grid_map { template<typename T> DeletionFilter<T>::DeletionFilter() { } template<typename T> DeletionFilter<T>::~DeletionFilter() { } template<typename T> bool DeletionFilter<T>::configure() { // Load Parameters if (!FilterBase<T>::getParam(std::string("layers"), layers_)) { ROS_ERROR("DeletionFilter did not find parameter 'layers'."); return false; } return true; } template<typename T> bool DeletionFilter<T>::update(const T& mapIn, T& mapOut) { mapOut = mapIn; for (const auto& layer : layers_) { // Check if layer exists. if (!mapOut.exists(layer)) { ROS_ERROR("Check your deletion layers! Type %s does not exist.", layer.c_str()); continue; } if (!mapOut.erase(layer)) { ROS_ERROR("Could not remove type %s.", layer.c_str()); } } return true; } } /* namespace */ PLUGINLIB_EXPORT_CLASS(grid_map::DeletionFilter<grid_map::GridMap>, filters::FilterBase<grid_map::GridMap>)
20.234375
107
0.680309
saikrn112
cd6a0ac75ba33cbd688135f9d2195d3c74ea56fb
411
cpp
C++
pepcoding_problem/decimal_to_any_base.cpp
sahilduhan/Learn-C-plus-plus
80dba2ee08b36985deb297293a0318da5d6ace94
[ "RSA-MD" ]
null
null
null
pepcoding_problem/decimal_to_any_base.cpp
sahilduhan/Learn-C-plus-plus
80dba2ee08b36985deb297293a0318da5d6ace94
[ "RSA-MD" ]
null
null
null
pepcoding_problem/decimal_to_any_base.cpp
sahilduhan/Learn-C-plus-plus
80dba2ee08b36985deb297293a0318da5d6ace94
[ "RSA-MD" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int get_value_base(int num, int base) { int rv = 0; int p = 1; while (num > 0) { int dig = num % base; num = num / base; rv += dig * p; p = p * 10; } return rv; } int main() { int num = 634; int base = 8; int ans = 0; ans = get_value_base(num, base); cout << ans << endl; return 0; }
15.807692
37
0.479319
sahilduhan
cd6b4e146f8b9dc27e50e2dccd2cfbba91574315
1,493
cpp
C++
art-of-prog/31-longest_inc_seq/31-longest_inc_seq.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
art-of-prog/31-longest_inc_seq/31-longest_inc_seq.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
art-of-prog/31-longest_inc_seq/31-longest_inc_seq.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <cstring> #include <cstdlib> /**< 问题:最长递增子序列 */ // Ref: http://blog.csdn.net/joylnwang/article/details/6766317 // Ref: http://qiemengdao.iteye.com/blog/1660229 /* 给定一个长度为 N 的数组 a0, a1, a2, ..., an - 1,找出一个最长的单调递增子序列 * 递增的意思是对于任意的 i < j,都满足 ai < aj,此外子序列的意思是不要求连续,顺序不乱即可。 * 例如,长度为 6 的数组 A = {5, 6, 7, 1, 2, 8},则其最长的单调递增子序列为 {5, 6, 7, 8},长度为 4。 */ int LIncSeq1(int const* inArr, int const len) { if (len < 0) return len; int* const dp = new int[len]; int* const pre = new int[len]; // 储存开始位置 for (int k = 0; k < len; ++k) { dp[k] = 1; pre[k] = k; } // 寻找以 k 为末尾的最长递增子序列 for (int k = 1; k < len; ++k) for (int m = 0; m < k; ++m) { if (inArr[m] < inArr[k] && dp[k] < dp[m] + 1) { dp[k] = dp[m] + 1; pre[k] = m; } } int liss = 1; int iE = 0; // 末尾 for (int k = 1; k < len; ++k) if (liss < dp[k]) { liss = dp[k]; iE = k; } int* rst = new int[liss]; int pos = liss - 1; while (pre[iE] != iE) { rst[pos] = inArr[iE]; --pos; iE = pre[iE]; } rst[pos] = inArr[iE]; // 输出原始数组和结果 printf("\nArray (%d):\n", len); for (int k = 0; k < len; ++k) printf(" %+d", inArr[k]);; printf("\nLongest Increase Sub-Sequence (%d):\n", liss); for (int k = 0; k < liss; ++k) printf(" %+d", rst[k]); delete[] dp; delete[] pre; delete[] rst; return liss; } int main() { int const arr1[] = { 35, 36, 39, 3, 15, 27, 6, 42 }; int const n1 = sizeof(arr1) / sizeof(arr1[0]); LIncSeq1(arr1, n1); printf("\n"); return 0; }
22.283582
75
0.536504
Ginkgo-Biloba
cd6c1f3bac89b2e9d9ec5091e854dd1ed3be62d5
3,001
cpp
C++
5804.cpp
viniciusmalloc/live-archive
b867987512872a9ae8156bbbcfbf47caf5e9ed8e
[ "MIT" ]
null
null
null
5804.cpp
viniciusmalloc/live-archive
b867987512872a9ae8156bbbcfbf47caf5e9ed8e
[ "MIT" ]
null
null
null
5804.cpp
viniciusmalloc/live-archive
b867987512872a9ae8156bbbcfbf47caf5e9ed8e
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define FOR(i, a, b) for (int i = a; i <= b; ++i) #define RFOR(i, b, a) for (int i = b; i >= a; --i) #define REP(i, N) for (int i = 0; i < N; ++i) #define MAXN 10000 #define INF 0x3F3F3F3F #define LINF 0x3F3F3F3FFFFFFFFFLL #define pb push_back #define mp make_pair using namespace std; struct tri { int atual, custo; tri(int atual = 0, int custo = 0) : atual(atual) , custo(custo) { } }; int n, m; typedef vector<int> vi; typedef vector<vi> vii; typedef vector<tri> vtri; typedef vector<vtri> vvtri; typedef long long int64; typedef unsigned long long uint64; typedef pair<int, int> ii; int visitado[100000], dist[1000000], res[1001][1001], p[10000], visited[10000], check = 1, s, t, f; vvtri grafo; void initialize() { REP(i, n) { FOR(j, i, n) res[i][j] = res[j][i] = 0; res[i][i] = 0; } } void augment(int v, int minEdge) { if (v == s) { f = minEdge; return; } else if (p[v] != -1) { augment(p[v], min(minEdge, res[p[v]][v])); res[p[v]][v] -= f; res[v][p[v]] += f; } } void dfs(int u) { if (u == t) return; REP(i, grafo[u].size()) { tri atual = grafo[u][i]; if (visited[atual.atual] != check && res[u][atual.atual] > 0) { visited[atual.atual] = check; p[atual.atual] = u; dfs(atual.atual); } } } int djsktra(int de, int para) { REP(i, n) { dist[i] = INF; visitado[i] = false; } tri atual; ii at; priority_queue<ii> pq; pq.push(mp(INF, de)); dist[de] = 0; int ans = 0; while (!pq.empty()) { at = pq.top(); pq.pop(); if (at.second == para) ans = max(ans, at.first); if (visitado[at.second]) continue; visitado[at.second] = true; int custo = at.first; int v = at.second; REP(i, grafo[v].size()) { atual = grafo[v][i]; pq.push(mp(min(custo, atual.custo), atual.atual)); } } return ans; } int main() { ios::sync_with_stdio(false); int tt, de, para, atoa, custo; cin >> tt; while (tt--) { cin >> atoa >> n >> m >> s >> t; grafo.resize(n + 10); initialize(); REP(i, m) { cin >> de >> para >> custo; grafo[de].pb(tri(para, custo)); grafo[para].pb(tri(de, custo)); res[de][para] = custo; } int ans, mf = 0; ans = djsktra(s, t); while (true) { f = 0; REP(i, t + 1) p[i] = -1; visited[s] = check; dfs(s); check++; augment(t, INF); if (!f) break; mf += f; } cout << atoa << " " << setprecision(3) << fixed << (double)mf / (double)ans << "\n"; grafo.clear(); check++; } return 0; }
21.589928
99
0.461846
viniciusmalloc
cd6c4ec5bc7be4140ea8941d1cbc673016774ea5
2,739
cpp
C++
src/volt/config.cpp
voltengine/volt
fbefe2e0a8e461b6130ffe926870c4848bd6e7d1
[ "MIT" ]
null
null
null
src/volt/config.cpp
voltengine/volt
fbefe2e0a8e461b6130ffe926870c4848bd6e7d1
[ "MIT" ]
null
null
null
src/volt/config.cpp
voltengine/volt
fbefe2e0a8e461b6130ffe926870c4848bd6e7d1
[ "MIT" ]
null
null
null
#include <volt/pch.hpp> #include <volt/config.hpp> #include <volt/util/util.hpp> #include <volt/log.hpp> #include <volt/paths.hpp> namespace fs = std::filesystem; namespace nl = nlohmann; #ifdef VOLT_DEVELOPMENT static nl::json base_config; #endif static nl::json default_config, config; static nl::json cleave(nl::json from, const nl::json &what) { // Cleave from + what std::stack<std::pair<nl::json &, const nl::json &>> objects_to_cleave; objects_to_cleave.emplace(from, what); while (!objects_to_cleave.empty()) { nl::json &from = objects_to_cleave.top().first; const nl::json &what = objects_to_cleave.top().second; objects_to_cleave.pop(); for (auto it = from.begin(); it != from.end();) { auto prev = it++; if (what.contains(prev.key())) { nl::json &from_v = prev.value(); const nl::json &what_v = what[prev.key()]; if (from_v == what_v) from.erase(prev); else if (from_v.is_object() && what_v.is_object()) objects_to_cleave.emplace(from_v, what_v); } } } return from; } namespace volt::config { static void load_from_data() { try { ::config.update(nl::json::parse(util::read_text_file( paths::data() / "config.json"))); VOLT_LOG_INFO("User configuration has been loaded.") } catch (...) { VOLT_LOG_INFO("No user configuration available.") } } nl::json &json() { return ::config; } void save() { nl::json cleaved = cleave(::config, default_config); util::write_file(paths::data() / "config.json", cleaved.dump(1, '\t')); } void reset_to_default() { ::config = default_config; } #ifdef VOLT_DEVELOPMENT void save_default() { nl::json cleaved = cleave(default_config, base_config); util::write_file(fs::path(VOLT_DEVELOPMENT_PATH) / "config.json", cleaved.dump(1, '\t')); } void reset_to_base() { ::config = default_config = base_config; } void load() { load_from_data(); } #endif } namespace volt::config::_internal { void init() { #ifdef VOLT_DEVELOPMENT std::vector<std::string> paths = util::split(util::read_text_file( fs::path(VOLT_DEVELOPMENT_PATH) / "cache" / "packages.txt"), "\n"); base_config = nl::json::object(); for (auto &path_item : paths) { auto path = path_item.substr(path_item.find(' ') + 1) / fs::path("config.json"); if (fs::exists(path)) base_config.update(nl::json::parse(util::read_text_file(path))); } default_config = base_config; auto path = fs::path(VOLT_DEVELOPMENT_PATH) / "config.json"; if (fs::exists(path)) default_config.update(nl::json::parse(util::read_text_file(path))); #else default_config = nl::json::parse(util::read_text_file( fs::current_path() / ".." / "config.json")); #endif ::config = default_config; #ifndef VOLT_DEVELOPMENT load_from_data(); #endif } }
22.636364
82
0.676159
voltengine
cd6f29d280057686f7e946b62b09f9681663264e
5,851
cpp
C++
REDSI_1160929_1161573/boost_1_67_0/libs/contract/test/invariant/ifdef_macro.cpp
Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo
eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8
[ "MIT" ]
32
2019-02-27T06:57:07.000Z
2021-08-29T10:56:19.000Z
REDSI_1160929_1161573/boost_1_67_0/libs/contract/test/invariant/ifdef_macro.cpp
Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo
eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8
[ "MIT" ]
1
2019-04-04T18:00:00.000Z
2019-04-04T18:00:00.000Z
REDSI_1160929_1161573/boost_1_67_0/libs/contract/test/invariant/ifdef_macro.cpp
Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo
eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8
[ "MIT" ]
5
2019-08-20T13:45:04.000Z
2022-03-01T18:23:49.000Z
// Copyright (C) 2008-2018 Lorenzo Caminiti // Distributed under the Boost Software License, Version 1.0 (see accompanying // file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt). // See: http://www.boost.org/doc/libs/release/libs/contract/doc/html/index.html // Test invariant compilation on/off (using macro interface). #include "../detail/oteststream.hpp" #include "../detail/unprotected_commas.hpp" #include <boost/contract_macro.hpp> #include <boost/detail/lightweight_test.hpp> #include <sstream> boost::contract::test::detail::oteststream out; class a { public: BOOST_CONTRACT_STATIC_INVARIANT({ boost::contract::test::detail::unprotected_commas<void, void, void>:: call(); out << "a::static_inv" << std::endl; }) BOOST_CONTRACT_INVARIANT_VOLATILE({ boost::contract::test::detail::unprotected_commas<void, void, void>:: call(); out << "a::cv_inv" << std::endl; }) BOOST_CONTRACT_INVARIANT({ boost::contract::test::detail::unprotected_commas<void, void, void>:: call(); out << "a::const_inv" << std::endl; }) a() { // Test check both cv and const invariant (at exit if no throw). BOOST_CONTRACT_CONSTRUCTOR(boost::contract::test::detail:: unprotected_commas<void, void, void>::same(this)); out << "a::ctor::body" << std::endl; } ~a() { // Test check both cv and const invariant (at entry). BOOST_CONTRACT_DESTRUCTOR(boost::contract::test::detail:: unprotected_commas<void, void, void>::same(this)); out << "a::dtor::body" << std::endl; } void m() { // Test check const invariant (at entry and exit). BOOST_CONTRACT_PUBLIC_FUNCTION(boost::contract::test::detail:: unprotected_commas<void, void, void>::same(this)); out << "a::m::body" << std::endl; } void c() const { // Test check const invariant (at entry and exit). BOOST_CONTRACT_PUBLIC_FUNCTION(boost::contract::test::detail:: unprotected_commas<void, void, void>::same(this)); out << "a::c::body" << std::endl; } void v() volatile { // Test check cv invariant (at entry and exit). BOOST_CONTRACT_PUBLIC_FUNCTION(boost::contract::test::detail:: unprotected_commas<void, void, void>::same(this)); out << "a::v::body" << std::endl; } void cv() const volatile { // Test check cv invariant (at entry and exit). BOOST_CONTRACT_PUBLIC_FUNCTION(boost::contract::test::detail:: unprotected_commas<void, void, void>::same(this)); out << "a::cv::body" << std::endl; } }; int main() { std::ostringstream ok; { out.str(""); a aa; ok.str(""); ok #ifndef BOOST_CONTRACT_NO_ENTRY_INVARIANTS << "a::static_inv" << std::endl #endif << "a::ctor::body" << std::endl #ifndef BOOST_CONTRACT_NO_EXIT_INVARIANTS << "a::static_inv" << std::endl << "a::cv_inv" << std::endl << "a::const_inv" << std::endl #endif ; BOOST_TEST(out.eq(ok.str())); out.str(""); aa.m(); ok.str(""); ok #ifndef BOOST_CONTRACT_NO_ENTRY_INVARIANTS << "a::static_inv" << std::endl << "a::const_inv" << std::endl #endif << "a::m::body" << std::endl #ifndef BOOST_CONTRACT_NO_EXIT_INVARIANTS << "a::static_inv" << std::endl << "a::const_inv" << std::endl #endif ; BOOST_TEST(out.eq(ok.str())); out.str(""); aa.c(); ok.str(""); ok #ifndef BOOST_CONTRACT_NO_ENTRY_INVARIANTS << "a::static_inv" << std::endl << "a::const_inv" << std::endl #endif << "a::c::body" << std::endl #ifndef BOOST_CONTRACT_NO_EXIT_INVARIANTS << "a::static_inv" << std::endl << "a::const_inv" << std::endl #endif ; BOOST_TEST(out.eq(ok.str())); out.str(""); aa.v(); ok.str(""); ok #ifndef BOOST_CONTRACT_NO_ENTRY_INVARIANTS << "a::static_inv" << std::endl << "a::cv_inv" << std::endl #endif << "a::v::body" << std::endl #ifndef BOOST_CONTRACT_NO_EXIT_INVARIANTS << "a::static_inv" << std::endl << "a::cv_inv" << std::endl #endif ; BOOST_TEST(out.eq(ok.str())); out.str(""); aa.cv(); ok.str(""); ok #ifndef BOOST_CONTRACT_NO_ENTRY_INVARIANTS << "a::static_inv" << std::endl << "a::cv_inv" << std::endl #endif << "a::cv::body" << std::endl #ifndef BOOST_CONTRACT_NO_EXIT_INVARIANTS << "a::static_inv" << std::endl << "a::cv_inv" << std::endl #endif ; BOOST_TEST(out.eq(ok.str())); out.str(""); } // Call dtor. ok.str(""); ok #ifndef BOOST_CONTRACT_NO_ENTRY_INVARIANTS << "a::static_inv" << std::endl << "a::cv_inv" << std::endl << "a::const_inv" << std::endl #endif << "a::dtor::body" << std::endl #ifndef BOOST_CONTRACT_NO_EXIT_INVARIANTS << "a::static_inv" << std::endl #endif ; BOOST_TEST(out.eq(ok.str())); return boost::report_errors(); }
34.216374
80
0.508631
Wultyc
cd70c8416a48b9fcb1fee0c060b9d22f4b4d9b86
11,349
cpp
C++
samples/ExternalFunction/ExternalFunction.cpp
kidaa/xalan-c
bb666d0ab3d0a192410823e6857c203d83c27b16
[ "Apache-2.0" ]
null
null
null
samples/ExternalFunction/ExternalFunction.cpp
kidaa/xalan-c
bb666d0ab3d0a192410823e6857c203d83c27b16
[ "Apache-2.0" ]
1
2021-08-18T12:32:31.000Z
2021-08-18T12:32:31.000Z
samples/ExternalFunction/ExternalFunction.cpp
AaronNGray/xalan
6741bbdcb64a9d33df8bd7e21b558d66bb4292ec
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <xalanc/Include/PlatformDefinitions.hpp> #include <cmath> #include <cstring> #include <ctime> #if defined(XALAN_CLASSIC_IOSTREAMS) #include <iostream.h> #else #include <iostream> #endif #include <xercesc/util/PlatformUtils.hpp> #include <xalanc/XalanTransformer/XalanTransformer.hpp> #include <xalanc/XPath/Function.hpp> #include <xalanc/XPath/XObjectFactory.hpp> XALAN_USING_XALAN(Function) XALAN_USING_XALAN(Locator) XALAN_USING_XALAN(XPathExecutionContext) XALAN_USING_XALAN(XalanDOMString) XALAN_USING_XALAN(XalanNode) XALAN_USING_XALAN(XObjectPtr) XALAN_USING_XALAN(MemoryManager) XALAN_USING_XALAN(XalanCopyConstruct) // This class defines a function that will return the square root // of its argument. class FunctionSquareRoot : public Function { public: /** * Execute an XPath function object. The function must return a valid * object. Extension functions should override this version of execute(), * rather than one of the other calls designed for a specific number of * arguments. * * @param executionContext executing context * @param context current context node * @param args vector of pointers to XObject arguments * @param locator Locator for the XPath expression that contains the function call * @return pointer to the result XObject */ virtual XObjectPtr execute( XPathExecutionContext& executionContext, XalanNode* context, const XObjectArgVectorType& args, const Locator* locator) const { if (args.size() != 1) { XPathExecutionContext::GetAndReleaseCachedString theGuard(executionContext); generalError(executionContext, context, locator); } assert(args[0].null() == false); #if defined(XALAN_STRICT_ANSI_HEADERS) using std::sqrt; #endif return executionContext.getXObjectFactory().createNumber(sqrt(args[0]->num(executionContext))); } using Function::execute; /** * Create a copy of the function object. * * @return pointer to the new object */ #if defined(XALAN_NO_COVARIANT_RETURN_TYPE) virtual Function* #else virtual FunctionSquareRoot* #endif clone(MemoryManager& theManager) const { return XalanCopyConstruct(theManager, *this); } protected: /** * Get the error message to report when * the function is called with the wrong * number of arguments. * * @return function error message */ const XalanDOMString& getError(XalanDOMString& theResult) const { theResult.assign("The square-root() function accepts one argument!"); return theResult; } private: // Not implemented... FunctionSquareRoot& operator=(const FunctionSquareRoot&); bool operator==(const FunctionSquareRoot&) const; }; // This class defines a function that will return the cube // of its argument. class FunctionCube : public Function { public: /** * Execute an XPath function object. The function must return a valid * object. Extension functions should override this version of execute(), * rather than one of the other calls designed for a specific number of * arguments. * * @param executionContext executing context * @param context current context node * @param args vector of pointers to XObject arguments * @param locator Locator for the XPath expression that contains the function call * @return pointer to the result XObject */ virtual XObjectPtr execute( XPathExecutionContext& executionContext, XalanNode* context, const XObjectArgVectorType& args, const Locator* locator) const { if (args.size() != 1) { XPathExecutionContext::GetAndReleaseCachedString theGuard(executionContext); generalError(executionContext, context, locator); } assert(args[0].null() == false); #if defined(XALAN_STRICT_ANSI_HEADERS) using std::pow; #endif return executionContext.getXObjectFactory().createNumber(pow(args[0]->num(executionContext), 3)); } using Function::execute; /** * Create a copy of the function object. * * @return pointer to the new object */ #if defined(XALAN_NO_COVARIANT_RETURN_TYPE) virtual Function* #else virtual FunctionCube* #endif clone(MemoryManager& theManager) const { return XalanCopyConstruct(theManager, *this); } protected: /** * Get the error message to report when * the function is called with the wrong * number of arguments. * * @return function error message */ const XalanDOMString& getError(XalanDOMString& theResult) const { theResult.assign("The cube() function accepts one argument!"); return theResult; } private: // Not implemented... FunctionCube& operator=(const FunctionCube&); bool operator==(const FunctionCube&) const; }; // This class defines a function that runs the C function // asctime() using the current system time. class FunctionAsctime : public Function { public: /** * Execute an XPath function object. The function must return a valid * object. Extension functions should override this version of execute(), * rather than one of the other calls designed for a specific number of * arguments. * * @param executionContext executing context * @param context current context node * @param args vector of pointers to XObject arguments * @param locator Locator for the XPath expression that contains the function call * @return pointer to the result XObject */ virtual XObjectPtr execute( XPathExecutionContext& executionContext, XalanNode* context, const XObjectArgVectorType& args, const Locator* locator) const { if (args.empty() == false) { generalError(executionContext, context, locator); } #if defined(XALAN_STRICT_ANSI_HEADERS) using std::time; using std::time_t; using std::localtime; using std::asctime; using std::strlen; #endif time_t theTime; time(&theTime); char* const theTimeString = asctime(localtime(&theTime)); assert(theTimeString != 0); // The resulting string has a newline character at the end, // so get rid of it. theTimeString[strlen(theTimeString) - 1] = '\0'; return executionContext.getXObjectFactory().createString(XalanDOMString(theTimeString)); } using Function::execute; /** * Create a copy of the function object. * * @return pointer to the new object */ #if defined(XALAN_NO_COVARIANT_RETURN_TYPE) virtual Function* #else virtual FunctionAsctime* #endif clone(MemoryManager& theManager) const { return XalanCopyConstruct(theManager, *this); } protected: /** * Get the error message to report when * the function is called with the wrong * number of arguments. * * @return function error message */ const XalanDOMString& getError(XalanDOMString& theResult) const { theResult.assign("The asctime() function accepts one argument!"); return theResult; } private: // Not implemented... FunctionAsctime& operator=(const FunctionAsctime&); bool operator==(const FunctionAsctime&) const; }; int main( int argc, char* /* argv */[]) { XALAN_USING_STD(cerr) XALAN_USING_STD(endl) int theResult = 0; if (argc != 1) { cerr << "Usage: ExternalFunction" << endl << endl; } else { XALAN_USING_XERCES(XMLPlatformUtils) XALAN_USING_XERCES(XMLException) XALAN_USING_XALAN(XalanTransformer) // Call the static initializer for Xerces. try { XMLPlatformUtils::Initialize(); } catch (const XMLException& toCatch) { cerr << "Error during Xerces initialization. Error code was " << toCatch.getCode() << "." << endl; theResult = -1; } if (theResult == 0) { // Initialize Xalan. XalanTransformer::initialize(); { // Create a XalanTransformer. XalanTransformer theXalanTransformer; // The namespace for our functions... const XalanDOMString theNamespace("http://ExternalFunction.xalan-c++.xml.apache.org"); // Install the functions in the local space. They will only // be installed in this instance, so no other instances // will know about them... theXalanTransformer.installExternalFunction( theNamespace, XalanDOMString("asctime"), FunctionAsctime()); theXalanTransformer.installExternalFunction( theNamespace, XalanDOMString("square-root"), FunctionSquareRoot()); theXalanTransformer.installExternalFunction( theNamespace, XalanDOMString("cube"), FunctionCube()); // Do the transform. theResult = theXalanTransformer.transform("foo.xml", "foo.xsl", "foo.out"); if(theResult != 0) { cerr << "ExternalFunction Error: \n" << theXalanTransformer.getLastError() << endl << endl; } } // Terminate Xalan... XalanTransformer::terminate(); } // Terminate Xerces... XMLPlatformUtils::Terminate(); // Clean up the ICU, if it's integrated... XalanTransformer::ICUCleanUp(); } return theResult; }
27.021429
105
0.61186
kidaa
cd7180fb7a54729b962f716841121ad3318c625a
2,541
cc
C++
src/eckit/linalg/sparse/LinearAlgebraEigen.cc
matthewrmshin/eckit
ea30183f8d7a65ed89abf97f86d97e02ec366144
[ "Apache-2.0" ]
null
null
null
src/eckit/linalg/sparse/LinearAlgebraEigen.cc
matthewrmshin/eckit
ea30183f8d7a65ed89abf97f86d97e02ec366144
[ "Apache-2.0" ]
null
null
null
src/eckit/linalg/sparse/LinearAlgebraEigen.cc
matthewrmshin/eckit
ea30183f8d7a65ed89abf97f86d97e02ec366144
[ "Apache-2.0" ]
null
null
null
/* * (C) Copyright 1996- ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation * nor does it submit to any jurisdiction. */ #include "eckit/linalg/sparse/LinearAlgebraEigen.h" #include <ostream> #include "eckit/exception/Exceptions.h" #include "eckit/linalg/Matrix.h" #include "eckit/linalg/SparseMatrix.h" #include "eckit/linalg/Vector.h" #include "eckit/linalg/sparse/LinearAlgebraGeneric.h" #include "eckit/maths/Eigen.h" namespace eckit { namespace linalg { namespace sparse { static const LinearAlgebraEigen __la("eigen"); using vec_t = Eigen::VectorXd::MapType; using mat_t = Eigen::MatrixXd::MapType; using spm_t = Eigen::MappedSparseMatrix<Scalar, Eigen::RowMajor, Index>; void LinearAlgebraEigen::print(std::ostream& out) const { out << "LinearAlgebraEigen[]"; } void LinearAlgebraEigen::spmv(const SparseMatrix& A, const Vector& x, Vector& y) const { ASSERT(x.size() == A.cols()); ASSERT(y.size() == A.rows()); // We expect indices to be 0-based ASSERT(A.outer()[0] == 0); // Eigen requires non-const pointers to the data spm_t Ai(A.rows(), A.cols(), A.nonZeros(), const_cast<Index*>(A.outer()), const_cast<Index*>(A.inner()), const_cast<Scalar*>(A.data())); vec_t xi(Eigen::VectorXd::Map(const_cast<Scalar*>(x.data()), x.size())); vec_t yi(Eigen::VectorXd::Map(y.data(), y.size())); yi = Ai * xi; } void LinearAlgebraEigen::spmm(const SparseMatrix& A, const Matrix& B, Matrix& C) const { ASSERT(A.cols() == B.rows()); ASSERT(A.rows() == C.rows()); ASSERT(B.cols() == C.cols()); // We expect indices to be 0-based ASSERT(A.outer()[0] == 0); // Eigen requires non-const pointers to the data spm_t Ai(A.rows(), A.cols(), A.nonZeros(), const_cast<Index*>(A.outer()), const_cast<Index*>(A.inner()), const_cast<Scalar*>(A.data())); mat_t Bi(Eigen::MatrixXd::Map(const_cast<Scalar*>(B.data()), B.rows(), B.cols())); mat_t Ci(Eigen::MatrixXd::Map(C.data(), C.rows(), C.cols())); Ci = Ai * Bi; } void LinearAlgebraEigen::dsptd(const Vector& x, const SparseMatrix& A, const Vector& y, SparseMatrix& B) const { static const sparse::LinearAlgebraGeneric generic; generic.dsptd(x, A, y, B); } } // namespace sparse } // namespace linalg } // namespace eckit
30.25
140
0.677292
matthewrmshin
cd721d3b8d1bf423a2e2d42632a35078e291a2cc
28,059
cpp
C++
packages/arb-avm-cpp/tests/checkpoint.cpp
mrsmkl/arbitrum
7941a8c4870f98ed7999357049a5eec4a75d8c78
[ "Apache-2.0" ]
null
null
null
packages/arb-avm-cpp/tests/checkpoint.cpp
mrsmkl/arbitrum
7941a8c4870f98ed7999357049a5eec4a75d8c78
[ "Apache-2.0" ]
null
null
null
packages/arb-avm-cpp/tests/checkpoint.cpp
mrsmkl/arbitrum
7941a8c4870f98ed7999357049a5eec4a75d8c78
[ "Apache-2.0" ]
1
2020-09-20T19:25:23.000Z
2020-09-20T19:25:23.000Z
/* * Copyright 2019, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.hpp" #include "helper.hpp" #include <avm/machinestate/machinestate.hpp> #include <avm_values/vmValueParser.hpp> #include <data_storage/checkpoint/checkpointstorage.hpp> #include <data_storage/checkpoint/machinestatedeleter.hpp> #include <data_storage/checkpoint/machinestatefetcher.hpp> #include <data_storage/checkpoint/machinestatesaver.hpp> #include <catch2/catch.hpp> #include <boost/filesystem.hpp> void saveValue(MachineStateSaver& saver, const value& val, int expected_ref_count, bool expected_status) { auto results = saver.saveValue(val); saver.commitTransaction(); REQUIRE(results.status.ok() == expected_status); REQUIRE(results.reference_count == expected_ref_count); } void getValue(MachineStateFetcher& fetcher, std::vector<unsigned char>& hash_key, int expected_ref_count, uint256_t& expected_hash, ValueTypes expected_value_type, bool expected_status) { auto results = fetcher.getValue(hash_key); auto serialized_val = checkpoint::utils::serializeValue(results.data); auto type = (ValueTypes)serialized_val[0]; REQUIRE(results.status.ok() == expected_status); REQUIRE(results.reference_count == expected_ref_count); REQUIRE(type == expected_value_type); REQUIRE(hash(results.data) == expected_hash); } void saveTuple(MachineStateSaver& saver, const Tuple& tup, int expected_ref_count, bool expected_status) { auto results = saver.saveTuple(tup); saver.commitTransaction(); REQUIRE(results.status.ok() == expected_status); REQUIRE(results.reference_count == expected_ref_count); } void getTuple(MachineStateFetcher& fetcher, std::vector<unsigned char>& hash_key, int expected_ref_count, uint256_t& expected_hash, int expected_tuple_size, bool expected_status) { auto results = fetcher.getTuple(hash_key); REQUIRE(results.reference_count == expected_ref_count); REQUIRE(results.data.calculateHash() == expected_hash); REQUIRE(results.data.tuple_size() == expected_tuple_size); REQUIRE(results.status.ok() == expected_status); } void getTupleValues(MachineStateFetcher& fetcher, std::vector<unsigned char>& hash_key, std::vector<uint256_t> value_hashes) { auto results = fetcher.getTuple(hash_key); REQUIRE(results.data.tuple_size() == value_hashes.size()); for (size_t i = 0; i < value_hashes.size(); i++) { REQUIRE(hash(results.data.get_element(i)) == value_hashes[i]); } } TEST_CASE("Save value") { DBDeleter deleter; CheckpointStorage storage(dbpath, test_contract_path); auto saver = MachineStateSaver(storage.makeTransaction()); SECTION("save 1 num tuple") { TuplePool pool; uint256_t num = 1; auto tuple = Tuple(num, &pool); saveValue(saver, tuple, 1, true); } SECTION("save num") { uint256_t num = 1; saveValue(saver, num, 1, true); } SECTION("save codepoint") { auto code_point = CodePoint(1, Operation(), 0); saveValue(saver, code_point, 1, true); } } TEST_CASE("Save tuple") { DBDeleter deleter; CheckpointStorage storage(dbpath, test_contract_path); auto saver = MachineStateSaver(storage.makeTransaction()); TuplePool pool; SECTION("save 1 num tuple") { uint256_t num = 1; auto tuple = Tuple(num, &pool); saveTuple(saver, tuple, 1, true); } SECTION("save 2, 1 num tuples") { uint256_t num = 1; auto tuple = Tuple(num, &pool); saveTuple(saver, tuple, 1, true); saveTuple(saver, tuple, 2, true); } SECTION("saved tuple in tuple") { uint256_t num = 1; auto inner_tuple = Tuple(num, &pool); auto tuple = Tuple(inner_tuple, &pool); saveTuple(saver, tuple, 1, true); saveTuple(saver, tuple, 2, true); } } TEST_CASE("Save and get value") { SECTION("save empty tuple") { DBDeleter deleter; CheckpointStorage storage(dbpath, test_contract_path); auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); auto tuple = Tuple(); auto hash_key = GetHashKey(tuple); auto tup_hash = tuple.calculateHash(); saveValue(saver, tuple, 1, true); getValue(fetcher, hash_key, 1, tup_hash, TUPLE, true); } SECTION("save tuple") { DBDeleter deleter; CheckpointStorage storage(dbpath, test_contract_path); auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); uint256_t num = 1; TuplePool pool; auto tuple = Tuple(num, &pool); auto hash_key = GetHashKey(tuple); auto tup_hash = tuple.calculateHash(); saveValue(saver, tuple, 1, true); getValue(fetcher, hash_key, 1, tup_hash, TUPLE, true); } SECTION("save num") { DBDeleter deleter; CheckpointStorage storage(dbpath, test_contract_path); auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); uint256_t num = 1; auto hash_key = GetHashKey(num); auto num_hash = hash(num); saveValue(saver, num, 1, true); getValue(fetcher, hash_key, 1, num_hash, NUM, true); } SECTION("save codepoint") { DBDeleter deleter; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[0]; auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); auto hash_key = GetHashKey(code_point); auto cp_hash = hash(code_point); saveValue(saver, code_point, 1, true); getValue(fetcher, hash_key, 1, cp_hash, CODEPT, true); } SECTION("save err codepoint") { DBDeleter deleter; CheckpointStorage storage(dbpath, test_contract_path); auto code_point = getErrCodePoint(); auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); auto hash_key = GetHashKey(code_point); auto cp_hash = hash(code_point); saveValue(saver, code_point, 1, true); getValue(fetcher, hash_key, 1, cp_hash, CODEPT, true); } } TEST_CASE("Save and get tuple values") { SECTION("save num tuple") { DBDeleter deleter; CheckpointStorage storage(dbpath, test_contract_path); auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); uint256_t num = 1; TuplePool pool; auto tuple = Tuple(num, &pool); saveTuple(saver, tuple, 1, true); std::vector<uint256_t> hashes{hash(num)}; auto hash_key = GetHashKey(tuple); getTupleValues(fetcher, hash_key, hashes); } SECTION("save codepoint tuple") { DBDeleter deleter; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[1]; auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); TuplePool pool; auto tuple = Tuple(code_point, &pool); saveTuple(saver, tuple, 1, true); std::vector<uint256_t> hashes{hash(code_point)}; auto hash_key = GetHashKey(tuple); getTupleValues(fetcher, hash_key, hashes); } SECTION("save codepoint tuple") { DBDeleter deleter; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[0]; auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); TuplePool pool; auto tuple = Tuple(code_point, &pool); saveValue(saver, tuple, 1, true); std::vector<uint256_t> hashes{hash(code_point)}; auto hash_key = GetHashKey(tuple); getTupleValues(fetcher, hash_key, hashes); } SECTION("save nested tuple") { DBDeleter deleter; CheckpointStorage storage(dbpath, test_contract_path); auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); auto inner_tuple = Tuple(); TuplePool pool; auto tuple = Tuple(inner_tuple, &pool); saveTuple(saver, tuple, 1, true); std::vector<uint256_t> hashes{hash(inner_tuple)}; auto hash_key = GetHashKey(tuple); getTupleValues(fetcher, hash_key, hashes); } SECTION("save multiple valued tuple") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[0]; auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); auto inner_tuple = Tuple(); uint256_t num = 1; auto tuple = Tuple(inner_tuple, num, code_point, &pool); saveTuple(saver, tuple, 1, true); std::vector<uint256_t> hashes{hash(inner_tuple), hash(num), hash(code_point)}; auto hash_key = GetHashKey(tuple); getTupleValues(fetcher, hash_key, hashes); } SECTION("save multiple valued tuple, saveValue()") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[2]; auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); auto inner_tuple = Tuple(); uint256_t num = 1; auto tuple = Tuple(inner_tuple, num, code_point, &pool); saveValue(saver, tuple, 1, true); std::vector<uint256_t> hashes{hash(inner_tuple), hash(num), hash(code_point)}; auto hash_key = GetHashKey(tuple); getTupleValues(fetcher, hash_key, hashes); } } TEST_CASE("Save And Get Tuple") { SECTION("save 1 num tuple") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); uint256_t num = 1; auto tuple = Tuple(num, &pool); auto tup_hash = tuple.calculateHash(); auto hash_key = GetHashKey(tuple); saveTuple(saver, tuple, 1, true); getTuple(fetcher, hash_key, 1, tup_hash, 1, true); } SECTION("save codepoint in tuple") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); auto code_point = storage.getInitialVmValues().code[0]; auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); auto tuple = Tuple(code_point, &pool); auto tup_hash = tuple.calculateHash(); auto hash_key = GetHashKey(tuple); saveTuple(saver, tuple, 1, true); getTuple(fetcher, hash_key, 1, tup_hash, 1, true); } SECTION("save 1 num tuple twice") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); auto saver = MachineStateSaver(storage.makeTransaction()); auto saver2 = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); uint256_t num = 1; auto tuple = Tuple(num, &pool); auto tup_hash = tuple.calculateHash(); auto hash_key = GetHashKey(tuple); saveTuple(saver, tuple, 1, true); saveTuple(saver2, tuple, 2, true); getTuple(fetcher, hash_key, 2, tup_hash, 1, true); } SECTION("save 2 num tuple") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); std::vector<CodePoint> code; auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); uint256_t num = 1; uint256_t num2 = 2; auto tuple = Tuple(num, num2, &pool); auto tup_hash = tuple.calculateHash(); auto hash_key = GetHashKey(tuple); saveTuple(saver, tuple, 1, true); getTuple(fetcher, hash_key, 1, tup_hash, 2, true); } SECTION("save tuple in tuple") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); uint256_t num = 1; auto inner_tuple = Tuple(num, &pool); auto tuple = Tuple(inner_tuple, &pool); saveTuple(saver, tuple, 1, true); auto inner_hash_key = GetHashKey(inner_tuple); auto inner_tup_hash = inner_tuple.calculateHash(); auto hash_key = GetHashKey(tuple); auto tup_hash = tuple.calculateHash(); getTuple(fetcher, hash_key, 1, tup_hash, 1, true); getTuple(fetcher, inner_hash_key, 1, inner_tup_hash, 1, true); } SECTION("save 2 tuples in tuple") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); uint256_t num = 1; auto inner_tuple = Tuple(num, &pool); uint256_t num2 = 2; auto inner_tuple2 = Tuple(num2, &pool); auto tuple = Tuple(inner_tuple, inner_tuple2, &pool); saveTuple(saver, tuple, 1, true); auto inner_hash_key = GetHashKey(inner_tuple); auto inner_tup_hash = inner_tuple.calculateHash(); auto inner_hash_key2 = GetHashKey(inner_tuple2); auto inner_tup_hash2 = inner_tuple2.calculateHash(); auto hash_key = GetHashKey(tuple); auto tup_hash = tuple.calculateHash(); getTuple(fetcher, hash_key, 1, tup_hash, 2, true); getTuple(fetcher, inner_hash_key, 1, inner_tup_hash, 1, true); getTuple(fetcher, inner_hash_key2, 1, inner_tup_hash2, 1, true); } SECTION("save saved tuple in tuple") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); auto saver = MachineStateSaver(storage.makeTransaction()); auto saver2 = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); uint256_t num = 1; auto inner_tuple = Tuple(num, &pool); auto tuple = Tuple(inner_tuple, &pool); auto inner_hash_key = GetHashKey(inner_tuple); auto inner_tup_hash = inner_tuple.calculateHash(); auto hash_key = GetHashKey(tuple); auto tup_hash = tuple.calculateHash(); saveTuple(saver, inner_tuple, 1, true); getTuple(fetcher, inner_hash_key, 1, inner_tup_hash, 1, true); saveTuple(saver2, tuple, 1, true); getTuple(fetcher, hash_key, 1, tup_hash, 1, true); getTuple(fetcher, inner_hash_key, 2, inner_tup_hash, 1, true); } } void saveState(MachineStateSaver& saver, MachineStateKeys storage_data, std::vector<unsigned char> checkpoint_name) { auto results = saver.saveMachineState(storage_data, checkpoint_name); auto status = saver.commitTransaction(); REQUIRE(results.reference_count == 1); REQUIRE(results.status.ok()); } void getSavedState(MachineStateFetcher& fetcher, std::vector<unsigned char> checkpoint_name, MachineStateKeys expected_data, int expected_ref_count, std::vector<std::vector<unsigned char>> keys) { auto results = fetcher.getMachineState(checkpoint_name); REQUIRE(results.status.ok()); REQUIRE(results.reference_count == expected_ref_count); auto data = results.data; REQUIRE(data.status_char == expected_data.status_char); REQUIRE(data.pc_key == expected_data.pc_key); REQUIRE(data.datastack_key == expected_data.datastack_key); REQUIRE(data.auxstack_key == expected_data.auxstack_key); REQUIRE(data.register_val_key == expected_data.register_val_key); for (auto& key : keys) { auto res = fetcher.getValue(key); REQUIRE(res.status.ok()); } } void deleteCheckpoint(CheckpointStorage& storage, MachineStateFetcher& fetcher, std::vector<unsigned char> checkpoint_name, std::vector<std::vector<unsigned char>> deleted_values) { auto res = deleteCheckpoint(storage, checkpoint_name); auto results = fetcher.getMachineState(checkpoint_name); REQUIRE(results.status.ok() == false); for (auto& hash_key : deleted_values) { auto res = fetcher.getValue(hash_key); REQUIRE(res.status.ok() == false); } } void deleteCheckpointSavedTwice( CheckpointStorage& storage, MachineStateFetcher& fetcher, std::vector<unsigned char> checkpoint_name, std::vector<std::vector<unsigned char>> deleted_values) { auto res = deleteCheckpoint(storage, checkpoint_name); auto res2 = deleteCheckpoint(storage, checkpoint_name); auto results = fetcher.getMachineState(checkpoint_name); REQUIRE(results.status.ok() == false); for (auto& hash_key : deleted_values) { auto res = fetcher.getValue(hash_key); REQUIRE(res.status.ok() == false); } } void deleteCheckpointSavedTwiceReordered( CheckpointStorage& storage, MachineStateFetcher& fetcher, std::vector<unsigned char> checkpoint_name, std::vector<std::vector<unsigned char>> deleted_values) { auto resultsx = fetcher.getMachineState(checkpoint_name); for (auto& hash_key : deleted_values) { auto res = fetcher.getValue(hash_key); REQUIRE(res.status.ok()); } auto res = deleteCheckpoint(storage, checkpoint_name); auto results = fetcher.getMachineState(checkpoint_name); REQUIRE(results.status.ok() == true); for (auto& hash_key : deleted_values) { auto res = fetcher.getValue(hash_key); REQUIRE(res.status.ok()); } auto res2 = deleteCheckpoint(storage, checkpoint_name); auto results2 = fetcher.getMachineState(checkpoint_name); REQUIRE(results2.status.ok() == false); for (auto& hash_key : deleted_values) { auto res = fetcher.getValue(hash_key); REQUIRE(res.status.ok() == false); } } MachineStateKeys makeStorageData(MachineStateSaver& stateSaver, value registerVal, Datastack stack, Datastack auxstack, Status state, CodePoint pc, CodePoint err_pc, BlockReason blockReason) { TuplePool pool; auto datastack_results = stack.checkpointState(stateSaver, &pool); auto auxstack_results = auxstack.checkpointState(stateSaver, &pool); auto register_val_results = stateSaver.saveValue(registerVal); auto pc_results = stateSaver.saveValue(pc); auto err_pc_results = stateSaver.saveValue(err_pc); auto status_str = (unsigned char)state; return MachineStateKeys{ register_val_results.storage_key, datastack_results.storage_key, auxstack_results.storage_key, pc_results.storage_key, err_pc_results.storage_key, status_str}; } MachineStateKeys getStateValues(MachineStateSaver& saver) { TuplePool pool; uint256_t register_val = 100; auto static_val = Tuple(register_val, Tuple(), &pool); auto code_point = CodePoint(1, Operation(), 0); auto tup1 = Tuple(register_val, &pool); auto tup2 = Tuple(code_point, tup1, &pool); Datastack data_stack; data_stack.push(register_val); Datastack aux_stack; aux_stack.push(register_val); aux_stack.push(code_point); CodePoint pc_codepoint(0, Operation(), 0); CodePoint err_pc_codepoint(0, Operation(), 0); Status state = Status::Extensive; auto inbox_blocked = InboxBlocked(0); auto saved_data = makeStorageData(saver, register_val, data_stack, aux_stack, state, pc_codepoint, err_pc_codepoint, inbox_blocked); return saved_data; } MachineStateKeys getDefaultValues(MachineStateSaver& saver) { TuplePool pool; auto register_val = Tuple(); auto data_stack = Tuple(); auto aux_stack = Tuple(); Status state = Status::Extensive; CodePoint code_point(0, Operation(), 0); auto data = makeStorageData(saver, Tuple(), Datastack(), Datastack(), state, code_point, code_point, NotBlocked()); return data; } std::vector<std::vector<unsigned char>> getHashKeys(MachineStateKeys data) { std::vector<std::vector<unsigned char>> hash_keys; hash_keys.push_back(data.auxstack_key); hash_keys.push_back(data.datastack_key); hash_keys.push_back(data.pc_key); hash_keys.push_back(data.err_pc_key); hash_keys.push_back(data.register_val_key); return hash_keys; } TEST_CASE("Save Machinestatedata") { SECTION("default") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[0]; auto saver = MachineStateSaver(storage.makeTransaction()); auto data_values = getDefaultValues(saver); std::vector<unsigned char> checkpoint_key = {'k', 'e', 'y'}; saveState(saver, data_values, checkpoint_key); } SECTION("with values") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[0]; CodePoint code_point2 = storage.getInitialVmValues().code[1]; auto saver = MachineStateSaver(storage.makeTransaction()); auto state_data = getStateValues(saver); std::vector<unsigned char> checkpoint_key = {'k', 'e', 'y'}; saveState(saver, state_data, checkpoint_key); } } TEST_CASE("Get Machinestate data") { SECTION("default") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[0]; auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); auto data_values = getDefaultValues(saver); auto keys = getHashKeys(data_values); std::vector<unsigned char> checkpoint_key = {'k', 'e', 'y'}; saver.saveMachineState(data_values, checkpoint_key); saver.commitTransaction(); getSavedState(fetcher, checkpoint_key, data_values, 1, keys); } SECTION("with values") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[0]; CodePoint code_point2 = storage.getInitialVmValues().code[1]; auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); auto state_data = getStateValues(saver); auto keys = getHashKeys(state_data); std::vector<unsigned char> checkpoint_key = {'k', 'e', 'y'}; saveState(saver, state_data, checkpoint_key); getSavedState(fetcher, checkpoint_key, state_data, 1, keys); } } TEST_CASE("Delete checkpoint") { SECTION("default") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[0]; auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); auto data_values = getDefaultValues(saver); std::vector<unsigned char> checkpoint_key = {'k', 'e', 'y'}; saver.saveMachineState(data_values, checkpoint_key); saver.commitTransaction(); auto hash_keys = getHashKeys(data_values); deleteCheckpoint(storage, fetcher, checkpoint_key, hash_keys); } SECTION("with actual state values") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[0]; CodePoint code_point2 = storage.getInitialVmValues().code[2]; auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); auto data_values = getStateValues(saver); std::vector<unsigned char> checkpoint_key = {'k', 'e', 'y'}; saver.saveMachineState(data_values, checkpoint_key); saver.commitTransaction(); auto hash_keys = getHashKeys(data_values); deleteCheckpoint(storage, fetcher, checkpoint_key, hash_keys); } SECTION("delete checkpoint saved twice") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[0]; CodePoint code_point2 = storage.getInitialVmValues().code[1]; auto fetcher = MachineStateFetcher(storage); auto saver = MachineStateSaver(storage.makeTransaction()); auto data_values = getStateValues(saver); std::vector<unsigned char> checkpoint_key = {'k', 'e', 'y'}; saver.saveMachineState(data_values, checkpoint_key); saver.saveMachineState(data_values, checkpoint_key); saver.commitTransaction(); auto hash_keys = getHashKeys(data_values); deleteCheckpointSavedTwice(storage, fetcher, checkpoint_key, hash_keys); } SECTION("delete checkpoint saved twice, reordered") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[0]; CodePoint code_point2 = storage.getInitialVmValues().code[1]; auto fetcher = MachineStateFetcher(storage); auto saver = MachineStateSaver(storage.makeTransaction()); auto saver2 = MachineStateSaver(storage.makeTransaction()); auto data_values = getStateValues(saver); std::vector<unsigned char> checkpoint_key = {'k', 'e', 'y'}; saver.saveMachineState(data_values, checkpoint_key); saver.commitTransaction(); saver2.saveMachineState(data_values, checkpoint_key); saver2.commitTransaction(); auto hash_keys = getHashKeys(data_values); deleteCheckpointSavedTwiceReordered(storage, fetcher, checkpoint_key, hash_keys); } }
35.42803
80
0.656545
mrsmkl
cd725f4ea754645fb58c747c8a825c92039711a7
27,365
cpp
C++
Source/Urho3D/IK/IKSolver.cpp
jayrulez/Urho3D
ff211d94240c1e848304aaaa9ccfa8d4f6315457
[ "MIT" ]
null
null
null
Source/Urho3D/IK/IKSolver.cpp
jayrulez/Urho3D
ff211d94240c1e848304aaaa9ccfa8d4f6315457
[ "MIT" ]
null
null
null
Source/Urho3D/IK/IKSolver.cpp
jayrulez/Urho3D
ff211d94240c1e848304aaaa9ccfa8d4f6315457
[ "MIT" ]
null
null
null
// Copyright (c) 2008-2022 the Urho3D project // License: MIT #include "../IK/IKSolver.h" #include "../IK/IKConstraint.h" #include "../IK/IKEvents.h" #include "../IK/IKEffector.h" #include "../IK/IKConverters.h" #include "../Core/Context.h" #include "../Core/Profiler.h" #include "../Graphics/Animation.h" #include "../Graphics/AnimationState.h" #include "../Graphics/DebugRenderer.h" #include "../IO/Log.h" #include "../Scene/SceneEvents.h" #include <ik/effector.h> #include <ik/node.h> #include <ik/solver.h> #include <ik/util.h> namespace Urho3D { extern const char* IK_CATEGORY; // ---------------------------------------------------------------------------- IKSolver::IKSolver(Context* context) : Component(context), solver_(nullptr), algorithm_(FABRIK), features_(AUTO_SOLVE | JOINT_ROTATIONS | UPDATE_ACTIVE_POSE), chainTreesNeedUpdating_(false), treeNeedsRebuild(true), solverTreeValid_(false) { context_->RequireIK(); SetAlgorithm(FABRIK); SubscribeToEvent(E_COMPONENTADDED, URHO3D_HANDLER(IKSolver, HandleComponentAdded)); SubscribeToEvent(E_COMPONENTREMOVED, URHO3D_HANDLER(IKSolver, HandleComponentRemoved)); SubscribeToEvent(E_NODEADDED, URHO3D_HANDLER(IKSolver, HandleNodeAdded)); SubscribeToEvent(E_NODEREMOVED, URHO3D_HANDLER(IKSolver, HandleNodeRemoved)); } // ---------------------------------------------------------------------------- IKSolver::~IKSolver() { // Destroying the solver tree will destroy the effector objects, so remove // any references any of the IKEffector objects could be holding for (Vector<IKEffector*>::ConstIterator it = effectorList_.Begin(); it != effectorList_.End(); ++it) (*it)->SetIKEffectorNode(nullptr); ik_solver_destroy(solver_); context_->ReleaseIK(); } // ---------------------------------------------------------------------------- void IKSolver::RegisterObject(Context* context) { context->RegisterFactory<IKSolver>(IK_CATEGORY); static const char* algorithmNames[] = { "1 Bone", "2 Bone", "FABRIK", /* not implemented, "MSD (Mass/Spring/Damper)", "Jacobian Inverse", "Jacobian Transpose",*/ nullptr }; URHO3D_ENUM_ACCESSOR_ATTRIBUTE("Algorithm", GetAlgorithm, SetAlgorithm, Algorithm, algorithmNames, FABRIK, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Max Iterations", GetMaximumIterations, SetMaximumIterations, unsigned, 20, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Convergence Tolerance", GetTolerance, SetTolerance, float, 0.001, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Joint Rotations", GetJOINT_ROTATIONS, SetJOINT_ROTATIONS, bool, true, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Target Rotations", GetTARGET_ROTATIONS, SetTARGET_ROTATIONS, bool, false, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Update Original Pose", GetUPDATE_ORIGINAL_POSE, SetUPDATE_ORIGINAL_POSE, bool, false, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Update Active Pose", GetUPDATE_ACTIVE_POSE, SetUPDATE_ACTIVE_POSE, bool, true, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Use Original Pose", GetUSE_ORIGINAL_POSE, SetUSE_ORIGINAL_POSE, bool, false, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Enable Constraints", GetCONSTRAINTS, SetCONSTRAINTS, bool, false, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Auto Solve", GetAUTO_SOLVE, SetAUTO_SOLVE, bool, true, AM_DEFAULT); } // ---------------------------------------------------------------------------- IKSolver::Algorithm IKSolver::GetAlgorithm() const { return algorithm_; } // ---------------------------------------------------------------------------- void IKSolver::SetAlgorithm(IKSolver::Algorithm algorithm) { algorithm_ = algorithm; /* We need to rebuild the tree so make sure that the scene is in the * initial pose when this occurs.*/ if (node_ != nullptr) ApplyOriginalPoseToScene(); // Initial flags for when there is no solver to destroy uint8_t initialFlags = 0; // Destroys the tree and the solver if (solver_ != nullptr) { initialFlags = solver_->flags; DestroyTree(); ik_solver_destroy(solver_); } switch (algorithm_) { case ONE_BONE : solver_ = ik_solver_create(SOLVER_ONE_BONE); break; case TWO_BONE : solver_ = ik_solver_create(SOLVER_TWO_BONE); break; case FABRIK : solver_ = ik_solver_create(SOLVER_FABRIK); break; /*case MSD : solver_ = ik_solver_create(SOLVER_MSD); break;*/ } solver_->flags = initialFlags; if (node_ != nullptr) RebuildTree(); } // ---------------------------------------------------------------------------- bool IKSolver::GetFeature(Feature feature) const { return (features_ & feature) != 0; } // ---------------------------------------------------------------------------- void IKSolver::SetFeature(Feature feature, bool enable) { switch (feature) { case CONSTRAINTS: { solver_->flags &= ~SOLVER_ENABLE_CONSTRAINTS; if (enable) solver_->flags |= SOLVER_ENABLE_CONSTRAINTS; } break; case TARGET_ROTATIONS: { solver_->flags &= ~SOLVER_CALCULATE_TARGET_ROTATIONS; if (enable) solver_->flags |= SOLVER_CALCULATE_TARGET_ROTATIONS; } break; case AUTO_SOLVE: { if (((features_ & AUTO_SOLVE) != 0) == enable) break; if (enable) SubscribeToEvent(GetScene(), E_SCENEDRAWABLEUPDATEFINISHED, URHO3D_HANDLER(IKSolver, HandleSceneDrawableUpdateFinished)); else UnsubscribeFromEvent(GetScene(), E_SCENEDRAWABLEUPDATEFINISHED); } break; default: break; } features_ &= ~feature; if (enable) features_ |= feature; } // ---------------------------------------------------------------------------- unsigned IKSolver::GetMaximumIterations() const { return solver_->max_iterations; } // ---------------------------------------------------------------------------- void IKSolver::SetMaximumIterations(unsigned iterations) { solver_->max_iterations = iterations; } // ---------------------------------------------------------------------------- float IKSolver::GetTolerance() const { return solver_->tolerance; } // ---------------------------------------------------------------------------- void IKSolver::SetTolerance(float tolerance) { if (tolerance < M_EPSILON) tolerance = M_EPSILON; solver_->tolerance = tolerance; } // ---------------------------------------------------------------------------- ik_node_t* IKSolver::CreateIKNodeFromUrhoNode(const Node* node) { ik_node_t* ikNode = ik_node_create(node->GetID()); // Set initial position/rotation and pass in Node* as user data for later ikNode->original_position = Vec3Urho2IK(node->GetWorldPosition()); ikNode->original_rotation = QuatUrho2IK(node->GetWorldRotation()); ikNode->user_data = (void*)node; /* * If Urho's node has an effector, also create and attach one to the * library's node. At this point, the IKEffector component shouldn't be * holding a reference to any internal effector. Check this for debugging * purposes and log if it does. */ auto* effector = node->GetComponent<IKEffector>(); if (effector != nullptr) { #ifdef DEBUG if (effector->ikEffectorNode_ != nullptr) URHO3D_LOGWARNINGF("[ik] IKEffector (attached to node \"%s\") has a reference to a possibly invalid internal effector. Should be NULL.", effector->GetNode()->GetName().CString()); #endif ik_effector_t* ikEffector = ik_effector_create(); ik_node_attach_effector(ikNode, ikEffector); // ownership of effector effector->SetIKSolver(this); effector->SetIKEffectorNode(ikNode); } // Exact same deal with the constraint auto* constraint = node->GetComponent<IKConstraint>(); if (constraint != nullptr) { #ifdef DEBUG if (constraint->ikConstraintNode_ != nullptr) URHO3D_LOGWARNINGF("[ik] IKConstraint (attached to node \"%s\") has a reference to a possibly invalid internal constraint. Should be NULL.", constraint->GetNode()->GetName().CString()); #endif constraint->SetIKConstraintNode(ikNode); } return ikNode; } // ---------------------------------------------------------------------------- void IKSolver::DestroyTree() { ik_solver_destroy_tree(solver_); effectorList_.Clear(); constraintList_.Clear(); } // ---------------------------------------------------------------------------- void IKSolver::RebuildTree() { assert (node_ != nullptr); // Destroy current tree and set a new root node DestroyTree(); ik_node_t* ikRoot = CreateIKNodeFromUrhoNode(node_); ik_solver_set_tree(solver_, ikRoot); /* * Collect all effectors and constraints from children, and filter them to * make sure they are in our subtree. */ node_->GetComponents<IKEffector>(effectorList_, true); node_->GetComponents<IKConstraint>(constraintList_, true); for (Vector<IKEffector*>::Iterator it = effectorList_.Begin(); it != effectorList_.End();) { if (ComponentIsInOurSubtree(*it)) { BuildTreeToEffector((*it)); ++it; } else { it = effectorList_.Erase(it); } } for (Vector<IKConstraint*>::Iterator it = constraintList_.Begin(); it != constraintList_.End();) { if (ComponentIsInOurSubtree(*it)) ++it; else it = constraintList_.Erase(it); } treeNeedsRebuild = false; MarkChainsNeedUpdating(); } // ---------------------------------------------------------------------------- bool IKSolver::BuildTreeToEffector(IKEffector* effector) { /* * NOTE: This function makes the assumption that the node the effector is * attached to is -- without a doubt -- in our subtree (by using * ComponentIsInOurSubtree() first). If this is not the case, the program * will abort. */ /* * we need to build tree up to the node where this effector was added. Do * this by following the chain of parent nodes until we hit a node that * exists in the solver's subtree. Then iterate backwards again and add each * missing node to the solver's tree. */ const Node* iterNode = effector->GetNode(); ik_node_t* ikNode; Vector<const Node*> missingNodes; while ((ikNode = ik_node_find_child(solver_->tree, iterNode->GetID())) == nullptr) { missingNodes.Push(iterNode); iterNode = iterNode->GetParent(); // Assert the assumptions made (described in the beginning of this function) assert(iterNode != nullptr); assert (iterNode->HasComponent<IKSolver>() == false || iterNode == node_); } while (missingNodes.Size() > 0) { iterNode = missingNodes.Back(); missingNodes.Pop(); ik_node_t* ikChildNode = CreateIKNodeFromUrhoNode(iterNode); ik_node_add_child(ikNode, ikChildNode); ikNode = ikChildNode; } return true; } // ---------------------------------------------------------------------------- bool IKSolver::ComponentIsInOurSubtree(Component* component) const { const Node* iterNode = component->GetNode(); while (true) { // Note part of our subtree if (iterNode == nullptr) return false; // Reached the root node, it's part of our subtree! if (iterNode == node_) return true; // Path to us is being blocked by another solver Component* otherSolver = iterNode->GetComponent<IKSolver>(); if (otherSolver != nullptr && otherSolver != component) return false; iterNode = iterNode->GetParent(); } return true; } // ---------------------------------------------------------------------------- void IKSolver::RebuildChainTrees() { solverTreeValid_ = (ik_solver_rebuild_chain_trees(solver_) == 0); ik_calculate_rotation_weight_decays(&solver_->chain_tree); chainTreesNeedUpdating_ = false; } // ---------------------------------------------------------------------------- void IKSolver::RecalculateSegmentLengths() { ik_solver_recalculate_segment_lengths(solver_); } // ---------------------------------------------------------------------------- void IKSolver::CalculateJointRotations() { ik_solver_calculate_joint_rotations(solver_); } // ---------------------------------------------------------------------------- void IKSolver::Solve() { URHO3D_PROFILE(IKSolve); if (treeNeedsRebuild) RebuildTree(); if (chainTreesNeedUpdating_) RebuildChainTrees(); if (IsSolverTreeValid() == false) return; if (features_ & UPDATE_ORIGINAL_POSE) ApplySceneToOriginalPose(); if (features_ & UPDATE_ACTIVE_POSE) ApplySceneToActivePose(); if (features_ & USE_ORIGINAL_POSE) ApplyOriginalPoseToActivePose(); for (Vector<IKEffector*>::ConstIterator it = effectorList_.Begin(); it != effectorList_.End(); ++it) { (*it)->UpdateTargetNodePosition(); } ik_solver_solve(solver_); if (features_ & JOINT_ROTATIONS) ik_solver_calculate_joint_rotations(solver_); ApplyActivePoseToScene(); } // ---------------------------------------------------------------------------- static void ApplyInitialPoseToSceneCallback(ik_node_t* ikNode) { auto* node = (Node*)ikNode->user_data; node->SetWorldRotation(QuatIK2Urho(&ikNode->original_rotation)); node->SetWorldPosition(Vec3IK2Urho(&ikNode->original_position)); } void IKSolver::ApplyOriginalPoseToScene() { ik_solver_iterate_tree(solver_, ApplyInitialPoseToSceneCallback); } // ---------------------------------------------------------------------------- static void ApplySceneToInitialPoseCallback(ik_node_t* ikNode) { auto* node = (Node*)ikNode->user_data; ikNode->original_rotation = QuatUrho2IK(node->GetWorldRotation()); ikNode->original_position = Vec3Urho2IK(node->GetWorldPosition()); } void IKSolver::ApplySceneToOriginalPose() { ik_solver_iterate_tree(solver_, ApplySceneToInitialPoseCallback); } // ---------------------------------------------------------------------------- static void ApplyActivePoseToSceneCallback(ik_node_t* ikNode) { auto* node = (Node*)ikNode->user_data; node->SetWorldRotation(QuatIK2Urho(&ikNode->rotation)); node->SetWorldPosition(Vec3IK2Urho(&ikNode->position)); } void IKSolver::ApplyActivePoseToScene() { ik_solver_iterate_tree(solver_, ApplyActivePoseToSceneCallback); } // ---------------------------------------------------------------------------- static void ApplySceneToActivePoseCallback(ik_node_t* ikNode) { auto* node = (Node*)ikNode->user_data; ikNode->rotation = QuatUrho2IK(node->GetWorldRotation()); ikNode->position = Vec3Urho2IK(node->GetWorldPosition()); } void IKSolver::ApplySceneToActivePose() { ik_solver_iterate_tree(solver_, ApplySceneToActivePoseCallback); } // ---------------------------------------------------------------------------- void IKSolver::ApplyOriginalPoseToActivePose() { ik_solver_reset_to_original_pose(solver_); } // ---------------------------------------------------------------------------- void IKSolver::MarkChainsNeedUpdating() { chainTreesNeedUpdating_ = true; } // ---------------------------------------------------------------------------- void IKSolver::MarkTreeNeedsRebuild() { treeNeedsRebuild = true; } // ---------------------------------------------------------------------------- bool IKSolver::IsSolverTreeValid() const { return solverTreeValid_; } // ---------------------------------------------------------------------------- /* * This next section maintains the internal list of effector nodes. Whenever * nodes are deleted or added to the scene, or whenever components are added * or removed from nodes, we must check to see which of those nodes are/were * IK effector nodes and update our internal list accordingly. * * Unfortunately, E_COMPONENTREMOVED and E_COMPONENTADDED do not fire when a * parent node is removed/added containing child effector nodes, so we must * also monitor E_NODEREMOVED AND E_NODEADDED. */ // ---------------------------------------------------------------------------- void IKSolver::OnSceneSet(Scene* scene) { if (features_ & AUTO_SOLVE) SubscribeToEvent(scene, E_SCENEDRAWABLEUPDATEFINISHED, URHO3D_HANDLER(IKSolver, HandleSceneDrawableUpdateFinished)); } // ---------------------------------------------------------------------------- void IKSolver::OnNodeSet(Node* node) { ApplyOriginalPoseToScene(); DestroyTree(); if (node != nullptr) RebuildTree(); } // ---------------------------------------------------------------------------- void IKSolver::HandleComponentAdded(StringHash eventType, VariantMap& eventData) { using namespace ComponentAdded; (void)eventType; auto* node = static_cast<Node*>(eventData[P_NODE].GetPtr()); auto* component = static_cast<Component*>(eventData[P_COMPONENT].GetPtr()); /* * When a solver gets added into the scene, any parent solver's tree will * be invalidated. We need to find all parent solvers (by iterating up the * tree) and mark them as such. */ if (component->GetType() == IKSolver::GetTypeStatic()) { for (Node* iterNode = node; iterNode != nullptr; iterNode = iterNode->GetParent()) { auto* parentSolver = iterNode->GetComponent<IKSolver>(); if (parentSolver != nullptr) parentSolver->MarkTreeNeedsRebuild(); } return; // No need to continue processing effectors or constraints } if (solver_->tree == nullptr) return; /* * Update tree if component is an effector and is part of our subtree. */ if (component->GetType() == IKEffector::GetTypeStatic()) { // Not interested in components that won't be part of our if (ComponentIsInOurSubtree(component) == false) return; BuildTreeToEffector(static_cast<IKEffector*>(component)); effectorList_.Push(static_cast<IKEffector*>(component)); return; } if (component->GetType() == IKConstraint::GetTypeStatic()) { if (ComponentIsInOurSubtree(component) == false) return; constraintList_.Push(static_cast<IKConstraint*>(component)); } } // ---------------------------------------------------------------------------- void IKSolver::HandleComponentRemoved(StringHash eventType, VariantMap& eventData) { using namespace ComponentRemoved; if (solver_->tree == nullptr) return; auto* node = static_cast<Node*>(eventData[P_NODE].GetPtr()); auto* component = static_cast<Component*>(eventData[P_COMPONENT].GetPtr()); /* * When a solver gets added into the scene, any parent solver's tree will * be invalidated. We need to find all parent solvers (by iterating up the * tree) and mark them as such. */ if (component->GetType() == IKSolver::GetTypeStatic()) { for (Node* iterNode = node; iterNode != nullptr; iterNode = iterNode->GetParent()) { auto* parentSolver = iterNode->GetComponent<IKSolver>(); if (parentSolver != nullptr) parentSolver->MarkTreeNeedsRebuild(); } return; // No need to continue processing effectors or constraints } // If an effector was removed, the tree will have to be rebuilt. if (component->GetType() == IKEffector::GetTypeStatic()) { if (ComponentIsInOurSubtree(component) == false) return; ik_node_t* ikNode = ik_node_find_child(solver_->tree, node->GetID()); assert(ikNode != nullptr); ik_node_destroy_effector(ikNode); static_cast<IKEffector*>(component)->SetIKEffectorNode(nullptr); effectorList_.RemoveSwap(static_cast<IKEffector*>(component)); ApplyOriginalPoseToScene(); MarkTreeNeedsRebuild(); return; } // Remove the ikNode* reference the IKConstraint was holding if (component->GetType() == IKConstraint::GetTypeStatic()) { if (ComponentIsInOurSubtree(component) == false) return; ik_node_t* ikNode = ik_node_find_child(solver_->tree, node->GetID()); assert(ikNode != nullptr); static_cast<IKConstraint*>(component)->SetIKConstraintNode(nullptr); constraintList_.RemoveSwap(static_cast<IKConstraint*>(component)); } } // ---------------------------------------------------------------------------- void IKSolver::HandleNodeAdded(StringHash eventType, VariantMap& eventData) { using namespace NodeAdded; if (solver_->tree == nullptr) return; auto* node = static_cast<Node*>(eventData[P_NODE].GetPtr()); Vector<IKEffector*> effectors; node->GetComponents<IKEffector>(effectors, true); for (Vector<IKEffector*>::ConstIterator it = effectors.Begin(); it != effectors.End(); ++it) { if (ComponentIsInOurSubtree(*it) == false) continue; BuildTreeToEffector(*it); effectorList_.Push(*it); } Vector<IKConstraint*> constraints; node->GetComponents<IKConstraint>(constraints, true); for (Vector<IKConstraint*>::ConstIterator it = constraints.Begin(); it != constraints.End(); ++it) { if (ComponentIsInOurSubtree(*it) == false) continue; constraintList_.Push(*it); } } // ---------------------------------------------------------------------------- void IKSolver::HandleNodeRemoved(StringHash eventType, VariantMap& eventData) { using namespace NodeRemoved; if (solver_->tree == nullptr) return; auto* node = static_cast<Node*>(eventData[P_NODE].GetPtr()); // Remove cached IKEffectors from our list Vector<IKEffector*> effectors; node->GetComponents<IKEffector>(effectors, true); for (Vector<IKEffector*>::ConstIterator it = effectors.Begin(); it != effectors.End(); ++it) { (*it)->SetIKEffectorNode(nullptr); effectorList_.RemoveSwap(*it); } Vector<IKConstraint*> constraints; node->GetComponents<IKConstraint>(constraints, true); for (Vector<IKConstraint*>::ConstIterator it = constraints.Begin(); it != constraints.End(); ++it) { constraintList_.RemoveSwap(*it); } // Special case, if the node being destroyed is the root node, destroy the // solver's tree instead of destroying the single node. Calling // ik_node_destroy() on the solver's root node will cause segfaults. ik_node_t* ikNode = ik_node_find_child(solver_->tree, node->GetID()); if (ikNode != nullptr) { if (ikNode == solver_->tree) ik_solver_destroy_tree(solver_); else ik_node_destroy(ikNode); MarkChainsNeedUpdating(); } } // ---------------------------------------------------------------------------- void IKSolver::HandleSceneDrawableUpdateFinished(StringHash eventType, VariantMap& eventData) { Solve(); } // ---------------------------------------------------------------------------- void IKSolver::DrawDebugGeometry(bool depthTest) { auto* debug = GetScene()->GetComponent<DebugRenderer>(); if (debug) DrawDebugGeometry(debug, depthTest); } // ---------------------------------------------------------------------------- void IKSolver::DrawDebugGeometry(DebugRenderer* debug, bool depthTest) { // Draws all scene segments for (Vector<IKEffector*>::ConstIterator it = effectorList_.Begin(); it != effectorList_.End(); ++it) (*it)->DrawDebugGeometry(debug, depthTest); ORDERED_VECTOR_FOR_EACH(&solver_->effector_nodes_list, ik_node_t*, pnode) ik_effector_t* effector = (*pnode)->effector; // Calculate average length of all segments so we can determine the radius // of the debug spheres to draw int chainLength = effector->chain_length == 0 ? -1 : effector->chain_length; ik_node_t* a = *pnode; ik_node_t* b = a->parent; float averageLength = 0.0f; unsigned numberOfSegments = 0; while (b && chainLength-- != 0) { vec3_t v = a->original_position; vec3_sub_vec3(v.f, b->original_position.f); averageLength += vec3_length(v.f); ++numberOfSegments; a = b; b = b->parent; } averageLength /= numberOfSegments; // connect all chained nodes together with lines chainLength = effector->chain_length == 0 ? -1 : effector->chain_length; a = *pnode; b = a->parent; debug->AddSphere( Sphere(Vec3IK2Urho(&a->original_position), averageLength * 0.1f), Color(0, 0, 255), depthTest ); debug->AddSphere( Sphere(Vec3IK2Urho(&a->position), averageLength * 0.1f), Color(255, 128, 0), depthTest ); while (b && chainLength-- != 0) { debug->AddLine( Vec3IK2Urho(&a->original_position), Vec3IK2Urho(&b->original_position), Color(0, 255, 255), depthTest ); debug->AddSphere( Sphere(Vec3IK2Urho(&b->original_position), averageLength * 0.1f), Color(0, 0, 255), depthTest ); debug->AddLine( Vec3IK2Urho(&a->position), Vec3IK2Urho(&b->position), Color(255, 0, 0), depthTest ); debug->AddSphere( Sphere(Vec3IK2Urho(&b->position), averageLength * 0.1f), Color(255, 128, 0), depthTest ); a = b; b = b->parent; } ORDERED_VECTOR_END_EACH } // ---------------------------------------------------------------------------- // Need these wrapper functions flags of GetFeature/SetFeature can be correctly // exposed to the editor // ---------------------------------------------------------------------------- #define DEF_FEATURE_GETTER(feature_name) \ bool IKSolver::Get##feature_name() const \ { \ return GetFeature(feature_name); \ } #define DEF_FEATURE_SETTER(feature_name) \ void IKSolver::Set##feature_name(bool enable) \ { \ SetFeature(feature_name, enable); \ } DEF_FEATURE_GETTER(JOINT_ROTATIONS) DEF_FEATURE_GETTER(TARGET_ROTATIONS) DEF_FEATURE_GETTER(UPDATE_ORIGINAL_POSE) DEF_FEATURE_GETTER(UPDATE_ACTIVE_POSE) DEF_FEATURE_GETTER(USE_ORIGINAL_POSE) DEF_FEATURE_GETTER(CONSTRAINTS) DEF_FEATURE_GETTER(AUTO_SOLVE) DEF_FEATURE_SETTER(JOINT_ROTATIONS) DEF_FEATURE_SETTER(TARGET_ROTATIONS) DEF_FEATURE_SETTER(UPDATE_ORIGINAL_POSE) DEF_FEATURE_SETTER(UPDATE_ACTIVE_POSE) DEF_FEATURE_SETTER(USE_ORIGINAL_POSE) DEF_FEATURE_SETTER(CONSTRAINTS) DEF_FEATURE_SETTER(AUTO_SOLVE) } // namespace Urho3D
33.250304
197
0.587466
jayrulez
cd74b2c0719fc846f8b3ecd83fd50fd4f8253f4f
3,349
cpp
C++
examples/Pose2SLAMwSPCG.cpp
zwn/gtsam
3422c3bb66bef319d66a950857bb6ec073b43703
[ "BSD-3-Clause" ]
1,402
2017-03-28T00:18:11.000Z
2022-03-30T10:28:32.000Z
examples/Pose2SLAMwSPCG.cpp
zwn/gtsam
3422c3bb66bef319d66a950857bb6ec073b43703
[ "BSD-3-Clause" ]
851
2017-11-27T15:09:56.000Z
2022-03-31T22:26:38.000Z
examples/Pose2SLAMwSPCG.cpp
zwn/gtsam
3422c3bb66bef319d66a950857bb6ec073b43703
[ "BSD-3-Clause" ]
565
2017-11-30T16:15:59.000Z
2022-03-31T02:53:04.000Z
/* ---------------------------------------------------------------------------- * GTSAM Copyright 2010, Georgia Tech Research Corporation, * Atlanta, Georgia 30332-0415 * All Rights Reserved * Authors: Frank Dellaert, et al. (see THANKS for the full author list) * See LICENSE for the license information * -------------------------------------------------------------------------- */ /** * @file Pose2SLAMwSPCG.cpp * @brief A 2D Pose SLAM example using the SimpleSPCGSolver. * @author Yong-Dian Jian * @date June 2, 2012 */ // For an explanation of headers below, please see Pose2SLAMExample.cpp #include <gtsam/slam/BetweenFactor.h> #include <gtsam/geometry/Pose2.h> #include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h> // In contrast to that example, however, we will use a PCG solver here #include <gtsam/linear/SubgraphSolver.h> using namespace std; using namespace gtsam; int main(int argc, char** argv) { // 1. Create a factor graph container and add factors to it NonlinearFactorGraph graph; // 2a. Add a prior on the first pose, setting it to the origin Pose2 prior(0.0, 0.0, 0.0); // prior at origin auto priorNoise = noiseModel::Diagonal::Sigmas(Vector3(0.3, 0.3, 0.1)); graph.addPrior(1, prior, priorNoise); // 2b. Add odometry factors auto odometryNoise = noiseModel::Diagonal::Sigmas(Vector3(0.2, 0.2, 0.1)); graph.emplace_shared<BetweenFactor<Pose2> >(1, 2, Pose2(2.0, 0.0, M_PI_2), odometryNoise); graph.emplace_shared<BetweenFactor<Pose2> >(2, 3, Pose2(2.0, 0.0, M_PI_2), odometryNoise); graph.emplace_shared<BetweenFactor<Pose2> >(3, 4, Pose2(2.0, 0.0, M_PI_2), odometryNoise); graph.emplace_shared<BetweenFactor<Pose2> >(4, 5, Pose2(2.0, 0.0, M_PI_2), odometryNoise); // 2c. Add the loop closure constraint auto model = noiseModel::Diagonal::Sigmas(Vector3(0.2, 0.2, 0.1)); graph.emplace_shared<BetweenFactor<Pose2> >(5, 1, Pose2(0.0, 0.0, 0.0), model); graph.print("\nFactor Graph:\n"); // print // 3. Create the data structure to hold the initialEstimate estimate to the // solution Values initialEstimate; initialEstimate.insert(1, Pose2(0.5, 0.0, 0.2)); initialEstimate.insert(2, Pose2(2.3, 0.1, 1.1)); initialEstimate.insert(3, Pose2(2.1, 1.9, 2.8)); initialEstimate.insert(4, Pose2(-.3, 2.5, 4.2)); initialEstimate.insert(5, Pose2(0.1, -0.7, 5.8)); initialEstimate.print("\nInitial Estimate:\n"); // print // 4. Single Step Optimization using Levenberg-Marquardt LevenbergMarquardtParams parameters; parameters.verbosity = NonlinearOptimizerParams::ERROR; parameters.verbosityLM = LevenbergMarquardtParams::LAMBDA; // LM is still the outer optimization loop, but by specifying "Iterative" // below We indicate that an iterative linear solver should be used. In // addition, the *type* of the iterativeParams decides on the type of // iterative solver, in this case the SPCG (subgraph PCG) parameters.linearSolverType = NonlinearOptimizerParams::Iterative; parameters.iterativeParams = boost::make_shared<SubgraphSolverParameters>(); LevenbergMarquardtOptimizer optimizer(graph, initialEstimate, parameters); Values result = optimizer.optimize(); result.print("Final Result:\n"); cout << "subgraph solver final error = " << graph.error(result) << endl; return 0; }
41.345679
92
0.682293
zwn
cd7686a48ce1c8136bd51fd436830fa2d92e7f41
30,608
cc
C++
chrome/browser/instant/instant_controller.cc
junmin-zhu/chromium-rivertrail
eb1a57aca71fe68d96e48af8998dcfbe45171ee1
[ "BSD-3-Clause" ]
5
2018-03-10T13:08:42.000Z
2021-07-26T15:02:11.000Z
chrome/browser/instant/instant_controller.cc
sanyaade-mobiledev/chromium.src
d496dfeebb0f282468827654c2b3769b3378c087
[ "BSD-3-Clause" ]
1
2015-07-21T08:02:01.000Z
2015-07-21T08:02:01.000Z
chrome/browser/instant/instant_controller.cc
jianglong0156/chromium.src
d496dfeebb0f282468827654c2b3769b3378c087
[ "BSD-3-Clause" ]
6
2016-11-14T10:13:35.000Z
2021-01-23T15:29:53.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/instant/instant_controller.h" #include "base/command_line.h" #include "base/i18n/case_conversion.h" #include "base/metrics/histogram.h" #include "base/string_util.h" #include "base/time.h" #include "base/utf_string_conversions.h" #include "chrome/browser/autocomplete/autocomplete_provider.h" #include "chrome/browser/google/google_util.h" #include "chrome/browser/history/history.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/history/history_tab_helper.h" #include "chrome/browser/instant/instant_loader.h" #include "chrome/browser/platform_util.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/search_engines/template_url_service.h" #include "chrome/browser/search_engines/template_url_service_factory.h" #include "chrome/browser/ui/browser_instant_controller.h" #include "chrome/browser/ui/search/search.h" #include "chrome/browser/ui/search/search_tab_helper.h" #include "chrome/browser/ui/tab_contents/tab_contents.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "content/public/browser/favicon_status.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "net/base/escape.h" #include "unicode/normalizer2.h" #include "unicode/unistr.h" #if defined(TOOLKIT_VIEWS) #include "ui/views/widget/widget.h" #endif namespace { enum PreviewUsageType { PREVIEW_CREATED = 0, PREVIEW_DELETED, PREVIEW_LOADED, PREVIEW_SHOWED, PREVIEW_COMMITTED, PREVIEW_NUM_TYPES, }; // An artificial delay (in milliseconds) we introduce before telling the Instant // page about the new omnibox bounds, in cases where the bounds shrink. This is // to avoid the page jumping up/down very fast in response to bounds changes. const int kUpdateBoundsDelayMS = 1000; // The maximum number of times we'll load a non-Instant-supporting search engine // before we give up and blacklist it for the rest of the browsing session. const int kMaxInstantSupportFailures = 10; // If an Instant page has not been used in these many milliseconds, it is // reloaded so that the page does not become stale. const int kStaleLoaderTimeoutMS = 3 * 3600 * 1000; std::string ModeToString(InstantController::Mode mode) { switch (mode) { case InstantController::EXTENDED: return "_Extended"; case InstantController::INSTANT: return "_Instant"; case InstantController::DISABLED: return "_Disabled"; } NOTREACHED(); return std::string(); } void AddPreviewUsageForHistogram(InstantController::Mode mode, PreviewUsageType usage) { DCHECK(0 <= usage && usage < PREVIEW_NUM_TYPES) << usage; base::Histogram* histogram = base::LinearHistogram::FactoryGet( "Instant.Previews" + ModeToString(mode), 1, PREVIEW_NUM_TYPES, PREVIEW_NUM_TYPES + 1, base::Histogram::kUmaTargetedHistogramFlag); histogram->Add(usage); } void AddSessionStorageHistogram(InstantController::Mode mode, const TabContents* tab1, const TabContents* tab2) { base::Histogram* histogram = base::BooleanHistogram::FactoryGet( "Instant.SessionStorageNamespace" + ModeToString(mode), base::Histogram::kUmaTargetedHistogramFlag); const content::SessionStorageNamespaceMap& session_storage_map1 = tab1->web_contents()->GetController().GetSessionStorageNamespaceMap(); const content::SessionStorageNamespaceMap& session_storage_map2 = tab2->web_contents()->GetController().GetSessionStorageNamespaceMap(); bool is_session_storage_the_same = session_storage_map1.size() == session_storage_map2.size(); if (is_session_storage_the_same) { // The size is the same, so let's check that all entries match. for (content::SessionStorageNamespaceMap::const_iterator it1 = session_storage_map1.begin(), it2 = session_storage_map2.begin(); it1 != session_storage_map1.end() && it2 != session_storage_map2.end(); ++it1, ++it2) { if (it1->first != it2->first || it1->second != it2->second) { is_session_storage_the_same = false; break; } } } histogram->AddBoolean(is_session_storage_the_same); } InstantController::Mode GetModeForProfile(Profile* profile) { if (chrome::search::IsInstantExtendedAPIEnabled(profile)) return InstantController::EXTENDED; if (!profile || profile->IsOffTheRecord() || !profile->GetPrefs() || !profile->GetPrefs()->GetBoolean(prefs::kInstantEnabled)) return InstantController::DISABLED; return InstantController::INSTANT; } string16 Normalize(const string16& str) { UErrorCode status = U_ZERO_ERROR; const icu::Normalizer2* normalizer = icu::Normalizer2::getInstance(NULL, "nfkc_cf", UNORM2_COMPOSE, status); if (normalizer == NULL || U_FAILURE(status)) return str; icu::UnicodeString norm_str(normalizer->normalize( icu::UnicodeString(FALSE, str.c_str(), str.size()), status)); if (U_FAILURE(status)) return str; return string16(norm_str.getBuffer(), norm_str.length()); } bool NormalizeAndStripPrefix(string16* text, const string16& prefix) { const string16 norm_prefix = Normalize(prefix); string16 norm_text = Normalize(*text); if (norm_prefix.size() <= norm_text.size() && norm_text.compare(0, norm_prefix.size(), norm_prefix) == 0) { *text = norm_text.erase(0, norm_prefix.size()); return true; } return false; } } // namespace InstantController::~InstantController() { if (GetPreviewContents()) AddPreviewUsageForHistogram(mode_, PREVIEW_DELETED); } // static InstantController* InstantController::CreateInstant( Profile* profile, chrome::BrowserInstantController* browser) { const Mode mode = GetModeForProfile(profile); return mode == DISABLED ? NULL : new InstantController(browser, mode); } // static bool InstantController::IsExtendedAPIEnabled(Profile* profile) { return GetModeForProfile(profile) == EXTENDED; } // static bool InstantController::IsInstantEnabled(Profile* profile) { const Mode mode = GetModeForProfile(profile); return mode == EXTENDED || mode == INSTANT; } // static void InstantController::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterBooleanPref(prefs::kInstantConfirmDialogShown, false, PrefService::SYNCABLE_PREF); prefs->RegisterBooleanPref(prefs::kInstantEnabled, false, PrefService::SYNCABLE_PREF); } bool InstantController::Update(const AutocompleteMatch& match, const string16& user_text, const string16& full_text, bool verbatim) { const TabContents* active_tab = browser_->GetActiveTabContents(); // We could get here with no active tab if the Browser is closing. if (!active_tab) { Hide(); return false; } std::string instant_url; Profile* profile = active_tab->profile(); // If the match's TemplateURL is valid, it's a search query; use it. If it's // not valid, it's likely a URL; in EXTENDED mode, try using the default // search engine's TemplateURL instead. const GURL& tab_url = active_tab->web_contents()->GetURL(); if (GetInstantURL(match.GetTemplateURL(profile, false), tab_url, &instant_url)) { ResetLoader(instant_url, active_tab); } else if (mode_ != EXTENDED || !CreateDefaultLoader()) { Hide(); return false; } if (full_text.empty()) { Hide(); return false; } // Track the non-Instant search URL for this query. url_for_history_ = match.destination_url; last_transition_type_ = match.transition; last_active_tab_ = active_tab; last_match_was_search_ = AutocompleteMatch::IsSearchType(match.type); // In EXTENDED mode, we send only |user_text| as the query text. In all other // modes, we use the entire |full_text|. const string16& query_text = mode_ == EXTENDED ? user_text : full_text; string16 last_query_text = mode_ == EXTENDED ? last_user_text_ : last_full_text_; last_user_text_ = user_text; last_full_text_ = full_text; // Don't send an update to the loader if the query text hasn't changed. if (query_text == last_query_text && verbatim == last_verbatim_) { // Reuse the last suggestion, as it's still valid. browser_->SetInstantSuggestion(last_suggestion_); // We need to call Show() here because of this: // 1. User has typed a query (say Q). Instant overlay is showing results. // 2. User arrows-down to a URL entry or erases all omnibox text. Both of // these cause the overlay to Hide(). // 3. User arrows-up to Q or types Q again. The last text we processed is // still Q, so we don't Update() the loader, but we do need to Show(). if (loader_processed_last_update_) Show(100, INSTANT_SIZE_PERCENT); return true; } last_verbatim_ = verbatim; loader_processed_last_update_ = false; last_suggestion_ = InstantSuggestion(); loader_->Update(query_text, verbatim); content::NotificationService::current()->Notify( chrome::NOTIFICATION_INSTANT_CONTROLLER_UPDATED, content::Source<InstantController>(this), content::NotificationService::NoDetails()); // We don't have suggestions yet, but need to reset any existing "gray text". browser_->SetInstantSuggestion(InstantSuggestion()); // Though we may have handled a URL match above, we return false here, so that // omnibox prerendering can kick in. TODO(sreeram): Remove this (and always // return true) once we are able to commit URLs as well. return last_match_was_search_; } // TODO(tonyg): This method only fires when the omnibox bounds change. It also // needs to fire when the preview bounds change (e.g.: open/close info bar). void InstantController::SetOmniboxBounds(const gfx::Rect& bounds) { if (omnibox_bounds_ == bounds) return; omnibox_bounds_ = bounds; if (omnibox_bounds_.height() > last_omnibox_bounds_.height()) { update_bounds_timer_.Stop(); SendBoundsToPage(); } else if (!update_bounds_timer_.IsRunning()) { update_bounds_timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(kUpdateBoundsDelayMS), this, &InstantController::SendBoundsToPage); } } void InstantController::HandleAutocompleteResults( const std::vector<AutocompleteProvider*>& providers) { if (mode_ != EXTENDED || !GetPreviewContents()) return; std::vector<InstantAutocompleteResult> results; for (ACProviders::const_iterator provider = providers.begin(); provider != providers.end(); ++provider) { for (ACMatches::const_iterator match = (*provider)->matches().begin(); match != (*provider)->matches().end(); ++match) { InstantAutocompleteResult result; result.provider = UTF8ToUTF16((*provider)->GetName()); result.is_search = AutocompleteMatch::IsSearchType(match->type); result.contents = match->description; result.destination_url = match->destination_url; result.relevance = match->relevance; results.push_back(result); } } loader_->SendAutocompleteResults(results); } bool InstantController::OnUpOrDownKeyPressed(int count) { if (mode_ != EXTENDED || !GetPreviewContents()) return false; loader_->OnUpOrDownKeyPressed(count); return true; } TabContents* InstantController::GetPreviewContents() const { return loader_.get() ? loader_->preview_contents() : NULL; } void InstantController::Hide() { last_active_tab_ = NULL; // The only time when the model is not already in the desired NOT_READY state // and GetPreviewContents() returns NULL is when we are in the commit path. // In that case, don't change the state just yet; otherwise we may cause the // preview to hide unnecessarily. Instead, the state will be set correctly // after the commit is done. if (GetPreviewContents()) model_.SetDisplayState(InstantModel::NOT_READY, 0, INSTANT_SIZE_PERCENT); if (GetPreviewContents() && !last_full_text_.empty()) { // Send a blank query to ask the preview to clear out old results. last_full_text_.clear(); last_user_text_.clear(); loader_->Update(last_full_text_, true); } } bool InstantController::IsCurrent() const { return !IsOutOfDate() && GetPreviewContents() && loader_->supports_instant() && last_match_was_search_; } void InstantController::CommitCurrentPreview(InstantCommitType type) { TabContents* preview = loader_->ReleasePreviewContents(type, last_full_text_); if (mode_ == EXTENDED) { // Consider what's happening: // 1. The user has typed a query in the omnibox and committed it (either // by pressing Enter or clicking on the preview). // 2. We commit the preview to the tab strip, and tell the page. // 3. The page will update the URL hash fragment with the query terms. // After steps 1 and 3, the omnibox will show the query terms. However, if // the URL we are committing at step 2 doesn't already have query terms, it // will flash for a brief moment as a plain URL. So, avoid that flicker by // pretending that the plain URL is actually the typed query terms. // TODO(samarth,beaudoin): Instead of this hack, we should add a new field // to NavigationEntry to keep track of what the correct query, if any, is. content::NavigationEntry* entry = preview->web_contents()->GetController().GetVisibleEntry(); std::string url = entry->GetVirtualURL().spec(); if (!google_util::IsInstantExtendedAPIGoogleSearchUrl(url) && google_util::IsGoogleDomainUrl(url, google_util::ALLOW_SUBDOMAIN, google_util::ALLOW_NON_STANDARD_PORTS)) { entry->SetVirtualURL(GURL( url + "#q=" + net::EscapeQueryParamValue(UTF16ToUTF8(last_full_text_), true))); chrome::search::SearchTabHelper::FromWebContents( preview->web_contents())->NavigationEntryUpdated(); } } // If the preview page has navigated since the last Update(), we need to add // the navigation to history ourselves. Else, the page will navigate after // commit, and it will be added to history in the usual manner. const history::HistoryAddPageArgs& last_navigation = loader_->last_navigation(); if (!last_navigation.url.is_empty()) { content::NavigationEntry* entry = preview->web_contents()->GetController().GetActiveEntry(); DCHECK_EQ(last_navigation.url, entry->GetURL()); // Add the page to history. HistoryTabHelper* history_tab_helper = HistoryTabHelper::FromWebContents(preview->web_contents()); history_tab_helper->UpdateHistoryForNavigation(last_navigation); // Update the page title. history_tab_helper->UpdateHistoryPageTitle(*entry); } // Add a fake history entry with a non-Instant search URL, so that search // terms extraction (for autocomplete history matches) works. if (HistoryService* history = HistoryServiceFactory::GetForProfile( preview->profile(), Profile::EXPLICIT_ACCESS)) { history->AddPage(url_for_history_, base::Time::Now(), NULL, 0, GURL(), history::RedirectList(), last_transition_type_, history::SOURCE_BROWSED, false); } AddPreviewUsageForHistogram(mode_, PREVIEW_COMMITTED); DeleteLoader(); preview->web_contents()->GetController().PruneAllButActive(); if (type != INSTANT_COMMIT_PRESSED_ALT_ENTER) { const TabContents* active_tab = browser_->GetActiveTabContents(); AddSessionStorageHistogram(mode_, active_tab, preview); preview->web_contents()->GetController().CopyStateFromAndPrune( &active_tab->web_contents()->GetController()); } // Browser takes ownership of the preview. browser_->CommitInstant(preview, type == INSTANT_COMMIT_PRESSED_ALT_ENTER); content::NotificationService::current()->Notify( chrome::NOTIFICATION_INSTANT_COMMITTED, content::Source<content::WebContents>(preview->web_contents()), content::NotificationService::NoDetails()); model_.SetDisplayState(InstantModel::NOT_READY, 0, INSTANT_SIZE_PERCENT); // Try to create another loader immediately so that it is ready for the next // user interaction. CreateDefaultLoader(); } void InstantController::OnAutocompleteLostFocus( gfx::NativeView view_gaining_focus) { is_omnibox_focused_ = false; // If there is no preview, nothing to do. if (!GetPreviewContents()) return; loader_->OnAutocompleteLostFocus(); // If the preview is not showing, only need to check for loader staleness. if (!model_.is_ready()) { MaybeOnStaleLoader(); return; } #if defined(OS_MACOSX) if (!loader_->IsPointerDownFromActivate()) { Hide(); MaybeOnStaleLoader(); } #else content::RenderWidgetHostView* rwhv = GetPreviewContents()->web_contents()->GetRenderWidgetHostView(); if (!view_gaining_focus || !rwhv) { Hide(); MaybeOnStaleLoader(); return; } #if defined(TOOLKIT_VIEWS) // For views the top level widget is always focused. If the focus change // originated in views determine the child Widget from the view that is being // focused. views::Widget* widget = views::Widget::GetWidgetForNativeView(view_gaining_focus); if (widget) { views::FocusManager* focus_manager = widget->GetFocusManager(); if (focus_manager && focus_manager->is_changing_focus() && focus_manager->GetFocusedView() && focus_manager->GetFocusedView()->GetWidget()) { view_gaining_focus = focus_manager->GetFocusedView()->GetWidget()->GetNativeView(); } } #endif gfx::NativeView tab_view = GetPreviewContents()->web_contents()->GetNativeView(); // Focus is going to the renderer. if (rwhv->GetNativeView() == view_gaining_focus || tab_view == view_gaining_focus) { // If the mouse is not down, focus is not going to the renderer. Someone // else moved focus and we shouldn't commit. if (!loader_->IsPointerDownFromActivate()) { Hide(); MaybeOnStaleLoader(); } return; } // Walk up the view hierarchy. If the view gaining focus is a subview of the // WebContents view (such as a windowed plugin or http auth dialog), we want // to keep the preview contents. Otherwise, focus has gone somewhere else, // such as the JS inspector, and we want to cancel the preview. gfx::NativeView view_gaining_focus_ancestor = view_gaining_focus; while (view_gaining_focus_ancestor && view_gaining_focus_ancestor != tab_view) { view_gaining_focus_ancestor = platform_util::GetParent(view_gaining_focus_ancestor); } if (view_gaining_focus_ancestor) { CommitCurrentPreview(INSTANT_COMMIT_FOCUS_LOST); return; } Hide(); MaybeOnStaleLoader(); #endif } void InstantController::OnAutocompleteGotFocus() { is_omnibox_focused_ = true; if (GetPreviewContents()) loader_->OnAutocompleteGotFocus(); CreateDefaultLoader(); } void InstantController::OnActiveTabModeChanged(bool active_tab_is_ntp) { active_tab_is_ntp_ = active_tab_is_ntp; if (GetPreviewContents()) loader_->OnActiveTabModeChanged(active_tab_is_ntp_); } bool InstantController::commit_on_pointer_release() const { return GetPreviewContents() && loader_->IsPointerDownFromActivate(); } void InstantController::SetSuggestions( InstantLoader* loader, const std::vector<InstantSuggestion>& suggestions) { if (loader_ != loader || IsOutOfDate()) return; loader_processed_last_update_ = true; InstantSuggestion suggestion; if (!suggestions.empty()) suggestion = suggestions[0]; if (suggestion.behavior == INSTANT_COMPLETE_REPLACE) { // We don't get an Update() when changing the omnibox due to a REPLACE // suggestion (so that we don't inadvertently cause the preview to change // what it's showing, as the user arrows up/down through the page-provided // suggestions). So, update these state variables here. last_full_text_ = suggestion.text; last_user_text_.clear(); last_verbatim_ = true; last_suggestion_ = InstantSuggestion(); last_match_was_search_ = suggestion.type == INSTANT_SUGGESTION_SEARCH; browser_->SetInstantSuggestion(suggestion); } else { // Suggestion text should be a full URL for URL suggestions, or the // completion of a query for query suggestions. if (suggestion.type == INSTANT_SUGGESTION_URL) { if (!StartsWith(suggestion.text, ASCIIToUTF16("http://"), false) && !StartsWith(suggestion.text, ASCIIToUTF16("https://"), false)) suggestion.text = ASCIIToUTF16("http://") + suggestion.text; } else if (StartsWith(suggestion.text, last_user_text_, true)) { // The user typed an exact prefix of the suggestion. suggestion.text.erase(0, last_user_text_.size()); } else if (!NormalizeAndStripPrefix(&suggestion.text, last_user_text_)) { // Unicode normalize and case-fold the user text and suggestion. If the // user text is a prefix, suggest the normalized, case-folded completion; // for instance, if the user types 'i' and the suggestion is 'INSTANT', // suggestion 'nstant'. Otherwise, the user text really isn't a prefix, // so suggest nothing. suggestion.text.clear(); } last_suggestion_ = suggestion; // Set the suggested text if the suggestion behavior is // INSTANT_COMPLETE_NEVER irrespective of verbatim because in this case // the suggested text does not get committed if the user presses enter. if (suggestion.behavior == INSTANT_COMPLETE_NEVER || !last_verbatim_) browser_->SetInstantSuggestion(suggestion); } Show(100, INSTANT_SIZE_PERCENT); } void InstantController::CommitInstantLoader(InstantLoader* loader) { if (loader_ != loader || !model_.is_ready() || IsOutOfDate()) return; CommitCurrentPreview(INSTANT_COMMIT_FOCUS_LOST); } void InstantController::ShowInstantPreview(InstantLoader* loader, InstantShownReason reason, int height, InstantSizeUnits units) { // Show even if IsOutOfDate() on the extended mode NTP to enable a search // provider call SetInstantPreviewHeight() to show a custom logo, e.g. a // Google doodle, before the user interacts with the page. if (loader_ != loader || mode_ != EXTENDED || (IsOutOfDate() && !active_tab_is_ntp_)) return; Show(height, units); } void InstantController::InstantLoaderPreviewLoaded(InstantLoader* loader) { AddPreviewUsageForHistogram(mode_, PREVIEW_LOADED); } void InstantController::InstantSupportDetermined(InstantLoader* loader, bool supports_instant) { if (supports_instant) { blacklisted_urls_.erase(loader->instant_url()); } else { ++blacklisted_urls_[loader->instant_url()]; if (loader_ == loader) DeleteLoader(); } content::NotificationService::current()->Notify( chrome::NOTIFICATION_INSTANT_SUPPORT_DETERMINED, content::Source<InstantController>(this), content::NotificationService::NoDetails()); } void InstantController::SwappedTabContents(InstantLoader* loader) { if (loader_ == loader) model_.SetPreviewContents(GetPreviewContents()); } void InstantController::InstantLoaderContentsFocused(InstantLoader* loader) { #if defined(USE_AURA) // On aura the omnibox only receives a focus lost if we initiate the focus // change. This does that. if (model_.is_ready() && !IsOutOfDate()) browser_->InstantPreviewFocused(); #endif } InstantController::InstantController(chrome::BrowserInstantController* browser, Mode mode) : browser_(browser), model_(ALLOW_THIS_IN_INITIALIZER_LIST(this)), mode_(mode), last_active_tab_(NULL), last_verbatim_(false), last_transition_type_(content::PAGE_TRANSITION_LINK), last_match_was_search_(false), loader_processed_last_update_(false), is_omnibox_focused_(false), active_tab_is_ntp_(false) { } void InstantController::ResetLoader(const std::string& instant_url, const TabContents* active_tab) { if (GetPreviewContents() && loader_->instant_url() != instant_url) DeleteLoader(); if (!GetPreviewContents()) { loader_.reset(new InstantLoader(this, instant_url, active_tab)); loader_->Init(); // Ensure the searchbox API has the correct focus state and context. if (is_omnibox_focused_) loader_->OnAutocompleteGotFocus(); else loader_->OnAutocompleteLostFocus(); loader_->OnActiveTabModeChanged(active_tab_is_ntp_); AddPreviewUsageForHistogram(mode_, PREVIEW_CREATED); // Reset the loader timer. stale_loader_timer_.Stop(); stale_loader_timer_.Start( FROM_HERE, base::TimeDelta::FromMilliseconds(kStaleLoaderTimeoutMS), this, &InstantController::OnStaleLoader); } } bool InstantController::CreateDefaultLoader() { const TabContents* active_tab = browser_->GetActiveTabContents(); // We could get here with no active tab if the Browser is closing. if (!active_tab) return false; const TemplateURL* template_url = TemplateURLServiceFactory::GetForProfile(active_tab->profile())-> GetDefaultSearchProvider(); const GURL& tab_url = active_tab->web_contents()->GetURL(); std::string instant_url; if (!GetInstantURL(template_url, tab_url, &instant_url)) return false; ResetLoader(instant_url, active_tab); return true; } void InstantController::OnStaleLoader() { // If the loader is showing, do not delete it. It will get deleted the next // time the autocomplete loses focus. if (model_.is_ready()) return; DeleteLoader(); CreateDefaultLoader(); } void InstantController::MaybeOnStaleLoader() { if (!stale_loader_timer_.IsRunning()) OnStaleLoader(); } void InstantController::DeleteLoader() { last_active_tab_ = NULL; last_full_text_.clear(); last_user_text_.clear(); last_verbatim_ = false; last_suggestion_ = InstantSuggestion(); last_match_was_search_ = false; loader_processed_last_update_ = false; last_omnibox_bounds_ = gfx::Rect(); url_for_history_ = GURL(); if (GetPreviewContents()) { AddPreviewUsageForHistogram(mode_, PREVIEW_DELETED); model_.SetDisplayState(InstantModel::NOT_READY, 0, INSTANT_SIZE_PERCENT); } // Schedule the deletion for later, since we may have gotten here from a call // within a |loader_| method (i.e., it's still on the stack). If we deleted // the loader immediately, things would still be fine so long as the caller // doesn't access any instance members after we return, but why rely on that? MessageLoop::current()->DeleteSoon(FROM_HERE, loader_.release()); } void InstantController::Show(int height, InstantSizeUnits units) { // Call even if showing in case height changed. if (!model_.is_ready()) AddPreviewUsageForHistogram(mode_, PREVIEW_SHOWED); model_.SetDisplayState(InstantModel::QUERY_RESULTS, height, units); } void InstantController::SendBoundsToPage() { if (last_omnibox_bounds_ == omnibox_bounds_ || IsOutOfDate() || !GetPreviewContents() || loader_->IsPointerDownFromActivate()) return; last_omnibox_bounds_ = omnibox_bounds_; gfx::Rect preview_bounds = browser_->GetInstantBounds(); gfx::Rect intersection = gfx::IntersectRects(omnibox_bounds_, preview_bounds); // Translate into window coordinates. if (!intersection.IsEmpty()) { intersection.Offset(-preview_bounds.origin().x(), -preview_bounds.origin().y()); } // In the current Chrome UI, these must always be true so they sanity check // the above operations. In a future UI, these may be removed or adjusted. // There is no point in sanity-checking |intersection.y()| because the omnibox // can be placed anywhere vertically relative to the preview (for example, in // Mac fullscreen mode, the omnibox is fully enclosed by the preview bounds). DCHECK_LE(0, intersection.x()); DCHECK_LE(0, intersection.width()); DCHECK_LE(0, intersection.height()); loader_->SetOmniboxBounds(intersection); } bool InstantController::GetInstantURL(const TemplateURL* template_url, const GURL& tab_url, std::string* instant_url) const { CommandLine* command_line = CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kInstantURL)) { *instant_url = command_line->GetSwitchValueASCII(switches::kInstantURL); return template_url != NULL; } if (!template_url) return false; const TemplateURLRef& instant_url_ref = template_url->instant_url_ref(); if (!instant_url_ref.IsValid()) return false; // Even if the URL template doesn't have search terms, it may have other // components (such as {google:baseURL}) that need to be replaced. *instant_url = instant_url_ref.ReplaceSearchTerms( TemplateURLRef::SearchTermsArgs(string16())); // Extended mode should always use HTTPS. TODO(sreeram): This section can be // removed if TemplateURLs supported "https://{google:host}/..." instead of // only supporting "{google:baseURL}...". if (mode_ == EXTENDED) { GURL url_obj(*instant_url); if (!url_obj.is_valid()) return false; if (!url_obj.SchemeIsSecure()) { const std::string new_scheme = "https"; const std::string new_port = "443"; GURL::Replacements secure; secure.SetSchemeStr(new_scheme); secure.SetPortStr(new_port); url_obj = url_obj.ReplaceComponents(secure); if (!url_obj.is_valid()) return false; *instant_url = url_obj.spec(); } } std::map<std::string, int>::const_iterator iter = blacklisted_urls_.find(*instant_url); if (iter != blacklisted_urls_.end() && iter->second > kMaxInstantSupportFailures) return false; return true; } bool InstantController::IsOutOfDate() const { return !last_active_tab_ || last_active_tab_ != browser_->GetActiveTabContents(); }
37.100606
80
0.711154
junmin-zhu
cd778fa773c1ed4aa674daa897d493533115fcdb
23,425
cpp
C++
aidl.cpp
00liujj/aidl-cpp
24ddb77dc7f38e12627f1c7cdaed34d66cd2baf4
[ "Apache-2.0" ]
6
2017-06-30T05:36:52.000Z
2022-03-24T01:08:46.000Z
aidl.cpp
00liujj/aidl-cpp
24ddb77dc7f38e12627f1c7cdaed34d66cd2baf4
[ "Apache-2.0" ]
3
2018-06-06T07:02:22.000Z
2018-06-06T11:29:16.000Z
aidl.cpp
00liujj/aidl-cpp
24ddb77dc7f38e12627f1c7cdaed34d66cd2baf4
[ "Apache-2.0" ]
20
2017-06-15T01:37:23.000Z
2022-03-25T23:13:06.000Z
/* * Copyright (C) 2015, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "aidl.h" #include <fcntl.h> #include <iostream> #include <map> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/param.h> #include <sys/stat.h> #include <unistd.h> #ifdef _WIN32 #include <io.h> #include <direct.h> #include <sys/stat.h> #endif #include <android-base/strings.h> #include "aidl_language.h" #include "generate_cpp.h" #include "generate_java.h" #include "import_resolver.h" #include "logging.h" #include "options.h" #include "os.h" #include "type_cpp.h" #include "type_java.h" #include "type_namespace.h" #ifndef O_BINARY # define O_BINARY 0 #endif using android::base::Join; using android::base::Split; using std::cerr; using std::endl; using std::map; using std::set; using std::string; using std::unique_ptr; using std::vector; namespace android { namespace aidl { namespace { // The following are gotten as the offset from the allowable id's between // android.os.IBinder.FIRST_CALL_TRANSACTION=1 and // android.os.IBinder.LAST_CALL_TRANSACTION=16777215 const int kMinUserSetMethodId = 0; const int kMaxUserSetMethodId = 16777214; bool check_filename(const std::string& filename, const std::string& package, const std::string& name, unsigned line) { const char* p; string expected; string fn; size_t len; bool valid = false; if (!IoDelegate::GetAbsolutePath(filename, &fn)) { return false; } if (!package.empty()) { expected = package; expected += '.'; } len = expected.length(); for (size_t i=0; i<len; i++) { if (expected[i] == '.') { expected[i] = OS_PATH_SEPARATOR; } } expected.append(name, 0, name.find('.')); expected += ".aidl"; len = fn.length(); valid = (len >= expected.length()); if (valid) { p = fn.c_str() + (len - expected.length()); #ifdef _WIN32 if (OS_PATH_SEPARATOR != '/') { // Input filename under cygwin most likely has / separators // whereas the expected string uses \\ separators. Adjust // them accordingly. for (char *c = const_cast<char *>(p); *c; ++c) { if (*c == '/') *c = OS_PATH_SEPARATOR; } } #endif // aidl assumes case-insensitivity on Mac Os and Windows. #if defined(__linux__) valid = (expected == p); #else valid = !strcasecmp(expected.c_str(), p); #endif } if (!valid) { fprintf(stderr, "%s:%d interface %s should be declared in a file" " called %s.\n", filename.c_str(), line, name.c_str(), expected.c_str()); } return valid; } bool check_filenames(const std::string& filename, const AidlDocument* doc) { if (!doc) return true; const AidlInterface* interface = doc->GetInterface(); if (interface) { return check_filename(filename, interface->GetPackage(), interface->GetName(), interface->GetLine()); } bool success = true; for (const auto& item : doc->GetParcelables()) { success &= check_filename(filename, item->GetPackage(), item->GetName(), item->GetLine()); } return success; } bool gather_types(const std::string& filename, const AidlDocument* doc, TypeNamespace* types) { bool success = true; const AidlInterface* interface = doc->GetInterface(); if (interface) return types->AddBinderType(*interface, filename); for (const auto& item : doc->GetParcelables()) { success &= types->AddParcelableType(*item, filename); } return success; } int check_types(const string& filename, const AidlInterface* c, TypeNamespace* types) { int err = 0; if (c->IsUtf8() && c->IsUtf8InCpp()) { cerr << filename << ":" << c->GetLine() << "Interface cannot be marked as both @utf8 and @utf8InCpp"; err = 1; } // Has to be a pointer due to deleting copy constructor. No idea why. map<string, const AidlMethod*> method_names; for (const auto& m : c->GetMethods()) { bool oneway = m->IsOneway() || c->IsOneway(); if (!types->MaybeAddContainerType(m->GetType())) { err = 1; // return type is invalid } const ValidatableType* return_type = types->GetReturnType(m->GetType(), filename, *c); if (!return_type) { err = 1; } m->GetMutableType()->SetLanguageType(return_type); if (oneway && m->GetType().GetName() != "void") { cerr << filename << ":" << m->GetLine() << " oneway method '" << m->GetName() << "' cannot return a value" << endl; err = 1; } int index = 1; for (const auto& arg : m->GetArguments()) { if (!types->MaybeAddContainerType(arg->GetType())) { err = 1; } const ValidatableType* arg_type = types->GetArgType(*arg, index, filename, *c); if (!arg_type) { err = 1; } arg->GetMutableType()->SetLanguageType(arg_type); if (oneway && arg->IsOut()) { cerr << filename << ":" << m->GetLine() << " oneway method '" << m->GetName() << "' cannot have out parameters" << endl; err = 1; } } auto it = method_names.find(m->GetName()); // prevent duplicate methods if (it == method_names.end()) { method_names[m->GetName()] = m.get(); } else { cerr << filename << ":" << m->GetLine() << " attempt to redefine method " << m->GetName() << "," << endl << filename << ":" << it->second->GetLine() << " previously defined here." << endl; err = 1; } } return err; } void write_common_dep_file(const string& output_file, const vector<string>& aidl_sources, CodeWriter* writer) { // Encode that the output file depends on aidl input files. writer->Write("%s : \\\n", output_file.c_str()); writer->Write(" %s", Join(aidl_sources, " \\\n ").c_str()); writer->Write("\n\n"); // Output "<input_aidl_file>: " so make won't fail if the input .aidl file // has been deleted, moved or renamed in incremental build. for (const auto& src : aidl_sources) { writer->Write("%s :\n", src.c_str()); } } bool write_java_dep_file(const JavaOptions& options, const vector<unique_ptr<AidlImport>>& imports, const IoDelegate& io_delegate, const string& output_file_name) { string dep_file_name = options.DependencyFilePath(); if (dep_file_name.empty()) { return true; // nothing to do } CodeWriterPtr writer = io_delegate.GetCodeWriter(dep_file_name); if (!writer) { LOG(ERROR) << "Could not open dependency file: " << dep_file_name; return false; } vector<string> source_aidl = {options.input_file_name_}; for (const auto& import : imports) { if (!import->GetFilename().empty()) { source_aidl.push_back(import->GetFilename()); } } write_common_dep_file(output_file_name, source_aidl, writer.get()); return true; } bool write_cpp_dep_file(const CppOptions& options, const AidlInterface& interface, const vector<unique_ptr<AidlImport>>& imports, const IoDelegate& io_delegate) { using ::android::aidl::cpp::HeaderFile; using ::android::aidl::cpp::ClassNames; string dep_file_name = options.DependencyFilePath(); if (dep_file_name.empty()) { return true; // nothing to do } CodeWriterPtr writer = io_delegate.GetCodeWriter(dep_file_name); if (!writer) { LOG(ERROR) << "Could not open dependency file: " << dep_file_name; return false; } vector<string> source_aidl = {options.InputFileName()}; for (const auto& import : imports) { if (!import->GetFilename().empty()) { source_aidl.push_back(import->GetFilename()); } } vector<string> headers; for (ClassNames c : {ClassNames::CLIENT, ClassNames::SERVER, ClassNames::INTERFACE}) { headers.push_back(options.OutputHeaderDir() + '/' + HeaderFile(interface, c, false /* use_os_sep */)); } write_common_dep_file(options.OutputCppFilePath(), source_aidl, writer.get()); writer->Write("\n"); // Generated headers also depend on the source aidl files. writer->Write("%s : \\\n %s\n", Join(headers, " \\\n ").c_str(), Join(source_aidl, " \\\n ").c_str()); return true; } string generate_outputFileName(const JavaOptions& options, const AidlInterface& interface) { const string& name = interface.GetName(); string package = interface.GetPackage(); string result; // create the path to the destination folder based on the // interface package name result = options.output_base_folder_; result += OS_PATH_SEPARATOR; string packageStr = package; size_t len = packageStr.length(); for (size_t i=0; i<len; i++) { if (packageStr[i] == '.') { packageStr[i] = OS_PATH_SEPARATOR; } } result += packageStr; // add the filename by replacing the .aidl extension to .java result += OS_PATH_SEPARATOR; result.append(name, 0, name.find('.')); result += ".java"; return result; } int check_and_assign_method_ids(const char * filename, const std::vector<std::unique_ptr<AidlMethod>>& items) { // Check whether there are any methods with manually assigned id's and any that are not. // Either all method id's must be manually assigned or all of them must not. // Also, check for duplicates of user set id's and that the id's are within the proper bounds. set<int> usedIds; bool hasUnassignedIds = false; bool hasAssignedIds = false; for (const auto& item : items) { if (item->HasId()) { hasAssignedIds = true; // Ensure that the user set id is not duplicated. if (usedIds.find(item->GetId()) != usedIds.end()) { // We found a duplicate id, so throw an error. fprintf(stderr, "%s:%d Found duplicate method id (%d) for method: %s\n", filename, item->GetLine(), item->GetId(), item->GetName().c_str()); return 1; } // Ensure that the user set id is within the appropriate limits if (item->GetId() < kMinUserSetMethodId || item->GetId() > kMaxUserSetMethodId) { fprintf(stderr, "%s:%d Found out of bounds id (%d) for method: %s\n", filename, item->GetLine(), item->GetId(), item->GetName().c_str()); fprintf(stderr, " Value for id must be between %d and %d inclusive.\n", kMinUserSetMethodId, kMaxUserSetMethodId); return 1; } usedIds.insert(item->GetId()); } else { hasUnassignedIds = true; } if (hasAssignedIds && hasUnassignedIds) { fprintf(stderr, "%s: You must either assign id's to all methods or to none of them.\n", filename); return 1; } } // In the case that all methods have unassigned id's, set a unique id for them. if (hasUnassignedIds) { int newId = 0; for (const auto& item : items) { item->SetId(newId++); } } // success return 0; } bool validate_constants(const AidlInterface& interface) { bool success = true; set<string> names; for (const std::unique_ptr<AidlIntConstant>& int_constant : interface.GetIntConstants()) { if (names.count(int_constant->GetName()) > 0) { LOG(ERROR) << "Found duplicate constant name '" << int_constant->GetName() << "'"; success = false; } names.insert(int_constant->GetName()); // We've logged an error message for this on object construction. success = success && int_constant->IsValid(); } for (const std::unique_ptr<AidlStringConstant>& string_constant : interface.GetStringConstants()) { if (names.count(string_constant->GetName()) > 0) { LOG(ERROR) << "Found duplicate constant name '" << string_constant->GetName() << "'"; success = false; } names.insert(string_constant->GetName()); // We've logged an error message for this on object construction. success = success && string_constant->IsValid(); } return success; } // TODO: Remove this in favor of using the YACC parser b/25479378 bool ParsePreprocessedLine(const string& line, string* decl, vector<string>* package, string* class_name) { // erase all trailing whitespace and semicolons const size_t end = line.find_last_not_of(" ;\t"); if (end == string::npos) { return false; } if (line.rfind(';', end) != string::npos) { return false; } decl->clear(); string type; vector<string> pieces = Split(line.substr(0, end + 1), " \t"); for (const string& piece : pieces) { if (piece.empty()) { continue; } if (decl->empty()) { *decl = std::move(piece); } else if (type.empty()) { type = std::move(piece); } else { return false; } } // Note that this logic is absolutely wrong. Given a parcelable // org.some.Foo.Bar, the class name is Foo.Bar, but this code will claim that // the class is just Bar. However, this was the way it was done in the past. // // See b/17415692 size_t dot_pos = type.rfind('.'); if (dot_pos != string::npos) { *class_name = type.substr(dot_pos + 1); *package = Split(type.substr(0, dot_pos), "."); } else { *class_name = type; package->clear(); } return true; } } // namespace namespace internals { bool parse_preprocessed_file(const IoDelegate& io_delegate, const string& filename, TypeNamespace* types) { bool success = true; unique_ptr<LineReader> line_reader = io_delegate.GetLineReader(filename); if (!line_reader) { LOG(ERROR) << "cannot open preprocessed file: " << filename; success = false; return success; } string line; unsigned lineno = 1; for ( ; line_reader->ReadLine(&line); ++lineno) { if (line.empty() || line.compare(0, 2, "//") == 0) { // skip comments and empty lines continue; } string decl; vector<string> package; string class_name; if (!ParsePreprocessedLine(line, &decl, &package, &class_name)) { success = false; break; } if (decl == "parcelable") { AidlParcelable doc(new AidlQualifiedName(class_name, ""), lineno, package); types->AddParcelableType(doc, filename); } else if (decl == "interface") { auto temp = new std::vector<std::unique_ptr<AidlMember>>(); AidlInterface doc(class_name, lineno, "", false, temp, package); types->AddBinderType(doc, filename); } else { success = false; break; } } if (!success) { LOG(ERROR) << filename << ':' << lineno << " malformed preprocessed file line: '" << line << "'"; } return success; } AidlError load_and_validate_aidl( const std::vector<std::string>& preprocessed_files, const std::vector<std::string>& import_paths, const std::string& input_file_name, const IoDelegate& io_delegate, TypeNamespace* types, std::unique_ptr<AidlInterface>* returned_interface, std::vector<std::unique_ptr<AidlImport>>* returned_imports) { AidlError err = AidlError::OK; std::map<AidlImport*,std::unique_ptr<AidlDocument>> docs; // import the preprocessed file for (const string& s : preprocessed_files) { if (!parse_preprocessed_file(io_delegate, s, types)) { err = AidlError::BAD_PRE_PROCESSED_FILE; } } if (err != AidlError::OK) { return err; } // parse the input file Parser p{io_delegate}; if (!p.ParseFile(input_file_name)) { return AidlError::PARSE_ERROR; } AidlDocument* parsed_doc = p.GetDocument(); unique_ptr<AidlInterface> interface(parsed_doc->ReleaseInterface()); if (!interface) { LOG(ERROR) << "refusing to generate code from aidl file defining " "parcelable"; return AidlError::FOUND_PARCELABLE; } if (!check_filename(input_file_name.c_str(), interface->GetPackage(), interface->GetName(), interface->GetLine()) || !types->IsValidPackage(interface->GetPackage())) { LOG(ERROR) << "Invalid package declaration '" << interface->GetPackage() << "'"; return AidlError::BAD_PACKAGE; } // parse the imports of the input file ImportResolver import_resolver{io_delegate, import_paths}; for (auto& import : p.GetImports()) { if (types->HasImportType(*import)) { // There are places in the Android tree where an import doesn't resolve, // but we'll pick the type up through the preprocessed types. // This seems like an error, but legacy support demands we support it... continue; } string import_path = import_resolver.FindImportFile(import->GetNeededClass()); if (import_path.empty()) { cerr << import->GetFileFrom() << ":" << import->GetLine() << ": couldn't find import for class " << import->GetNeededClass() << endl; err = AidlError::BAD_IMPORT; continue; } import->SetFilename(import_path); Parser p{io_delegate}; if (!p.ParseFile(import->GetFilename())) { cerr << "error while parsing import for class " << import->GetNeededClass() << endl; err = AidlError::BAD_IMPORT; continue; } std::unique_ptr<AidlDocument> document(p.ReleaseDocument()); if (!check_filenames(import->GetFilename(), document.get())) err = AidlError::BAD_IMPORT; docs[import.get()] = std::move(document); } if (err != AidlError::OK) { return err; } // gather the types that have been declared if (!types->AddBinderType(*interface.get(), input_file_name)) { err = AidlError::BAD_TYPE; } interface->SetLanguageType(types->GetInterfaceType(*interface)); for (const auto& import : p.GetImports()) { // If we skipped an unresolved import above (see comment there) we'll have // an empty bucket here. const auto import_itr = docs.find(import.get()); if (import_itr == docs.cend()) { continue; } if (!gather_types(import->GetFilename(), import_itr->second.get(), types)) { err = AidlError::BAD_TYPE; } } // check the referenced types in parsed_doc to make sure we've imported them if (check_types(input_file_name, interface.get(), types) != 0) { err = AidlError::BAD_TYPE; } if (err != AidlError::OK) { return err; } // assign method ids and validate. if (check_and_assign_method_ids(input_file_name.c_str(), interface->GetMethods()) != 0) { return AidlError::BAD_METHOD_ID; } if (!validate_constants(*interface)) { return AidlError::BAD_CONSTANTS; } if (returned_interface) *returned_interface = std::move(interface); if (returned_imports) p.ReleaseImports(returned_imports); return AidlError::OK; } } // namespace internals int compile_aidl_to_cpp(const CppOptions& options, const IoDelegate& io_delegate) { unique_ptr<AidlInterface> interface; std::vector<std::unique_ptr<AidlImport>> imports; unique_ptr<cpp::TypeNamespace> types(new cpp::TypeNamespace()); types->Init(); AidlError err = internals::load_and_validate_aidl( std::vector<std::string>{}, // no preprocessed files options.ImportPaths(), options.InputFileName(), io_delegate, types.get(), &interface, &imports); if (err != AidlError::OK) { return 1; } if (!write_cpp_dep_file(options, *interface, imports, io_delegate)) { return 1; } return (cpp::GenerateCpp(options, *types, *interface, io_delegate)) ? 0 : 1; } int compile_aidl_to_java(const JavaOptions& options, const IoDelegate& io_delegate) { unique_ptr<AidlInterface> interface; std::vector<std::unique_ptr<AidlImport>> imports; unique_ptr<java::JavaTypeNamespace> types(new java::JavaTypeNamespace()); types->Init(); AidlError aidl_err = internals::load_and_validate_aidl( options.preprocessed_files_, options.import_paths_, options.input_file_name_, io_delegate, types.get(), &interface, &imports); if (aidl_err == AidlError::FOUND_PARCELABLE && !options.fail_on_parcelable_) { // We aborted code generation because this file contains parcelables. // However, we were not told to complain if we find parcelables. // Just generate a dep file and exit quietly. The dep file is for a legacy // use case by the SDK. write_java_dep_file(options, imports, io_delegate, ""); return 0; } if (aidl_err != AidlError::OK) { return 1; } string output_file_name = options.output_file_name_; // if needed, generate the output file name from the base folder if (output_file_name.empty() && !options.output_base_folder_.empty()) { output_file_name = generate_outputFileName(options, *interface); } // make sure the folders of the output file all exists if (!io_delegate.CreatePathForFile(output_file_name)) { return 1; } if (!write_java_dep_file(options, imports, io_delegate, output_file_name)) { return 1; } return generate_java(output_file_name, options.input_file_name_.c_str(), interface.get(), types.get(), io_delegate); } bool preprocess_aidl(const JavaOptions& options, const IoDelegate& io_delegate) { unique_ptr<CodeWriter> writer = io_delegate.GetCodeWriter(options.output_file_name_); for (const auto& file : options.files_to_preprocess_) { Parser p{io_delegate}; if (!p.ParseFile(file)) return false; AidlDocument* doc = p.GetDocument(); string line; const AidlInterface* interface = doc->GetInterface(); if (interface != nullptr && !writer->Write("interface %s;\n", interface->GetCanonicalName().c_str())) { return false; } for (const auto& parcelable : doc->GetParcelables()) { if (!writer->Write("parcelable %s;\n", parcelable->GetCanonicalName().c_str())) { return false; } } } return writer->Close(); } } // namespace android } // namespace aidl
30.343264
98
0.613917
00liujj
cd77d64ff58bcd54cc6fd4ece1ce31e8ec2b701b
2,741
hpp
C++
libraries/boost/include/boost/mp11/set.hpp
cucubao/eosio.cdt
4985359a30da1f883418b7133593f835927b8046
[ "MIT" ]
918
2016-12-22T02:53:08.000Z
2022-03-22T06:21:35.000Z
libraries/boost/include/boost/mp11/set.hpp
cucubao/eosio.cdt
4985359a30da1f883418b7133593f835927b8046
[ "MIT" ]
594
2018-09-06T02:03:01.000Z
2022-03-23T19:18:26.000Z
libraries/boost/include/boost/mp11/set.hpp
cucubao/eosio.cdt
4985359a30da1f883418b7133593f835927b8046
[ "MIT" ]
349
2018-09-06T05:02:09.000Z
2022-03-12T11:07:17.000Z
#ifndef BOOST_MP11_SET_HPP_INCLUDED #define BOOST_MP11_SET_HPP_INCLUDED // Copyright 2015 Peter Dimov. // // Distributed under the Boost Software License, Version 1.0. // // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt #include <boost/mp11/utility.hpp> #include <boost/mp11/detail/mp_list.hpp> #include <type_traits> namespace boost { namespace mp11 { // mp_set_contains<S, V> namespace detail { template<class S, class V> struct mp_set_contains_impl; template<template<class...> class L, class... T, class V> struct mp_set_contains_impl<L<T...>, V> { using type = mp_to_bool<std::is_base_of<mp_identity<V>, mp_inherit<mp_identity<T>...>>>; }; } // namespace detail template<class S, class V> using mp_set_contains = typename detail::mp_set_contains_impl<S, V>::type; // mp_set_push_back<S, T...> namespace detail { template<class S, class... T> struct mp_set_push_back_impl; template<template<class...> class L, class... U> struct mp_set_push_back_impl<L<U...>> { using type = L<U...>; }; template<template<class...> class L, class... U, class T1, class... T> struct mp_set_push_back_impl<L<U...>, T1, T...> { using S = mp_if<mp_set_contains<L<U...>, T1>, L<U...>, L<U..., T1>>; using type = typename mp_set_push_back_impl<S, T...>::type; }; } // namespace detail template<class S, class... T> using mp_set_push_back = typename detail::mp_set_push_back_impl<S, T...>::type; // mp_set_push_front<S, T...> namespace detail { template<class S, class... T> struct mp_set_push_front_impl; template<template<class...> class L, class... U> struct mp_set_push_front_impl<L<U...>> { using type = L<U...>; }; template<template<class...> class L, class... U, class T1> struct mp_set_push_front_impl<L<U...>, T1> { using type = mp_if<mp_set_contains<L<U...>, T1>, L<U...>, L<T1, U...>>; }; template<template<class...> class L, class... U, class T1, class... T> struct mp_set_push_front_impl<L<U...>, T1, T...> { using S = typename mp_set_push_front_impl<L<U...>, T...>::type; using type = typename mp_set_push_front_impl<S, T1>::type; }; } // namespace detail template<class S, class... T> using mp_set_push_front = typename detail::mp_set_push_front_impl<S, T...>::type; // mp_is_set<S> namespace detail { template<class S> struct mp_is_set_impl { using type = mp_false; }; template<template<class...> class L, class... T> struct mp_is_set_impl<L<T...>> { using type = mp_to_bool<std::is_same<mp_list<T...>, mp_set_push_back<mp_list<>, T...>>>; }; } // namespace detail template<class S> using mp_is_set = typename detail::mp_is_set_impl<S>::type; } // namespace mp11 } // namespace boost #endif // #ifndef BOOST_MP11_SET_HPP_INCLUDED
26.355769
119
0.690259
cucubao
cd79d8a3e59f4884b569d0550939fe09b6451429
14,287
cpp
C++
applications/structural_application/constitutive_laws/Isotropic_Damage_3D.cpp
jiaqiwang969/Kratos-test
ed082abc163e7b627f110a1ae1da465f52f48348
[ "BSD-4-Clause" ]
null
null
null
applications/structural_application/constitutive_laws/Isotropic_Damage_3D.cpp
jiaqiwang969/Kratos-test
ed082abc163e7b627f110a1ae1da465f52f48348
[ "BSD-4-Clause" ]
null
null
null
applications/structural_application/constitutive_laws/Isotropic_Damage_3D.cpp
jiaqiwang969/Kratos-test
ed082abc163e7b627f110a1ae1da465f52f48348
[ "BSD-4-Clause" ]
null
null
null
/* ============================================================================== KratosStructuralApplication A library based on: Kratos A General Purpose Software for Multi-Physics Finite Element Analysis Version 1.0 (Released on march 05, 2007). Copyright 2007 Pooyan Dadvand, Riccardo Rossi, Janosch Stascheit, Felix Nagel pooyan@cimne.upc.edu rrossi@cimne.upc.edu janosch.stascheit@rub.de nagel@sd.rub.de - CIMNE (International Center for Numerical Methods in Engineering), Gran Capita' s/n, 08034 Barcelona, Spain - Ruhr-University Bochum, Institute for Structural Mechanics, Germany 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 condition: Distribution of this code for any commercial purpose is permissible ONLY BY DIRECT ARRANGEMENT WITH THE COPYRIGHT OWNERS. 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 variablesIS", 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. ============================================================================== */ /* ********************************************************* * * Last Modified by: $Author: nelson $ * Date: $Date: 2008-09-03 \* Revision: $Revision: 1.1 $ * * ***********************************************************/ // System includes #include <iostream> // External includes #include<cmath> // Project includes #include "includes/define.h" #include "constitutive_laws/Isotropic_Damage_3D.h" #include "includes/constitutive_law.h" #include "utilities/math_utils.h" #include "custom_utilities/sd_math_utils.h" #include "custom_utilities/Tensor_utils.h" #include "includes/variables.h" #include "includes/process_info.h" #include "structural_application.h" #include "includes/properties.h" namespace Kratos { namespace Isotropic_Damage_3D_Auxiliaries { boost::numeric::ublas::bounded_matrix<double,3,3> mstemp; #pragma omp threadprivate(mstemp) boost::numeric::ublas::bounded_matrix<double,3,3> msaux; #pragma omp threadprivate(msaux) Matrix StressTensor(0,0); #pragma omp threadprivate(StressTensor) Matrix InvertedMatrix(0,0); #pragma omp threadprivate(InvertedMatrix) Vector PrincipalStress(0); #pragma omp threadprivate(PrincipalStress) Vector Aux_Vector(0); #pragma omp threadprivate(Aux_Vector) // Ver pagina 57 " Metodologia de Evaluacion de Estructuras de Hormigon Armado" Matrix C(0,0); #pragma omp threadprivate(C) Matrix D(0,0); #pragma omp threadprivate(D) Matrix V(0,0); #pragma omp threadprivate(V) Vector d_Sigma(0); #pragma omp threadprivate(d_Sigma) } using namespace Isotropic_Damage_3D_Auxiliaries; /** * TO BE TESTED!!! */ Isotropic_Damage_3D::Isotropic_Damage_3D() : ConstitutiveLaw< Node<3> >() { } /** * TO BE TESTED!!! */ Isotropic_Damage_3D::~Isotropic_Damage_3D() { } bool Isotropic_Damage_3D::Has( const Variable<double>& rThisVariable ) { return false; } bool Isotropic_Damage_3D::Has( const Variable<Vector>& rThisVariable ) { return false; } bool Isotropic_Damage_3D::Has( const Variable<Matrix>& rThisVariable ) { return false; } double Isotropic_Damage_3D::GetValue( const Variable<double>& rThisVariable ) { if( rThisVariable == DAMAGE) { return md; } else { return 0.00; //KRATOS_ERROR(std::logic_error, "double Variable case not considered", ""); } } Vector Isotropic_Damage_3D::GetValue( const Variable<Vector>& rThisVariable ) { KRATOS_ERROR(std::logic_error, "Vector Variable case not considered", ""); } Matrix Isotropic_Damage_3D::GetValue( const Variable<Matrix>& rThisVariable ) { KRATOS_ERROR(std::logic_error, "Matrix Variable case not considered", ""); } void Isotropic_Damage_3D::SetValue( const Variable<double>& rThisVariable, const double& rValue, const ProcessInfo& rCurrentProcessInfo ) { } void Isotropic_Damage_3D::SetValue( const Variable<Vector>& rThisVariable, const Vector& rValue, const ProcessInfo& rCurrentProcessInfo ) { } void Isotropic_Damage_3D::SetValue( const Variable<Matrix>& rThisVariable, const Matrix& rValue, const ProcessInfo& rCurrentProcessInfo ) { } void Isotropic_Damage_3D::Calculate(const Variable<Matrix >& rVariable, Matrix& rResult, const ProcessInfo& rCurrentProcessInfo) { } //*********************************************************************************************** //*********************************************************************************************** void Isotropic_Damage_3D::InitializeMaterial( const Properties& props, const GeometryType& geom, const Vector& ShapeFunctionsValues ) { // Nota: Estas Variables no seran necesarias almacenarlas por cada elemento. // Basta con llamarlas con sus propiedades. mFc = props[FC]; mFt = props[FT]; mEc = props[CONCRETE_YOUNG_MODULUS_C]; mEt = props[CONCRETE_YOUNG_MODULUS_T]; mNU = props[POISSON_RATIO]; mGE = props[FRACTURE_ENERGY]; ml = pow(fabs(geom.Volume()),0.333333333333333333); // longitud del elemento mr_old = mFt/sqrt(mEc); // KRATOS_WATCH(geom.Volume()); // KRATOS_WATCH(ml); } //*********************************************************************************************** //*********************************************************************************************** void Isotropic_Damage_3D::InitializeSolutionStep( const Properties& props, const GeometryType& geom, const Vector& ShapeFunctionsValues , const ProcessInfo& CurrentProcessInfo) { //KRATOS_WATCH(ml); } //*********************************************************************************************** //*********************************************************************************************** void Isotropic_Damage_3D::CalculateNoDamageElasticMatrix(Matrix& C, const double E, const double NU) { C.resize(6,6, false); //setting up material matrix double c1 = E / ((1.00+NU)*(1-2*NU)); double c2 = c1 * (1-NU); double c3 = c1 * NU; double c4 = c1 * 0.5 * (1 - 2*NU); //filling material matrix C(0,0) = c2; C(0,1) = c3; C(0,2) = c3; C(0,3) = 0.0; C(0,4) = 0.0; C(0,5) = 0.0; C(1,0) = c3; C(1,1) = c2; C(1,2) = c3; C(1,3) = 0.0; C(1,4) = 0.0; C(1,5) = 0.0; C(2,0) = c3; C(2,1) = c3; C(2,2) = c2; C(2,3) = 0.0; C(2,4) = 0.0; C(2,5) = 0.0; C(3,0) = 0.0; C(3,1) = 0.0; C(3,2) = 0.0; C(3,3) = c4; C(3,4) = 0.0; C(3,5) = 0.0; C(4,0) = 0.0; C(4,1) = 0.0; C(4,2) = 0.0; C(4,3) = 0.0; C(4,4) = c4; C(4,5) = 0.0; C(5,0) = 0.0; C(5,1) = 0.0; C(5,2) = 0.0; C(5,3) = 0.0; C(5,4) = 0.0; C(5,5) = c4; //KRATOS_WATCH(C); } //*********************************************************************************************** //*********************************************************************************************** void Isotropic_Damage_3D::CalculateConstitutiveMatrix(const Vector& StrainVector, Matrix& ConstitutiveMatrix) { //Vector StressVector; ConstitutiveMatrix.resize(6,6,false); //StressVector.resize(3, false); Isotropic_Damage_3D::CalculateNoDamageElasticMatrix(ConstitutiveMatrix,mEc,mNU); ConstitutiveMatrix = (1.00-md)*ConstitutiveMatrix; //Isotropic_Damage_3D::CalculateStressAndTangentMatrix(StressVector,StrainVector,ConstitutiveMatrix); } //*********************************************************************************************** //*********************************************************************************************** void Isotropic_Damage_3D::CalculateDamage(const Matrix& ConstitutiveMatrix, const Vector& StressVector, double& d) { double Tau = 0.00; double A = 0.00; double crit = 1.0e-9; double zero = 1.0e-9; double teta_a = 0.00; double teta_b = 0.00; double teta = 0.00; double r = 0.00; double elev = 0.00; double norma = 0.00; if (Aux_Vector.size() != 6) { StressTensor.resize(3,3,false); InvertedMatrix.resize(6,6, false); PrincipalStress.resize(3, false); Aux_Vector.resize(6, false); } double ro = mFt/sqrt(mEc); //Suponiendo el Ec=Ect double n = mFc/mFt; A = 1.00/((mGE*mEc)/(ml*mFt*mFt)-0.5); //KRATOS_WATCH(A); if (A < 0.00) { A = 0.00; std::cout<< "Warning: A is less than zero"<<std::endl; } StressTensor = MathUtils<double>::StressVectorToTensor(StressVector); SD_MathUtils<double>::InvertMatrix(ConstitutiveMatrix, InvertedMatrix); // Calculando norma de una matriz norma = SD_MathUtils<double>::normTensor(StressTensor); if(norma<1e-9) { PrincipalStress(0) = 0.00; PrincipalStress(1) = 0.00; PrincipalStress(2) = 0.00; } else { PrincipalStress = SD_MathUtils<double>::EigneValues(StressTensor,crit, zero); } // KRATOS_WATCH(PrincipalStress); teta_a = Tensor_Utils<double>::Mc_aully(PrincipalStress); teta_b = norm_1(PrincipalStress); // Condicion para no tener divison de 0/0 if (teta_a==0.00 && teta_b==0.00) teta = 1.00; else teta = teta_a/teta_b; noalias(Aux_Vector) = prod(trans(StressVector),InvertedMatrix); Tau = inner_prod(StressVector,Aux_Vector); Tau = sqrt(Tau); Tau = (teta + (1.00-teta)/n)*Tau; r = std::max(mr_old,Tau); // rold por ro elev = A*(1.00-r/ro); d = 1.00 - (ro/r)*exp(elev); if (d < 0.00) { d = fabs(d); //std::cout<<"Warning: Damage is less than zero"<<std::endl; } this-> md = d; this-> mr_new = r; } //*********************************************************************************************** //*********************************************************************************************** void Isotropic_Damage_3D::FinalizeSolutionStep( const Properties& props, const GeometryType& geom, const Vector& ShapeFunctionsValues , const ProcessInfo& CurrentProcessInfo) { mr_old = mr_new; //KRATOS_WATCH(mr_old); } //*********************************************************************************************** //*********************************************************************************************** void Isotropic_Damage_3D::CalculateNoDamageStress(const Vector& StrainVector, Vector& StressVector) { double c1 = mEc / ((1.00+mNU)*(1-2*mNU)); double c2 = c1 * (1-mNU); double c3 = c1 * mNU; double c4 = c1 * 0.5 * (1 - 2*mNU); StressVector[0] = c2*StrainVector[0] + c3 * (StrainVector[1] + StrainVector[2]) ; StressVector[1] = c2*StrainVector[1] + c3 * (StrainVector[0] + StrainVector[2]) ; StressVector[2] = c2*StrainVector[2] + c3 * (StrainVector[0] + StrainVector[1]) ; StressVector[3] = c4*StrainVector[3]; StressVector[4] = c4*StrainVector[4]; StressVector[5] = c4*StrainVector[5]; } //*********************************************************************************************** //*********************************************************************************************** void Isotropic_Damage_3D::CalculateStress( const Vector& StrainVector, Vector& StressVector) { Matrix ConstitutiveMatrix; ConstitutiveMatrix.resize(6,6, false); double d=0.00; Isotropic_Damage_3D::CalculateNoDamageStress(StrainVector, StressVector); Isotropic_Damage_3D::CalculateNoDamageElasticMatrix(ConstitutiveMatrix,mEc,mNU); Isotropic_Damage_3D::CalculateDamage(ConstitutiveMatrix, StressVector, d); StressVector = (1.00-d)*StressVector; } //*********************************************************************************************** //*********************************************************************************************** void Isotropic_Damage_3D::CalculateCauchyStresses( Vector& rCauchy_StressVector, const Matrix& rF, const Vector& rPK2_StressVector, const Vector& rGreenLagrangeStrainVector) { Matrix S = MathUtils<double>::StressVectorToTensor( rPK2_StressVector ); double J = MathUtils<double>::Det2( rF ); noalias(mstemp) = prod(rF,S); noalias(msaux) = prod(mstemp,trans(rF)); msaux *= J; if(rCauchy_StressVector.size() != 6) rCauchy_StressVector.resize(6); rCauchy_StressVector[0] = msaux(0,0); rCauchy_StressVector[1] = msaux(1,1); rCauchy_StressVector[2] = msaux(2,2); rCauchy_StressVector[3] = msaux(1,2); rCauchy_StressVector[4] = msaux(1,3); rCauchy_StressVector[5] = msaux(2,3); } //*********************************************************************************************** //*********************************************************************************************** void Isotropic_Damage_3D::CalculateStressAndTangentMatrix(Vector& StressVector, const Vector& StrainVector, Matrix& algorithmicTangent) { } }
33.071759
115
0.547981
jiaqiwang969
cd7a8303bf8d76d374813d0d463c93329f6c1104
1,306
cpp
C++
server/src/route_server/route_server.cpp
xiaominfc/TeamTalk
20084010a9804d1ff0ed7bb5924fde7041b952eb
[ "Apache-2.0" ]
65
2017-11-18T15:43:56.000Z
2022-01-30T08:07:11.000Z
server/src/route_server/route_server.cpp
xiaominfc/TeamTalk
20084010a9804d1ff0ed7bb5924fde7041b952eb
[ "Apache-2.0" ]
3
2018-09-04T14:27:45.000Z
2020-10-29T07:22:45.000Z
server/src/route_server/route_server.cpp
xiaominfc/TeamTalk
20084010a9804d1ff0ed7bb5924fde7041b952eb
[ "Apache-2.0" ]
36
2018-07-10T04:21:08.000Z
2021-11-09T07:21:10.000Z
/* * @Author: xiaominfc * @Date: 2020-09-02 17:10:06 * @Description: main run for routeserver */ #include "RouteConn.h" #include "netlib.h" #include "ConfigFileReader.h" #include "version.h" #include "EventSocket.h" int main(int argc, char* argv[]) { PRINTSERVERVERSION() signal(SIGPIPE, SIG_IGN); srand(time(NULL)); CConfigFileReader config_file("routeserver.conf"); char* listen_ip = config_file.GetConfigName("ListenIP"); char* str_listen_msg_port = config_file.GetConfigName("ListenMsgPort"); if (!listen_ip || !str_listen_msg_port) { log("config item missing, exit... "); return -1; } uint16_t listen_msg_port = atoi(str_listen_msg_port); int ret = netlib_init(); if (ret == NETLIB_ERROR) return ret; CStrExplode listen_ip_list(listen_ip, ';'); for (uint32_t i = 0; i < listen_ip_list.GetItemCnt(); i++) { //ret = netlib_listen(listen_ip_list.GetItem(i), listen_msg_port, route_serv_callback, NULL); ret = tcp_server_listen(listen_ip_list.GetItem(i), listen_msg_port,new IMConnEventDefaultFactory<CRouteConn>()); if (ret == NETLIB_ERROR) return ret; } printf("server start listen on: %s:%d\n", listen_ip, listen_msg_port); init_routeconn_timer_callback(); printf("now enter the event loop...\n"); writePid(); netlib_eventloop(); return 0; }
22.517241
114
0.715161
xiaominfc
cd7b73eef8ed24ae058e730c5dd8ef970f0fa29f
2,107
cpp
C++
SpecialNumbers.cpp
valbuenaster/hackerEarthCodes
ce95294e16327b6de12a3a5e45694140ba6e2f00
[ "MIT" ]
null
null
null
SpecialNumbers.cpp
valbuenaster/hackerEarthCodes
ce95294e16327b6de12a3a5e45694140ba6e2f00
[ "MIT" ]
null
null
null
SpecialNumbers.cpp
valbuenaster/hackerEarthCodes
ce95294e16327b6de12a3a5e45694140ba6e2f00
[ "MIT" ]
null
null
null
#include <iostream> #include <map> #include <string> #include <vector> #include <math.h> #include<bits/stdc++.h> using namespace std; char Mapa[4] = {'a','b','c','d'}; vector<int> returnQuaternary(long int value, long int n_pos) { vector<int> retVect; int target = value; int module_r = 0; int counter = 0; int ii = 0; while(ii<n_pos) { while(target!=0) { module_r = target % 4; target = target / 4; retVect.push_back(module_r); ii++; } if(retVect.size()<n_pos)retVect.push_back(0); ii++; } /* cout<<"n = "<<value<<", quad = "; while(counter < retVect.size() ) { cout<<retVect[counter]; counter++; } cout<<endl; */ return retVect; } void returnManyPos(long int value,long int *offset,long int *n_pos) { long int counter = 1; long int target = value; long int adv = pow(4,counter); long int prev_adv = 0; while(adv<target) { counter++; prev_adv = adv; adv += pow(4,counter); } *offset = prev_adv; *n_pos = counter++; } string Solve (long int k, long int np) { // Write your code here string s; int counter = 0; string Letter; vector<int> vect; vect = returnQuaternary(k, np); counter = vect.size()-1; while(counter >= 0) { Letter = Mapa[vect[counter]]; s.append(Letter); counter--; } counter = 0; while(counter < vect.size()) { Letter = Mapa[vect[counter]]; s.append(Letter); counter++; } return s; } int main() { ios::sync_with_stdio(0); cin.tie(0); int T; long int n_offset = 0; long int n_position = 0; cin >> T; for(int t_i=0; t_i<T; t_i++) { int k; cin >> k; returnManyPos(k, &n_offset,&n_position); //cout<<"n_offset "<<n_offset<<", n_pos "<<n_position <<endl; string out_; out_ = Solve(k-n_offset-1,n_position); cout << out_; cout << "\n"; } }
18.008547
69
0.517798
valbuenaster
cd7c370d5e067c713e65b3adbbf7388d2017e962
5,763
cpp
C++
src/CloudFile.cpp
VirgilSecurity/virgil-messenger-qt
cc29129705c8374580f2d7e76226544093838ca0
[ "BSD-3-Clause" ]
6
2020-04-24T06:20:18.000Z
2021-09-30T13:06:12.000Z
src/CloudFile.cpp
VirgilSecurity/virgil-messenger-qt
cc29129705c8374580f2d7e76226544093838ca0
[ "BSD-3-Clause" ]
13
2020-04-28T08:39:19.000Z
2021-04-26T08:09:13.000Z
src/CloudFile.cpp
VirgilSecurity/virgil-messenger-qt
cc29129705c8374580f2d7e76226544093838ca0
[ "BSD-3-Clause" ]
2
2020-04-16T11:57:14.000Z
2020-09-07T17:34:19.000Z
// Copyright (C) 2015-2021 Virgil Security, Inc. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // (1) Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // (3) Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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. // // Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com> #include "CloudFile.h" #include <QDir> #include "Utils.h" using namespace vm; CloudFileId CloudFile::id() const noexcept { return m_id; } void CloudFile::setId(const CloudFileId &id) { m_id = id; } CloudFileId CloudFile::parentId() const noexcept { return m_parentId; } void CloudFile::setParentId(const CloudFileId &id) { m_parentId = id; } QString CloudFile::name() const noexcept { return m_name; } void CloudFile::setName(const QString &name) { m_name = name; } bool CloudFile::isFolder() const noexcept { return m_isFolder; } void CloudFile::setIsFolder(const bool isFolder) { m_isFolder = isFolder; } QString CloudFile::type() const { return m_type; } void CloudFile::setType(const QString &type) { m_type = type; } quint64 CloudFile::size() const noexcept { return m_size; } void CloudFile::setSize(const quint64 size) { m_size = size; } QDateTime CloudFile::createdAt() const noexcept { return m_createdAt; } void CloudFile::setCreatedAt(const QDateTime &dateTime) { m_createdAt = dateTime; } QDateTime CloudFile::updatedAt() const noexcept { return m_updatedAt; } void CloudFile::setUpdatedAt(const QDateTime &dateTime) { m_updatedAt = dateTime; } UserId CloudFile::updatedBy() const noexcept { return m_updatedBy; } void CloudFile::setUpdatedBy(const UserId &userId) { m_updatedBy = userId; } QByteArray CloudFile::encryptedKey() const noexcept { return m_encryptedKey; } void CloudFile::setEncryptedKey(const QByteArray &key) { m_encryptedKey = key; } QByteArray CloudFile::publicKey() const noexcept { return m_publicKey; } void CloudFile::setPublicKey(const QByteArray &key) { m_publicKey = key; } QString CloudFile::localPath() const noexcept { return m_localPath; } void CloudFile::setLocalPath(const QString &path) { m_localPath = path; } QString CloudFile::fingerprint() const noexcept { return m_fingerprint; } void CloudFile::setFingerprint(const QString &fingerprint) { m_fingerprint = fingerprint; } CloudFsSharedGroupId CloudFile::sharedGroupId() const { return m_sharedGroupId; } void CloudFile::setSharedGroupId(const CloudFsSharedGroupId &sharedGroupId) { m_sharedGroupId = sharedGroupId; } bool CloudFile::isRoot() const { return m_isFolder && m_id == CloudFileId::root(); } bool CloudFile::isShared() const { return m_sharedGroupId.isValid(); } void CloudFile::update(const CloudFile &file, const CloudFileUpdateSource source) { if (file.id() != id()) { throw std::logic_error("Failed to update cloud file: source id is different"); } if (isFolder() != file.isFolder()) { throw std::logic_error("Failed to update cloud file: used file and folder"); } setParentId(file.parentId()); // update always if (source == CloudFileUpdateSource::ListedParent) { setName(file.name()); setCreatedAt(file.createdAt()); setUpdatedAt(file.updatedAt()); setUpdatedBy(file.updatedBy()); setLocalPath(file.localPath()); if (isFolder()) { setEncryptedKey(file.encryptedKey()); setPublicKey(file.publicKey()); setSharedGroupId(file.sharedGroupId()); } } else if (source == CloudFileUpdateSource::ListedChild) { setName(file.name()); setCreatedAt(file.createdAt()); setUpdatedAt(file.updatedAt()); setUpdatedBy(file.updatedBy()); setLocalPath(file.localPath()); if (isFolder()) { if (file.updatedAt() > updatedAt()) { setEncryptedKey(QByteArray()); setPublicKey(QByteArray()); setSharedGroupId(CloudFsSharedGroupId()); } } else { setType(file.type()); setSize(file.size()); if (file.updatedAt() > updatedAt()) { setFingerprint(QString()); } } } else if (source == CloudFileUpdateSource::Download) { if (!isFolder()) { setFingerprint(file.fingerprint()); } } }
24.112971
86
0.681069
VirgilSecurity
cd7d73f759922ffcefdf3bed814dffc7e3d9b9c1
721
cpp
C++
LeetCode/230 - Kth Smallest Element in a BST.cpp
GokulVSD/ScratchPad
53dee2293a2039186b00c7a465c7ef28e2b8e291
[ "Unlicense" ]
null
null
null
LeetCode/230 - Kth Smallest Element in a BST.cpp
GokulVSD/ScratchPad
53dee2293a2039186b00c7a465c7ef28e2b8e291
[ "Unlicense" ]
null
null
null
LeetCode/230 - Kth Smallest Element in a BST.cpp
GokulVSD/ScratchPad
53dee2293a2039186b00c7a465c7ef28e2b8e291
[ "Unlicense" ]
null
null
null
// https://leetcode.com/problems/kth-smallest-element-in-a-bst/ // Honestly, this problem should be classified as easy. class Solution { public: int kthSmallest(TreeNode* root, int k) { stack<TreeNode*> s; TreeNode* cur = root; while(cur != NULL){ s.push(cur); cur = cur->left; } while(k--){ cur = s.top(); s.pop(); if(k > 0 && cur->right != NULL){ s.push(cur->right); cur = cur->right; while(cur->left != NULL){ s.push(cur->left); cur = cur->left; } } } return cur->val; } };
25.75
63
0.424411
GokulVSD
cd80bd2dcf925d2dfd4d4bcf05fd50de26f5b5b5
1,130
hh
C++
maxutils/maxbase/include/maxbase/watchedworker.hh
blylei/MaxScale
2de10c9de12664e6d59f1ef879fd90d44b73d472
[ "BSD-3-Clause" ]
null
null
null
maxutils/maxbase/include/maxbase/watchedworker.hh
blylei/MaxScale
2de10c9de12664e6d59f1ef879fd90d44b73d472
[ "BSD-3-Clause" ]
null
null
null
maxutils/maxbase/include/maxbase/watchedworker.hh
blylei/MaxScale
2de10c9de12664e6d59f1ef879fd90d44b73d472
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2018 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2025-03-24 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ #pragma once #include <maxbase/ccdefs.hh> #include <atomic> #include <maxbase/worker.hh> #include <maxbase/watchdognotifier.hh> namespace maxbase { /** * @class WatchedWorker * * Base-class for workers that should be watched, that is, monitored * to ensure that they are processing epoll events. * * If a watched worker stops processing events it will cause the systemd * watchdog notification *not* to be generated, with the effect that the * process is killed and restarted. */ class WatchedWorker : public Worker, public WatchdogNotifier::Dependent { public: ~WatchedWorker(); protected: WatchedWorker(mxb::WatchdogNotifier* pNotifier); private: void call_epoll_tick() override final; }; }
24.042553
75
0.723894
blylei
cd815b3421431d195915dd110c2752fa87d8a2e0
25,507
cpp
C++
src/compiler.cpp
AndroidModLoader/gta3sc
07504a7334eb67cfac14e1f788331d1ba2b9343a
[ "MIT" ]
54
2016-06-22T22:26:58.000Z
2022-02-23T09:25:59.000Z
src/compiler.cpp
AndroidModLoader/gta3sc
07504a7334eb67cfac14e1f788331d1ba2b9343a
[ "MIT" ]
112
2016-06-21T22:52:17.000Z
2022-02-08T14:15:13.000Z
src/compiler.cpp
thelink2012/gta3sc
07504a7334eb67cfac14e1f788331d1ba2b9343a
[ "MIT" ]
9
2016-06-24T22:27:55.000Z
2021-01-11T16:37:36.000Z
#include <stdinc.h> #include "compiler.hpp" #include "symtable.hpp" #include "commands.hpp" #include "program.hpp" template<typename T, typename = std::enable_if_t<std::is_integral<T>::value>> static ArgVariant conv_int(T integral) { int32_t i = static_cast<int32_t>(integral); if(i >= std::numeric_limits<int8_t>::min() && i <= std::numeric_limits<int8_t>::max()) return int8_t(i); else if(i >= std::numeric_limits<int16_t>::min() && i <= std::numeric_limits<int16_t>::max()) return int16_t(i); else return int32_t(i); } void CompilerContext::compile() { Expects(compiled.empty()); Expects(script->top_label->code_position == nullopt); Expects(script->start_label->code_position == nullopt); program.supported_or_fatal(nocontext, commands.andor, "ANDOR"); program.supported_or_fatal(nocontext, commands.goto_, "GOTO"); program.supported_or_fatal(nocontext, commands.goto_if_false, "GOTO_IF_FALSE"); compile_label(script->top_label); compile_label(script->start_label); return compile_statements(*script->tree); } shared_ptr<Label> CompilerContext::make_internal_label() { this->internal_labels.emplace_back(std::make_shared<Label>(this->current_scope, this->script)); return this->internal_labels.back(); } void CompilerContext::compile_label(const SyntaxTree& label_node) { return compile_label(label_node.annotation<shared_ptr<Label>>()); } void CompilerContext::compile_label(shared_ptr<Label> label_ptr) { this->compiled.emplace_back(std::move(label_ptr)); } void CompilerContext::compile_command(const Command& command, ArgList args, bool not_flag) { if(command.extension && program.opt.pedantic) program.pedantic(this->script, "use of command {} which is a language extension [-pedantic]", command.name); if(command.has_optional()) { assert(args.size() == 0 || !is<EOAL>(args.back())); args.emplace_back(EOAL{}); } this->compiled.emplace_back(CompiledCommand{ not_flag, command, std::move(args) }); } void CompilerContext::compile_command(const SyntaxTree& command_node, bool not_flag) { if(command_node.maybe_annotation<DummyCommandAnnotation>()) { // compile nothing } else if(auto opt_annot = command_node.maybe_annotation<const ReplacedCommandAnnotation&>()) { const Command& command = opt_annot->command; if(commands.equal(command, commands.skip_cutscene_start_internal)) { this->label_skip_cutscene_end = any_cast<shared_ptr<Label>>(opt_annot->params[0]); } compile_command(command, get_args(opt_annot->command, opt_annot->params)); } else { const Command& command = command_node.annotation<std::reference_wrapper<const Command>>(); if(commands.equal(command, commands.skip_cutscene_end) && this->label_skip_cutscene_end) { compile_label(this->label_skip_cutscene_end); this->label_skip_cutscene_end = nullptr; } compile_command(command, get_args(command, command_node), not_flag); } } void CompilerContext::compile_statements(const SyntaxTree& base) { for(auto it = base.begin(); it != base.end(); ++it) compile_statement(*it->get()); } void CompilerContext::compile_statements(const SyntaxTree& parent, size_t from_id, size_t to_id_including) { for(size_t i = from_id; i <= to_id_including; ++i) compile_statement(parent.child(i)); } void CompilerContext::compile_statement(const SyntaxTree& node, bool not_flag) { switch(node.type()) { case NodeType::Block: // group of anything, usually group of statements compile_statements(node); break; case NodeType::NOT: compile_statement(node.child(0), !not_flag); break; case NodeType::Command: compile_command(node, not_flag); break; case NodeType::MISSION_START: case NodeType::SCRIPT_START: break; case NodeType::MISSION_END: case NodeType::SCRIPT_END: compile_mission_end(node, not_flag); break; case NodeType::Greater: case NodeType::GreaterEqual: case NodeType::Lesser: case NodeType::LesserEqual: compile_condition(node, not_flag); break; case NodeType::Equal: case NodeType::Cast: compile_expr(node, not_flag); break; case NodeType::Increment: case NodeType::Decrement: compile_incdec(node, not_flag); break; case NodeType::Label: compile_label(node); break; case NodeType::Scope: compile_scope(node); break; case NodeType::IF: compile_if(node); break; case NodeType::WHILE: compile_while(node); break; case NodeType::REPEAT: compile_repeat(node); break; case NodeType::SWITCH: compile_switch(node); break; case NodeType::BREAK: compile_break(node); break; case NodeType::CONTINUE: compile_continue(node); break; case NodeType::VAR_INT: case NodeType::LVAR_INT: case NodeType::VAR_FLOAT: case NodeType::LVAR_FLOAT: case NodeType::VAR_TEXT_LABEL: case NodeType::LVAR_TEXT_LABEL: case NodeType::VAR_TEXT_LABEL16: case NodeType::LVAR_TEXT_LABEL16: break; case NodeType::CONST_INT: case NodeType::CONST_FLOAT: break; case NodeType::DUMP: compile_dump(node); break; default: Unreachable(); } } void CompilerContext::compile_dump(const SyntaxTree& node) { this->compiled.emplace_back(node.annotation<DumpAnnotation>().bytes); } void CompilerContext::compile_scope(const SyntaxTree& scope_node) { auto guard = make_scope_guard([this] { this->current_scope = nullptr; }); Expects(this->current_scope == nullptr); this->current_scope = scope_node.annotation<shared_ptr<Scope>>(); compile_statements(scope_node.child(0)); } void CompilerContext::compile_if(const SyntaxTree& if_node) { if(if_node.child_count() == 3) // [conds, case_true, else] { auto else_ptr = make_internal_label(); auto end_ptr = make_internal_label(); compile_conditions(if_node.child(0), else_ptr); compile_statements(if_node.child(1)); compile_command(*this->commands.goto_, { end_ptr }); compile_label(else_ptr); compile_statements(if_node.child(2)); compile_label(end_ptr); } else // [conds, case_true] { auto end_ptr = make_internal_label(); compile_conditions(if_node.child(0), end_ptr); compile_statements(if_node.child(1)); compile_label(end_ptr); } } void CompilerContext::compile_while(const SyntaxTree& while_node) { auto beg_ptr = make_internal_label(); auto end_ptr = make_internal_label(); loop_stack.emplace_back(LoopInfo { beg_ptr, end_ptr }); compile_label(beg_ptr); compile_conditions(while_node.child(0), end_ptr); compile_statements(while_node.child(1)); compile_command(*this->commands.goto_, { beg_ptr }); compile_label(end_ptr); loop_stack.pop_back(); } void CompilerContext::compile_repeat(const SyntaxTree& repeat_node) { auto& annotation = repeat_node.annotation<const RepeatAnnotation&>(); auto& times = repeat_node.child(0); auto& var = repeat_node.child(1); auto continue_ptr = make_internal_label(); auto break_ptr = make_internal_label(); auto loop_ptr = make_internal_label(); loop_stack.emplace_back(LoopInfo { continue_ptr, break_ptr }); compile_command(annotation.set_var_to_zero, { get_arg(var), get_arg(annotation.number_zero) }); compile_label(loop_ptr); compile_statements(repeat_node.child(2)); compile_label(continue_ptr); compile_command(annotation.add_var_with_one, { get_arg(var), get_arg(annotation.number_one) }); compile_command(annotation.is_var_geq_times, { get_arg(var), get_arg(times) }); compile_command(*this->commands.goto_if_false, { loop_ptr }); compile_label(break_ptr); loop_stack.pop_back(); } void CompilerContext::compile_switch(const SyntaxTree& switch_node) { auto continue_ptr = nullptr; auto break_ptr = make_internal_label(); loop_stack.emplace_back(LoopInfo{ continue_ptr, break_ptr }); std::vector<Case> cases; cases.reserve(1 + switch_node.annotation<const SwitchAnnotation&>().num_cases); auto& switch_body = switch_node.child(1); for(size_t i = 0; i < switch_body.child_count(); ++i) { auto& node = switch_body.child(i); switch(node.type()) { case NodeType::CASE: { auto value = node.child(0).annotation<int32_t>(); auto& isveq = node.annotation<const SwitchCaseAnnotation&>().is_var_eq_int; cases.emplace_back(value, isveq); break; } case NodeType::DEFAULT: { cases.emplace_back(nullopt, nullopt); break; } default: // statement { if(!cases.empty()) { auto& prev_case = cases.back(); if(prev_case.first_statement_id == SIZE_MAX) prev_case.first_statement_id = i; prev_case.last_statement_id = i; } break; } } } auto blank_cases_begin = cases.end(); auto blank_cases_end = cases.end(); for(auto it = cases.begin(); it != cases.end(); ++it) { if(it->is_empty()) { if(blank_cases_begin == cases.end()) { blank_cases_begin = it; blank_cases_end = std::next(it); } else { blank_cases_end = std::next(it); } } else { if(blank_cases_begin != cases.end()) { for(auto e = blank_cases_begin; e != blank_cases_end; ++e) { e->first_statement_id = it->first_statement_id; e->last_statement_id = it->last_statement_id; } blank_cases_begin = cases.end(); blank_cases_end = cases.end(); } } } auto opt_switch_start = commands.switch_start; auto opt_switch_continued = commands.switch_continued; if(opt_switch_start && opt_switch_start->supported && opt_switch_continued && opt_switch_continued->supported) { compile_switch_withop(switch_node, cases, break_ptr); } else { compile_switch_ifchain(switch_node, cases, break_ptr); } loop_stack.pop_back(); } void CompilerContext::compile_switch_withop(const SyntaxTree& swnode, std::vector<Case>& cases, shared_ptr<Label> break_ptr) { std::vector<Case*> sorted_cases; // does not contain default, unlike `cases` sorted_cases.resize(cases.size()); bool has_default = swnode.annotation<const SwitchAnnotation&>().has_default; const Case* case_default = nullptr; const Command& switch_start = this->commands.switch_start.value(); const Command& switch_continued = this->commands.switch_continued.value(); std::transform(cases.begin(), cases.end(), sorted_cases.begin(), [] (auto& c) { return std::addressof<Case>(c); }); std::sort(sorted_cases.begin(), sorted_cases.end(), [](const Case* a, const Case* b) { if(a->is_default()) return false; // default should be the last if(b->is_default()) return true; // !a->is_default() == true return *a->value < *b->value; }); if(has_default) { case_default = sorted_cases.back(); sorted_cases.pop_back(); assert(case_default->is_default()); } for(auto& c : cases) c.target = make_internal_label(); for(size_t i = 0; i < sorted_cases.size(); ) { std::vector<ArgVariant> args; args.reserve(18); const Command& switch_op = (i == 0? switch_start : switch_continued); size_t max_cases_here = (i == 0? 7 : 9); if(i == 0) { args.emplace_back(get_arg(swnode.child(0))); args.emplace_back(conv_int(sorted_cases.size())); args.emplace_back(conv_int(has_default)); args.emplace_back(has_default? case_default->target : break_ptr); } for(size_t k = 0; k < max_cases_here; ++k, ++i) { if(i < sorted_cases.size()) { args.emplace_back(conv_int(*sorted_cases[i]->value)); args.emplace_back(sorted_cases[i]->target); } else { args.emplace_back(conv_int(-1)); args.emplace_back(break_ptr); } } compile_command(switch_op, std::move(args)); } for(auto it = cases.begin(); it != cases.end(); ++it) { compile_label(it->target); if(std::next(it) == cases.end() || !std::next(it)->same_body_as(*it)) { compile_statements(swnode.child(1), it->first_statement_id, it->last_statement_id); } } compile_label(break_ptr); } void CompilerContext::compile_switch_ifchain(const SyntaxTree& swnode, std::vector<Case>& cases, shared_ptr<Label> break_ptr) { Case* default_case = nullptr; for(auto it = cases.begin(), next_it = cases.end(); it != cases.end(); it = next_it) { auto next_ptr = make_internal_label(); auto body_ptr = make_internal_label(); next_it = std::find_if(std::next(it), cases.end(), [&](const Case& c){ return !c.same_body_as(*it); }); auto num_ifs = std::accumulate(it, next_it, size_t(0), [](size_t accum, const Case& c) { return accum + (c.is_default()? 0 : 1); }); if(num_ifs > 8) program.error(swnode, "more than 8 cases with the same body not supported using if-chain"); else if(num_ifs > 1) compile_command(*commands.andor, { conv_int(21 + num_ifs - 2) }); else if(num_ifs == 0 && it->is_default()) { default_case = std::addressof(*it); continue; } for(auto k = it; k != next_it; ++k) { if(!k->is_default()) { if(k->is_var_eq_int == nullopt) program.fatal_error(nocontext, "unexpected failure at {}", __func__); compile_command(**k->is_var_eq_int, { get_arg(swnode.child(0)), conv_int(*k->value) }); } else default_case = std::addressof(*k); } if(num_ifs) compile_command(*commands.goto_if_false, { next_ptr }); compile_label(body_ptr); std::for_each(it, next_it, [&](Case& c) { c.target = body_ptr; }); compile_statements(swnode.child(1), it->first_statement_id, it->last_statement_id); compile_label(next_ptr); } if(default_case) { if(default_case->target) { compile_command(*commands.goto_, { default_case->target }); } else { default_case->target = make_internal_label(); compile_label(default_case->target); compile_statements(swnode.child(1), default_case->first_statement_id, default_case->last_statement_id); } } compile_label(break_ptr); } void CompilerContext::compile_break(const SyntaxTree& break_node) { for(auto it = loop_stack.rbegin(); it != loop_stack.rend(); ++it) { if(it->break_label) { compile_command(*commands.goto_, { it->break_label }); return; } } Unreachable(); } void CompilerContext::compile_continue(const SyntaxTree& continue_node) { for(auto it = loop_stack.rbegin(); it != loop_stack.rend(); ++it) { if(it->continue_label) { compile_command(*commands.goto_, { it->continue_label }); return; } } Unreachable(); } void CompilerContext::compile_expr(const SyntaxTree& eq_node, bool not_flag) { if(eq_node.child(1).maybe_annotation<std::reference_wrapper<const Command>>()) { // 'a = b OP c' or 'a OP= b' const SyntaxTree& op_node = eq_node.child(1); const Command& cmd_set = eq_node.annotation<std::reference_wrapper<const Command>>(); const Command& cmd_op = op_node.annotation<std::reference_wrapper<const Command>>(); auto a = get_arg(eq_node.child(0)); auto b = get_arg(op_node.child(0)); auto c = get_arg(op_node.child(1)); if(!is_same_var(a, b)) { if(!is_same_var(a, c)) { compile_command(cmd_set, { a, b }, not_flag); compile_command(cmd_op, { a, c }, not_flag); } else { // Safe. The annotate_tree step won't allow non-commutative // operations (substraction or division) to be compiled. compile_command(cmd_op, { a, b }, not_flag); } } else { compile_command(cmd_op, { a, c }, not_flag); } } else { // 'a = b' or 'a =# b' or 'a > b' (and such) bool invert = (eq_node.type() == NodeType::Lesser || eq_node.type() == NodeType::LesserEqual); auto& a_node = eq_node.child(!invert? 0 : 1); auto& b_node = eq_node.child(!invert? 1 : 0); const Command& cmd_set = eq_node.annotation<std::reference_wrapper<const Command>>(); compile_command(cmd_set, { get_arg(a_node), get_arg(b_node) }, not_flag); } } void CompilerContext::compile_incdec(const SyntaxTree& op_node, bool not_flag) { auto& annotation = op_node.annotation<const IncDecAnnotation&>(); auto& var = op_node.child(0); compile_command(annotation.op_var_with_one, { get_arg(var), get_arg(annotation.number_one) }); } void CompilerContext::compile_mission_end(const SyntaxTree& me_node, bool not_flag) { const Command& command = me_node.annotation<std::reference_wrapper<const Command>>(); return compile_command(command, {}, not_flag); } void CompilerContext::compile_condition(const SyntaxTree& node, bool not_flag) { // also see compile_conditions switch(node.type()) { case NodeType::NOT: return compile_condition(node.child(0), !not_flag); case NodeType::Command: return compile_command(node, not_flag); case NodeType::Equal: case NodeType::Greater: case NodeType::GreaterEqual: case NodeType::Lesser: case NodeType::LesserEqual: return compile_expr(node, not_flag); default: Unreachable(); } } void CompilerContext::compile_conditions(const SyntaxTree& conds_node, const shared_ptr<Label>& else_ptr) { auto compile_multi_andor = [this](const auto& conds_node, size_t op) { assert(conds_node.child_count() <= 8); compile_command(*this->commands.andor, { conv_int(op + conds_node.child_count() - 2) }); for(auto& cond : conds_node) compile_condition(*cond); }; switch(conds_node.type()) { // single condition (also see compile_condition) case NodeType::NOT: case NodeType::Command: case NodeType::Equal: case NodeType::Greater: case NodeType::GreaterEqual: case NodeType::Lesser: case NodeType::LesserEqual: if (!this->program.opt.optimize_andor) compile_command(*this->commands.andor, { conv_int(0) }); compile_condition(conds_node); break; case NodeType::AND: // 1-8 compile_multi_andor(conds_node, 1); break; case NodeType::OR: // 21-28 compile_multi_andor(conds_node, 21); break; default: Unreachable(); } compile_command(*this->commands.goto_if_false, { else_ptr }); } auto CompilerContext::get_args(const Command& command, const std::vector<any>& params) -> ArgList { ArgList args; args.reserve(params.size()); for(auto& p : params) args.emplace_back(get_arg(p)); return args; } auto CompilerContext::get_args(const Command& command, const SyntaxTree& command_node) -> ArgList { Expects(command_node.child_count() >= 1); // command_name + [args...] ArgList args; args.reserve(command_node.child_count() - 1); for(auto it = std::next(command_node.begin()); it != command_node.end(); ++it) args.emplace_back( get_arg(**it) ); return args; } ArgVariant CompilerContext::get_arg(const Commands::MatchArgument& a) { if(is<int32_t>(a)) return conv_int(get<int32_t>(a)); else if(is<float>(a)) return get<float>(a); else return get_arg(*get<const SyntaxTree*>(a)); } ArgVariant CompilerContext::get_arg(const any& param) { if(auto opt = any_cast<int32_t>(&param)) return conv_int(*opt); else if(auto opt = any_cast<float>(&param)) return *opt; else if(auto opt = any_cast<shared_ptr<Label>>(&param)) return std::move(*opt); else Unreachable(); // implement more on necessity } ArgVariant CompilerContext::get_arg(const SyntaxTree& arg_node) { switch(arg_node.type()) { case NodeType::Integer: { return conv_int(arg_node.annotation<int32_t>()); } case NodeType::Float: { return arg_node.annotation<float>(); } case NodeType::Text: { if(auto opt_int = arg_node.maybe_annotation<int32_t>()) { return conv_int(*opt_int); } else if(auto opt_flt = arg_node.maybe_annotation<float>()) { return *opt_flt; } else if(auto opt_var = arg_node.maybe_annotation<shared_ptr<Var>>()) { return CompiledVar{ std::move(*opt_var), nullopt }; } else if(auto opt_var = arg_node.maybe_annotation<const ArrayAnnotation&>()) { if(is<shared_ptr<Var>>(opt_var->index)) return CompiledVar { opt_var->base, get<shared_ptr<Var>>(opt_var->index) }; else return CompiledVar { opt_var->base, get<int32_t>(opt_var->index) }; } else if(auto opt_label = arg_node.maybe_annotation<shared_ptr<Label>>()) { auto label = std::move(*opt_label); if(!label->may_branch_from(*this->script, program)) { auto sckind_ = to_string(label->script.lock()->type); program.error(arg_node, "reference to local label outside of its {} script", sckind_); program.note(*label->script.lock(), "label belongs to this script"); } return label; } else if(auto opt_text = arg_node.maybe_annotation<const TextLabelAnnotation&>()) { // TODO FIXME this is not the correct place to put this check, but I'm too lazy atm to put in the analyzes phase. if(program.opt.warn_conflict_text_label_var && symbols.find_var(opt_text->string, this->current_scope)) program.warning(arg_node, "text label collides with some variable name"); auto type = opt_text->is_varlen? CompiledString::Type::StringVar : CompiledString::Type::TextLabel8; return CompiledString{ type, opt_text->preserve_case, opt_text->string }; } else if(auto opt_umodel = arg_node.maybe_annotation<const ModelAnnotation&>()) { assert(opt_umodel->where.expired() == false); int32_t i32 = opt_umodel->where.lock()->find_model_at(opt_umodel->id); return conv_int(i32); } else { Unreachable(); } break; } case NodeType::String: { if(auto opt_text = arg_node.maybe_annotation<const TextLabelAnnotation&>()) { auto type = opt_text->is_varlen? CompiledString::Type::StringVar : CompiledString::Type::TextLabel8; return CompiledString{ type, opt_text->preserve_case, opt_text->string }; } else if(auto opt_buffer = arg_node.maybe_annotation<const String128Annotation&>()) { return CompiledString { CompiledString::Type::String128, false, opt_buffer->string }; } else { Unreachable(); } break; } default: Unreachable(); } } bool CompilerContext::is_same_var(const ArgVariant& lhs, const ArgVariant& rhs) { if(is<CompiledVar>(lhs) && is<CompiledVar>(rhs)) { return get<CompiledVar>(lhs) == get<CompiledVar>(rhs); } return false; }
32.617647
129
0.599757
AndroidModLoader
cd81a0755febba52e79794a767cdaabda45aba10
3,894
cpp
C++
src/modules/commander/Arming/PreFlightCheck/checks/imuConsistencyCheck.cpp
sundxfansky/Firmware
0e70578052d938ea87c70837a15185b99dbb2309
[ "BSD-3-Clause" ]
10
2020-11-25T14:04:15.000Z
2022-03-02T23:46:57.000Z
src/modules/commander/Arming/PreFlightCheck/checks/imuConsistencyCheck.cpp
choudhary0parivesh/Firmware
02f4ad61ec8eb4f7906dd06b4eb1fd6abb994244
[ "BSD-3-Clause" ]
20
2017-11-30T09:49:45.000Z
2018-02-12T07:56:29.000Z
src/modules/commander/Arming/PreFlightCheck/checks/imuConsistencyCheck.cpp
choudhary0parivesh/Firmware
02f4ad61ec8eb4f7906dd06b4eb1fd6abb994244
[ "BSD-3-Clause" ]
10
2019-04-02T09:06:30.000Z
2021-06-23T15:52:33.000Z
/**************************************************************************** * * Copyright (c) 2019 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "../PreFlightCheck.hpp" #include <HealthFlags.h> #include <lib/parameters/param.h> #include <systemlib/mavlink_log.h> #include <uORB/Subscription.hpp> #include <uORB/topics/sensor_preflight.h> #include <uORB/topics/subsystem_info.h> bool PreFlightCheck::imuConsistencyCheck(orb_advert_t *mavlink_log_pub, vehicle_status_s &status, const bool report_status) { float test_limit = 1.0f; // pass limit re-used for each test // Get sensor_preflight data if available and exit with a fail recorded if not uORB::SubscriptionData<sensor_preflight_s> sensors_sub{ORB_ID(sensor_preflight)}; sensors_sub.update(); const sensor_preflight_s &sensors = sensors_sub.get(); // Use the difference between IMU's to detect a bad calibration. // If a single IMU is fitted, the value being checked will be zero so this check will always pass. param_get(param_find("COM_ARM_IMU_ACC"), &test_limit); if (sensors.accel_inconsistency_m_s_s > test_limit) { if (report_status) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: Accels inconsistent - Check Cal"); set_health_flags_healthy(subsystem_info_s::SUBSYSTEM_TYPE_ACC, false, status); set_health_flags_healthy(subsystem_info_s::SUBSYSTEM_TYPE_ACC2, false, status); } return false; } else if (sensors.accel_inconsistency_m_s_s > test_limit * 0.8f) { if (report_status) { mavlink_log_info(mavlink_log_pub, "Preflight Advice: Accels inconsistent - Check Cal"); } } // Fail if gyro difference greater than 5 deg/sec and notify if greater than 2.5 deg/sec param_get(param_find("COM_ARM_IMU_GYR"), &test_limit); if (sensors.gyro_inconsistency_rad_s > test_limit) { if (report_status) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: Gyros inconsistent - Check Cal"); set_health_flags_healthy(subsystem_info_s::SUBSYSTEM_TYPE_GYRO, false, status); set_health_flags_healthy(subsystem_info_s::SUBSYSTEM_TYPE_GYRO2, false, status); } return false; } else if (sensors.gyro_inconsistency_rad_s > test_limit * 0.5f) { if (report_status) { mavlink_log_info(mavlink_log_pub, "Preflight Advice: Gyros inconsistent - Check Cal"); } } return true; }
41.870968
99
0.736518
sundxfansky
cd81fecd4c9d9f99fcbe88efe5f5214345719f6c
47,585
cpp
C++
gdal/ogr/ogrsf_frmts/libkml/ogrlibkmlfield.cpp
chambbj/gdal
3d56aecb5b8e9890dae8f560acd099992e707d12
[ "MIT" ]
1
2015-02-16T16:51:38.000Z
2015-02-16T16:51:38.000Z
gdal/ogr/ogrsf_frmts/libkml/ogrlibkmlfield.cpp
theduckylittle/gdal
61be261cae524582ba28bceebb027cc1e967e0ab
[ "MIT" ]
null
null
null
gdal/ogr/ogrsf_frmts/libkml/ogrlibkmlfield.cpp
theduckylittle/gdal
61be261cae524582ba28bceebb027cc1e967e0ab
[ "MIT" ]
null
null
null
/****************************************************************************** * * Project: KML Translator * Purpose: Implements OGRLIBKMLDriver * Author: Brian Case, rush at winkey dot org * ****************************************************************************** * Copyright (c) 2010, Brian Case * * 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 <ogrsf_frmts.h> #include <ogr_feature.h> #include "ogr_p.h" #include <kml/dom.h> #include <iostream> using kmldom::ExtendedDataPtr; using kmldom::SchemaPtr; using kmldom::SchemaDataPtr; using kmldom::SimpleDataPtr; using kmldom::DataPtr; using kmldom::TimeStampPtr; using kmldom::TimeSpanPtr; using kmldom::TimePrimitivePtr; using kmldom::PointPtr; using kmldom::LineStringPtr; using kmldom::PolygonPtr; using kmldom::MultiGeometryPtr; using kmldom::GeometryPtr; using kmldom::FeaturePtr; using kmldom::GroundOverlayPtr; using kmldom::IconPtr; #include "ogr_libkml.h" #include "ogrlibkmlfield.h" void ogr2altitudemode_rec ( GeometryPtr poKmlGeometry, int iAltitudeMode, int isGX ) { PointPtr poKmlPoint; LineStringPtr poKmlLineString; PolygonPtr poKmlPolygon; MultiGeometryPtr poKmlMultiGeometry; size_t nGeom; size_t i; switch ( poKmlGeometry->Type ( ) ) { case kmldom::Type_Point: poKmlPoint = AsPoint ( poKmlGeometry ); if ( !isGX ) poKmlPoint->set_altitudemode ( iAltitudeMode ); else poKmlPoint->set_gx_altitudemode ( iAltitudeMode ); break; case kmldom::Type_LineString: poKmlLineString = AsLineString ( poKmlGeometry ); if ( !isGX ) poKmlLineString->set_altitudemode ( iAltitudeMode ); else poKmlLineString->set_gx_altitudemode ( iAltitudeMode ); break; case kmldom::Type_LinearRing: break; case kmldom::Type_Polygon: poKmlPolygon = AsPolygon ( poKmlGeometry ); if ( !isGX ) poKmlPolygon->set_altitudemode ( iAltitudeMode ); else poKmlPolygon->set_gx_altitudemode ( iAltitudeMode ); break; case kmldom::Type_MultiGeometry: poKmlMultiGeometry = AsMultiGeometry ( poKmlGeometry ); nGeom = poKmlMultiGeometry->get_geometry_array_size ( ); for ( i = 0; i < nGeom; i++ ) { ogr2altitudemode_rec ( poKmlMultiGeometry-> get_geometry_array_at ( i ), iAltitudeMode, isGX ); } break; default: break; } } void ogr2extrude_rec ( int nExtrude, GeometryPtr poKmlGeometry ) { PointPtr poKmlPoint; LineStringPtr poKmlLineString; PolygonPtr poKmlPolygon; MultiGeometryPtr poKmlMultiGeometry; size_t nGeom; size_t i; switch ( poKmlGeometry->Type ( ) ) { case kmldom::Type_Point: poKmlPoint = AsPoint ( poKmlGeometry ); poKmlPoint->set_extrude ( nExtrude ); break; case kmldom::Type_LineString: poKmlLineString = AsLineString ( poKmlGeometry ); poKmlLineString->set_extrude ( nExtrude ); break; case kmldom::Type_LinearRing: break; case kmldom::Type_Polygon: poKmlPolygon = AsPolygon ( poKmlGeometry ); poKmlPolygon->set_extrude ( nExtrude ); break; case kmldom::Type_MultiGeometry: poKmlMultiGeometry = AsMultiGeometry ( poKmlGeometry ); nGeom = poKmlMultiGeometry->get_geometry_array_size ( ); for ( i = 0; i < nGeom; i++ ) { ogr2extrude_rec ( nExtrude, poKmlMultiGeometry-> get_geometry_array_at ( i ) ); } break; default: break; } } void ogr2tessellate_rec ( int nTessellate, GeometryPtr poKmlGeometry ) { LineStringPtr poKmlLineString; PolygonPtr poKmlPolygon; MultiGeometryPtr poKmlMultiGeometry; size_t nGeom; size_t i; switch ( poKmlGeometry->Type ( ) ) { case kmldom::Type_Point: break; case kmldom::Type_LineString: poKmlLineString = AsLineString ( poKmlGeometry ); poKmlLineString->set_tessellate ( nTessellate ); break; case kmldom::Type_LinearRing: break; case kmldom::Type_Polygon: poKmlPolygon = AsPolygon ( poKmlGeometry ); poKmlPolygon->set_tessellate ( nTessellate ); break; case kmldom::Type_MultiGeometry: poKmlMultiGeometry = AsMultiGeometry ( poKmlGeometry ); nGeom = poKmlMultiGeometry->get_geometry_array_size ( ); for ( i = 0; i < nGeom; i++ ) { ogr2tessellate_rec ( nTessellate, poKmlMultiGeometry-> get_geometry_array_at ( i ) ); } break; default: break; } } /************************************************************************/ /* OGRLIBKMLSanitizeUTF8String() */ /************************************************************************/ static char* OGRLIBKMLSanitizeUTF8String(const char* pszString) { if (!CPLIsUTF8(pszString, -1) && CSLTestBoolean(CPLGetConfigOption("OGR_FORCE_ASCII", "YES"))) { static int bFirstTime = TRUE; if (bFirstTime) { bFirstTime = FALSE; CPLError(CE_Warning, CPLE_AppDefined, "%s is not a valid UTF-8 string. Forcing it to ASCII.\n" "If you still want the original string and change the XML file encoding\n" "afterwards, you can define OGR_FORCE_ASCII=NO as configuration option.\n" "This warning won't be issued anymore", pszString); } else { CPLDebug("OGR", "%s is not a valid UTF-8 string. Forcing it to ASCII", pszString); } return CPLForceToASCII(pszString, -1, '?'); } else return CPLStrdup(pszString); } /****************************************************************************** function to output ogr fields in kml args: poOgrFeat pointer to the feature the field is in poOgrLayer pointer to the layer the feature is in poKmlFactory pointer to the libkml dom factory poKmlPlacemark pointer to the placemark to add to returns: nothing env vars: LIBKML_TIMESTAMP_FIELD default: OFTDate or OFTDateTime named timestamp LIBKML_TIMESPAN_BEGIN_FIELD default: OFTDate or OFTDateTime named begin LIBKML_TIMESPAN_END_FIELD default: OFTDate or OFTDateTime named end LIBKML_DESCRIPTION_FIELD default: none LIBKML_NAME_FIELD default: OFTString field named name ******************************************************************************/ void field2kml ( OGRFeature * poOgrFeat, OGRLIBKMLLayer * poOgrLayer, KmlFactory * poKmlFactory, PlacemarkPtr poKmlPlacemark ) { int i; SchemaDataPtr poKmlSchemaData = poKmlFactory->CreateSchemaData ( ); SchemaPtr poKmlSchema = poOgrLayer->GetKmlSchema ( ); /***** set the url to the schema *****/ if ( poKmlSchema && poKmlSchema->has_id ( ) ) { std::string oKmlSchemaID = poKmlSchema->get_id ( ); std::string oKmlSchemaURL = "#"; oKmlSchemaURL.append ( oKmlSchemaID ); poKmlSchemaData->set_schemaurl ( oKmlSchemaURL ); } /***** get the field config *****/ struct fieldconfig oFC; get_fieldconfig( &oFC ); TimeSpanPtr poKmlTimeSpan = NULL; int nFields = poOgrFeat->GetFieldCount ( ); int iSkip1 = -1; int iSkip2 = -1; for ( i = 0; i < nFields; i++ ) { /***** if the field is set to skip, do so *****/ if ( i == iSkip1 || i == iSkip2 ) continue; /***** if the field isn't set just bail now *****/ if ( !poOgrFeat->IsFieldSet ( i ) ) continue; OGRFieldDefn *poOgrFieldDef = poOgrFeat->GetFieldDefnRef ( i ); OGRFieldType type = poOgrFieldDef->GetType ( ); const char *name = poOgrFieldDef->GetNameRef ( ); SimpleDataPtr poKmlSimpleData = NULL; int year, month, day, hour, min, sec, tz; switch ( type ) { case OFTString: // String of ASCII chars { char* pszUTF8String = OGRLIBKMLSanitizeUTF8String( poOgrFeat->GetFieldAsString ( i )); if( pszUTF8String[0] == '\0' ) { CPLFree( pszUTF8String ); continue; } /***** name *****/ if ( EQUAL ( name, oFC.namefield ) ) { poKmlPlacemark->set_name ( pszUTF8String ); CPLFree( pszUTF8String ); continue; } /***** description *****/ else if ( EQUAL ( name, oFC.descfield ) ) { poKmlPlacemark->set_description ( pszUTF8String ); CPLFree( pszUTF8String ); continue; } /***** altitudemode *****/ else if ( EQUAL ( name, oFC.altitudeModefield ) ) { const char *pszAltitudeMode = pszUTF8String ; int isGX = FALSE; int iAltitudeMode = kmldom::ALTITUDEMODE_CLAMPTOGROUND; if ( EQUAL ( pszAltitudeMode, "clampToGround" ) ) iAltitudeMode = kmldom::ALTITUDEMODE_CLAMPTOGROUND; else if ( EQUAL ( pszAltitudeMode, "relativeToGround" ) ) iAltitudeMode = kmldom::ALTITUDEMODE_RELATIVETOGROUND; else if ( EQUAL ( pszAltitudeMode, "absolute" ) ) iAltitudeMode = kmldom::ALTITUDEMODE_ABSOLUTE; else if ( EQUAL ( pszAltitudeMode, "relativeToSeaFloor" ) ) { iAltitudeMode = kmldom::GX_ALTITUDEMODE_RELATIVETOSEAFLOOR; isGX = TRUE; } else if ( EQUAL ( pszAltitudeMode, "clampToSeaFloor" ) ) { iAltitudeMode = kmldom::GX_ALTITUDEMODE_CLAMPTOSEAFLOOR; isGX = TRUE; } if ( poKmlPlacemark->has_geometry ( ) ) { GeometryPtr poKmlGeometry = poKmlPlacemark->get_geometry ( ); ogr2altitudemode_rec ( poKmlGeometry, iAltitudeMode, isGX ); } CPLFree( pszUTF8String ); continue; } /***** timestamp *****/ else if ( EQUAL ( name, oFC.tsfield ) ) { TimeStampPtr poKmlTimeStamp = poKmlFactory->CreateTimeStamp ( ); poKmlTimeStamp->set_when ( pszUTF8String ); poKmlPlacemark->set_timeprimitive ( poKmlTimeStamp ); CPLFree( pszUTF8String ); continue; } /***** begin *****/ if ( EQUAL ( name, oFC.beginfield ) ) { if ( !poKmlTimeSpan ) { poKmlTimeSpan = poKmlFactory->CreateTimeSpan ( ); poKmlPlacemark->set_timeprimitive ( poKmlTimeSpan ); } poKmlTimeSpan->set_begin ( pszUTF8String ); CPLFree( pszUTF8String ); continue; } /***** end *****/ else if ( EQUAL ( name, oFC.endfield ) ) { if ( !poKmlTimeSpan ) { poKmlTimeSpan = poKmlFactory->CreateTimeSpan ( ); poKmlPlacemark->set_timeprimitive ( poKmlTimeSpan ); } poKmlTimeSpan->set_end ( pszUTF8String ); CPLFree( pszUTF8String ); continue; } /***** icon *****/ else if ( EQUAL ( name, oFC.iconfield ) ) { CPLFree( pszUTF8String ); continue; } /***** other *****/ poKmlSimpleData = poKmlFactory->CreateSimpleData ( ); poKmlSimpleData->set_name ( name ); poKmlSimpleData->set_text ( pszUTF8String ); CPLFree( pszUTF8String ); break; } case OFTDate: // Date { poOgrFeat->GetFieldAsDateTime ( i, &year, &month, &day, &hour, &min, &sec, &tz ); int iTimeField; for ( iTimeField = i + 1; iTimeField < nFields; iTimeField++ ) { if ( iTimeField == iSkip1 || iTimeField == iSkip2 ) continue; OGRFieldDefn *poOgrFieldDef2 = poOgrFeat->GetFieldDefnRef ( i ); OGRFieldType type2 = poOgrFieldDef2->GetType ( ); const char *name2 = poOgrFieldDef2->GetNameRef ( ); if ( EQUAL ( name2, name ) && type2 == OFTTime && ( EQUAL ( name, oFC.tsfield ) || EQUAL ( name, oFC.beginfield ) || EQUAL ( name, oFC.endfield ) ) ) { int year2, month2, day2, hour2, min2, sec2, tz2; poOgrFeat->GetFieldAsDateTime ( iTimeField, &year2, &month2, &day2, &hour2, &min2, &sec2, &tz2 ); hour = hour2; min = min2; sec = sec2; tz = tz2; if ( 0 > iSkip1 ) iSkip1 = iTimeField; else iSkip2 = iTimeField; } } goto Do_DateTime; } case OFTTime: // Time { poOgrFeat->GetFieldAsDateTime ( i, &year, &month, &day, &hour, &min, &sec, &tz ); int iTimeField; for ( iTimeField = i + 1; iTimeField < nFields; iTimeField++ ) { if ( iTimeField == iSkip1 || iTimeField == iSkip2 ) continue; OGRFieldDefn *poOgrFieldDef2 = poOgrFeat->GetFieldDefnRef ( i ); OGRFieldType type2 = poOgrFieldDef2->GetType ( ); const char *name2 = poOgrFieldDef2->GetNameRef ( ); if ( EQUAL ( name2, name ) && type2 == OFTTime && ( EQUAL ( name, oFC.tsfield ) || EQUAL ( name, oFC.beginfield ) || EQUAL ( name, oFC.endfield ) ) ) { int year2, month2, day2, hour2, min2, sec2, tz2; poOgrFeat->GetFieldAsDateTime ( iTimeField, &year2, &month2, &day2, &hour2, &min2, &sec2, &tz2 ); year = year2; month = month2; day = day2; if ( 0 > iSkip1 ) iSkip1 = iTimeField; else iSkip2 = iTimeField; } } goto Do_DateTime; } case OFTDateTime: // Date and Time { poOgrFeat->GetFieldAsDateTime ( i, &year, &month, &day, &hour, &min, &sec, &tz ); Do_DateTime: /***** timestamp *****/ if ( EQUAL ( name, oFC.tsfield ) ) { char *timebuf = OGRGetXMLDateTime ( year, month, day, hour, min, sec, tz ); TimeStampPtr poKmlTimeStamp = poKmlFactory->CreateTimeStamp ( ); poKmlTimeStamp->set_when ( timebuf ); poKmlPlacemark->set_timeprimitive ( poKmlTimeStamp ); CPLFree( timebuf ); continue; } /***** begin *****/ if ( EQUAL ( name, oFC.beginfield ) ) { char *timebuf = OGRGetXMLDateTime ( year, month, day, hour, min, sec, tz ); if ( !poKmlTimeSpan ) { poKmlTimeSpan = poKmlFactory->CreateTimeSpan ( ); poKmlPlacemark->set_timeprimitive ( poKmlTimeSpan ); } poKmlTimeSpan->set_begin ( timebuf ); CPLFree( timebuf ); continue; } /***** end *****/ else if ( EQUAL ( name, oFC.endfield ) ) { char *timebuf = OGRGetXMLDateTime ( year, month, day, hour, min, sec, tz ); if ( !poKmlTimeSpan ) { poKmlTimeSpan = poKmlFactory->CreateTimeSpan ( ); poKmlPlacemark->set_timeprimitive ( poKmlTimeSpan ); } poKmlTimeSpan->set_end ( timebuf ); CPLFree( timebuf ); continue; } /***** other *****/ poKmlSimpleData = poKmlFactory->CreateSimpleData ( ); poKmlSimpleData->set_name ( name ); poKmlSimpleData->set_text ( poOgrFeat-> GetFieldAsString ( i ) ); break; } case OFTInteger: // Simple 32bit integer /***** extrude *****/ if ( EQUAL ( name, oFC.extrudefield ) ) { if ( poKmlPlacemark->has_geometry ( ) && -1 < poOgrFeat->GetFieldAsInteger ( i ) ) { GeometryPtr poKmlGeometry = poKmlPlacemark->get_geometry ( ); ogr2extrude_rec ( poOgrFeat->GetFieldAsInteger ( i ), poKmlGeometry ); } continue; } /***** tessellate *****/ if ( EQUAL ( name, oFC.tessellatefield ) ) { if ( poKmlPlacemark->has_geometry ( ) && -1 < poOgrFeat->GetFieldAsInteger ( i ) ) { GeometryPtr poKmlGeometry = poKmlPlacemark->get_geometry ( ); ogr2tessellate_rec ( poOgrFeat->GetFieldAsInteger ( i ), poKmlGeometry ); } continue; } /***** visibility *****/ if ( EQUAL ( name, oFC.visibilityfield ) ) { if ( -1 < poOgrFeat->GetFieldAsInteger ( i ) ) poKmlPlacemark->set_visibility ( poOgrFeat-> GetFieldAsInteger ( i ) ); continue; } /***** icon *****/ else if ( EQUAL ( name, oFC.drawOrderfield ) ) { continue; } /***** other *****/ poKmlSimpleData = poKmlFactory->CreateSimpleData ( ); poKmlSimpleData->set_name ( name ); poKmlSimpleData->set_text ( poOgrFeat->GetFieldAsString ( i ) ); break; case OFTReal: // Double Precision floating point { poKmlSimpleData = poKmlFactory->CreateSimpleData ( ); poKmlSimpleData->set_name ( name ); char* pszStr = CPLStrdup( poOgrFeat->GetFieldAsString ( i ) ); /* Use point as decimal separator */ char* pszComma = strchr(pszStr, ','); if (pszComma) *pszComma = '.'; poKmlSimpleData->set_text ( pszStr ); CPLFree(pszStr); break; } case OFTStringList: // Array of strings case OFTIntegerList: // List of 32bit integers case OFTRealList: // List of doubles case OFTBinary: // Raw Binary data case OFTWideStringList: // deprecated default: /***** other *****/ poKmlSimpleData = poKmlFactory->CreateSimpleData ( ); poKmlSimpleData->set_name ( name ); poKmlSimpleData->set_text ( poOgrFeat->GetFieldAsString ( i ) ); break; } poKmlSchemaData->add_simpledata ( poKmlSimpleData ); } /***** dont add it to the placemark unless there is data *****/ if ( poKmlSchemaData->get_simpledata_array_size ( ) > 0 ) { ExtendedDataPtr poKmlExtendedData = poKmlFactory->CreateExtendedData ( ); poKmlExtendedData->add_schemadata ( poKmlSchemaData ); poKmlPlacemark->set_extendeddata ( poKmlExtendedData ); } return; } /****************************************************************************** recursive function to read altitude mode from the geometry ******************************************************************************/ int kml2altitudemode_rec ( GeometryPtr poKmlGeometry, int *pnAltitudeMode, int *pbIsGX ) { PointPtr poKmlPoint; LineStringPtr poKmlLineString; PolygonPtr poKmlPolygon; MultiGeometryPtr poKmlMultiGeometry; size_t nGeom; size_t i; switch ( poKmlGeometry->Type ( ) ) { case kmldom::Type_Point: poKmlPoint = AsPoint ( poKmlGeometry ); if ( poKmlPoint->has_altitudemode ( ) ) { *pnAltitudeMode = poKmlPoint->get_altitudemode ( ); return TRUE; } else if ( poKmlPoint->has_gx_altitudemode ( ) ) { *pnAltitudeMode = poKmlPoint->get_gx_altitudemode ( ); *pbIsGX = TRUE; return TRUE; } break; case kmldom::Type_LineString: poKmlLineString = AsLineString ( poKmlGeometry ); if ( poKmlLineString->has_altitudemode ( ) ) { *pnAltitudeMode = poKmlLineString->get_altitudemode ( ); return TRUE; } else if ( poKmlLineString->has_gx_altitudemode ( ) ) { *pnAltitudeMode = poKmlLineString->get_gx_altitudemode ( ); *pbIsGX = TRUE; return TRUE; } break; case kmldom::Type_LinearRing: break; case kmldom::Type_Polygon: poKmlPolygon = AsPolygon ( poKmlGeometry ); if ( poKmlPolygon->has_altitudemode ( ) ) { *pnAltitudeMode = poKmlPolygon->get_altitudemode ( ); return TRUE; } else if ( poKmlPolygon->has_gx_altitudemode ( ) ) { *pnAltitudeMode = poKmlPolygon->get_gx_altitudemode ( ); *pbIsGX = TRUE; return TRUE; } break; case kmldom::Type_MultiGeometry: poKmlMultiGeometry = AsMultiGeometry ( poKmlGeometry ); nGeom = poKmlMultiGeometry->get_geometry_array_size ( ); for ( i = 0; i < nGeom; i++ ) { if ( kml2altitudemode_rec ( poKmlMultiGeometry-> get_geometry_array_at ( i ), pnAltitudeMode, pbIsGX ) ) return TRUE; } break; default: break; } return FALSE; } /****************************************************************************** recursive function to read extrude from the geometry ******************************************************************************/ int kml2extrude_rec ( GeometryPtr poKmlGeometry, int *pnExtrude ) { PointPtr poKmlPoint; LineStringPtr poKmlLineString; PolygonPtr poKmlPolygon; MultiGeometryPtr poKmlMultiGeometry; size_t nGeom; size_t i; switch ( poKmlGeometry->Type ( ) ) { case kmldom::Type_Point: poKmlPoint = AsPoint ( poKmlGeometry ); if ( poKmlPoint->has_extrude ( ) ) { *pnExtrude = poKmlPoint->get_extrude ( ); return TRUE; } break; case kmldom::Type_LineString: poKmlLineString = AsLineString ( poKmlGeometry ); if ( poKmlLineString->has_extrude ( ) ) { *pnExtrude = poKmlLineString->get_extrude ( ); return TRUE; } break; case kmldom::Type_LinearRing: break; case kmldom::Type_Polygon: poKmlPolygon = AsPolygon ( poKmlGeometry ); if ( poKmlPolygon->has_extrude ( ) ) { *pnExtrude = poKmlPolygon->get_extrude ( ); return TRUE; } break; case kmldom::Type_MultiGeometry: poKmlMultiGeometry = AsMultiGeometry ( poKmlGeometry ); nGeom = poKmlMultiGeometry->get_geometry_array_size ( ); for ( i = 0; i < nGeom; i++ ) { if ( kml2extrude_rec ( poKmlMultiGeometry-> get_geometry_array_at ( i ), pnExtrude ) ) return TRUE; } break; default: break; } return FALSE; } /****************************************************************************** recursive function to read tessellate from the geometry ******************************************************************************/ int kml2tessellate_rec ( GeometryPtr poKmlGeometry, int *pnTessellate ) { LineStringPtr poKmlLineString; PolygonPtr poKmlPolygon; MultiGeometryPtr poKmlMultiGeometry; size_t nGeom; size_t i; switch ( poKmlGeometry->Type ( ) ) { case kmldom::Type_Point: break; case kmldom::Type_LineString: poKmlLineString = AsLineString ( poKmlGeometry ); if ( poKmlLineString->has_tessellate ( ) ) { *pnTessellate = poKmlLineString->get_tessellate ( ); return TRUE; } break; case kmldom::Type_LinearRing: break; case kmldom::Type_Polygon: poKmlPolygon = AsPolygon ( poKmlGeometry ); if ( poKmlPolygon->has_tessellate ( ) ) { *pnTessellate = poKmlPolygon->get_tessellate ( ); return TRUE; } break; case kmldom::Type_MultiGeometry: poKmlMultiGeometry = AsMultiGeometry ( poKmlGeometry ); nGeom = poKmlMultiGeometry->get_geometry_array_size ( ); for ( i = 0; i < nGeom; i++ ) { if ( kml2tessellate_rec ( poKmlMultiGeometry-> get_geometry_array_at ( i ), pnTessellate ) ) return TRUE; } break; default: break; } return FALSE; } /****************************************************************************** function to read kml into ogr fields ******************************************************************************/ void kml2field ( OGRFeature * poOgrFeat, FeaturePtr poKmlFeature ) { /***** get the field config *****/ struct fieldconfig oFC; get_fieldconfig( &oFC ); /***** name *****/ if ( poKmlFeature->has_name ( ) ) { const std::string oKmlName = poKmlFeature->get_name ( ); int iField = poOgrFeat->GetFieldIndex ( oFC.namefield ); if ( iField > -1 ) poOgrFeat->SetField ( iField, oKmlName.c_str ( ) ); } /***** description *****/ if ( poKmlFeature->has_description ( ) ) { const std::string oKmlDesc = poKmlFeature->get_description ( ); int iField = poOgrFeat->GetFieldIndex ( oFC.descfield ); if ( iField > -1 ) poOgrFeat->SetField ( iField, oKmlDesc.c_str ( ) ); } if ( poKmlFeature->has_timeprimitive ( ) ) { TimePrimitivePtr poKmlTimePrimitive = poKmlFeature->get_timeprimitive ( ); /***** timestamp *****/ if ( poKmlTimePrimitive->IsA ( kmldom::Type_TimeStamp ) ) { TimeStampPtr poKmlTimeStamp = AsTimeStamp ( poKmlTimePrimitive ); if ( poKmlTimeStamp->has_when ( ) ) { const std::string oKmlWhen = poKmlTimeStamp->get_when ( ); int iField = poOgrFeat->GetFieldIndex ( oFC.tsfield ); if ( iField > -1 ) { int nYear, nMonth, nDay, nHour, nMinute, nTZ; float fSecond; if ( OGRParseXMLDateTime ( oKmlWhen.c_str ( ), &nYear, &nMonth, &nDay, &nHour, &nMinute, &fSecond, &nTZ ) ) poOgrFeat->SetField ( iField, nYear, nMonth, nDay, nHour, nMinute, ( int )fSecond, nTZ ); } } } /***** timespan *****/ if ( poKmlTimePrimitive->IsA ( kmldom::Type_TimeSpan ) ) { TimeSpanPtr poKmlTimeSpan = AsTimeSpan ( poKmlTimePrimitive ); /***** begin *****/ if ( poKmlTimeSpan->has_begin ( ) ) { const std::string oKmlWhen = poKmlTimeSpan->get_begin ( ); int iField = poOgrFeat->GetFieldIndex ( oFC.beginfield ); if ( iField > -1 ) { int nYear, nMonth, nDay, nHour, nMinute, nTZ; float fSecond; if ( OGRParseXMLDateTime ( oKmlWhen.c_str ( ), &nYear, &nMonth, &nDay, &nHour, &nMinute, &fSecond, &nTZ ) ) poOgrFeat->SetField ( iField, nYear, nMonth, nDay, nHour, nMinute, ( int )fSecond, nTZ ); } } /***** end *****/ if ( poKmlTimeSpan->has_end ( ) ) { const std::string oKmlWhen = poKmlTimeSpan->get_end ( ); int iField = poOgrFeat->GetFieldIndex ( oFC.endfield ); if ( iField > -1 ) { int nYear, nMonth, nDay, nHour, nMinute, nTZ; float fSecond; if ( OGRParseXMLDateTime ( oKmlWhen.c_str ( ), &nYear, &nMonth, &nDay, &nHour, &nMinute, &fSecond, &nTZ ) ) poOgrFeat->SetField ( iField, nYear, nMonth, nDay, nHour, nMinute, ( int )fSecond, nTZ ); } } } } /***** placemark *****/ PlacemarkPtr poKmlPlacemark = AsPlacemark ( poKmlFeature ); GroundOverlayPtr poKmlGroundOverlay = AsGroundOverlay ( poKmlFeature ); if ( poKmlPlacemark && poKmlPlacemark->has_geometry ( ) ) { GeometryPtr poKmlGeometry = poKmlPlacemark->get_geometry ( ); /***** altitudeMode *****/ int bIsGX = FALSE; int nAltitudeMode = -1; int iField = poOgrFeat->GetFieldIndex ( oFC.altitudeModefield ); if ( iField > -1 ) { if ( kml2altitudemode_rec ( poKmlGeometry, &nAltitudeMode, &bIsGX ) ) { if ( !bIsGX ) { switch ( nAltitudeMode ) { case kmldom::ALTITUDEMODE_CLAMPTOGROUND: poOgrFeat->SetField ( iField, "clampToGround" ); break; case kmldom::ALTITUDEMODE_RELATIVETOGROUND: poOgrFeat->SetField ( iField, "relativeToGround" ); break; case kmldom::ALTITUDEMODE_ABSOLUTE: poOgrFeat->SetField ( iField, "absolute" ); break; } } else { switch ( nAltitudeMode ) { case kmldom::GX_ALTITUDEMODE_RELATIVETOSEAFLOOR: poOgrFeat->SetField ( iField, "relativeToSeaFloor" ); break; case kmldom::GX_ALTITUDEMODE_CLAMPTOSEAFLOOR: poOgrFeat->SetField ( iField, "clampToSeaFloor" ); break; } } } } /***** tessellate *****/ int nTessellate = -1; kml2tessellate_rec ( poKmlGeometry, &nTessellate ); iField = poOgrFeat->GetFieldIndex ( oFC.tessellatefield ); if ( iField > -1 ) poOgrFeat->SetField ( iField, nTessellate ); /***** extrude *****/ int nExtrude = -1; kml2extrude_rec ( poKmlGeometry, &nExtrude ); iField = poOgrFeat->GetFieldIndex ( oFC.extrudefield ); if ( iField > -1 ) poOgrFeat->SetField ( iField, nExtrude ); } /***** ground overlay *****/ else if ( poKmlGroundOverlay ) { /***** icon *****/ int iField = poOgrFeat->GetFieldIndex ( oFC.iconfield ); if ( iField > -1 ) { if ( poKmlGroundOverlay->has_icon ( ) ) { IconPtr icon = poKmlGroundOverlay->get_icon ( ); if ( icon->has_href ( ) ) { poOgrFeat->SetField ( iField, icon->get_href ( ).c_str ( ) ); } } } /***** drawOrder *****/ iField = poOgrFeat->GetFieldIndex ( oFC.drawOrderfield ); if ( iField > -1 ) { if ( poKmlGroundOverlay->has_draworder ( ) ) { poOgrFeat->SetField ( iField, poKmlGroundOverlay->get_draworder ( ) ); } } /***** altitudeMode *****/ iField = poOgrFeat->GetFieldIndex ( oFC.altitudeModefield ); if ( iField > -1 ) { if ( poKmlGroundOverlay->has_altitudemode ( ) ) { switch ( poKmlGroundOverlay->get_altitudemode ( ) ) { case kmldom::ALTITUDEMODE_CLAMPTOGROUND: poOgrFeat->SetField ( iField, "clampToGround" ); break; case kmldom::ALTITUDEMODE_RELATIVETOGROUND: poOgrFeat->SetField ( iField, "relativeToGround" ); break; case kmldom::ALTITUDEMODE_ABSOLUTE: poOgrFeat->SetField ( iField, "absolute" ); break; } } else if ( poKmlGroundOverlay->has_gx_altitudemode ( ) ) { switch ( poKmlGroundOverlay->get_gx_altitudemode ( ) ) { case kmldom::GX_ALTITUDEMODE_RELATIVETOSEAFLOOR: poOgrFeat->SetField ( iField, "relativeToSeaFloor" ); break; case kmldom::GX_ALTITUDEMODE_CLAMPTOSEAFLOOR: poOgrFeat->SetField ( iField, "clampToSeaFloor" ); break; } } } } /***** visibility *****/ int nVisibility = -1; if ( poKmlFeature->has_visibility ( ) ) nVisibility = poKmlFeature->get_visibility ( ); int iField = poOgrFeat->GetFieldIndex ( oFC.visibilityfield ); if ( iField > -1 ) poOgrFeat->SetField ( iField, nVisibility ); ExtendedDataPtr poKmlExtendedData = NULL; if ( poKmlFeature->has_extendeddata ( ) ) { poKmlExtendedData = poKmlFeature->get_extendeddata ( ); /***** loop over the schemadata_arrays *****/ size_t nSchemaData = poKmlExtendedData->get_schemadata_array_size ( ); size_t iSchemaData; for ( iSchemaData = 0; iSchemaData < nSchemaData; iSchemaData++ ) { SchemaDataPtr poKmlSchemaData = poKmlExtendedData->get_schemadata_array_at ( iSchemaData ); /***** loop over the simpledata array *****/ size_t nSimpleData = poKmlSchemaData->get_simpledata_array_size ( ); size_t iSimpleData; for ( iSimpleData = 0; iSimpleData < nSimpleData; iSimpleData++ ) { SimpleDataPtr poKmlSimpleData = poKmlSchemaData->get_simpledata_array_at ( iSimpleData ); /***** find the field index *****/ int iField = -1; if ( poKmlSimpleData->has_name ( ) ) { const string oName = poKmlSimpleData->get_name ( ); const char *pszName = oName.c_str ( ); iField = poOgrFeat->GetFieldIndex ( pszName ); } /***** if it has trxt set the field *****/ if ( iField > -1 && poKmlSimpleData->has_text ( ) ) { string oText = poKmlSimpleData->get_text ( ); /* SerializePretty() adds a new line before the data */ /* ands trailing spaces. I believe this is wrong */ /* as it breaks round-tripping */ /* Trim trailing spaces */ while (oText.size() != 0 && oText[oText.size()-1] == ' ') oText.resize(oText.size()-1); /* Skip leading newline and spaces */ const char* pszText = oText.c_str ( ); if (pszText[0] == '\n') pszText ++; while (pszText[0] == ' ') pszText ++; poOgrFeat->SetField ( iField, pszText ); } } } if (nSchemaData == 0 && poKmlExtendedData->get_data_array_size() > 0 ) { int bLaunderFieldNames = CSLTestBoolean(CPLGetConfigOption("LIBKML_LAUNDER_FIELD_NAMES", "YES")); size_t nDataArraySize = poKmlExtendedData->get_data_array_size(); for(size_t i=0; i < nDataArraySize; i++) { const DataPtr& data = poKmlExtendedData->get_data_array_at(i); if (data->has_name() && data->has_value()) { CPLString osName = data->get_name(); if (bLaunderFieldNames) osName = OGRLIBKMLLayer::LaunderFieldNames(osName); int iField = poOgrFeat->GetFieldIndex ( osName ); if (iField >= 0) { poOgrFeat->SetField ( iField, data->get_value().c_str() ); } } } } } } /****************************************************************************** function create a simplefield from a FieldDefn ******************************************************************************/ SimpleFieldPtr FieldDef2kml ( OGRFieldDefn * poOgrFieldDef, KmlFactory * poKmlFactory ) { SimpleFieldPtr poKmlSimpleField = poKmlFactory->CreateSimpleField ( ); const char *pszFieldName = poOgrFieldDef->GetNameRef ( ); poKmlSimpleField->set_name ( pszFieldName ); /***** get the field config *****/ struct fieldconfig oFC; get_fieldconfig( &oFC ); SimpleDataPtr poKmlSimpleData = NULL; switch ( poOgrFieldDef->GetType ( ) ) { case OFTInteger: case OFTIntegerList: if ( EQUAL ( pszFieldName, oFC.tessellatefield ) || EQUAL ( pszFieldName, oFC.extrudefield ) || EQUAL ( pszFieldName, oFC.visibilityfield ) || EQUAL ( pszFieldName, oFC.drawOrderfield ) ) break; poKmlSimpleField->set_type ( "int" ); return poKmlSimpleField; case OFTReal: case OFTRealList: poKmlSimpleField->set_type ( "float" ); return poKmlSimpleField; case OFTBinary: poKmlSimpleField->set_type ( "bool" ); return poKmlSimpleField; case OFTString: case OFTStringList: if ( EQUAL ( pszFieldName, oFC.namefield ) || EQUAL ( pszFieldName, oFC.descfield ) || EQUAL ( pszFieldName, oFC.altitudeModefield ) || EQUAL ( pszFieldName, oFC.iconfield ) ) break; poKmlSimpleField->set_type ( "string" ); return poKmlSimpleField; /***** kml has these types but as timestamp/timespan *****/ case OFTDate: case OFTTime: case OFTDateTime: if ( EQUAL ( pszFieldName, oFC.tsfield ) || EQUAL ( pszFieldName, oFC.beginfield ) || EQUAL ( pszFieldName, oFC.endfield ) ) break; default: poKmlSimpleField->set_type ( "string" ); return poKmlSimpleField; } return NULL; } /****************************************************************************** function to add the simpleFields in a schema to a featuredefn ******************************************************************************/ void kml2FeatureDef ( SchemaPtr poKmlSchema, OGRFeatureDefn * poOgrFeatureDefn ) { size_t nSimpleFields = poKmlSchema->get_simplefield_array_size ( ); size_t iSimpleField; for ( iSimpleField = 0; iSimpleField < nSimpleFields; iSimpleField++ ) { SimpleFieldPtr poKmlSimpleField = poKmlSchema->get_simplefield_array_at ( iSimpleField ); const char *pszType = "string"; string osName = "Unknown"; string osType; if ( poKmlSimpleField->has_type ( ) ) { osType = poKmlSimpleField->get_type ( ); pszType = osType.c_str ( ); } /* FIXME? We cannot set displayname as the field name because in kml2field() we make the */ /* lookup on fields based on their name. We would need some map if we really */ /* want to use displayname, but that might not be a good idea because displayname */ /* may have HTML formatting, which makes it impractical when converting to other */ /* drivers or to make requests */ /* Example: http://www.jasonbirch.com/files/newt_combined.kml */ /*if ( poKmlSimpleField->has_displayname ( ) ) { osName = poKmlSimpleField->get_displayname ( ); } else*/ if ( poKmlSimpleField->has_name ( ) ) { osName = poKmlSimpleField->get_name ( ); } if ( EQUAL ( pszType, "bool" ) || EQUAL ( pszType, "int" ) || EQUAL ( pszType, "short" ) || EQUAL ( pszType, "ushort" ) ) { OGRFieldDefn oOgrFieldName ( osName.c_str(), OFTInteger ); poOgrFeatureDefn->AddFieldDefn ( &oOgrFieldName ); } else if ( EQUAL ( pszType, "float" ) || EQUAL ( pszType, "double" ) || /* a too big uint wouldn't fit in a int, so we map it to OFTReal for now ... */ EQUAL ( pszType, "uint" ) ) { OGRFieldDefn oOgrFieldName ( osName.c_str(), OFTReal ); poOgrFeatureDefn->AddFieldDefn ( &oOgrFieldName ); } else /* string, or any other unrecognized type */ { OGRFieldDefn oOgrFieldName ( osName.c_str(), OFTString ); poOgrFeatureDefn->AddFieldDefn ( &oOgrFieldName ); } } return; } /******************************************************************************* * function to fetch the field config options * *******************************************************************************/ void get_fieldconfig( struct fieldconfig *oFC) { oFC->namefield = CPLGetConfigOption ( "LIBKML_NAME_FIELD", "Name" ); oFC->descfield = CPLGetConfigOption ( "LIBKML_DESCRIPTION_FIELD", "description" ); oFC->tsfield = CPLGetConfigOption ( "LIBKML_TIMESTAMP_FIELD", "timestamp" ); oFC->beginfield = CPLGetConfigOption ( "LIBKML_BEGIN_FIELD", "begin" ); oFC->endfield = CPLGetConfigOption ( "LIBKML_END_FIELD", "end" ); oFC->altitudeModefield = CPLGetConfigOption ( "LIBKML_ALTITUDEMODE_FIELD", "altitudeMode" ); oFC->tessellatefield = CPLGetConfigOption ( "LIBKML_TESSELLATE_FIELD", "tessellate" ); oFC->extrudefield = CPLGetConfigOption ( "LIBKML_EXTRUDE_FIELD", "extrude" ); oFC->visibilityfield = CPLGetConfigOption ( "LIBKML_VISIBILITY_FIELD", "visibility" ); oFC->drawOrderfield = CPLGetConfigOption ( "LIBKML_DRAWORDER_FIELD", "drawOrder" ); oFC->iconfield = CPLGetConfigOption ( "LIBKML_ICON_FIELD", "icon" ); }
31.575979
99
0.482484
chambbj
cd83150fc6d12a4b0ed589589c985cd461a0f936
2,768
cpp
C++
OpenGLExample_21/OpenGLExample_21/src/CreateWindow.cpp
SnowyLake/OpenGL_Learn
ae389cb45992eb90595482e0b4eca41b967e63b3
[ "MIT" ]
4
2020-11-27T14:20:28.000Z
2022-03-12T03:11:04.000Z
OpenGLExample_21/OpenGLExample_21/src/CreateWindow.cpp
SnowyLake/OpenGL_Learn
ae389cb45992eb90595482e0b4eca41b967e63b3
[ "MIT" ]
null
null
null
OpenGLExample_21/OpenGLExample_21/src/CreateWindow.cpp
SnowyLake/OpenGL_Learn
ae389cb45992eb90595482e0b4eca41b967e63b3
[ "MIT" ]
null
null
null
#include"CreateWindow.h" //setting const unsigned int SCR_WIDTH = 800; const unsigned int SCR_HEIGHT = 600; //camera GLCamera camera(glm::vec3(0.0f, 0.0f, 6.0f)); float lastX = SCR_WIDTH / 2.0f; float lastY = SCR_HEIGHT / 2.0f; bool firstMouse = true; //timing float deltaTime = 0.0f; // time between current frame and last frame float lastTime = 0.0f; GLFWwindow* CreateWindow(unsigned int width, unsigned int height, const char* Title) { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef _APPLE_ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif // _APPLE_ //glfw:create window GLFWwindow* window = glfwCreateWindow(width, height, Title, NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return nullptr; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, FrameBufferSizeCallback); glfwSetCursorPosCallback(window, MouseCallback); glfwSetScrollCallback(window, ScrollCallback); //tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); //glad if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return nullptr; } return window; } void ProcessInput(GLFWwindow* window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) { glfwSetWindowShouldClose(window, true); } if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { camera.ProcessKeyboard(FORWARD, deltaTime); } if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { camera.ProcessKeyboard(BACKWARD, deltaTime); } if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { camera.ProcessKeyboard(LEFT, deltaTime); } if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) { camera.ProcessKeyboard(RIGHT, deltaTime); } if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS) { camera.ProcessKeyboard(RISE, deltaTime); } if (glfwGetKey(window, GLFW_KEY_CAPS_LOCK) == GLFW_PRESS) { camera.ProcessKeyboard(FALL, deltaTime); } } void FrameBufferSizeCallback(GLFWwindow* window, int width, int height) { glViewport(0, 0, width, height); } void MouseCallback(GLFWwindow* window, double xPos, double yPos) { if (firstMouse) { lastX = xPos; lastY = yPos; firstMouse = false; } float xoffset = xPos - lastX; float yoffset = lastY - yPos; lastX = xPos; lastY = yPos; camera.ProcessMouseMovement(xoffset, yoffset); } void ScrollCallback(GLFWwindow* window, double xOffset, double yOffset) { camera.ProcessMouseScroll(yOffset); }
26.113208
85
0.717847
SnowyLake
cd8344de5018d08c30e74df0f59e0eeaadfa5a1e
1,841
cpp
C++
CG_AUEB_LAB_4/Lab4/Source/SceneGraph/Node.cpp
kvarcg/opengl_course
9f6613a0e165f44630de553051eb8722387b7ac8
[ "MIT" ]
null
null
null
CG_AUEB_LAB_4/Lab4/Source/SceneGraph/Node.cpp
kvarcg/opengl_course
9f6613a0e165f44630de553051eb8722387b7ac8
[ "MIT" ]
null
null
null
CG_AUEB_LAB_4/Lab4/Source/SceneGraph/Node.cpp
kvarcg/opengl_course
9f6613a0e165f44630de553051eb8722387b7ac8
[ "MIT" ]
null
null
null
//----------------------------------------------------// // // // File: Node.cpp // // This scene graph is a basic example for the // // object relational management of the scene // // This is the basic node class // // // // Author: // // Kostas Vardis // // // // These files are provided as part of the BSc course // // of Computer Graphics at the Athens University of // // Economics and Business (AUEB) // // // //----------------------------------------------------// // includes //////////////////////////////////////// #include "../HelpLib.h" // - Library for including GL libraries, checking for OpenGL errors, writing to Output window, etc. #include "Node.h" // - Header file for the Node class // defines ///////////////////////////////////////// // Constructor Node::Node(const char* name): m_name(name), m_parent(nullptr) { } // Destructor Node::~Node() { } void Node::SetName(const char * str) { if (!str) return; m_name = std::string(str); } void Node::Init() { } void Node::Update() { } void Node::Draw() { } const char * Node::GetName() { return m_name.c_str(); } glm::mat4x4 Node::GetTransform() { if (m_parent) return m_parent->GetTransform(); else return glm::mat4x4(1); } glm::vec3 Node::GetWorldPosition() { glm::vec4 p4(0,0,0,1); glm::vec4 result = GetTransform()*p4; return glm::vec3(result/result.w); } // eof ///////////////////////////////// class Node
22.728395
123
0.415535
kvarcg
cd85fac14b7d699039f12d0621ae3469ae582e2d
4,632
cpp
C++
scout_webots_sim/src/scout_webots_runner.cpp
westonrobot/scout_navigation
7e8c79cb41205b98a33a81e87bdea6bd6411bca3
[ "BSD-3-Clause" ]
14
2020-09-02T14:05:14.000Z
2021-08-31T02:19:37.000Z
scout_webots_sim/src/scout_webots_runner.cpp
westonrobot/scout_navigation
7e8c79cb41205b98a33a81e87bdea6bd6411bca3
[ "BSD-3-Clause" ]
4
2020-09-18T12:50:15.000Z
2021-10-16T13:06:16.000Z
scout_webots_sim/src/scout_webots_runner.cpp
westonrobot/scout_navigation
7e8c79cb41205b98a33a81e87bdea6bd6411bca3
[ "BSD-3-Clause" ]
4
2020-10-16T06:31:28.000Z
2021-08-31T02:21:50.000Z
/* * scout_webots_runner.cpp * * Created on: Sep 18, 2020 11:13 * Description: * * Copyright (c) 2020 Ruixiang Du (rdu) */ #include <signal.h> #include <webots_ros/set_float.h> #include "scout_base/scout_messenger.hpp" #include "scout_webots_sim/scout_webots_runner.hpp" #include "scout_webots_sim/scout_webots_interface.hpp" namespace westonrobot { ScoutWebotsRunner::ScoutWebotsRunner(ros::NodeHandle *nh, ros::NodeHandle *pnh) : nh_(nh), pnh_(pnh) { std::cout << "Creating runner" << std::endl; } void ScoutWebotsRunner::AddExtension( std::shared_ptr<WebotsExtension> extension) { extensions_.push_back(extension); } int ScoutWebotsRunner::Run() { // get the list of availables controllers std::string controllerName; ros::Subscriber name_sub = nh_->subscribe( "model_name", 100, &ScoutWebotsRunner::ControllerNameCallback, this); while (controller_count_ == 0 || controller_count_ < name_sub.getNumPublishers()) { ros::spinOnce(); ros::spinOnce(); ros::spinOnce(); } ros::spinOnce(); // if there is more than one controller available, it let the user choose if (controller_count_ == 1) controllerName = controller_list_[0]; else { int wantedController = 0; std::cout << "Choose the # of the controller you want to use:\n"; std::cin >> wantedController; if (1 <= wantedController && wantedController <= controller_count_) controllerName = controller_list_[wantedController - 1]; else { ROS_ERROR("Invalid number for controller choice."); return 1; } } ROS_INFO("Using controller: '%s'", controllerName.c_str()); name_sub.shutdown(); // fetch parameters before connecting to robot std::string port_name; std::string odom_frame; std::string base_frame; std::string odom_topic_name; bool is_omni_wheel = false; bool is_simulated = false; int sim_rate = 50; bool is_scout_mini = false; pnh_->param<std::string>("port_name", port_name, std::string("can0")); pnh_->param<std::string>("odom_frame", odom_frame, std::string("odom")); pnh_->param<std::string>("base_frame", base_frame, std::string("base_link")); pnh_->param<bool>("is_omni_wheel", is_omni_wheel, false); pnh_->param<bool>("simulated_robot", is_simulated, true); pnh_->param<int>("control_rate", sim_rate, 50); pnh_->param<std::string>("odom_topic_name", odom_topic_name, std::string("odom")); pnh_->param<bool>("is_scout_mini", is_scout_mini, false); std::shared_ptr<ScoutWebotsInterface> robot = std::make_shared<ScoutWebotsInterface>(nh_); // init robot components robot->Initialize(controllerName); if (!extensions_.empty()) { for (auto &ext : extensions_) ext->Setup(nh_, controllerName, static_broadcaster_); } std::unique_ptr<ScoutMessenger<ScoutWebotsInterface>> messenger = std::unique_ptr<ScoutMessenger<ScoutWebotsInterface>>( new ScoutMessenger<ScoutWebotsInterface>(robot, nh_)); messenger->SetOdometryFrame(odom_frame); messenger->SetBaseFrame(base_frame); messenger->SetOdometryTopicName(odom_topic_name); messenger->SetSimulationMode(); messenger->SetupSubscription(); const uint32_t time_step = 1000 / sim_rate; ROS_INFO( "Chosen time step: '%d', make sure you set the same time step in Webots \"basicTimeStep\"" "scene", time_step); ROS_INFO("Entering ROS main loop..."); // main loop time_step_client_ = nh_->serviceClient<webots_ros::set_int>( "/" + controllerName + "/robot/time_step"); time_step_srv_.request.value = time_step; ros::Rate loop_rate(sim_rate); ros::AsyncSpinner spinner(2); spinner.start(); while (ros::ok()) { if (time_step_client_.call(time_step_srv_) && time_step_srv_.response.success) { messenger->Update(); } else { static int32_t error_cnt = 0; ROS_ERROR("Failed to call service time_step for next step."); if (++error_cnt > 50) break; } // ros::spinOnce(); loop_rate.sleep(); } time_step_srv_.request.value = 0; time_step_client_.call(time_step_srv_); spinner.stop(); ros::shutdown(); return 0; } void ScoutWebotsRunner::Stop() { ROS_INFO("User stopped the 'scout_webots_node'."); time_step_srv_.request.value = 0; time_step_client_.call(time_step_srv_); ros::shutdown(); } void ScoutWebotsRunner::ControllerNameCallback( const std_msgs::String::ConstPtr &name) { controller_count_++; controller_list_.push_back(name->data); ROS_INFO("Controller #%d: %s.", controller_count_, controller_list_.back().c_str()); } } // namespace westonrobot
31.087248
96
0.696244
westonrobot
cd8a3b795b2ef7c574629303bc5eab4eb050a8af
18,686
cc
C++
library/impl/gviz/gvznode.cc
flyfire100/dot-editor
76fedb74bfdd51f7740d66befe8f868eb0ecff28
[ "BSD-3-Clause" ]
3
2016-04-09T18:23:40.000Z
2021-11-23T10:34:44.000Z
library/impl/gviz/gvznode.cc
flyfire100/dot-editor
76fedb74bfdd51f7740d66befe8f868eb0ecff28
[ "BSD-3-Clause" ]
7
2017-03-10T08:19:20.000Z
2021-10-21T13:02:37.000Z
library/impl/gviz/gvznode.cc
flyfire100/dot-editor
76fedb74bfdd51f7740d66befe8f868eb0ecff28
[ "BSD-3-Clause" ]
2
2015-08-21T09:52:26.000Z
2021-07-22T08:14:08.000Z
/* ========================================================================= */ /* ------------------------------------------------------------------------- */ /*! \file gvznode.cc \date May 2012 \author TNick \brief Contains the implementation of GVzNode class *//* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Please read COPYING and README files in root folder ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* ------------------------------------------------------------------------- */ /* ========================================================================= */ // // // // /* INCLUDES ------------------------------------------------------------ */ #ifdef DE_WITH_GRAPHVIZ #include <dot-editor.h> #include <QDebug> #include <QPainter> #include <QBrush> #include <QPen> #include <QFont> #include <QStyleOptionGraphicsItem> #include <impl/gviz/gvzedge.h> #include "gvznode.h" /* INCLUDES ============================================================ */ // // // // /* DEFINITIONS --------------------------------------------------------- */ /* DEFINITIONS ========================================================= */ // // // // /* DATA ---------------------------------------------------------------- */ /* related to NdShape */ const char * GVzNode::shape_names[] = { "Mcircle", "Mdiamond", "Msquare", "box", "box3d", "circle", "component", "diamond", "doublecircle", "doubleoctagon", "egg", "ellipse", "folder", "hexagon", "house", "invhouse", "invtrapezium", "invtriangle", "none", "note", "octagon", "oval", "parallelogram", "pentagon", "plaintext", "point", "polygon", "rect", "rectangle", "septagon", "square", "tab", "trapezium", "triangle", "tripleoctagon", 0 }; /* DATA ================================================================ */ // // // // /* CLASS --------------------------------------------------------------- */ /* ------------------------------------------------------------------------- */ GVzNode::GVzNode ( QGraphicsItem * fth_g, Agnode_t * node, GVzNode * parent_n ) : QGraphicsItem( fth_g ) { setFlags( ItemIsMovable | ItemIsSelectable | ItemIsFocusable); dot_n_ = node; fth_ = parent_n; st_lst_ = STNONE; updateCachedData(); } /* ========================================================================= */ /* ------------------------------------------------------------------------- */ GVzNode::~GVzNode () { edg_l_.clear(); } /* ========================================================================= */ /* ------------------------------------------------------------------------- */ QString GVzNode::label () const { if (dot_n_ == NULL) return QString(); textlabel_t * tl = ND_label (dot_n_); if (tl == NULL) return QString(); return tl->text; } /* ========================================================================= */ /* ------------------------------------------------------------------------- */ QRectF GVzNode::boundingRect () const { qreal penWidth = 1; qreal w = ND_width( dot_n_ ) * 72; qreal h = ND_height( dot_n_ ) * 72; return QRectF( - ( w / 2 + penWidth / 2 ), - ( h / 2 + penWidth / 2 ), w + penWidth, h + penWidth ); } /* ========================================================================= */ /* ------------------------------------------------------------------------- */ void octogonInRect (QRectF & r, QPointF * pts) { /* 9 POINTS EXPECTED */ qreal x_3 = r.width() / 3; qreal y_3 = r.height() / 3; qreal x_2_3 = x_3 * 2; qreal y_2_3 = y_3 * 2; pts[0].setX (r.left() ); pts[0].setY( r.top() + y_3); pts[1].setX (r.left() + x_3 ); pts[1].setY( r.top()); pts[2].setX (r.left() + x_2_3 ); pts[2].setY( r.top()); pts[3].setX (r.right() ); pts[3].setY( r.top() + y_3); pts[4].setX (r.right() ); pts[4].setY( r.top() + y_2_3); pts[5].setX (r.left() + x_2_3 ); pts[5].setY( r.bottom()); pts[6].setX (r.left() + x_3 ); pts[6].setY( r.bottom()); pts[7].setX (r.left() ); pts[7].setY( r.top() + y_2_3); pts[8] = pts[0]; } /* ========================================================================= */ #define q_agfindattr(a,b) agfindattr( a, const_cast<char *>( b ) ) /* ------------------------------------------------------------------------- */ void GVzNode::paint( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget ) { Q_UNUSED (option); Q_UNUSED (widget); QPointF pts[16]; QRectF bb2; qreal a; if (dot_n_ == NULL) return; Agsym_t * atr_clr = q_agfindattr (dot_n_, "color"); Agsym_t * atr_fillclr = q_agfindattr (dot_n_, "fillcolor"); Agsym_t * atr_bgcolor = q_agfindattr (dot_n_, "bgcolor"); Agsym_t * atr_style = q_agfindattr (dot_n_, "style"); // Agsym_t * atr_fontcolor = q_agfindattr (dot_n_, "fontcolor"); // Agsym_t * atr_fontname = q_agfindattr (dot_n_, "fontname"); // Agsym_t * atr_fontsize = q_agfindattr (dot_n_, "fontsize"); // Agsym_t * atr_label = q_agfindattr (dot_n_, "label"); char * vl; if (atr_clr != NULL){ vl = agxget (dot_n_, atr_clr->index); painter->setPen (QColor( vl ).toRgb()); } if (atr_fillclr != NULL){ QBrush brs; vl = agxget (dot_n_, atr_fillclr->index); brs.setColor (QColor( vl )); brs.setStyle (Qt:: SolidPattern); painter->setBrush (brs); } if (atr_bgcolor != NULL){ /* ? where to use this? */ vl = agxget (dot_n_, atr_bgcolor->index); } if (atr_style != NULL){ /* ? where to use this? */ vl = agxget (dot_n_, atr_style->index); } QRectF bb = boundingRect(); if (isHighlited()) { painter->setPen (QColor( Qt::red )); painter->setBrush (QBrush( QColor( 0x00, 0xf5, 0xf5, 0x50 ) )); } /* draw based on provided shape */ switch ( shp_ ) { case SHP_RECT: case SHP_RECTANGLE: case SHP_SQUARE: case SHP_BOX: painter->drawRect (bb); break; case SHP_NONE: break; case SHP_MCIRCLE: { a = bb.height() / 8; bb2 = bb.adjusted( a, a, -a, -a); painter->drawEllipse (bb); painter->drawRect (bb2); break;} case SHP_MDIAMOND: case SHP_MSQUARE: { painter->drawRect (bb); pts[0].setX (bb.left() ); pts[0].setY( bb.top()+bb.height()/2); pts[1].setX (bb.left()+bb.width()/2 ); pts[1].setY( bb.top()); pts[2].setX (bb.right() ); pts[2].setY( pts[0].y()); pts[3].setX (pts[1].x() ); pts[3].setY( bb.bottom()); painter->drawConvexPolygon (&pts[0], 4); break;} case SHP_CIRCLE: case SHP_ELLIPSE: case SHP_OVAL: case SHP_EGG: painter->drawEllipse (bb); break; case SHP_DOUBLECIRCLE: { a = 2;//bb.width() / 10; bb2 = bb.adjusted( a, a, -a, -a); painter->drawEllipse (bb); painter->drawEllipse (bb2); break;} case SHP_BOX3D: { a = bb.width() / 8; bb2 = bb.adjusted (0, a, -a, 0); painter->drawRect (bb2); pts[0].setX (bb2.left() ); pts[0].setY( bb2.top()); pts[1].setX (bb2.left()+a ); pts[1].setY( bb.top()); pts[2].setX (bb.right() ); pts[2].setY( bb.top()); pts[3].setX (bb.right() ); pts[3].setY( bb2.bottom()-a); pts[4].setX (bb2.right() ); pts[4].setY( bb2.bottom()); painter->drawPolyline (&pts[0], 5); painter->drawLine (pts[2], bb2.topRight()); break;} case SHP_COMPONENT: { a = bb.width() / 12; bb2 = bb.adjusted (a, 0, 0, 0); painter->drawRect (bb2); bb2 = QRectF (bb.left(), bb.top()+a, a*2, a); painter->drawRect (bb2); bb2.translate (0, bb.height() - a*3); painter->drawRect (bb2); break;} case SHP_DIAMOND: { pts[0].setX (bb.left() ); pts[0].setY( bb.top()+bb.height()/2); pts[1].setX (bb.left()+bb.width()/2 ); pts[1].setY( bb.top()); pts[2].setX (bb.right() ); pts[2].setY( pts[0].y()); pts[3].setX (pts[1].x() ); pts[3].setY( bb.bottom()); painter->drawConvexPolygon (&pts[0], 4); break;} case SHP_TRIPLEOCTAGON: { a = bb.height() / 16; bb2 = bb.adjusted (a, a, -a, -a); octogonInRect (bb, &pts[0]); painter->drawPolyline (&pts[0], 9); octogonInRect (bb2, &pts[0]); painter->drawPolyline (&pts[0], 9); bb2 = bb2.adjusted (a, a, -a, -a); octogonInRect (bb2, &pts[0]); painter->drawConvexPolygon (&pts[0], 8); break;} case SHP_DOUBLEOCTAGON: { a = bb.height() / 16; bb2 = bb.adjusted (a, a, -a, -a); octogonInRect (bb, &pts[0]); painter->drawPolyline (&pts[0], 9); octogonInRect (bb2, &pts[0]); painter->drawConvexPolygon (&pts[0], 8); break;} case SHP_OCTAGON: { octogonInRect (bb, &pts[0]); painter->drawConvexPolygon (&pts[0], 8); break;} case SHP_HEXAGON: { a = bb.height() / 2; pts[0].setX (bb.left() ); pts[0].setY( bb.top()+a); pts[1].setX (bb.left()+a ); pts[1].setY( bb.top()); pts[2].setX (bb.right()-a ); pts[2].setY( bb.top()); pts[3].setX (bb.right() ); pts[3].setY( bb.top()+a); pts[4].setX (bb.right()-a ); pts[4].setY( bb.bottom()); pts[5].setX (bb.left()+a ); pts[5].setY( bb.bottom()); painter->drawConvexPolygon (&pts[0], 6); break;} case SHP_HOUSE: { a = bb.height() / 3; pts[0].setX (bb.left() ); pts[0].setY( bb.top()+a); pts[1].setX (bb.left()+bb.width()/2 ); pts[1].setY( bb.top()); pts[2].setX (bb.right() ); pts[2].setY( bb.top()+a); pts[3].setX (bb.right() ); pts[3].setY( bb.bottom()); pts[4].setX (bb.left() ); pts[4].setY( bb.bottom()); painter->drawConvexPolygon (&pts[0], 5); break;} case SHP_INVHOUSE: { a = bb.height() / 3; pts[0].setX (bb.left() ); pts[0].setY( bb.bottom()-a); pts[1].setX (bb.left()+bb.width()/2 ); pts[1].setY( bb.bottom()); pts[2].setX (bb.right() ); pts[2].setY( bb.bottom()-a); pts[3].setX (bb.right() ); pts[3].setY( bb.top()); pts[4].setX (bb.left() ); pts[4].setY( bb.top()); painter->drawConvexPolygon (&pts[0], 5); break;} case SHP_TRIANGLE: { pts[0].setX (bb.left() ); pts[0].setY( bb.bottom()); pts[1].setX (bb.left()+bb.width()/2 ); pts[1].setY( bb.top()); pts[2].setX (bb.right() ); pts[2].setY( bb.bottom()); painter->drawConvexPolygon (&pts[0], 3); break;} case SHP_INVTRIANGLE: { pts[0].setX (bb.left() ); pts[0].setY( bb.top()); pts[1].setX (bb.left()+bb.width()/2 ); pts[1].setY( bb.bottom()); pts[2].setX (bb.right() ); pts[2].setY( bb.top()); painter->drawConvexPolygon (&pts[0], 3); break;} case SHP_TRAPEZIUM: { a = bb.width() / 8; pts[0].setX (bb.left() ); pts[0].setY( bb.bottom()); pts[1].setX (bb.left()+a ); pts[1].setY( bb.top()); pts[2].setX (bb.right()-a ); pts[2].setY( bb.top()); pts[3].setX (bb.right() ); pts[3].setY( bb.bottom()); pts[4] = pts[0]; painter->drawConvexPolygon (&pts[0], 4); break;} case SHP_INVTRAPEZIUM: { a = bb.width() / 8; pts[0].setX (bb.left() ); pts[0].setY( bb.top()); pts[1].setX (bb.left()+a ); pts[1].setY( bb.bottom()); pts[2].setX (bb.right()-a ); pts[2].setY( bb.bottom()); pts[3].setX (bb.right() ); pts[3].setY( bb.top()); painter->drawConvexPolygon (&pts[0], 4); break;} case SHP_NOTE: { a = bb.width() / 8; pts[0].setX (bb.left() ); pts[0].setY( bb.top()); pts[1].setX (bb.right()-a ); pts[1].setY( bb.top()); pts[2].setX (bb.right() ); pts[2].setY( bb.top()+a); pts[3].setX (bb.right() ); pts[3].setY( bb.bottom()); pts[4].setX (bb.left() ); pts[4].setY( bb.bottom()); painter->drawConvexPolygon (&pts[0], 5); pts[3] = pts[2]; pts[2].setX (pts[1].x()); /* y already == to 3.y) */ painter->drawPolyline (&pts[1], 3); break;} case SHP_PLAINTEXT: break; case SHP_PARALLELOGRAM: { a = bb.width() / 8; pts[0].setX (bb.left() ); pts[0].setY( bb.bottom()); pts[1].setX (bb.left()+a ); pts[1].setY( bb.top()); pts[2].setX (bb.right() ); pts[2].setY( bb.top()); pts[3].setX (bb.right()-a ); pts[3].setY( bb.bottom()); painter->drawConvexPolygon (&pts[0], 4); break;} case SHP_POLYGON: case SHP_SEPTAGON: { qreal a_1_3 = bb.height() / 3; qreal a_2_3 = a_1_3 * 2; pts[0].setX (bb.left() ); pts[0].setY( bb.top()+a_2_3); pts[1].setX (bb.left()+a_1_3/2 ); pts[1].setY( bb.top()+a_1_3/2); pts[2].setX (bb.left()+bb.width()/2 ); pts[2].setY( bb.top()); pts[3].setX (bb.right()-a_1_3/2 ); pts[3].setY( pts[1].y()); pts[4].setX (bb.right() ); pts[4].setY( pts[0].y()); pts[5].setX (bb.right()-a_1_3 ); pts[5].setY( bb.bottom()); pts[6].setX (bb.left()+a_1_3 ); pts[6].setY( bb.bottom()); painter->drawConvexPolygon (&pts[0], 7); break;} case SHP_POINT: { painter->drawEllipse (bb); break;} case SHP_PENTAGON: { a = bb.height() / 3; pts[0].setX (bb.left() ); pts[0].setY( bb.top()+a); pts[1].setX (bb.left()+bb.width()/2 ); pts[1].setY( bb.top()); pts[2].setX (bb.right() ); pts[2].setY( bb.top()+a); pts[3].setX (bb.right()-a ); pts[3].setY( bb.bottom()); pts[4].setX (bb.left()+a ); pts[4].setY( bb.bottom()); painter->drawConvexPolygon (&pts[0], 5); break;} case SHP_FOLDER: { qreal a = bb.width() / 8; QRectF bb2 (bb.right()-a*2, bb.top(), a*2, a); painter->drawRect (bb); painter->drawRect (bb2); break;} case SHP_TAB: { qreal a = bb.width() / 8; QRectF bb2 (bb.left(), bb.top(), a*2, a); painter->drawRect (bb); painter->drawRect (bb2); break;} default: painter->drawRoundedRect (bb, 5, 5); } /* the label */ textlabel_t * tl = ND_label (dot_n_); QString lbl = tl->text; if (tl->html) { /** @todo html rendering */ } else { } if (lbl.isEmpty() == false) { painter->setPen (QColor( tl->fontcolor ).toRgb()); QFont f = painter->font(); f.setFamily (tl->fontname); f.setPointSize (tl->fontsize); painter->setFont (f); QTextOption to; to.setWrapMode (QTextOption::WordWrap); Qt::AlignmentFlag align; switch ( tl->valign ) { case 't': align = Qt::AlignTop; break; case 'b': align = Qt::AlignBottom; break; default: align = Qt::AlignVCenter; } /* stuuuuuupid */ align = (Qt::AlignmentFlag) (0x0004 | align); to.setAlignment (align); lbl.replace ("\\N", "\n", Qt::CaseInsensitive); lbl.replace ("\\T", "\t", Qt::CaseInsensitive); lbl.replace ("\\R", "\r", Qt::CaseInsensitive); lbl.replace ("\\\\", "\\"); painter->drawText (bb, lbl, to); } // if (atr_label != NULL){ // vl = agxget (dot_n_, atr_label->index); // if (atr_fontcolor != NULL){ // vl = agxget (dot_n_, atr_fontcolor->index); // painter->setPen (QColor( vl ).toRgb()); // } // if (atr_fontname != NULL){ // vl = agxget (dot_n_, atr_fontname->index); // QFont f = painter->font(); // f.setFamily (vl); // painter->setFont (f); // } // if (atr_fontsize != NULL){ // vl = agxget (dot_n_, atr_fontsize->index); // QFont f = painter->font(); // a = QString (vl ).toDouble( &b_ok); // if (b_ok && ( a > 1 )) // { // f.setPointSize (a); // painter->setFont (f); // } // } } /* ========================================================================= */ /* ------------------------------------------------------------------------- */ void GVzNode::updateCachedData () { if (dot_n_ == NULL) return; /* position */ pointf center = ND_coord (dot_n_); setPos (center.x, -center.y); /* shape */ shape_desc * shp = ND_shape (dot_n_); shp_ = SHP_UDEF; if (shp->usershape == false) { int i; int j; for ( i = 0; ; i++ ) { if (shape_names[i] == NULL) { break; } j = strcmp (shape_names[i], shp->name); if (j == 0) { shp_ = (NdShape)i; break; } else if (j > 0) { break; } } } } /* ========================================================================= */ /* ------------------------------------------------------------------------- */ QList<GVzNode*> GVzNode::nodes () const { QList<GVzNode*> l_nodes; GVzEdge * edg; foreach( edg, edg_l_ ) { GVzNode * nd = edg->destination(); if (nd != NULL) { l_nodes.append (nd); } } return l_nodes; } /* ========================================================================= */ /* ------------------------------------------------------------------------- */ void GVzNode::setHighlite (bool b_sts) { if (b_sts) { st_lst_ = (States) (st_lst_ | ST_HIGHLITE); } else { st_lst_ = (States) (st_lst_ & (~ST_HIGHLITE)); } update(); } /* ========================================================================= */ #endif // DE_WITH_GRAPHVIZ /* CLASS =============================================================== */ // // // // /* ------------------------------------------------------------------------- */ /* ========================================================================= */ /* graph with color */ /* digraph graph_name { node [ style = filled fillcolor = "#FCE975" color ="#ff007f" fontcolor="#005500" ] a -> b } */ /* test graph for node shapes */ /* digraph shapes_test { node_Mcircle [ shape=Mcircle label="Mcircle" ] node_Mdiamond [ shape=Mdiamond label="Mdiamond" ] node_Msquare [ shape=Msquare label="Msquare" ] node_box [ shape=box label="box" ] node_box3d [ shape=box3d label="box3d" ] node_circle [ shape=circle label="circle" ] node_component [ shape=component label="component" ] node_diamond [ shape=diamond label="diamond" ] node_doublecircle [ shape=doublecircle label="doublecircle" ] node_doubleoctagon [ shape=doubleoctagon label="doubleoctagon" ] node_egg [ shape=egg label="egg" ] node_ellipse [ shape=ellipse label="ellipse" ] node_folder [ shape=folder label="folder" ] node_hexagon [ shape=hexagon label="hexagon" ] node_house [ shape=house label="house" ] node_invhouse [ shape=invhouse label="invhouse" ] node_invtrapezium [ shape=invtrapezium label="invtrapezium" ] node_invtriangle [ shape=invtriangle label="invtriangle" ] node_none [ shape=none label="none" ] node_note [ shape=note label="note" ] node_octagon [ shape=octagon label="octagon" ] node_oval [ shape=oval label="oval" ] node_parallelogram [ shape=parallelogram label="parallelogram" ] node_pentagon [ shape=pentagon label="pentagon" ] node_plaintext [ shape=plaintext label="plaintext" ] node_point [ shape=point label="point" ] node_polygon [ shape=polygon label="polygon" ] node_rect [ shape=rect label="rect" ] node_rectangle [ shape=rectangle label="rectangle" ] node_septagon [ shape=septagon label="septagon" ] node_square [ shape=square label="square" ] node_tab [ shape=tab label="tab" ] node_trapezium [ shape=trapezium label="trapezium" ] node_triangle [ shape=triangle label="triangle" ] node_tripleoctagon [ shape=tripleoctagon label="tripleoctagon" ] } */
22.009423
79
0.505031
flyfire100
cd8b1e066b48e12c8309f635958842cfc37e95c6
5,902
cpp
C++
apps/interpolate_generator/interpolate_generator.cpp
Neo-Vincent/Halide
50c40dc185b040b93f1a90b6373a82744312cfd6
[ "MIT" ]
null
null
null
apps/interpolate_generator/interpolate_generator.cpp
Neo-Vincent/Halide
50c40dc185b040b93f1a90b6373a82744312cfd6
[ "MIT" ]
null
null
null
apps/interpolate_generator/interpolate_generator.cpp
Neo-Vincent/Halide
50c40dc185b040b93f1a90b6373a82744312cfd6
[ "MIT" ]
null
null
null
#include "Halide.h" namespace { class Interpolate : public Halide::Generator<Interpolate> { public: GeneratorParam<int> levels_{"levels", 10}; Input<Buffer<float>> input_{"input", 3}; Output<Buffer<float>> output_{"output", 3}; void generate() { Var x("x"), y("y"), c("c"); const int levels = levels_; // Input must have four color channels - rgba input_.dim(2).set_bounds(0, 4); Func downsampled[levels]; Func downx[levels]; Func interpolated[levels]; Func upsampled[levels]; Func upsampledx[levels]; Func clamped = Halide::BoundaryConditions::repeat_edge(input_); downsampled[0](x, y, c) = select(c < 3, clamped(x, y, c) * clamped(x, y, 3), clamped(x, y, 3)); for (int l = 1; l < levels; ++l) { Func prev = downsampled[l-1]; if (l == 4) { // Also add a boundary condition at a middle pyramid level // to prevent the footprint of the downsamplings to extend // too far off the base image. Otherwise we look 512 // pixels off each edge. Expr w = input_.width()/(1 << l); Expr h = input_.height()/(1 << l); prev = lambda(x, y, c, prev(clamp(x, 0, w), clamp(y, 0, h), c)); } downx[l](x, y, c) = (prev(x*2-1, y, c) + 2.0f * prev(x*2, y, c) + prev(x*2+1, y, c)) * 0.25f; downsampled[l](x, y, c) = (downx[l](x, y*2-1, c) + 2.0f * downx[l](x, y*2, c) + downx[l](x, y*2+1, c)) * 0.25f; } interpolated[levels-1](x, y, c) = downsampled[levels-1](x, y, c); for (int l = levels-2; l >= 0; --l) { upsampledx[l](x, y, c) = (interpolated[l+1](x/2, y, c) + interpolated[l+1]((x+1)/2, y, c)) / 2.0f; upsampled[l](x, y, c) = (upsampledx[l](x, y/2, c) + upsampledx[l](x, (y+1)/2, c)) / 2.0f; interpolated[l](x, y, c) = downsampled[l](x, y, c) + (1.0f - downsampled[l](x, y, 3)) * upsampled[l](x, y, c); } Func normalize("normalize"); normalize(x, y, c) = interpolated[0](x, y, c) / interpolated[0](x, y, 3); // Schedule if (auto_schedule) { output_ = normalize; } else { Var yo, yi, xo, xi, ci; if (get_target().has_gpu_feature()) { // Some gpus don't have enough memory to process the entire // image, so we process the image in tiles. // We can't compute the entire output stage at once on the GPU // - it takes too much GPU memory on some of our build bots, // so we wrap the final stage in a CPU stage. Func cpu_wrapper = normalize.in(); cpu_wrapper .reorder(c, x, y) .bound(c, 0, 3) .tile(x, y, xo, yo, xi, yi, input_.width()/4, input_.height()/4) .vectorize(xi, 8); normalize .compute_at(cpu_wrapper, xo) .reorder(c, x, y) .gpu_tile(x, y, xi, yi, 16, 16) .unroll(c); // Start from level 1 to save memory - level zero will be computed on demand for (int l = 1; l < levels; ++l) { int tile_size = 32 >> l; if (tile_size < 1) tile_size = 1; if (tile_size > 8) tile_size = 8; downsampled[l] .compute_root() .gpu_tile(x, y, c, xi, yi, ci, tile_size, tile_size, 4); if (l == 1 || l == 4) { interpolated[l] .compute_at(cpu_wrapper, xo) .gpu_tile(x, y, c, xi, yi, ci, 8, 8, 4); } else { int parent = l > 4 ? 4 : 1; interpolated[l] .compute_at(interpolated[parent], x) .gpu_threads(x, y, c); } } // The cpu wrapper is our new output Func output_ = cpu_wrapper; } else { for (int l = 1; l < levels-1; ++l) { downsampled[l] .compute_root() .parallel(y, 8) .vectorize(x, 4); interpolated[l] .compute_root() .parallel(y, 8) .unroll(x, 2) .unroll(y, 2) .vectorize(x, 8); } normalize .reorder(c, x, y) .bound(c, 0, 3) .unroll(c) .tile(x, y, xi, yi, 2, 2) .unroll(xi) .unroll(yi) .parallel(y, 8) .vectorize(x, 8) .bound(x, 0, input_.width()) .bound(y, 0, input_.height()); output_ = normalize; } } // Estimates (for autoscheduler; ignored otherwise) { input_.dim(0).set_bounds_estimate(0, 1536) .dim(1).set_bounds_estimate(0, 2560) .dim(2).set_bounds_estimate(0, 4); output_.dim(0).set_bounds_estimate(0, 1536) .dim(1).set_bounds_estimate(0, 2560) .dim(2).set_bounds_estimate(0, 3); } } }; } // namespace HALIDE_REGISTER_GENERATOR(Interpolate, interpolate)
38.575163
122
0.420535
Neo-Vincent
cd8c5901bf224cd114a7c090461f91041992d6d8
2,340
cpp
C++
nntrainer/layers/addition_layer.cpp
JuYeong0413/nntrainer
37b7c2234dd591a994148d14dd399037702ccd31
[ "Apache-2.0" ]
null
null
null
nntrainer/layers/addition_layer.cpp
JuYeong0413/nntrainer
37b7c2234dd591a994148d14dd399037702ccd31
[ "Apache-2.0" ]
null
null
null
nntrainer/layers/addition_layer.cpp
JuYeong0413/nntrainer
37b7c2234dd591a994148d14dd399037702ccd31
[ "Apache-2.0" ]
null
null
null
// SPDX-License-Identifier: Apache-2.0 /** * Copyright (C) 2020 Parichay Kapoor <pk.kapoor@samsung.com> * * @file addition_layer.cpp * @date 30 July 2020 * @see https://github.com/nnstreamer/nntrainer * @author Parichay Kapoor <pk.kapoor@samsung.com> * @bug No known bugs except for NYI items * @brief This is Addition Layer Class for Neural Network * */ #include <addition_layer.h> #include <layer_internal.h> #include <nntrainer_error.h> #include <nntrainer_log.h> #include <parse_util.h> #include <util_func.h> namespace nntrainer { int AdditionLayer::initialize(Manager &manager) { int status = ML_ERROR_NONE; if (getNumInputs() == 0) { ml_loge("Error: number of inputs are not initialized"); return ML_ERROR_INVALID_PARAMETER; } for (unsigned int idx = 0; idx < getNumInputs(); ++idx) { if (input_dim[idx].getDataLen() == 1) { ml_logw("Warning: the length of previous layer dimension is one"); } } /** input dimension indicates the dimension for all the inputs to follow */ output_dim[0] = input_dim[0]; return status; } void AdditionLayer::forwarding(bool training) { Tensor &hidden_ = net_hidden[0]->getVariableRef(); TensorDim &in_dim = input_dim[0]; /** @todo check possibility for in-place of addition layer */ for (unsigned int idx = 0; idx < getNumInputs(); ++idx) { if (in_dim != net_input[idx]->getDim()) throw std::invalid_argument("Error: addition layer requires same " "shape from all input layers"); if (!idx) { hidden_.fill(net_input[idx]->getVariableRef(), false); } else { hidden_.add_i(net_input[idx]->getVariableRef()); } } } void AdditionLayer::calcDerivative() { for (unsigned int i = 0; i < getNumInputs(); ++i) { net_input[i]->getGradientRef() = net_hidden[0]->getGradientRef(); } } void AdditionLayer::setProperty(const PropertyType type, const std::string &value) { int status = ML_ERROR_NONE; switch (type) { case PropertyType::num_inputs: { if (!value.empty()) { unsigned int num_inputs; status = setUint(num_inputs, value); throw_status(status); setNumInputs(num_inputs); } } break; default: LayerV1::setProperty(type, value); break; } } } /* namespace nntrainer */
27.209302
77
0.654274
JuYeong0413
cd8c8e2fa39b6ec4c06e41041c36c41a2d2d183a
684
hpp
C++
door.hpp
thatoddmailbox/duck_hero
d96e379491b165dc0bb868ab2a0e4ef6f2365986
[ "MIT" ]
1
2021-02-19T05:09:10.000Z
2021-02-19T05:09:10.000Z
door.hpp
thatoddmailbox/duck_hero
d96e379491b165dc0bb868ab2a0e4ef6f2365986
[ "MIT" ]
2
2021-02-18T22:13:47.000Z
2021-02-18T22:30:41.000Z
door.hpp
thatoddmailbox/duck_hero
d96e379491b165dc0bb868ab2a0e4ef6f2365986
[ "MIT" ]
null
null
null
#ifndef _DOOR_HPP #define _DOOR_HPP #include <string> #include <vector> #include "content.hpp" #include "entity.hpp" namespace duckhero { struct DoorInfo { int x; int y; std::string map; }; class Door : public Entity { private: SDL_Texture * _texture; public: int key_id; bool unlocked; Door(); Door(const Door& other); Door& operator=(const Door& other); ~Door(); std::string GetSpritePath() override; SDL_Rect GetCollisionBox(int x, int y) override; bool CanInteract() override; void Interact(void * level_screen_pointer) override; void Update() override; void Draw(SDL_Renderer * r, int x_offset, int y_offset) override; }; } #endif
15.906977
67
0.695906
thatoddmailbox
cd8f7b5fd3faf3c17f80fc55481d60d0cea0818c
923
cpp
C++
PythonAPI/source/libcarla/Client.cpp
AbdulHoffmann/carla_carissma
8d382769ffa02a6c61a22c57160285505f5ff0a4
[ "MIT" ]
201
2019-07-03T05:55:58.000Z
2022-03-30T00:22:09.000Z
PythonAPI/source/libcarla/Client.cpp
AbdulHoffmann/carla_carissma
8d382769ffa02a6c61a22c57160285505f5ff0a4
[ "MIT" ]
33
2019-08-05T01:51:26.000Z
2022-03-11T03:51:07.000Z
PythonAPI/source/libcarla/Client.cpp
AbdulHoffmann/carla_carissma
8d382769ffa02a6c61a22c57160285505f5ff0a4
[ "MIT" ]
48
2019-09-24T17:02:31.000Z
2022-01-31T22:42:01.000Z
// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma // de Barcelona (UAB). // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #include <carla/PythonUtil.h> #include <carla/client/Client.h> #include <carla/client/World.h> static void SetTimeout(carla::client::Client &client, double seconds) { client.SetTimeout(TimeDurationFromSeconds(seconds)); } void export_client() { using namespace boost::python; namespace cc = carla::client; class_<cc::Client>("Client", init<std::string, uint16_t, size_t>((arg("host"), arg("port"), arg("worker_threads")=0u))) .def("set_timeout", &::SetTimeout, (arg("seconds"))) .def("get_client_version", &cc::Client::GetClientVersion) .def("get_server_version", CONST_CALL_WITHOUT_GIL(cc::Client, GetServerVersion)) .def("get_world", &cc::Client::GetWorld) ; }
34.185185
96
0.707476
AbdulHoffmann
cd8fa8c00674c099ddf78cc280e7623064b148da
501
cpp
C++
001_GFG/Data-Structures-And-Algorithms-Self-Paced/007_ Matrix/Practice/rotate_by_90_Anti_clockwise.cpp
Sahil1515/coding
2bd2a2257c8cac5a5c00b37e79bbb68a24e186d4
[ "RSA-MD" ]
null
null
null
001_GFG/Data-Structures-And-Algorithms-Self-Paced/007_ Matrix/Practice/rotate_by_90_Anti_clockwise.cpp
Sahil1515/coding
2bd2a2257c8cac5a5c00b37e79bbb68a24e186d4
[ "RSA-MD" ]
null
null
null
001_GFG/Data-Structures-And-Algorithms-Self-Paced/007_ Matrix/Practice/rotate_by_90_Anti_clockwise.cpp
Sahil1515/coding
2bd2a2257c8cac5a5c00b37e79bbb68a24e186d4
[ "RSA-MD" ]
null
null
null
class Solution { public: void rotateby90(vector<vector<int> >& matrix, int n) { // code here for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { swap(matrix[i][j],matrix[j][i]); } } for(int i=0;i<n;i++) { int j=0,k=n-1; while(j<k) { swap(matrix[j][i],matrix[k][i]); j++;k--; } } } };
18.555556
57
0.313373
Sahil1515
cd8faad5e9dc5f4f558502afc6e49c8b4806ac9b
749
hpp
C++
hhhaha/emmm/load_data_test.hpp
sublimationAC/DDE
fcde429b0db65100b8bd8bf607626b6beff8a431
[ "MIT" ]
null
null
null
hhhaha/emmm/load_data_test.hpp
sublimationAC/DDE
fcde429b0db65100b8bd8bf607626b6beff8a431
[ "MIT" ]
1
2019-01-05T06:12:34.000Z
2019-01-08T06:20:18.000Z
hhhaha/load_data_test.hpp
sublimationAC/DDE
fcde429b0db65100b8bd8bf607626b6beff8a431
[ "MIT" ]
null
null
null
#pragma once #include "dde_x.h" void load_land_coef(std::string &path, std::string sfx, std::vector<DataPoint> &img); void load_land(std::string p, DataPoint &temp); void load_img(std::string p, DataPoint &temp); void load_land(std::string p, DataPoint &temp); void cal_rect(DataPoint &temp); void load_fitting_coef_one(std::string name, DataPoint &temp); void load_bldshps(Eigen::MatrixXf &bldshps, std::string &name, Eigen::VectorXf &ide_sg_vl, std::string sg_vl_path); void load_inner_land_corr(Eigen::VectorXi &cor); void load_jaw_land_corr(Eigen::VectorXi &jaw_cor); void load_slt( std::vector <int> *slt_line, std::vector<std::pair<int, int> > *slt_point_rect, std::string path_slt, std::string path_rect);
29.96
116
0.727637
sublimationAC
cd8fab720c114d338d43d5f8dfc6cb4c66f260ea
3,128
cc
C++
content/renderer/devtools/devtools_agent_filter.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-05-24T13:52:28.000Z
2021-05-24T13:53:10.000Z
content/renderer/devtools/devtools_agent_filter.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/renderer/devtools/devtools_agent_filter.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2018-03-12T07:58:10.000Z
2019-08-31T04:53:58.000Z
// Copyright (c) 2012 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 "content/renderer/devtools/devtools_agent_filter.h" #include "base/bind.h" #include "content/child/child_process.h" #include "content/common/devtools_messages.h" #include "content/renderer/devtools/devtools_agent.h" #include "third_party/WebKit/public/platform/WebString.h" #include "third_party/WebKit/public/web/WebDevToolsAgent.h" using blink::WebDevToolsAgent; using blink::WebString; namespace content { namespace { class MessageImpl : public WebDevToolsAgent::MessageDescriptor { public: MessageImpl( const std::string& method, const std::string& message, int routing_id) : method_(method), msg_(message), routing_id_(routing_id) { } ~MessageImpl() override {} WebDevToolsAgent* Agent() override { DevToolsAgent* agent = DevToolsAgent::FromRoutingId(routing_id_); if (!agent) return 0; return agent->GetWebAgent(); } WebString Message() override { return WebString::FromUTF8(msg_); } WebString Method() override { return WebString::FromUTF8(method_); } private: std::string method_; std::string msg_; int routing_id_; }; } // namespace DevToolsAgentFilter::DevToolsAgentFilter() : io_task_runner_(ChildProcess::current()->io_task_runner()), current_routing_id_(0) {} bool DevToolsAgentFilter::OnMessageReceived(const IPC::Message& message) { // Dispatch debugger commands directly from IO. current_routing_id_ = message.routing_id(); IPC_BEGIN_MESSAGE_MAP(DevToolsAgentFilter, message) IPC_MESSAGE_HANDLER(DevToolsAgentMsg_DispatchOnInspectorBackend, OnDispatchOnInspectorBackend) IPC_END_MESSAGE_MAP() return false; } DevToolsAgentFilter::~DevToolsAgentFilter() {} void DevToolsAgentFilter::OnDispatchOnInspectorBackend( int session_id, int call_id, const std::string& method, const std::string& message) { if (embedded_worker_routes_.find(current_routing_id_) != embedded_worker_routes_.end()) { return; } if (WebDevToolsAgent::ShouldInterruptForMethod(WebString::FromUTF8(method))) { WebDevToolsAgent::InterruptAndDispatch( session_id, new MessageImpl(method, message, current_routing_id_)); } } void DevToolsAgentFilter::AddEmbeddedWorkerRouteOnMainThread( int32_t routing_id) { io_task_runner_->PostTask( FROM_HERE, base::Bind(&DevToolsAgentFilter::AddEmbeddedWorkerRoute, this, routing_id)); } void DevToolsAgentFilter::RemoveEmbeddedWorkerRouteOnMainThread( int32_t routing_id) { io_task_runner_->PostTask( FROM_HERE, base::Bind(&DevToolsAgentFilter::RemoveEmbeddedWorkerRoute, this, routing_id)); } void DevToolsAgentFilter::AddEmbeddedWorkerRoute(int32_t routing_id) { embedded_worker_routes_.insert(routing_id); } void DevToolsAgentFilter::RemoveEmbeddedWorkerRoute(int32_t routing_id) { embedded_worker_routes_.erase(routing_id); } } // namespace content
30.076923
80
0.73977
metux
cd8fadcce60260cb7a509d309b720f757dfec3b9
39,201
cpp
C++
custom_conf/etc/calamares/3rdparty/kdsingleapplicationguard/kdsingleapplicationguard.cpp
ix-os/IXOS
840abf7e022f46073d898fed5adb667bb5cb7166
[ "CC0-1.0" ]
null
null
null
custom_conf/etc/calamares/3rdparty/kdsingleapplicationguard/kdsingleapplicationguard.cpp
ix-os/IXOS
840abf7e022f46073d898fed5adb667bb5cb7166
[ "CC0-1.0" ]
13
2020-07-30T19:55:36.000Z
2020-12-07T16:57:23.000Z
custom_conf/etc/calamares/3rdparty/kdsingleapplicationguard/kdsingleapplicationguard.cpp
ix-os/IXOS
840abf7e022f46073d898fed5adb667bb5cb7166
[ "CC0-1.0" ]
null
null
null
/* * SPDX-License-Identifier: LGPL-2.0-only * License-Filename: LICENSES/LGPLv2-KDAB * * The KD Tools Library is Copyright (C) 2001-2010 Klaralvdalens Datakonsult AB. */ #include "kdsingleapplicationguard.h" #if QT_VERSION >= 0x040400 || defined(DOXYGEN_RUN) #ifndef QT_NO_SHAREDMEMORY #include "kdsharedmemorylocker.h" #include "kdlockedsharedmemorypointer.h" #include <QVector> #include <QCoreApplication> #include <QSharedMemory> #include <QSharedData> #include <QBasicTimer> #include <QElapsedTimer> #include <QTime> #include <algorithm> #include <limits> #include <cstdlib> #include <cstring> #include <cassert> #ifndef Q_WS_WIN #include <csignal> #include <unistd.h> #endif #ifdef Q_WS_WIN #include <windows.h> #ifndef _SSIZE_T_DEFINED typedef signed int ssize_t; #endif #endif using namespace kdtools; #ifndef KDSINGLEAPPLICATIONGUARD_TIMEOUT_SECONDS #define KDSINGLEAPPLICATIONGUARD_TIMEOUT_SECONDS 10 #endif #ifndef KDSINGLEAPPLICATIONGUARD_NUMBER_OF_PROCESSES #define KDSINGLEAPPLICATIONGUARD_NUMBER_OF_PROCESSES 10 #endif #ifndef KDSINGLEAPPLICATIONGUARD_MAX_COMMAND_LINE #define KDSINGLEAPPLICATIONGUARD_MAX_COMMAND_LINE 32768 #endif static unsigned int KDSINGLEAPPLICATIONGUARD_SHM_VERSION = 0; Q_GLOBAL_STATIC_WITH_ARGS( int, registerInstanceType, (qRegisterMetaType<KDSingleApplicationGuard::Instance>()) ) /*! \class KDSingleApplicationGuard::Instance \relates KDSingleApplicationGuard \ingroup core \brief Information about instances a KDSingleApplicationGuard knows about Instance represents instances of applications under KDSingleApplicationGuard protection, and allows access to their pid() and the arguments() they were started with. */ class KDSingleApplicationGuard::Instance::Private : public QSharedData { friend class ::KDSingleApplicationGuard::Instance; public: Private( const QStringList & args, bool truncated, qint64 pid ) : pid( pid ), arguments( args ), truncated( truncated ) {} private: qint64 pid; QStringList arguments; bool truncated; }; struct ProcessInfo; /*! \internal */ class KDSingleApplicationGuard::Private { friend class ::KDSingleApplicationGuard; friend class ::KDSingleApplicationGuard::Instance; friend struct ::ProcessInfo; KDSingleApplicationGuard * const q; public: Private( Policy policy, KDSingleApplicationGuard* qq ); ~Private(); void create( const QStringList& arguments ); bool checkOperational( const char * function, const char * act ) const; bool checkOperationalPrimary( const char * function, const char * act ) const; struct segmentheader { size_t size : 16; }; static void sharedmem_free( char* ); static char* sharedmem_malloc( size_t size ); private: void shutdownInstance(); void poll(); private: static KDSingleApplicationGuard* primaryInstance; private: QBasicTimer timer; QSharedMemory mem; int id; Policy policy; bool operational; bool exitRequested; }; /*! \internal */ KDSingleApplicationGuard::Instance::Instance( const QStringList & args, bool truncated, qint64 p ) : d( new Private( args, truncated, p ) ) { d->ref.ref(); (void)registerInstanceType(); } /*! Default constructor. Constructs in Instance that is \link isNull() null\endlink. \sa isNull() */ KDSingleApplicationGuard::Instance::Instance() : d( 0 ) {} /*! Copy constructor. */ KDSingleApplicationGuard::Instance::Instance( const Instance & other ) : d( other.d ) { if ( d ) d->ref.ref(); } /*! Destructor. */ KDSingleApplicationGuard::Instance::~Instance() { if ( d && !d->ref.deref() ) delete d; } /*! \fn KDSingleApplicationGuard::Instance::swap( Instance & other ) Swaps the contents of this and \a other. This function never throws exceptions. */ /*! \fn KDSingleApplicationGuard::Instance::operator=( Instance other ) Assigns the contents of \a other to this. This function is strongly exception-safe. */ /*! \fn std::swap( KDSingleApplicationGuard::Instance & lhs, KDSingleApplicationGuard::Instance & rhs ) \relates KDSingleApplicationGuard::Instance Specialisation of std::swap() for KDSingleApplicationGuard::Instance. Calls swap(). */ /*! \fn qSwap( KDSingleApplicationGuard::Instance & lhs, KDSingleApplicationGuard::Instance & rhs ) \relates KDSingleApplicationGuard::Instance Specialisation of qSwap() for KDSingleApplicationGuard::Instance. Calls swap(). */ /*! \fn KDSingleApplicationGuard::Instance::isNull() const Returns whether this instance is null. */ /*! Returns whether this instance is valid. A valid instance is neither null, nor does it have a negative PID. */ bool KDSingleApplicationGuard::Instance::isValid() const { return d && d->pid >= 0 ; } /*! Returns whether the #arguments are complete (\c false) or not (\c true), e.g. because they have been truncated due to limited storage space. \sa arguments() */ bool KDSingleApplicationGuard::Instance::areArgumentsTruncated() const { return d && d->truncated; } /*! Returns the arguments that this instance was started with. \sa areArgumentsTruncated() */ const QStringList & KDSingleApplicationGuard::Instance::arguments() const { if ( d ) return d->arguments; static const QStringList empty; return empty; } /*! Returns the process-id (PID) of this instance. */ qint64 KDSingleApplicationGuard::Instance::pid() const { if ( d ) return d->pid; else return -1; } /*! \class KDSingleApplicationGuard KDSingleApplicationGuard \ingroup core \brief A guard to protect an application from having several instances. KDSingleApplicationGuard can be used to make sure only one instance of an application is running at the same time. \note As KDSingleApplicationGuard currently uses QSharedMemory, Qt 4.4 or later is required. */ /*! \fn void KDSingleApplicationGuard::instanceStarted(const KDSingleApplicationGuard::Instance & instance) This signal is emitted by the primary instance whenever another instance \a instance started. */ /*! \fn void KDSingleApplicationGuard::instanceExited(const KDSingleApplicationGuard::Instance & instance) This signal is emitted by the primary instance whenever another instance \a instance exited. */ /*! \fn void KDSingleApplicationGuard::raiseRequested() This signal is emitted when the current running application is requested to raise its main window. */ /*! \fn void KDSingleApplicationGuard::exitRequested() This signal is emitted when the current running application has been asked to exit by calling kill on the instance. */ /*! \fn void KDSingleApplicationGuard::becamePrimaryInstance() This signal is emitted when the current running application becomes the new primary application. The old primary application has quit. */ /*! \fn void KDSingleApplicationGuard::becameSecondaryInstance() This signal is emmited when the primary instance became secondary instance. This happens when the instance doesn't update its status for some (default 10) seconds. Another instance got primary instance in that case. */ /*! \fn void KDSingleApplicationGuard::policyChanged( KDSingleApplicationGuard::Policy policy ) This signal is emitted when the #policy of the system changes. */ enum Command { NoCommand = 0x00, ExitedInstance = 0x01, NewInstance = 0x02, FreeInstance = 0x04, ShutDownCommand = 0x08, KillCommand = 0x10, BecomePrimaryCommand = 0x20, RaiseCommand = 0x40 }; static const quint16 PrematureEndOfOptions = -1; static const quint16 RegularEndOfOptions = -2; struct ProcessInfo { static const size_t MarkerSize = sizeof(quint16); explicit ProcessInfo( Command c = FreeInstance, const QStringList& arguments = QStringList(), qint64 p = -1 ) : pid( p ), command( c ), timestamp( 0 ), commandline( 0 ) { setArguments( arguments ); } void setArguments( const QStringList & arguments ); QStringList arguments( bool * prematureEnd ) const; qint64 pid; quint32 command; quint32 timestamp; char* commandline; }; static inline bool operator==( const ProcessInfo & lhs, const ProcessInfo & rhs ) { return lhs.command == rhs.command && ( lhs.commandline == rhs.commandline || ( lhs.commandline != 0 && rhs.commandline != 0 && ::strcmp( lhs.commandline, rhs.commandline ) == 0 ) ); } static inline bool operator!=( const ProcessInfo & lhs, const ProcessInfo & rhs ) { return !operator==( lhs, rhs ); } /*! This struct contains information about the managed process system. \internal */ struct InstanceRegister { explicit InstanceRegister( KDSingleApplicationGuard::Policy policy = KDSingleApplicationGuard::NoPolicy ) : policy( policy ), maxInstances( KDSINGLEAPPLICATIONGUARD_NUMBER_OF_PROCESSES ), version( 0 ) { std::fill_n( commandLines, KDSINGLEAPPLICATIONGUARD_MAX_COMMAND_LINE, 0 ); ::memcpy( magicCookie, "kdsingleapp", 12 ); } /*! Returns whether this register was properly initialized by the first instance. */ bool isValid() const { return ::strcmp( magicCookie, "kdsingleapp" ) == 0; } char magicCookie[ 12 ]; unsigned int policy : 8; quint32 maxInstances : 20; unsigned int version : 4; ProcessInfo info[ KDSINGLEAPPLICATIONGUARD_NUMBER_OF_PROCESSES ]; char commandLines[ KDSINGLEAPPLICATIONGUARD_MAX_COMMAND_LINE ]; Q_DISABLE_COPY( InstanceRegister ) }; void ProcessInfo::setArguments( const QStringList & arguments ) { if( commandline != 0 ) KDSingleApplicationGuard::Private::sharedmem_free( commandline ); commandline = 0; if( arguments.isEmpty() ) return; size_t totalsize = MarkerSize; for ( const QString& arg : arguments ) { const QByteArray utf8 = arg.toUtf8(); totalsize += utf8.size() + MarkerSize; } InstanceRegister* const reg = reinterpret_cast<InstanceRegister*>( KDSingleApplicationGuard::Private::primaryInstance->d->mem.data() ); this->commandline = KDSingleApplicationGuard::Private::sharedmem_malloc( totalsize ); if( this->commandline == 0 ) { qWarning("KDSingleApplicationguard: out of memory when trying to save arguments.\n"); return; } char* const commandline = this->commandline + reinterpret_cast<qptrdiff>(reg->commandLines); int argpos = 0; for ( const QString & arg : arguments ) { const QByteArray utf8 = arg.toUtf8(); const int required = MarkerSize + utf8.size() + MarkerSize ; const int available = KDSINGLEAPPLICATIONGUARD_MAX_COMMAND_LINE - argpos ; if ( required > available || utf8.size() > std::numeric_limits<quint16>::max() ) { // write a premature-eoo marker, and quit memcpy( commandline + argpos, &PrematureEndOfOptions, MarkerSize ); argpos += MarkerSize; qWarning( "KDSingleApplicationGuard: argument list is too long (bytes required: %d, used: %d, available: %d", required, argpos - 2, available ); return; } else { const quint16 len16 = utf8.size(); // write the size of the data... memcpy( commandline + argpos, &len16, MarkerSize ); argpos += MarkerSize; // then the data memcpy( commandline + argpos, utf8.data(), len16 ); argpos += len16; } } const ssize_t available = KDSINGLEAPPLICATIONGUARD_MAX_COMMAND_LINE - argpos; assert( available >= static_cast<ssize_t>( MarkerSize ) ); memcpy( commandline + argpos, &RegularEndOfOptions, MarkerSize ); argpos += MarkerSize; } QStringList ProcessInfo::arguments( bool * prematureEnd ) const { QStringList result; if( commandline == 0 ) { if( prematureEnd ) *prematureEnd = true; return result; } InstanceRegister* const reg = reinterpret_cast<InstanceRegister*>( KDSingleApplicationGuard::Private::primaryInstance->d->mem.data() ); const char* const commandline = this->commandline + reinterpret_cast<qptrdiff>(reg->commandLines); int argpos = 0; while ( true ) { const int available = KDSINGLEAPPLICATIONGUARD_MAX_COMMAND_LINE - argpos ; assert( available >= 2 ); quint16 marker; memcpy( &marker, commandline + argpos, MarkerSize ); argpos += MarkerSize; if ( marker == PrematureEndOfOptions ) { if ( prematureEnd ) *prematureEnd = true; break; } if ( marker == RegularEndOfOptions ) { if ( prematureEnd ) *prematureEnd = false; break; } const int requested = MarkerSize + marker + MarkerSize ; if ( requested > available ) { const long long int p = pid; qWarning( "KDSingleApplicationGuard: inconsistency detected when parsing command-line argument for process %lld", p ); if ( prematureEnd ) *prematureEnd = true; break; } result.push_back( QString::fromUtf8( commandline + argpos, marker ) ); argpos += marker; } return result; } KDSingleApplicationGuard::Private::~Private() { if( primaryInstance == q ) primaryInstance = 0; } bool KDSingleApplicationGuard::Private::checkOperational( const char * function, const char * act ) const { assert( function ); assert( act ); if ( !operational ) qWarning( "KDSingleApplicationGuard::%s: need to be operational to %s", function, act ); return operational; } bool KDSingleApplicationGuard::Private::checkOperationalPrimary( const char * function, const char * act ) const { if ( !checkOperational( function, act ) ) return false; if ( id != 0 ) qWarning( "KDSingleApplicationGuard::%s: need to be primary to %s", function, act ); return id == 0; } struct segmentheader { size_t size : 16; }; void KDSingleApplicationGuard::Private::sharedmem_free( char* pointer ) { InstanceRegister* const reg = reinterpret_cast<InstanceRegister*>( KDSingleApplicationGuard::Private::primaryInstance->d->mem.data() ); char* const heap = reg->commandLines; char* const heap_ptr = heap + reinterpret_cast<qptrdiff>(pointer) - sizeof( segmentheader ); const segmentheader* const header = reinterpret_cast< const segmentheader* >( heap_ptr ); const size_t size = header->size; char* end = heap + KDSINGLEAPPLICATIONGUARD_MAX_COMMAND_LINE; std::copy( heap_ptr + size, end, heap_ptr ); std::fill( end - size, end, 0 ); for( uint i = 0; i < reg->maxInstances; ++i ) { if( reg->info[ i ].commandline > pointer ) reg->info[ i ].commandline -= size + sizeof( segmentheader ); } } char* KDSingleApplicationGuard::Private::sharedmem_malloc( size_t size ) { InstanceRegister* const reg = reinterpret_cast<InstanceRegister*>( KDSingleApplicationGuard::Private::primaryInstance->d->mem.data() ); char* heap = reg->commandLines; while( heap + sizeof( segmentheader ) + size < reg->commandLines + KDSINGLEAPPLICATIONGUARD_MAX_COMMAND_LINE ) { segmentheader* const header = reinterpret_cast< segmentheader* >( heap ); if( header->size == 0 ) { header->size = size; return heap + sizeof( segmentheader ) - reinterpret_cast<qptrdiff>(reg->commandLines); } heap += sizeof( header ) + header->size; } return 0; } void KDSingleApplicationGuard::Private::shutdownInstance() { KDLockedSharedMemoryPointer< InstanceRegister > instances( &q->d->mem ); instances->info[ q->d->id ].command |= ExitedInstance; if( q->isPrimaryInstance() ) { // ohh... we need a new primary instance... for ( int i = 1, end = instances->maxInstances ; i < end ; ++i ) { if( ( instances->info[ i ].command & ( FreeInstance | ExitedInstance | ShutDownCommand | KillCommand ) ) == 0 ) { instances->info[ i ].command |= BecomePrimaryCommand; return; } } // none found? then my species is dead :-( } } KDSingleApplicationGuard* KDSingleApplicationGuard::Private::primaryInstance = 0; /*! Requests that the instance kills itself (by emitting exitRequested). If the instance has since exited, does nothing. \sa shutdown(), raise() */ void KDSingleApplicationGuard::Instance::kill() { KDLockedSharedMemoryPointer< InstanceRegister > instances( &KDSingleApplicationGuard::Private::primaryInstance->d->mem ); for ( int i = 0, end = instances->maxInstances ; i < end ; ++i ) { if( instances->info[ i ].pid != d->pid ) continue; if( ( instances->info[ i ].command & ( FreeInstance | ExitedInstance ) ) == 0 ) instances->info[ i ].command = KillCommand; } } /*! Requests that the instance shuts itself down (by calling QCoreApplication::quit()). If the instance has since exited, does nothing. \sa kill(), raise() */ void KDSingleApplicationGuard::Instance::shutdown() { KDLockedSharedMemoryPointer< InstanceRegister > instances( &KDSingleApplicationGuard::Private::primaryInstance->d->mem ); for ( int i = 0, end = instances->maxInstances ; i < end ; ++i ) { if( instances->info[ i ].pid != d->pid ) continue; if( ( instances->info[ i ].command & ( FreeInstance | ExitedInstance ) ) == 0 ) instances->info[ i ].command = ShutDownCommand; } } /*! Requests that the instance raises its main window. The effects are implementation-defined: the KDSingleApplicationGuard corresponding to the instance will emit its \link KDSingleApplicationGuard::raiseRequested() raiseRequested()\endlink signal. If the instance has since exited, does nothing. \sa kill(), shutdown() */ void KDSingleApplicationGuard::Instance::raise() { KDLockedSharedMemoryPointer< InstanceRegister > instances( &KDSingleApplicationGuard::Private::primaryInstance->d->mem ); for ( int i = 0, end = instances->maxInstances ; i < end ; ++i ) { if( instances->info[ i ].pid != d->pid ) continue; if( ( instances->info[ i ].command & ( FreeInstance | ExitedInstance ) ) == 0 ) instances->info[ i ].command = RaiseCommand; } } #ifndef Q_WS_WIN // static void KDSingleApplicationGuard::SIGINT_handler( int sig ) { if( sig == SIGINT && Private::primaryInstance != 0 ) Private::primaryInstance->d->shutdownInstance(); ::exit( 1 ); } #endif /*! \enum KDSingleApplicationGuard::Policy Defines the policy that a KDSingleApplicationGuard can enforce: */ /*! \var KDSingleApplicationGuard::NoPolicy instanceStarted() is emitted, and the new instance allowed to continue. */ /*! \var KDSingleApplicationGuard::AutoKillOtherInstances instanceStarted() is emitted, and the new instance is killed (Instance::kill()). */ /*! Creates a new KDSingleApplicationGuard with arguments QCoreApplication::arguments() and policy AutoKillOtherInstances, passing \a parent to the base class constructor, as usual. */ KDSingleApplicationGuard::KDSingleApplicationGuard( QObject * parent ) : QObject( parent ), d( new Private( AutoKillOtherInstances, this ) ) { d->create( QCoreApplication::arguments() ); } /*! Creates a new KDSingleApplicationGuard with arguments QCoreApplication::arguments() and policy \a policy, passing \a parent to the base class constructor, as usual. */ KDSingleApplicationGuard::KDSingleApplicationGuard( Policy policy, QObject * parent ) : QObject( parent ), d( new Private( policy, this ) ) { d->create( QCoreApplication::arguments() ); } /*! Creates a new KDSingleApplicationGuard with arguments \a arguments and policy AutoKillOtherInstances, passing \a parent to the base class constructor, as usual. */ KDSingleApplicationGuard::KDSingleApplicationGuard( const QStringList & arguments, QObject * parent ) : QObject( parent ), d( new Private( AutoKillOtherInstances, this ) ) { d->create( arguments ); } /*! Creates a new KDSingleApplicationGuard with arguments \a arguments and policy \a policy, passing \a parent to the base class constructor, as usual. */ KDSingleApplicationGuard::KDSingleApplicationGuard( const QStringList & arguments, Policy policy, QObject * parent ) : QObject( parent ), d( new Private( policy, this ) ) { d->create( arguments ); } KDSingleApplicationGuard::Private::Private( Policy policy_, KDSingleApplicationGuard * qq ) : q( qq ), id( -1 ), policy( policy_ ), operational( false ), exitRequested( false ) { } void KDSingleApplicationGuard::Private::create( const QStringList & arguments ) { if ( !QCoreApplication::instance() ) { qWarning( "KDSingleApplicationGuard: you need to construct a Q(Core)Application before you can construct a KDSingleApplicationGuard" ); return; } const QString name = QCoreApplication::applicationName(); if ( name.isEmpty() ) { qWarning( "KDSingleApplicationGuard: QCoreApplication::applicationName must not be empty" ); return; } (void)registerInstanceType(); if ( primaryInstance == 0 ) primaryInstance = q; mem.setKey( name ); // if another instance crashed, the shared memory segment is still there on Unix // the following lines trigger deletion in that case #ifndef Q_WS_WIN mem.attach(); mem.detach(); #endif const bool created = mem.create( sizeof( InstanceRegister ) ); if( !created ) { QString errorMsg; if( mem.error() != QSharedMemory::NoError && mem.error() != QSharedMemory::AlreadyExists ) errorMsg += QString::fromLatin1( "QSharedMemomry::create() failed: %1" ).arg( mem.errorString() ); if( !mem.attach() ) { if( mem.error() != QSharedMemory::NoError ) errorMsg += QString::fromLatin1( "QSharedMemomry::attach() failed: %1" ).arg( mem.errorString() ); qWarning( "KDSingleApplicationGuard: Could neither create nor attach to shared memory segment." ); qWarning( "%s\n", errorMsg.toLocal8Bit().constData() ); return; } const int maxWaitMSecs = 1000 * 60; // stop waiting after 60 seconds QElapsedTimer waitTimer; waitTimer.start(); // lets wait till the other instance initialized the register bool initialized = false; while( !initialized && waitTimer.elapsed() < maxWaitMSecs ) { const KDLockedSharedMemoryPointer< InstanceRegister > instances( &mem ); initialized = instances->isValid(); #ifdef Q_WS_WIN ::Sleep(20); #else usleep(20000); #endif } const KDLockedSharedMemoryPointer< InstanceRegister > instances( &mem ); if ( instances->version != 0 ) { qWarning( "KDSingleApplicationGuard: Detected version mismatch. " "Highest supported version: %ud, actual version: %ud", KDSINGLEAPPLICATIONGUARD_SHM_VERSION, instances->version ); return; } } KDLockedSharedMemoryPointer< InstanceRegister > instances( &mem ); if( !created ) { assert( instances->isValid() ); // we're _not_ the first instance // but the bool killOurSelf = false; // find a new slot... id = std::find( instances->info, instances->info + instances->maxInstances, ProcessInfo() ) - instances->info; ProcessInfo& info = instances->info[ id ]; info = ProcessInfo( NewInstance, arguments, QCoreApplication::applicationPid() ); killOurSelf = instances->policy == AutoKillOtherInstances; policy = static_cast<Policy>( instances->policy ); // but the signal that we tried to start was sent to the primary application if( killOurSelf ) exitRequested = true; } else { // ok.... we are the first instance new ( instances.get() ) InstanceRegister( policy ); // create a new list (in shared memory) id = 0; // our id = 0 // and we've no command instances->info[ 0 ] = ProcessInfo( NoCommand, arguments, QCoreApplication::applicationPid() ); } #ifndef Q_WS_WIN ::signal( SIGINT, SIGINT_handler ); #endif // now listen for commands timer.start( 750, q ); operational = true; } /*! Destroys this SingleApplicationGuard. If this instance has been the primary instance and no other instance is existing anymore, the application is shut down completely. Otherwise the destructor selects another instance to be the primary instances. */ KDSingleApplicationGuard::~KDSingleApplicationGuard() { if( d->id == -1 ) return; d->shutdownInstance(); } /*! \property KDSingleApplicationGuard::operational Contains whether this KDSingleApplicationGuard is operational. A non-operational KDSingleApplicationGuard cannot be used in any meaningful way. Reasons for a KDSingleApplicationGuard being non-operational include: \li it was constructed before QApplication (or at least QCoreApplication) was constructed \li it failed to create or attach to the shared memory segment that is used for communication Get this property's value using %isOperational(). */ bool KDSingleApplicationGuard::isOperational() const { return d->operational; } /*! \property KDSingleApplicationGuard::exitRequested Contains wheter this istance has been requested to exit. This will happen when this instance was just started, but the policy is AutoKillOtherInstances or by explicitely calling kill on this instance(). Get this property's value using %isExitRequested(). */ bool KDSingleApplicationGuard::isExitRequested() const { return d->exitRequested; }; /*! \property KDSingleApplicationGuard::primaryInstance Contains whether this instance is the primary instance. The primary instance is the first instance which was started or else the instance which got selected by KDSingleApplicationGuard's destructor, when the primary instance was shut down. Get this property's value using %isPrimaryInstance(), and monitor changes to it using becamePrimaryInstance(). */ bool KDSingleApplicationGuard::isPrimaryInstance() const { return d->id == 0; } /*! \property KDSingleApplicationGuard::policy Specifies the policy KDSingleApplicationGuard is using when new instances are started. This can only be set in the primary instance. Get this property's value using %policy(), set it using %setPolicy(), and monitor changes to it using policyChanged(). */ KDSingleApplicationGuard::Policy KDSingleApplicationGuard::policy() const { return d->policy; } void KDSingleApplicationGuard::setPolicy( Policy policy ) { if ( !d->checkOperationalPrimary( "setPolicy", "change the policy" ) ) return; if( d->policy == policy ) return; d->policy = policy; emit policyChanged( policy ); KDLockedSharedMemoryPointer< InstanceRegister > instances( &d->mem ); instances->policy = policy; } /*! Returns a list of all currently running instances. */ QVector<KDSingleApplicationGuard::Instance> KDSingleApplicationGuard::instances() const { if ( !d->checkOperational( "instances", "report on other instances" ) ) return QVector<Instance>(); if ( Private::primaryInstance == 0 ) { Private::primaryInstance = const_cast<KDSingleApplicationGuard*>( this ); } QVector<Instance> result; const KDLockedSharedMemoryPointer< InstanceRegister > instances( const_cast< QSharedMemory* >( &d->mem ) ); for ( int i = 0, end = instances->maxInstances ; i < end ; ++i ) { const ProcessInfo& info = instances->info[ i ]; if( ( info.command & ( FreeInstance | ExitedInstance ) ) == 0 ) { bool truncated; const QStringList arguments = info.arguments( &truncated ); result.push_back( Instance( arguments, truncated, info.pid ) ); } } return result; } /*! Shuts down all other instances. This can only be called from the the primary instance. Shut down is done gracefully via QCoreApplication::quit(). */ void KDSingleApplicationGuard::shutdownOtherInstances() { if ( !d->checkOperationalPrimary( "shutdownOtherInstances", "shut other instances down" ) ) return; KDLockedSharedMemoryPointer< InstanceRegister > instances( &d->mem ); for ( int i = 1, end = instances->maxInstances ; i < end ; ++i ) { if( ( instances->info[ i ].command & ( FreeInstance | ExitedInstance ) ) == 0 ) instances->info[ i ].command = ShutDownCommand; } } /*! Kills all other instances. This can only be called from the the primary instance. Killing is done via emitting exitRequested. It's up to the receiving instance to react properly. */ void KDSingleApplicationGuard::killOtherInstances() { if ( !d->checkOperationalPrimary( "killOtherInstances", "kill other instances" ) ) return; KDLockedSharedMemoryPointer< InstanceRegister > instances( &d->mem ); for ( int i = 1, end = instances->maxInstances ; i < end ; ++i ) { if( ( instances->info[ i ].command & ( FreeInstance | ExitedInstance ) ) == 0 ) instances->info[ i ].command = KillCommand; } } bool KDSingleApplicationGuard::event( QEvent * event ) { if ( event->type() == QEvent::Timer ) { const QTimerEvent * const te = static_cast<QTimerEvent*>( event ); if ( te->timerId() == d->timer.timerId() ) { d->poll(); return true; } } return QObject::event( event ); } void KDSingleApplicationGuard::Private::poll() { const quint32 now = QDateTime::currentDateTime().toTime_t(); if ( primaryInstance == 0 ) { primaryInstance = q; } if ( q->isPrimaryInstance() ) { // only the primary instance will get notified about new instances QVector< Instance > exitedInstances; QVector< Instance > startedInstances; { KDLockedSharedMemoryPointer< InstanceRegister > instances( &mem ); if( instances->info[ id ].pid != QCoreApplication::applicationPid() ) { for ( int i = 1, end = instances->maxInstances ; i < end && id == 0 ; ++i ) { if( instances->info[ i ].pid == QCoreApplication::applicationPid() ) id = i; } emit q->becameSecondaryInstance(); return; } instances->info[ id ].timestamp = now; for ( int i = 1, end = instances->maxInstances ; i < end ; ++i ) { ProcessInfo& info = instances->info[ i ]; if( info.command & NewInstance ) { bool truncated; const QStringList arguments = info.arguments( &truncated ); startedInstances.push_back( Instance( arguments, truncated, info.pid ) ); info.command &= ~NewInstance; // clear NewInstance flag } if( info.command & ExitedInstance ) { bool truncated; const QStringList arguments = info.arguments( &truncated ); exitedInstances.push_back( Instance( arguments, truncated, info.pid ) ); info.command = FreeInstance; // set FreeInstance flag } } } // one signal for every new instance - _after_ the memory segment was unlocked again for( QVector< Instance >::const_iterator it = startedInstances.constBegin(); it != startedInstances.constEnd(); ++it ) emit q->instanceStarted( *it ); for( QVector< Instance >::const_iterator it = exitedInstances.constBegin(); it != exitedInstances.constEnd(); ++it ) emit q->instanceExited( *it ); } else { // do we have a command? bool killOurSelf = false; bool shutDownOurSelf = false; bool policyDidChange = false; { KDLockedSharedMemoryPointer< InstanceRegister > instances( &mem ); const Policy oldPolicy = policy; policy = static_cast<Policy>( instances->policy ); policyDidChange = policy != oldPolicy; // check for the primary instance health status if( now - instances->info[ 0 ].timestamp > KDSINGLEAPPLICATIONGUARD_TIMEOUT_SECONDS ) { std::swap( instances->info[ 0 ], instances->info[ id ] ); id = 0; instances->info[ id ].timestamp = now; emit q->becamePrimaryInstance(); instances->info[ id ].command &= ~BecomePrimaryCommand; // afterwards, reset the flag } if( instances->info[ id ].command & BecomePrimaryCommand ) { // we became primary! instances->info[ 0 ] = instances->info[ id ]; instances->info[ id ] = ProcessInfo(); // change our id to 0 and declare the old slot as free id = 0; instances->info[ id ].timestamp = now; emit q->becamePrimaryInstance(); } if( instances->info[ id ].command & RaiseCommand ) { // raise ourself! emit q->raiseRequested(); instances->info[ id ].command &= ~RaiseCommand; // afterwards, reset the flag } killOurSelf = instances->info[ id ].command & KillCommand; // check for kill command shutDownOurSelf = instances->info[ id ].command & ShutDownCommand; // check for shut down command instances->info[ id ].command &= ~( KillCommand | ShutDownCommand | BecomePrimaryCommand ); // reset both flags if( killOurSelf ) { instances->info[ id ].command |= ExitedInstance; // upon kill, we have to set the ExitedInstance flag id = -1; // becauso our d'tor won't be called anymore } } if( killOurSelf ) // kill our self takes precedence { exitRequested = true; emit q->exitRequested(); } else if( shutDownOurSelf ) qApp->quit(); else if( policyDidChange ) emit q->policyChanged( policy ); } } #include "moc_kdsingleapplicationguard.cpp" #ifdef KDTOOLSCORE_UNITTESTS #include <kdunittest/test.h> #include "kdautopointer.h" #include <iostream> #include <QtCore/QTime> #include <QtCore/QUuid> #include <QtTest/QSignalSpy> static void wait( int msec, QSignalSpy * spy=0, int expectedCount=INT_MAX ) { QTime t; t.start(); while ( ( !spy || spy->count() < expectedCount ) && t.elapsed() < msec ) { qApp->processEvents( QEventLoop::WaitForMoreEvents, qMax( 10, msec - t.elapsed() ) ); } } static std::ostream& operator<<( std::ostream& stream, const QStringList& list ) { stream << "QStringList("; for( QStringList::const_iterator it = list.begin(); it != list.end(); ++it ) { stream << " " << it->toLocal8Bit().data(); if( it + 1 != list.end() ) stream << ","; } stream << " )"; return stream; } namespace { class ApplicationNameSaver { Q_DISABLE_COPY( ApplicationNameSaver ) const QString oldname; public: explicit ApplicationNameSaver( const QString & name ) : oldname( QCoreApplication::applicationName() ) { QCoreApplication::setApplicationName( name ); } ~ApplicationNameSaver() { QCoreApplication::setApplicationName( oldname ); } }; } KDAB_UNITTEST_SIMPLE( KDSingleApplicationGuard, "kdcoretools" ) { // set it to an unique name const ApplicationNameSaver saver( QUuid::createUuid().toString() ); KDAutoPointer<KDSingleApplicationGuard> guard3; KDAutoPointer<QSignalSpy> spy3; KDAutoPointer<QSignalSpy> spy4; { KDSingleApplicationGuard guard1; assertEqual( guard1.policy(), KDSingleApplicationGuard::AutoKillOtherInstances ); assertEqual( guard1.instances().count(), 1 ); assertTrue( guard1.isPrimaryInstance() ); guard1.setPolicy( KDSingleApplicationGuard::NoPolicy ); assertEqual( guard1.policy(), KDSingleApplicationGuard::NoPolicy ); QSignalSpy spy1( &guard1, SIGNAL(instanceStarted(KDSingleApplicationGuard::Instance)) ); KDSingleApplicationGuard guard2; assertEqual( guard1.instances().count(), 2 ); assertEqual( guard2.instances().count(), 2 ); assertEqual( guard2.policy(), KDSingleApplicationGuard::NoPolicy ); assertFalse( guard2.isPrimaryInstance() ); wait( 1000, &spy1, 1 ); assertEqual( spy1.count(), 1 ); guard3.reset( new KDSingleApplicationGuard ); spy3.reset( new QSignalSpy( guard3.get(), SIGNAL(becamePrimaryInstance()) ) ); spy4.reset( new QSignalSpy( guard3.get(), SIGNAL(instanceExited(KDSingleApplicationGuard::Instance) ) ) ); assertFalse( guard3->isPrimaryInstance() ); } wait( 1000, spy3.get(), 1 ); wait( 1000, spy4.get(), 1 ); assertEqual( spy3->count(), 1 ); assertEqual( guard3->instances().count(), 1 ); assertTrue( guard3->isPrimaryInstance() ); guard3.reset( new KDSingleApplicationGuard ); assertEqual( guard3->instances().first().arguments(), qApp->arguments() ); QSignalSpy spyStarted( guard3.get(), SIGNAL(instanceStarted(KDSingleApplicationGuard::Instance)) ); QSignalSpy spyExited( guard3.get(), SIGNAL(instanceExited(KDSingleApplicationGuard::Instance)) ); { KDSingleApplicationGuard guard1; KDSingleApplicationGuard guard2; wait( 1000, &spyStarted, 2 ); assertEqual( spyStarted.count(), 2 ); } wait( 1000, &spyExited, 2 ); assertEqual( spyExited.count(), 2 ); spyStarted.clear(); spyExited.clear(); { // check arguments-too-long handling: QStringList args; for ( unsigned int i = 0, end = KDSINGLEAPPLICATIONGUARD_MAX_COMMAND_LINE/16 ; i != end ; ++i ) args.push_back( QLatin1String( "0123456789ABCDEF" ) ); KDSingleApplicationGuard guard3( args ); wait( 1000, &spyStarted, 1 ); const QVector<KDSingleApplicationGuard::Instance> instances = guard3.instances(); assertEqual( instances.size(), 2 ); assertTrue( instances[1].areArgumentsTruncated() ); } } #endif // KDTOOLSCORE_UNITTESTS #endif // QT_NO_SHAREDMEMORY #endif // QT_VERSION >= 0x040400 || defined(DOXYGEN_RUN)
31.186158
155
0.65534
ix-os
cd90e19070eda01d8c2ebc58918ec11f4c6a09f7
936
cpp
C++
Week 1 - 03.02.2021/Selection Sort 19.cpp
abhisheks008/Design-and-Analysis-Algorithm-Lab-4th-Semester
80601b43b068729b4dadce0587b9c2a54184d08e
[ "Apache-2.0" ]
4
2021-05-19T09:35:13.000Z
2022-01-16T13:55:31.000Z
Week 1 - 03.02.2021/Selection Sort 19.cpp
abhisheks008/Design-and-Analysis-Algorithm-Lab-4th-Semester
80601b43b068729b4dadce0587b9c2a54184d08e
[ "Apache-2.0" ]
null
null
null
Week 1 - 03.02.2021/Selection Sort 19.cpp
abhisheks008/Design-and-Analysis-Algorithm-Lab-4th-Semester
80601b43b068729b4dadce0587b9c2a54184d08e
[ "Apache-2.0" ]
4
2021-03-12T07:31:31.000Z
2021-11-22T11:12:02.000Z
// Selection Sort using C++ // Author : Abhishek Sharma #include<iostream> using std::cout; using std::cin; using std::endl; void insertionsort(int p[],int no_of_steps,int n) { int min_ele; int addr; int temp; for (int i = 0; i<no_of_steps; ++i) { min_ele = p[i]; addr = i; for(int j=i+1;j<n;++j) { if (p[j]<min_ele) { min_ele = p[j]; addr = j; } } temp = p[i]; p[i] = p[addr]; p[addr] = temp; } } int main() { int n,no_of_steps; cin>>n>>no_of_steps; int a[n]; for(int i=0;i<n;++i) { cin>>a[i]; } // cout<<"output:"<<endl<<endl; // for(int i=0;i<n;++i) // { // cout<<a[i]<<' '; // } insertionsort(a,no_of_steps,n); for(int i=0;i<n;++i) { cout<<a[i]<<' '; } return 0; }
14.625
49
0.415598
abhisheks008
cd9205524109317c1bb2fbc2e4aa4c485289ae60
22,138
cxx
C++
PWGHF/vertexingHF/AliNormalizationCounter.cxx
wiechula/AliPhysics
6c5c45a5c985747ee82328d8fd59222b34529895
[ "BSD-3-Clause" ]
null
null
null
PWGHF/vertexingHF/AliNormalizationCounter.cxx
wiechula/AliPhysics
6c5c45a5c985747ee82328d8fd59222b34529895
[ "BSD-3-Clause" ]
null
null
null
PWGHF/vertexingHF/AliNormalizationCounter.cxx
wiechula/AliPhysics
6c5c45a5c985747ee82328d8fd59222b34529895
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************** * Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //************************************************************************* // Class AliNormalizationCounter // Class to store the informations relevant for the normalization in the // barrel for each run // Authors: G. Ortona, ortona@to.infn.it // D. Caffarri, davide.caffarri@pd.to.infn.it // with many thanks to P. Pillot ///////////////////////////////////////////////////////////// #include "AliLog.h" #include "AliNormalizationCounter.h" #include <AliESDEvent.h> #include <AliESDtrack.h> #include <AliAODEvent.h> #include <AliAODVZERO.h> #include <AliVParticle.h> #include <AliTriggerAnalysis.h> #include <TH1F.h> #include <TH2F.h> #include <TList.h> #include <TObjArray.h> #include <TString.h> #include <TCanvas.h> #include <AliPhysicsSelection.h> #include <AliMultiplicity.h> /// \cond CLASSIMP ClassImp(AliNormalizationCounter); /// \endcond //____________________________________________ AliNormalizationCounter::AliNormalizationCounter(): TNamed(), fCounters(), fESD(kFALSE), fMultiplicity(kFALSE), fMultiplicityEtaRange(1.0), fSpherocity(kFALSE), fSpherocitySteps(100.), fHistTrackFilterEvMult(0), fHistTrackAnaEvMult(0), fHistTrackFilterSpdMult(0), fHistTrackAnaSpdMult(0) { // empty constructor } //__________________________________________________ AliNormalizationCounter::AliNormalizationCounter(const char *name): TNamed(name,name), fCounters(name), fESD(kFALSE), fMultiplicity(kFALSE), fMultiplicityEtaRange(1.0), fSpherocity(kFALSE), fSpherocitySteps(100.), fHistTrackFilterEvMult(0), fHistTrackAnaEvMult(0), fHistTrackFilterSpdMult(0), fHistTrackAnaSpdMult(0) { ; } //______________________________________________ AliNormalizationCounter::~AliNormalizationCounter() { //destructor if(fHistTrackFilterEvMult){ delete fHistTrackFilterEvMult; fHistTrackFilterEvMult =0; } if(fHistTrackAnaEvMult){ delete fHistTrackAnaEvMult; fHistTrackAnaEvMult=0; } if(fHistTrackFilterSpdMult){ delete fHistTrackFilterSpdMult; fHistTrackFilterSpdMult=0; } if(fHistTrackAnaSpdMult){ delete fHistTrackAnaSpdMult; fHistTrackAnaSpdMult=0; } } //______________________________________________ void AliNormalizationCounter::Init() { //variables initialization fCounters.AddRubric("Event","triggered/V0AND/PileUp/PbPbC0SMH-B-NOPF-ALLNOTRD/Candles0.3/PrimaryV/countForNorm/noPrimaryV/zvtxGT10/!V0A&Candle03/!V0A&PrimaryV/Candid(Filter)/Candid(Analysis)/NCandid(Filter)/NCandid(Analysis)"); if(fMultiplicity) fCounters.AddRubric("Multiplicity", 5000); if(fSpherocity) fCounters.AddRubric("Spherocity", (Int_t)fSpherocitySteps+1); fCounters.AddRubric("Run", 1000000); fCounters.Init(); fHistTrackFilterEvMult=new TH2F("FiltCandidvsTracksinEv","FiltCandidvsTracksinEv",10000,-0.5,9999.5,200,-0.5,199.5); fHistTrackFilterEvMult->GetYaxis()->SetTitle("NCandidates"); fHistTrackFilterEvMult->GetXaxis()->SetTitle("NTracksinEvent"); fHistTrackAnaEvMult=new TH2F("AnaCandidvsTracksinEv","AnaCandidvsTracksinEv",10000,-0.5,9999.5,100,-0.5,99.5); fHistTrackAnaEvMult->GetYaxis()->SetTitle("NCandidates"); fHistTrackAnaEvMult->GetXaxis()->SetTitle("NTracksinEvent"); fHistTrackFilterSpdMult=new TH2F("FilterCandidvsSpdMult","FilterCandidvsSpdMult",5000,-0.5,4999.5,200,-0.5,199.5); fHistTrackFilterSpdMult->GetYaxis()->SetTitle("NCandidates"); fHistTrackFilterSpdMult->GetXaxis()->SetTitle("NSPDTracklets"); fHistTrackAnaSpdMult=new TH2F("AnaCandidvsSpdMult","AnaCandidvsSpdMult",5000,-0.5,4999.5,100,-0.5,99.5); fHistTrackAnaSpdMult->GetYaxis()->SetTitle("NCandidates"); fHistTrackAnaSpdMult->GetXaxis()->SetTitle("NSPDTracklets"); } //______________________________________________ Long64_t AliNormalizationCounter::Merge(TCollection* list){ if (!list) return 0; if (list->IsEmpty()) return 0;//(Long64_t)fCounters.Merge(list); TIter next(list); const TObject* obj = 0x0; while ((obj = next())) { // check that "obj" is an object of the class AliNormalizationCounter const AliNormalizationCounter* counter = dynamic_cast<const AliNormalizationCounter*>(obj); if (!counter) { AliError(Form("object named %s is not AliNormalizationCounter! Skipping it.", counter->GetName())); continue; } Add(counter); } return (Long64_t)1;//(Long64_t)fCounters->GetEntries(); } //_______________________________________ void AliNormalizationCounter::Add(const AliNormalizationCounter *norm){ fCounters.Add(&(norm->fCounters)); fHistTrackFilterEvMult->Add(norm->fHistTrackFilterEvMult); fHistTrackAnaEvMult->Add(norm->fHistTrackAnaEvMult); fHistTrackFilterSpdMult->Add(norm->fHistTrackFilterSpdMult); fHistTrackAnaSpdMult->Add(norm->fHistTrackAnaSpdMult); } //_______________________________________ /* Stores the variables used for normalization as function of run number returns kTRUE if the event is to be counted for normalization (pass event selection cuts OR has no primary vertex) */ void AliNormalizationCounter::StoreEvent(AliVEvent *event,AliRDHFCuts *rdCut,Bool_t mc, Int_t multiplicity, Double_t spherocity){ // Bool_t isEventSelected = rdCut->IsEventSelected(event); // events not passing physics selection. do nothing if(rdCut->IsEventRejectedDuePhysicsSelection()) return; Bool_t v0A=kFALSE; Bool_t v0B=kFALSE; Bool_t flag03=kFALSE; Bool_t flagPV=kFALSE; //Run Number Int_t runNumber = event->GetRunNumber(); // Evaluate the multiplicity if(fMultiplicity && multiplicity==-9999) Multiplicity(event); //Find CINT1B AliESDEvent *eventESD = (AliESDEvent*)event; if(!eventESD){AliError("ESD event not available");return;} if(mc&&event->GetEventType() != 0)return; //event must be either physics or MC if(!(event->GetEventType() == 7||event->GetEventType() == 0))return; FillCounters("triggered",runNumber,multiplicity,spherocity); //Find V0AND AliTriggerAnalysis trAn; /// Trigger Analysis AliAODVZERO* aodV0 = (AliAODVZERO*)event->GetVZEROData(); Bool_t isPP2012 = kFALSE; if(runNumber>=176326 && runNumber<=193766) isPP2012=kTRUE; if(aodV0 && !isPP2012){ v0B = trAn.IsOfflineTriggerFired(eventESD , AliTriggerAnalysis::kV0C); v0A = trAn.IsOfflineTriggerFired(eventESD , AliTriggerAnalysis::kV0A); } if(v0A&&v0B) FillCounters("V0AND",runNumber,multiplicity,spherocity); //FindPrimary vertex // AliVVertex *vtrc = (AliVVertex*)event->GetPrimaryVertex(); // if(vtrc && vtrc->GetNContributors()>0){ // fCounters.Count(Form("Event:PrimaryV/Run:%d",runNumber)); // flagPV=kTRUE; // } //trigger AliAODEvent *eventAOD = (AliAODEvent*)event; TString trigclass=eventAOD->GetFiredTriggerClasses(); if(trigclass.Contains("C0SMH-B-NOPF-ALLNOTRD")||trigclass.Contains("C0SMH-B-NOPF-ALL")){ FillCounters("PbPbC0SMH-B-NOPF-ALLNOTRD",runNumber,multiplicity,spherocity); } //FindPrimary vertex if(isEventSelected){ FillCounters("PrimaryV",runNumber,multiplicity,spherocity); flagPV=kTRUE; }else{ if(rdCut->GetWhyRejection()==0){ FillCounters("noPrimaryV",runNumber,multiplicity,spherocity); } //find good vtx outside range if(rdCut->GetWhyRejection()==6){ FillCounters("zvtxGT10",runNumber,multiplicity,spherocity); FillCounters("PrimaryV",runNumber,multiplicity,spherocity); flagPV=kTRUE; } if(rdCut->GetWhyRejection()==1){ FillCounters("PileUp",runNumber,multiplicity,spherocity); } } //to be counted for normalization if(rdCut->CountEventForNormalization()){ FillCounters("countForNorm",runNumber,multiplicity,spherocity); } //Find Candle Int_t trkEntries = (Int_t)event->GetNumberOfTracks(); for(Int_t i=0;i<trkEntries&&!flag03;i++){ AliAODTrack *track=(AliAODTrack*)event->GetTrack(i); if((track->Pt()>0.3)&&(!flag03)){ FillCounters("Candles0.3",runNumber,multiplicity,spherocity); flag03=kTRUE; break; } } if(!(v0A&&v0B)&&(flag03)){ FillCounters("!V0A&Candle03",runNumber,multiplicity,spherocity); } if(!(v0A&&v0B)&&flagPV){ FillCounters("!V0A&PrimaryV",runNumber,multiplicity,spherocity); } return; } //_____________________________________________________________________ void AliNormalizationCounter::StoreCandidates(AliVEvent *event,Int_t nCand,Bool_t flagFilter){ Int_t ntracks=event->GetNumberOfTracks(); if(flagFilter)fHistTrackFilterEvMult->Fill(ntracks,nCand); else fHistTrackAnaEvMult->Fill(ntracks,nCand); Int_t nSPD=0; if(fESD){ AliESDEvent *ESDevent=(AliESDEvent*)event; const AliMultiplicity *alimult = ESDevent->GetMultiplicity(); nSPD = alimult->GetNumberOfTracklets(); }else{ AliAODEvent *aodEvent =(AliAODEvent*)event; AliAODTracklets *trklets=aodEvent->GetTracklets(); nSPD = trklets->GetNumberOfTracklets(); } if(flagFilter)fHistTrackFilterSpdMult->Fill(nSPD,nCand); else fHistTrackAnaSpdMult->Fill(nSPD,nCand); Int_t runNumber = event->GetRunNumber(); Int_t multiplicity = Multiplicity(event); if(nCand==0)return; if(flagFilter){ if(fMultiplicity) fCounters.Count(Form("Event:Candid(Filter)/Run:%d/Multiplicity:%d",runNumber,multiplicity)); else fCounters.Count(Form("Event:Candid(Filter)/Run:%d",runNumber)); for(Int_t i=0;i<nCand;i++){ if(fMultiplicity) fCounters.Count(Form("Event:NCandid(Filter)/Run:%d/Multiplicity:%d",runNumber,multiplicity)); else fCounters.Count(Form("Event:NCandid(Filter)/Run:%d",runNumber)); } }else{ if(fMultiplicity) fCounters.Count(Form("Event:Candid(Analysis)/Run:%d/Multiplicity:%d",runNumber,multiplicity)); else fCounters.Count(Form("Event:Candid(Analysis)/Run:%d",runNumber)); for(Int_t i=0;i<nCand;i++){ if(fMultiplicity) fCounters.Count(Form("Event:NCandid(Analysis)/Run:%d/Multiplicity:%d",runNumber,multiplicity)); else fCounters.Count(Form("Event:NCandid(Analysis)/Run:%d",runNumber)); } } return; } //_______________________________________________________________________ TH1D* AliNormalizationCounter::DrawAgainstRuns(TString candle,Bool_t drawHist){ // fCounters.SortRubric("Run"); TString selection; selection.Form("event:%s",candle.Data()); TH1D* histoneD = fCounters.Get("run",selection.Data()); histoneD->Sumw2(); if(drawHist)histoneD->DrawClone(); return histoneD; } //___________________________________________________________________________ TH1D* AliNormalizationCounter::DrawRatio(TString candle1,TString candle2){ // fCounters.SortRubric("Run"); TString name; name.Form("%s/%s",candle1.Data(),candle2.Data()); TH1D* num=DrawAgainstRuns(candle1.Data(),kFALSE); TH1D* den=DrawAgainstRuns(candle2.Data(),kFALSE); den->SetTitle(candle2.Data()); den->SetName(candle2.Data()); num->Divide(num,den,1,1,"B"); num->SetTitle(name.Data()); num->SetName(name.Data()); num->DrawClone(); return num; } //___________________________________________________________________________ void AliNormalizationCounter::PrintRubrics(){ fCounters.PrintKeyWords(); } //___________________________________________________________________________ Double_t AliNormalizationCounter::GetSum(TString candle){ TString selection="event:"; selection.Append(candle); return fCounters.GetSum(selection.Data()); } //___________________________________________________________________________ TH2F* AliNormalizationCounter::GetHist(Bool_t filtercuts,Bool_t spdtracklets,Bool_t drawHist){ if(filtercuts){ if(spdtracklets){ if(drawHist)fHistTrackFilterSpdMult->DrawCopy("LEGO2Z 0"); return fHistTrackFilterSpdMult; }else{ if(drawHist)fHistTrackFilterEvMult->DrawCopy("LEGO2Z 0"); return fHistTrackFilterEvMult; } }else{ if(spdtracklets){ if(drawHist)fHistTrackAnaSpdMult->DrawCopy("LEGO2Z 0"); return fHistTrackAnaSpdMult; }else{ if(drawHist)fHistTrackAnaEvMult->DrawCopy("LEGO2Z 0"); return fHistTrackAnaEvMult; } } } //___________________________________________________________________________ Double_t AliNormalizationCounter::GetNEventsForNorm(){ Double_t noVtxzGT10=GetSum("noPrimaryV")*GetSum("zvtxGT10")/GetSum("PrimaryV"); return GetSum("countForNorm")-noVtxzGT10; } //___________________________________________________________________________ Double_t AliNormalizationCounter::GetNEventsForNorm(Int_t runnumber){ TString listofruns = fCounters.GetKeyWords("RUN"); if(!listofruns.Contains(Form("%d",runnumber))){ printf("WARNING: %d is not a valid run number\n",runnumber); fCounters.Print("Run","",kTRUE); return 0.; } TString suffix;suffix.Form("/RUN:%d",runnumber); TString zvtx;zvtx.Form("zvtxGT10%s",suffix.Data()); TString noPV;noPV.Form("noPrimaryV%s",suffix.Data()); TString pV;pV.Form("PrimaryV%s",suffix.Data()); TString tbc;tbc.Form("countForNorm%s",suffix.Data()); Double_t noVtxzGT10=GetSum(noPV.Data())*GetSum(zvtx.Data())/GetSum(pV.Data()); return GetSum(tbc.Data())-noVtxzGT10; } //___________________________________________________________________________ Double_t AliNormalizationCounter::GetNEventsForNorm(Int_t minmultiplicity, Int_t maxmultiplicity){ if(!fMultiplicity) { AliInfo("Sorry, you didn't activate the multiplicity in the counter!"); return 0.; } TString listofruns = fCounters.GetKeyWords("Multiplicity"); Int_t nmultbins = maxmultiplicity - minmultiplicity; Double_t sumnoPV=0., sumZvtx=0., sumPv=0., sumEvtNorm=0.; for (Int_t ibin=0; ibin<=nmultbins; ibin++) { // cout << " Looking at bin "<< ibin+minmultiplicity<<endl; if(!listofruns.Contains(Form("%d",ibin+minmultiplicity))){ // AliInfo(Form("WARNING: %d is not a valid multiplicity number. \n",ibin+minmultiplicity)); continue; } TString suffix;suffix.Form("/Multiplicity:%d",ibin+minmultiplicity); TString zvtx;zvtx.Form("zvtxGT10%s",suffix.Data()); TString noPV;noPV.Form("noPrimaryV%s",suffix.Data()); TString pV;pV.Form("PrimaryV%s",suffix.Data()); TString tbc;tbc.Form("countForNorm%s",suffix.Data()); sumnoPV += GetSum(noPV.Data()); sumZvtx += GetSum(zvtx.Data()); sumPv += GetSum(pV.Data()); sumEvtNorm += GetSum(tbc.Data()); } Double_t noVtxzGT10 = sumPv>0. ? sumnoPV * sumZvtx / sumPv : 0.; return sumEvtNorm - noVtxzGT10; } //___________________________________________________________________________ Double_t AliNormalizationCounter::GetNEventsForNorm(Int_t minmultiplicity, Int_t maxmultiplicity, Double_t minspherocity, Double_t maxspherocity){ if(!fMultiplicity || !fSpherocity) { AliInfo("You must activate both multiplicity and spherocity in the counters to use this method!"); return 0.; } TString listofruns = fCounters.GetKeyWords("Multiplicity"); TString listofruns2 = fCounters.GetKeyWords("Spherocity"); TObjArray* arr=listofruns2.Tokenize(","); Int_t nSphVals=arr->GetEntries(); Int_t nmultbins = maxmultiplicity - minmultiplicity; Int_t minSphToInteger=minspherocity*fSpherocitySteps; Int_t maxSphToInteger=maxspherocity*fSpherocitySteps; Int_t nstbins = maxSphToInteger - minSphToInteger; Double_t sumnoPV=0., sumZvtx=0., sumPv=0., sumEvtNorm=0.; for (Int_t ibin=0; ibin<=nmultbins; ibin++) { if(!listofruns.Contains(Form("%d",ibin+minmultiplicity))) continue; for (Int_t ibins=0; ibins<nstbins; ibins++) { Bool_t analyze=kFALSE; for(Int_t j=0; j<nSphVals; j++) if((((TObjString*)arr->At(j))->String()).Atoi()==(ibins+minSphToInteger)) analyze=kTRUE; if(!analyze) continue; if(listofruns2.Contains(",") && !listofruns2.Contains(Form("%d",ibins+minSphToInteger))) continue; TString suffix;suffix.Form("/Multiplicity:%d/Spherocity:%d",ibin+minmultiplicity,ibins+minSphToInteger); TString zvtx;zvtx.Form("zvtxGT10%s",suffix.Data()); TString noPV;noPV.Form("noPrimaryV%s",suffix.Data()); TString pV;pV.Form("PrimaryV%s",suffix.Data()); TString tbc;tbc.Form("countForNorm%s",suffix.Data()); sumnoPV += GetSum(noPV.Data()); sumZvtx += GetSum(zvtx.Data()); sumPv += GetSum(pV.Data()); sumEvtNorm += GetSum(tbc.Data()); } } delete arr; Double_t noVtxzGT10 = sumPv>0. ? sumnoPV * sumZvtx / sumPv : 0.; return sumEvtNorm - noVtxzGT10; } //___________________________________________________________________________ Double_t AliNormalizationCounter::GetNEventsForNormSpheroOnly(Double_t minspherocity, Double_t maxspherocity){ if(!fSpherocity) { AliInfo("Sorry, you didn't activate the sphericity in the counter!"); return 0.; } TString listofruns = fCounters.GetKeyWords("Spherocity"); TObjArray* arr=listofruns.Tokenize(","); Int_t nSphVals=arr->GetEntries(); Int_t minSphToInteger=minspherocity*fSpherocitySteps; Int_t maxSphToInteger=maxspherocity*fSpherocitySteps; Int_t nstbins = maxSphToInteger - minSphToInteger; Double_t sumnoPV=0., sumZvtx=0., sumPv=0., sumEvtNorm=0.; for (Int_t ibin=0; ibin<nstbins; ibin++) { Bool_t analyze=kFALSE; for(Int_t j=0; j<nSphVals; j++) if((((TObjString*)arr->At(j))->String()).Atoi()==(ibin+minSphToInteger)) analyze=kTRUE; if(!analyze) continue; TString suffix;suffix.Form("/Spherocity:%d",ibin+minSphToInteger); TString zvtx;zvtx.Form("zvtxGT10%s",suffix.Data()); TString noPV;noPV.Form("noPrimaryV%s",suffix.Data()); TString pV;pV.Form("PrimaryV%s",suffix.Data()); TString tbc;tbc.Form("countForNorm%s",suffix.Data()); sumnoPV += GetSum(noPV.Data()); sumZvtx += GetSum(zvtx.Data()); sumPv += GetSum(pV.Data()); sumEvtNorm += GetSum(tbc.Data()); } delete arr; Double_t noVtxzGT10 = sumPv>0. ? sumnoPV * sumZvtx / sumPv : 0.; return sumEvtNorm - noVtxzGT10; } //___________________________________________________________________________ Double_t AliNormalizationCounter::GetSum(TString candle,Int_t minmultiplicity, Int_t maxmultiplicity){ // counts events of given type in a given multiplicity range if(!fMultiplicity) { AliInfo("Sorry, you didn't activate the multiplicity in the counter!"); return 0.; } TString listofruns = fCounters.GetKeyWords("Multiplicity"); Double_t sum=0.; for (Int_t ibin=minmultiplicity; ibin<=maxmultiplicity; ibin++) { // cout << " Looking at bin "<< ibin+minmultiplicity<<endl; if(!listofruns.Contains(Form("%d",ibin))){ // AliInfo(Form("WARNING: %d is not a valid multiplicity number. \n",ibin)); continue; } TString suffix=Form("/Multiplicity:%d",ibin); TString name=Form("%s%s",candle.Data(),suffix.Data()); sum += GetSum(name.Data()); } return sum; } //___________________________________________________________________________ TH1D* AliNormalizationCounter::DrawNEventsForNorm(Bool_t drawRatio){ //usare algebra histos fCounters.SortRubric("Run"); TString selection; selection.Form("event:noPrimaryV"); TH1D* hnoPrimV = fCounters.Get("run",selection.Data()); hnoPrimV->Sumw2(); selection.Form("event:zvtxGT10"); TH1D* hzvtx= fCounters.Get("run",selection.Data()); hzvtx->Sumw2(); selection.Form("event:PrimaryV"); TH1D* hPrimV = fCounters.Get("run",selection.Data()); hPrimV->Sumw2(); hzvtx->Multiply(hnoPrimV); hzvtx->Divide(hPrimV); selection.Form("event:countForNorm"); TH1D* hCountForNorm = fCounters.Get("run",selection.Data()); hCountForNorm->Sumw2(); hCountForNorm->Add(hzvtx,-1.); if(drawRatio){ selection.Form("event:triggered"); TH1D* htriggered = fCounters.Get("run",selection.Data()); htriggered->Sumw2(); hCountForNorm->Divide(htriggered); } hCountForNorm->DrawClone(); return hCountForNorm; } //___________________________________________________________________________ Int_t AliNormalizationCounter::Multiplicity(AliVEvent* event){ Int_t multiplicity = 0; AliAODEvent *eventAOD = (AliAODEvent*)event; AliAODTracklets * aodTracklets = (AliAODTracklets*)eventAOD->GetTracklets(); Int_t ntracklets = (Int_t)aodTracklets->GetNumberOfTracklets(); for(Int_t i=0;i<ntracklets; i++){ Double_t theta = aodTracklets->GetTheta(i); Double_t eta = -TMath::Log( TMath::Tan(theta/2.) ); // check the formula if(TMath::Abs(eta)<fMultiplicityEtaRange){ // set the proper cut on eta multiplicity++; } } return multiplicity; } //___________________________________________________________________________ void AliNormalizationCounter::FillCounters(TString name, Int_t runNumber, Int_t multiplicity, Double_t spherocity){ Int_t sphToInteger=spherocity*fSpherocitySteps; if(fMultiplicity && !fSpherocity) fCounters.Count(Form("Event:%s/Run:%d/Multiplicity:%d",name.Data(),runNumber,multiplicity)); else if(fMultiplicity && fSpherocity) fCounters.Count(Form("Event:%s/Run:%d/Multiplicity:%d/Spherocity:%d",name.Data(),runNumber,multiplicity,sphToInteger)); else if(!fMultiplicity && fSpherocity) fCounters.Count(Form("Event:%s/Run:%d/Spherocity:%d",name.Data(),runNumber,sphToInteger)); else fCounters.Count(Form("Event:%s/Run:%d",name.Data(),runNumber)); return; }
37.39527
229
0.718087
wiechula
cd9593b4fa1fe9c662a604485f9e66d17c879764
2,710
cpp
C++
control/group_utils.cpp
TheMrButcher/offline-mentor
15c362710fc993b21ed2d23adfc98e797e2380db
[ "MIT" ]
null
null
null
control/group_utils.cpp
TheMrButcher/offline-mentor
15c362710fc993b21ed2d23adfc98e797e2380db
[ "MIT" ]
101
2017-03-11T19:09:46.000Z
2017-09-04T17:37:55.000Z
control/group_utils.cpp
TheMrButcher/offline-mentor
15c362710fc993b21ed2d23adfc98e797e2380db
[ "MIT" ]
1
2018-03-13T03:47:15.000Z
2018-03-13T03:47:15.000Z
#include "group_utils.h" #include "solution_utils.h" #include "settings.h" #include <QDir> namespace { QList<Group> groups; QHash<QUuid, const Group*> groupMap; QHash<QString, QList<const Group*>> userToGroupMap; const Group BAD_GROUP; const QList<const Group*> EMPTY_GROUP_LIST; void updateAll() { groupMap.clear(); userToGroupMap.clear(); for (auto& group : groups) { groupMap[group.id] = &group; if (group.sortedUserNames.size() != group.userNames.size()) group.sort(); for (const auto& userName : group.userNames) userToGroupMap[userName].append(&group); } updateUserNamesWithoutGroup(); } void saveGroups() { updateAll(); const auto& settings = Settings::instance(); Group::save(groups, settings.localGroupsPath()); if (!settings.groupsPath.isEmpty()) Group::save(groups, settings.groupsPath); } } void loadGroups() { groups.clear(); const auto& settings = Settings::instance(); if (!settings.groupsPath.isEmpty()) { QHash<QUuid, Group> allGroupMap; if (QDir().exists(settings.groupsPath)) { QList<Group> remoteGroups = Group::load(settings.groupsPath); for (const auto& group : remoteGroups) allGroupMap[group.id] = group; } if (QFile(settings.localGroupsPath()).exists()) { QList<Group> localGroups = Group::load(settings.localGroupsPath()); for (const auto& group : localGroups) allGroupMap[group.id] = group; } groups = allGroupMap.values(); saveGroups(); return; } if (QFile(settings.localGroupsPath()).exists()) groups = Group::load(settings.localGroupsPath()); updateAll(); } const QList<Group>& getGroups() { return groups; } const Group& getGroup(const QUuid& id) { auto it = groupMap.find(id); if (it == groupMap.end()) return BAD_GROUP; return *it.value(); } void removeGroup(const QUuid& id) { for (auto it = groups.begin(); it != groups.end(); ++it) { if (it->id == id) { groups.erase(it); saveGroups(); return; } } } void addGroup(const Group& group) { for (auto it = groups.begin(); it != groups.end(); ++it) { if (it->id == group.id) { *it = group; it->sortedUserNames.clear(); saveGroups(); return; } } groups.append(group); saveGroups(); } const QList<const Group*>& getGroupsByUserName(QString userName) { auto it = userToGroupMap.find(userName); if (it == userToGroupMap.end()) return EMPTY_GROUP_LIST; return it.value(); }
25.327103
79
0.597048
TheMrButcher
cd98b9ee25b889d835f5249f248b390bbe62a9e3
309
cpp
C++
Source/Minigame/src/source/ui/Image.cpp
marcspoon07/Project1_Minigame
d8da2892fc97cc2e8310cf9c042d75dcbad4a6ba
[ "MIT" ]
null
null
null
Source/Minigame/src/source/ui/Image.cpp
marcspoon07/Project1_Minigame
d8da2892fc97cc2e8310cf9c042d75dcbad4a6ba
[ "MIT" ]
null
null
null
Source/Minigame/src/source/ui/Image.cpp
marcspoon07/Project1_Minigame
d8da2892fc97cc2e8310cf9c042d75dcbad4a6ba
[ "MIT" ]
null
null
null
#include "../../headers/ui/Image.h" #include "../../headers/Renderer2D.h" Image::Image(const char * path, int x, int y) { pImageId = Resources::getInstance()->Load<Sprite>(path); px = x; py = y; } Image::~Image() { } void Image::Render() { Renderer2D::getInstance()->RenderGraphic(pImageId, px, py); }
16.263158
60
0.63754
marcspoon07
cd99a2cdcd1d5e8b08b64131088762f12eac5a73
4,903
cc
C++
ent/src/yb/master/catalog_entity_info.cc
adil246/yugabyte-db
dc886cdd43497543e8ad2ad07bb77ad02e4cd4b1
[ "Apache-2.0", "CC0-1.0" ]
1
2021-06-11T10:23:00.000Z
2021-06-11T10:23:00.000Z
ent/src/yb/master/catalog_entity_info.cc
adil246/yugabyte-db
dc886cdd43497543e8ad2ad07bb77ad02e4cd4b1
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
ent/src/yb/master/catalog_entity_info.cc
adil246/yugabyte-db
dc886cdd43497543e8ad2ad07bb77ad02e4cd4b1
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
// Copyright (c) YugaByte, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations // under the License. #include "yb/common/wire_protocol.h" #include "yb/master/catalog_entity_info.h" #include "yb/master/master.pb.h" using std::set; namespace yb { namespace master { // ================================================================================================ // CDCStreamInfo // ================================================================================================ const TableId& CDCStreamInfo::table_id() const { return LockForRead()->pb.table_id(); } std::string CDCStreamInfo::ToString() const { auto l = LockForRead(); return Format("$0 [table=$1] {metadata=$2} ", id(), l->pb.table_id(), l->pb.ShortDebugString()); } // ================================================================================================ // UniverseReplicationInfo // ================================================================================================ Result<std::shared_ptr<CDCRpcTasks>> UniverseReplicationInfo::GetOrCreateCDCRpcTasks( google::protobuf::RepeatedPtrField<HostPortPB> producer_masters) { std::vector<HostPort> hp; HostPortsFromPBs(producer_masters, &hp); std::string master_addrs = HostPort::ToCommaSeparatedString(hp); std::lock_guard<decltype(lock_)> l(lock_); if (cdc_rpc_tasks_ != nullptr) { // Master Addresses changed, update YBClient with new retry logic. if (master_addrs_ != master_addrs) { if (cdc_rpc_tasks_->UpdateMasters(master_addrs).ok()) { master_addrs_ = master_addrs; } } return cdc_rpc_tasks_; } auto result = CDCRpcTasks::CreateWithMasterAddrs(producer_id_, master_addrs); if (result.ok()) { cdc_rpc_tasks_ = *result; master_addrs_ = master_addrs; } return result; } std::string UniverseReplicationInfo::ToString() const { auto l = LockForRead(); return strings::Substitute("$0 [data=$1] ", id(), l->pb.ShortDebugString()); } //////////////////////////////////////////////////////////// // SnapshotInfo //////////////////////////////////////////////////////////// SnapshotInfo::SnapshotInfo(SnapshotId id) : snapshot_id_(std::move(id)) {} SysSnapshotEntryPB::State SnapshotInfo::state() const { return LockForRead()->state(); } const std::string& SnapshotInfo::state_name() const { return LockForRead()->state_name(); } std::string SnapshotInfo::ToString() const { return YB_CLASS_TO_STRING(snapshot_id); } bool SnapshotInfo::IsCreateInProgress() const { return LockForRead()->is_creating(); } bool SnapshotInfo::IsRestoreInProgress() const { return LockForRead()->is_restoring(); } bool SnapshotInfo::IsDeleteInProgress() const { return LockForRead()->is_deleting(); } void SnapshotInfo::AddEntries( const TableDescription& table_description, std::unordered_set<NamespaceId>* added_namespaces) { SysSnapshotEntryPB& pb = mutable_metadata()->mutable_dirty()->pb; AddEntries( table_description, pb.mutable_entries(), pb.mutable_tablet_snapshots(), added_namespaces); } template <class Info> auto AddInfoEntry(Info* info, google::protobuf::RepeatedPtrField<SysRowEntry>* out) { auto lock = info->LockForRead(); FillInfoEntry(*info, out->Add()); return lock; } void SnapshotInfo::AddEntries( const TableDescription& table_description, google::protobuf::RepeatedPtrField<SysRowEntry>* out, google::protobuf::RepeatedPtrField<SysSnapshotEntryPB::TabletSnapshotPB>* tablet_infos, std::unordered_set<NamespaceId>* added_namespaces) { // Note: SysSnapshotEntryPB includes PBs for stored (1) namespaces (2) tables (3) tablets. // Add namespace entry. if (added_namespaces->emplace(table_description.namespace_info->id()).second) { TRACE("Locking namespace"); AddInfoEntry(table_description.namespace_info.get(), out); } // Add table entry. { TRACE("Locking table"); AddInfoEntry(table_description.table_info.get(), out); } // Add tablet entries. for (const scoped_refptr<TabletInfo>& tablet : table_description.tablet_infos) { SysSnapshotEntryPB::TabletSnapshotPB* const tablet_info = tablet_infos ? tablet_infos->Add() : nullptr; TRACE("Locking tablet"); auto l = AddInfoEntry(tablet.get(), out); if (tablet_info) { tablet_info->set_id(tablet->id()); tablet_info->set_state(SysSnapshotEntryPB::CREATING); } } } } // namespace master } // namespace yb
33.128378
100
0.649194
adil246
cd99e5d0a13c82ca28e6238762db3bc55cb82eae
5,905
cc
C++
PMTSim/OldZSolid.cc
simoncblyth/j
9e7783d70dcee53425713192b84d11918c8856f0
[ "Apache-2.0" ]
1
2021-10-31T13:12:31.000Z
2021-10-31T13:12:31.000Z
PMTSim/OldZSolid.cc
simoncblyth/j
9e7783d70dcee53425713192b84d11918c8856f0
[ "Apache-2.0" ]
null
null
null
PMTSim/OldZSolid.cc
simoncblyth/j
9e7783d70dcee53425713192b84d11918c8856f0
[ "Apache-2.0" ]
null
null
null
#include <cassert> #include <sstream> #include <iomanip> #include "OldZSolid.hh" #include "ZSolid.h" #include "G4Ellipsoid.hh" #include "G4Tubs.hh" #include "G4Polycone.hh" #include "G4UnionSolid.hh" #include "NP.hh" std::string OldZSolid::desc() const { std::stringstream ss ; ss << " EntityTypeName " << std::setw(15) << ZSolid::EntityTypeName(solid) << " EntityType " << std::setw(3) << ZSolid::EntityType(solid) << " label " << std::setw(10) << label << " zdelta " << std::setw(10) << std::fixed << std::setprecision(3) << zdelta << " z1 " << std::setw(10) << std::fixed << std::setprecision(3) << z1() << " z0 " << std::setw(10) << std::fixed << std::setprecision(3) << z0() ; std::string s = ss.str(); return s ; } double OldZSolid::z0() const { double _z0, _z1 ; ZSolid::ZRange(_z0, _z1, solid ); return _z0 ; } double OldZSolid::z1() const { double _z0, _z1 ; ZSolid::ZRange(_z0, _z1, solid ); return _z1 ; } int OldZSolid::classifyZCut( double zcut ) const { double az0 = zdelta + z0() ; double az1 = zdelta + z1() ; return ZSolid::ClassifyZCut( az0, az1, zcut ); } void OldZSolid::applyZCut( double zcut ) { double az1 = zdelta + z1() ; double az0 = zdelta + z0() ; bool expect = az1 > az0 ; if(!expect) exit(EXIT_FAILURE); assert( expect ); assert( zcut < az1 && zcut > az0 ); double local_zcut = zcut - zdelta ; ZSolid::ApplyZCut( solid, local_zcut ); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void OldZSolidList::dump(const char* msg) const { std::cout << msg << std::endl ; for(unsigned i=0 ; i < solids.size() ; i++) { const OldZSolid& zsi = solids[i] ; double az0 = zsi.zdelta + zsi.z0() ; double az1 = zsi.zdelta + zsi.z1() ; std::cout << std::setw(3) << i << " " << zsi.desc() << " az1 " << std::setw(10) << std::fixed << std::setprecision(3) << az1 << " az0 " << std::setw(10) << std::fixed << std::setprecision(3) << az0 << std::endl ; } } void OldZSolidList::save(const char* path) const { std::vector<double> tmp ; unsigned num = solids.size() ; for(unsigned i=0 ; i < num ; i++) { const OldZSolid& zsi = solids[i] ; tmp.push_back(zsi.z0()); tmp.push_back(zsi.z1()); tmp.push_back(zsi.zdelta); tmp.push_back(0.); double az0 = zsi.zdelta + zsi.z0() ; double az1 = zsi.zdelta + zsi.z1() ; tmp.push_back(az0); tmp.push_back(az1); tmp.push_back(0.); tmp.push_back(0.); } NP* a = NP::Make<double>( num, 2, 4 ); a->read(tmp.data()); a->save(path); } G4VSolid* OldZSolidList::makeUnionSolid(const std::string& solidname) const { dump("OldZSolidList::makeUnionSolid"); G4VSolid* solid = solids[0].solid ; for(unsigned i=1 ; i < solids.size() ; i++) { const OldZSolid& zsi = solids[i] ; solid = new G4UnionSolid( solidname+zsi.label, solid, zsi.solid, 0, G4ThreeVector(0,0,zsi.zdelta) ); } save("/tmp/ZSolids.npy"); return solid ; } unsigned OldZSolidList::classifyZCutCount( double zcut, int q_cls ) { unsigned count(0); for(unsigned idx=0 ; idx < solids.size() ; idx++ ) { OldZSolid& zsi = solids[idx] ; if( zsi.classifyZCut(zcut) == q_cls ) count += 1 ; } return count ; } /** OldZSolids::makeUnionSolidZCut --------------------------------- Hmm how to do this with a tree of solids instead of the artifically collected vector ? **/ G4VSolid* OldZSolidList::makeUnionSolidZCut(const std::string& solidname, double zcut) { unsigned num_undefined = classifyZCutCount(zcut, ZSolid::UNDEFINED ); unsigned num_include = classifyZCutCount(zcut, ZSolid::INCLUDE ); unsigned num_straddle = classifyZCutCount(zcut, ZSolid::STRADDLE ); unsigned num_exclude = classifyZCutCount(zcut, ZSolid::EXCLUDE ); unsigned num_solid = num_include + num_straddle ; std::cout << "OldZSolids::makeUnionSolidZCut" << " num_undefined " << num_undefined << " num_include " << num_include << " num_straddle " << num_straddle << " num_exclude " << num_exclude << " num_solid " << num_solid << std::endl ; assert( num_undefined == 0 ); assert( num_solid > 0 ); OldZSolid& zsi0 = solids[0] ; G4VSolid* solid = zsi0.solid ; int cls = zsi0.classifyZCut(zcut ); assert( cls == ZSolid::INCLUDE || cls == ZSolid::STRADDLE ); // first solid must be at z top and at least partially included if( cls == ZSolid::STRADDLE ) zsi0.applyZCut( zcut ); if( num_solid == 1 ) return solid ; for(unsigned idx=1 ; idx < solids.size() ; idx++) { OldZSolid& zsi = solids[idx] ; cls = zsi.classifyZCut( zcut ); if( cls == ZSolid::STRADDLE ) zsi.applyZCut( zcut ); if( cls == ZSolid::INCLUDE || cls == ZSolid::STRADDLE ) { solid = new G4UnionSolid( solidname+zsi.label, solid, zsi.solid, 0, G4ThreeVector(0,0,zsi.zdelta) ); } } return solid ; }
27.593458
129
0.503472
simoncblyth
cd9ae0cdb42387c379c25e46709d5762a5031852
2,485
hpp
C++
src/container/containerBase.hpp
myrabiedermann/rsmd
97ccc65dbb3d9d16e5e6a88f256d97a36c511740
[ "Apache-2.0" ]
2
2021-01-30T00:30:32.000Z
2021-04-20T11:54:53.000Z
src/container/containerBase.hpp
myrabiedermann/rsmd
97ccc65dbb3d9d16e5e6a88f256d97a36c511740
[ "Apache-2.0" ]
null
null
null
src/container/containerBase.hpp
myrabiedermann/rsmd
97ccc65dbb3d9d16e5e6a88f256d97a36c511740
[ "Apache-2.0" ]
null
null
null
/************************************************ * * * rs@md * * (reactive steps @ molecular dynamics ) * * * ************************************************/ /* Copyright 2020 Myra Biedermann Licensed under the Apache License, Version 2.0 Parts of the code within this file was modified from "container_class_base.hpp" within github repository https://github.com/simonraschke/vesicle2.git, licensed under Apache License Version 2.0 Myra Biedermann thankfully acknowledges support from Simon Raschke. */ #pragma once #include <iterator> // // a container base class to derive from // // implements all iterator-related functions like begin() / end() etc. // for use in loops // as well as container-related operators like [] and () // template<typename T> struct ContainerBase { T data {}; inline auto& operator()(std::size_t i) { return data[i]; }; inline constexpr auto& operator()(std::size_t i) const { return data[i]; }; inline auto& operator[](std::size_t i) { return data[i]; }; inline constexpr auto& operator[](std::size_t i) const { return data[i]; }; inline auto begin() { return std::begin(data); }; inline auto end() { return std::end(data); }; inline auto begin() const { return std::begin(data); }; inline auto end() const { return std::end(data); }; inline auto cbegin() const { return std::cbegin(data); }; inline auto cend() const { return std::cend(data); }; inline auto rbegin() { return std::rbegin(data); }; inline auto rend() { return std::rend(data); }; inline auto rbegin() const { return std::rbegin(data); }; inline auto rend() const { return std::rend(data); }; inline auto crbegin() const { return std::crbegin(data); }; inline auto crend() const { return std::crend(data); }; inline auto size() const { return data.size(); }; inline auto& front() { return *this->begin(); } inline const auto& front() const { return *this->begin(); } inline auto& back() { auto tmp = this->end(); --tmp; return *tmp; } inline const auto& back() const { auto tmp = this->end(); --tmp; return *tmp; } virtual ~ContainerBase() = default; protected: ContainerBase() = default; };
34.513889
86
0.557344
myrabiedermann
cd9fcfdde8fb4d728f47f039587e4c30b13c56a7
2,190
hpp
C++
src/comm/protocol.hpp
spencercjh/LIBBLE-PS
ca6259ccf20d6ef7f683b2d4bc00d846da127c2c
[ "Apache-2.0" ]
null
null
null
src/comm/protocol.hpp
spencercjh/LIBBLE-PS
ca6259ccf20d6ef7f683b2d4bc00d846da127c2c
[ "Apache-2.0" ]
1
2021-07-06T12:08:21.000Z
2021-07-06T12:08:21.000Z
src/comm/protocol.hpp
spencercjh/LIBBLE-PS
ca6259ccf20d6ef7f683b2d4bc00d846da127c2c
[ "Apache-2.0" ]
null
null
null
/** * Copyright (c) 2017 LIBBLE team supervised by Dr. Wu-Jun LI at Nanjing University. * All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _PROTOCOL_HPP_ #define _PROTOCOL_HPP_ /* this file define the tag number used for MPI for sending different messages */ // from coordinator #define CW_PARAMS 100 // coordinator sends parameters to worker #define CW_INFO 101 // coordinator sends info to worker #define CW_GRAD 102 // coordinator sends full grad to worker #define CS_INFO 103 // coordinator sends info to server #define CSWPULL_INFO 104// coordinator sends pull w_id info to server #define CSWPUSH_INFO 105// coordinator sends push w_id info to server // from server #define SW_PARAMS 200// server sends parameters to worker #define SC_EPOCH 201 // server sends epoch to coordinator to count time #define SC_PARAMS 202// server sends parameters to coordinator in the end #define SW_C 203 // server sends c to worker #define SW_GRAD 204 // server sends full grad to worker // from worker #define WS_GRADS 300 // worker sends gradients to server #define WC_LOSS 301 // worker sends loss to coordinator #define WC_GRAD 302 // worker sends part full grad to coordinator #define WC_PARAMS 303// worker sends parameters to coordinator #define WS_PARAMS 304// worker sends parameters to coordinator #define WCP_INFO 305 // worker sends pull info to coordinator #define WCG_INFO 306 // worker sends push info to coordinator #define WS_C 307 // worker sends c to server #define WC_ACCU 308 // worker sends accuracy to coordinator #endif
46.595745
91
0.733333
spencercjh
cda0b0c65646a25196c4eecdc6c02dd6d81505c9
11,879
cpp
C++
qt-creator-opensource-src-4.6.1/src/libs/qmljs/qmljsscopechain.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
5
2018-12-22T14:49:13.000Z
2022-01-13T07:21:46.000Z
qt-creator-opensource-src-4.6.1/src/libs/qmljs/qmljsscopechain.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
null
null
null
qt-creator-opensource-src-4.6.1/src/libs/qmljs/qmljsscopechain.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
8
2018-07-17T03:55:48.000Z
2021-12-22T06:37:53.000Z
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #include "qmljsscopechain.h" #include "qmljsbind.h" #include "qmljsevaluate.h" #include "qmljsmodelmanagerinterface.h" #include "parser/qmljsengine_p.h" #include <QRegExp> using namespace QmlJS; /*! \class QmlJS::ScopeChain \brief The ScopeChain class describes the scopes used for global lookup in a specific location. \sa Document Context ScopeBuilder A ScopeChain is used to perform global lookup with the lookup() function and to access information about the enclosing scopes. Once constructed for a Document in a Context it represents the root scope of that Document. From there, a ScopeBuilder can be used to push and pop scopes corresponding to functions, object definitions, etc. It is an error to use the same ScopeChain from multiple threads; use a copy. Copying is cheap. Initial construction is currently expensive. When a QmlJSEditor::QmlJSEditorDocument is available, there's no need to construct a new ScopeChain. Instead use QmlJSEditorDocument::semanticInfo()::scopeChain(). */ QmlComponentChain::QmlComponentChain(const Document::Ptr &document) : m_document(document) { } QmlComponentChain::~QmlComponentChain() { qDeleteAll(m_instantiatingComponents); } Document::Ptr QmlComponentChain::document() const { return m_document; } QList<const QmlComponentChain *> QmlComponentChain::instantiatingComponents() const { return m_instantiatingComponents; } const ObjectValue *QmlComponentChain::idScope() const { if (!m_document) return 0; return m_document->bind()->idEnvironment(); } const ObjectValue *QmlComponentChain::rootObjectScope() const { if (!m_document) return 0; return m_document->bind()->rootObjectValue(); } void QmlComponentChain::addInstantiatingComponent(const QmlComponentChain *component) { m_instantiatingComponents.append(component); } ScopeChain::ScopeChain(const Document::Ptr &document, const ContextPtr &context) : m_document(document) , m_context(context) , m_globalScope(0) , m_cppContextProperties(0) , m_qmlTypes(0) , m_jsImports(0) , m_modified(false) { initializeRootScope(); } Document::Ptr ScopeChain::document() const { return m_document; } const ContextPtr &ScopeChain::context() const { return m_context; } const Value * ScopeChain::lookup(const QString &name, const ObjectValue **foundInScope) const { QList<const ObjectValue *> scopes = all(); for (int index = scopes.size() - 1; index != -1; --index) { const ObjectValue *scope = scopes.at(index); if (const Value *member = scope->lookupMember(name, m_context)) { if (foundInScope) *foundInScope = scope; return member; } } if (foundInScope) *foundInScope = 0; // we're confident to implement global lookup correctly, so return 'undefined' return m_context->valueOwner()->undefinedValue(); } const Value *ScopeChain::evaluate(AST::Node *node) const { Evaluate evaluator(this); return evaluator(node); } const ObjectValue *ScopeChain::globalScope() const { return m_globalScope; } void ScopeChain::setGlobalScope(const ObjectValue *globalScope) { m_modified = true; m_globalScope = globalScope; } const ObjectValue *ScopeChain::cppContextProperties() const { return m_cppContextProperties; } void ScopeChain::setCppContextProperties(const ObjectValue *cppContextProperties) { m_modified = true; m_cppContextProperties = cppContextProperties; } QSharedPointer<const QmlComponentChain> ScopeChain::qmlComponentChain() const { return m_qmlComponentScope; } void ScopeChain::setQmlComponentChain(const QSharedPointer<const QmlComponentChain> &qmlComponentChain) { m_modified = true; m_qmlComponentScope = qmlComponentChain; } QList<const ObjectValue *> ScopeChain::qmlScopeObjects() const { return m_qmlScopeObjects; } void ScopeChain::setQmlScopeObjects(const QList<const ObjectValue *> &qmlScopeObjects) { m_modified = true; m_qmlScopeObjects = qmlScopeObjects; } const TypeScope *ScopeChain::qmlTypes() const { return m_qmlTypes; } void ScopeChain::setQmlTypes(const TypeScope *qmlTypes) { m_modified = true; m_qmlTypes = qmlTypes; } const JSImportScope *ScopeChain::jsImports() const { return m_jsImports; } void ScopeChain::setJsImports(const JSImportScope *jsImports) { m_modified = true; m_jsImports = jsImports; } QList<const ObjectValue *> ScopeChain::jsScopes() const { return m_jsScopes; } void ScopeChain::setJsScopes(const QList<const ObjectValue *> &jsScopes) { m_modified = true; m_jsScopes = jsScopes; } void ScopeChain::appendJsScope(const ObjectValue *scope) { m_modified = true; m_jsScopes += scope; } QList<const ObjectValue *> ScopeChain::all() const { if (m_modified) update(); return m_all; } static void collectScopes(const QmlComponentChain *chain, QList<const ObjectValue *> *target) { foreach (const QmlComponentChain *parent, chain->instantiatingComponents()) collectScopes(parent, target); if (!chain->document()) return; if (const ObjectValue *root = chain->rootObjectScope()) target->append(root); if (const ObjectValue *ids = chain->idScope()) target->append(ids); } void ScopeChain::update() const { m_modified = false; m_all.clear(); m_all += m_globalScope; if (m_cppContextProperties) m_all += m_cppContextProperties; // the root scope in js files doesn't see instantiating components if (m_document->language() != Dialect::JavaScript || m_jsScopes.count() != 1) { if (m_qmlComponentScope) { foreach (const QmlComponentChain *parent, m_qmlComponentScope->instantiatingComponents()) collectScopes(parent, &m_all); } } ObjectValue *root = 0; ObjectValue *ids = 0; if (m_qmlComponentScope && m_qmlComponentScope->document()) { const Bind *bind = m_qmlComponentScope->document()->bind(); root = bind->rootObjectValue(); ids = bind->idEnvironment(); } if (root && !m_qmlScopeObjects.contains(root)) m_all += root; m_all += m_qmlScopeObjects; if (ids) m_all += ids; if (m_qmlTypes) m_all += m_qmlTypes; if (m_jsImports) m_all += m_jsImports; m_all += m_jsScopes; } static void addInstantiatingComponents(ContextPtr context, QmlComponentChain *chain) { const QRegExp importCommentPattern(QLatin1String("@scope\\s+(.*)")); foreach (const AST::SourceLocation &commentLoc, chain->document()->engine()->comments()) { const QString &comment = chain->document()->source().mid(commentLoc.begin(), commentLoc.length); // find all @scope annotations QStringList additionalScopes; int lastOffset = -1; forever { lastOffset = importCommentPattern.indexIn(comment, lastOffset + 1); if (lastOffset == -1) break; additionalScopes << QFileInfo(chain->document()->path() + QLatin1Char('/') + importCommentPattern.cap(1).trimmed()).absoluteFilePath(); } foreach (const QmlComponentChain *c, chain->instantiatingComponents()) additionalScopes.removeAll(c->document()->fileName()); foreach (const QString &scope, additionalScopes) { Document::Ptr doc = context->snapshot().document(scope); if (doc) { QmlComponentChain *ch = new QmlComponentChain(doc); chain->addInstantiatingComponent(ch); addInstantiatingComponents(context, ch); } } } } void ScopeChain::initializeRootScope() { ValueOwner *valueOwner = m_context->valueOwner(); const Snapshot &snapshot = m_context->snapshot(); Bind *bind = m_document->bind(); m_globalScope = valueOwner->globalObject(); m_cppContextProperties = valueOwner->cppQmlTypes().cppContextProperties(); QHash<const Document *, QmlComponentChain *> componentScopes; QmlComponentChain *chain = new QmlComponentChain(m_document); m_qmlComponentScope = QSharedPointer<const QmlComponentChain>(chain); if (const Imports *imports = m_context->imports(m_document.data())) { m_qmlTypes = imports->typeScope(); m_jsImports = imports->jsImportScope(); } if (m_document->qmlProgram()) { componentScopes.insert(m_document.data(), chain); makeComponentChain(chain, snapshot, &componentScopes); } else { // add scope chains for all components that import this file // unless there's .pragma library if (!m_document->bind()->isJsLibrary()) { foreach (Document::Ptr otherDoc, snapshot) { foreach (const ImportInfo &import, otherDoc->bind()->imports()) { if ((import.type() == ImportType::File && m_document->fileName() == import.path()) || (import.type() == ImportType::QrcFile && ModelManagerInterface::instance()->filesAtQrcPath(import.path()) .contains(m_document->fileName()))) { QmlComponentChain *component = new QmlComponentChain(otherDoc); componentScopes.insert(otherDoc.data(), component); chain->addInstantiatingComponent(component); makeComponentChain(component, snapshot, &componentScopes); } } } } if (bind->rootObjectValue()) m_jsScopes += bind->rootObjectValue(); } addInstantiatingComponents(m_context, chain); m_modified = true; } void ScopeChain::makeComponentChain( QmlComponentChain *target, const Snapshot &snapshot, QHash<const Document *, QmlComponentChain *> *components) { Document::Ptr doc = target->document(); if (!doc->qmlProgram()) return; const Bind *bind = doc->bind(); // add scopes for all components instantiating this one foreach (Document::Ptr otherDoc, snapshot) { if (otherDoc == doc) continue; if (otherDoc->bind()->usesQmlPrototype(bind->rootObjectValue(), m_context)) { if (!components->contains(otherDoc.data())) { QmlComponentChain *component = new QmlComponentChain(otherDoc); components->insert(otherDoc.data(), component); target->addInstantiatingComponent(component); makeComponentChain(component, snapshot, components); } } } }
30.458974
147
0.665797
kevinlq
cda180b0351ba801e73472770a55a9219d42ffd2
6,460
cpp
C++
deps/clipp-1.1.0/test/mixed_params_test.cpp
mbeckem/extpp
06aa153ebf617c779e66d612cfc11e01869c602a
[ "MIT" ]
1
2018-05-22T15:47:14.000Z
2018-05-22T15:47:14.000Z
deps/clipp-1.1.0/test/mixed_params_test.cpp
mbeckem/prequel
06aa153ebf617c779e66d612cfc11e01869c602a
[ "MIT" ]
null
null
null
deps/clipp-1.1.0/test/mixed_params_test.cpp
mbeckem/prequel
06aa153ebf617c779e66d612cfc11e01869c602a
[ "MIT" ]
null
null
null
/***************************************************************************** * * CLIPP - command line interfaces for modern C++ * * released under MIT license * * (c) 2017 André Müller; foss@andremueller-online.de * *****************************************************************************/ #include "testing.h" //------------------------------------------------------------------- struct active { int av = 0; int bv = 1; float cv = 0.0f, dv = 1.0f; double ev = 0.0, fv = 1.0; std::string gv; bool a = false, b = false, c = false, d = false, e = false, f = false, g = false, h = false, i = false; friend bool operator == (const active& x, const active& y) noexcept { if(x.a != y.a || x.b != y.b || x.c != y.c || x.d != y.d || x.e != y.e || x.f != y.f || x.g != y.g || x.h != y.h || x.i != y.i || x.av != y.av || x.bv != y.bv || x.gv != y.gv) return false; using std::abs; if(abs(x.cv - y.cv) > 1e-4f || abs(x.dv - y.dv) > 1e-4f || abs(x.ev - y.ev) > 1e-4 || abs(x.fv - y.fv) > 1e-4) return false; return true; } }; //------------------------------------------------------------------- void test(int lineNo, const std::initializer_list<const char*> args, const active& matches) { using namespace clipp; active m; auto cli = ( required("-a").set(m.a) & value("A",m.av), required("-b", "--bb").set(m.b) & value("B",m.bv), option("-c", "--cc").set(m.c) & value("C",m.cv) & opt_value("D",m.dv), option("-d", "--dd").set(m.d) & opt_value("D",m.dv), required("-e", "--ee").set(m.e) & value("E",m.ev), option("-f", "--ff").set(m.f) & opt_value("F",m.fv), value("G", m.gv).set(m.g), option("-h", "--hh", "---hhh").set(m.h), required("-i", "--ii").set(m.i) ); run_wrapped_variants({ __FILE__, lineNo }, args, cli, [&]{ m = active{}; }, [&]{ return m == matches; }); } //------------------------------------------------------------------- int main() { try { active m; test(__LINE__, {""}, m); m = active{}; m.a = true; test(__LINE__, {"-a"}, m); m = active{}; m.a = true; m.av = 65; test(__LINE__, {"-a", "65"}, m); test(__LINE__, {"-a65"}, m); m = active{}; m.b = true; test(__LINE__, {"-b"}, m); m = active{}; m.b = true; m.bv = 12; test(__LINE__, {"-b", "12"}, m); test(__LINE__, {"-b12"}, m); m = active{}; m.c = true; test(__LINE__, {"-c"}, m); m = active{}; m.c = true; m.cv = 2.3f; test(__LINE__, {"-c", "2.3"}, m); test(__LINE__, {"-c2.3"}, m); test(__LINE__, {"-c2", ".3"}, m); test(__LINE__, {"-c", "+2.3"}, m); test(__LINE__, {"-c+2.3"}, m); test(__LINE__, {"-c+2", ".3"}, m); m = active{}; m.c = true; m.cv = -2.3f; test(__LINE__, {"-c", "-2.3"}, m); test(__LINE__, {"-c-2.3"}, m); test(__LINE__, {"-c-2", ".3"}, m); m = active{}; m.c = true; m.cv = 1; m.dv = 2; test(__LINE__, {"-c", "1", "2"}, m); test(__LINE__, {"-c1", "2"}, m); test(__LINE__, {"-c1", "2"}, m); m = active{}; m.d = true; m.c = true; m.cv = 2; test(__LINE__, {"-c", "2", "-d"}, m); m = active{}; m.a = true; m.av = 1; m.c = true; m.cv = 2; test(__LINE__, {"-c", "2", "-a", "1"}, m); m = active{}; m.d = true; test(__LINE__, {"-d"}, m); m = active{}; m.d = true; m.dv = 2.3f; test(__LINE__, {"-d", "2.3"}, m); test(__LINE__, {"-d2.3"}, m); test(__LINE__, {"-d2", ".3"}, m); m = active{}; m.e = true; test(__LINE__, {"-e"}, m); m = active{}; m.e = true; m.ev = 2.3; test(__LINE__, {"-e", "2.3"}, m); test(__LINE__, {"-e2.3"}, m); test(__LINE__, {"-e2", ".3"}, m); m = active{}; m.f = true; test(__LINE__, {"-f"}, m); test(__LINE__, {"--ff"}, m); m = active{}; m.f = true; m.fv = 2.3; test(__LINE__, {"-f", "2.3"}, m); test(__LINE__, {"--ff", "2.3"}, m); test(__LINE__, {"-f2.3"}, m); test(__LINE__, {"--ff2.3"}, m); test(__LINE__, {"-f2", ".3"}, m); test(__LINE__, {"--ff2", ".3"}, m); m = active{}; m.g = true; m.gv = "xyz"; test(__LINE__, {"xyz"}, m); m = active{}; m.g = true; m.gv = "-h"; test(__LINE__, {"-h"}, m); m = active{}; m.g = true; m.gv = "--hh"; test(__LINE__, {"--hh"}, m); m = active{}; m.g = true; m.gv = "---hhh"; test(__LINE__, {"---hhh"}, m); m = active{}; m.g = true; m.gv = "--h"; test(__LINE__, {"--h"}, m); m = active{}; m.g = true; m.gv = "--hh"; test(__LINE__, {"--hh"}, m); m = active{}; m.g = true; m.gv = "-hh"; test(__LINE__, {"-hh"}, m); m = active{}; m.g = true; m.gv = "-hhh"; test(__LINE__, {"-hhh"}, m); m = active{}; m.h = true; m.g = true; m.gv = "x-y.z"; test(__LINE__, {"x-y.z", "-h"}, m); test(__LINE__, {"x-y.z", "--hh"}, m); test(__LINE__, {"x-y.z", "---hhh"}, m); m = active{}; m.i = true; m.g = true; m.gv = "xYz"; test(__LINE__, {"xYz", "-i"}, m); test(__LINE__, {"xYz", "--ii"}, m); m = active{}; m.g = true; m.gv = "-ii"; test(__LINE__, {"-ii"}, m); m = active{}; m.g = true; m.gv = "--i"; test(__LINE__, {"--i"}, m); m = active{}; m.a = true; m.av = 65; m.b = true; m.bv = 12; m.c = true; m.cv = -0.12f; m.d = true; m.dv = 2.3f; m.e = true; m.ev = 3.4; m.f = true; m.fv = 5.6; m.g = true; m.gv = "x-y.z"; m.h = true; m.i = true; test(__LINE__, {"-a", "65", "-b12", "-c", "-0.12f", "-d2.3", "-e3", ".4", "--ff", "5.6", "x-y.z", "-h", "--ii"}, m); test(__LINE__, {"-b12", "-c", "-0.12f", "-d2.3", "-e3", ".4", "-a", "65", "--ff", "5.6", "x-y.z", "-h", "--ii"}, m); test(__LINE__, {"-d2.3", "-e3", ".4", "-b12", "-c", "-0.12f", "-a", "65", "--ff", "5.6", "x-y.z", "-h", "--ii"}, m); } catch(std::exception& e) { std::cerr << e.what() << std::endl; return 1; } }
33.298969
81
0.377399
mbeckem
cda269db6115a616dfddb9275f904c4ed581b8e9
17,627
cpp
C++
printscan/faxsrv/com/whistler/faxoutboundroutinggroups.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
printscan/faxsrv/com/whistler/faxoutboundroutinggroups.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
printscan/faxsrv/com/whistler/faxoutboundroutinggroups.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 2000 Microsoft Corporation Module Name: FaxOutboundRoutingGroups.cpp Abstract: Implementation of CFaxOutboundRoutingGroups class. Author: Iv Garber (IvG) Jun, 2000 Revision History: --*/ #include "stdafx.h" #include "FaxComEx.h" #include "FaxOutboundRoutingGroups.h" #include "FaxOutboundRoutingGroup.h" // //================= FIND GROUP ======================================================= // STDMETHODIMP CFaxOutboundRoutingGroups::FindGroup( /*[in]*/ VARIANT vIndex, /*[out]*/ ContainerType::iterator &it ) /*++ Routine name : CFaxOutboundRoutingGroups::FindGroup Routine description: Find Group by given Variant : either Group Name either Group Index in the Collection Author: Iv Garber (IvG), Jun, 2000 Arguments: vIndex [in] - the Key to Find the Group it [out] - the found Group Iterator Return Value: Standard HRESULT code --*/ { HRESULT hr = S_OK; DBG_ENTER(_T("CFaxOutboundRoutingGroups::FindGroup"), hr); CComVariant var; if (vIndex.vt != VT_BSTR) { // // vIndex is not BSTR ==> convert to VT_I4 // hr = var.ChangeType(VT_I4, &vIndex); if (SUCCEEDED(hr)) { VERBOSE(DBG_MSG, _T("Parameter is Number : %d"), var.lVal); // // Check the Range of the Index // if (var.lVal > m_coll.size() || var.lVal < 1) { // // Invalid Index // hr = E_INVALIDARG; AtlReportError(CLSID_FaxOutboundRoutingGroups, IDS_ERROR_OUTOFRANGE, IID_IFaxOutboundRoutingGroups, hr); CALL_FAIL(GENERAL_ERR, _T("lIndex < 1 || lIndex > m_coll.size()"), hr); return hr; } // // Find the Group Object to Remove // it = m_coll.begin() + var.lVal - 1; return hr; } } // // We didnot success to convert the var to Number // So, try to convert it to the STRING // hr = var.ChangeType(VT_BSTR, &vIndex); if (FAILED(hr)) { hr = E_INVALIDARG; AtlReportError(CLSID_FaxOutboundRoutingGroups, IDS_ERROR_INVALID_ARGUMENT, IID_IFaxOutboundRoutingGroups, hr); CALL_FAIL(GENERAL_ERR, _T("var.ChangeType(VT_BSTR, &vIndex)"), hr); return hr; } VERBOSE(DBG_MSG, _T("Parameter is String : %s"), var.bstrVal); CComBSTR bstrName; it = m_coll.begin(); while (it != m_coll.end()) { hr = (*it)->get_Name(&bstrName); if (FAILED(hr)) { CALL_FAIL(GENERAL_ERR, _T("(*it)->get_Name(&bstrName)"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, IDS_ERROR_INVALID_ARGUMENT, IID_IFaxOutboundRoutingGroups, hr); return hr; } if (_tcsicmp(bstrName, var.bstrVal) == 0) { // // found the desired OR Group // return hr; } it++; } hr = E_INVALIDARG; CALL_FAIL(GENERAL_ERR, _T("Group Is Not Found"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, IDS_ERROR_INVALID_ARGUMENT, IID_IFaxOutboundRoutingGroups, hr); return hr; } // //===================== ADD GROUP ================================================= // STDMETHODIMP CFaxOutboundRoutingGroups::AddGroup( /*[in]*/ FAX_OUTBOUND_ROUTING_GROUP *pInfo, /*[out]*/ IFaxOutboundRoutingGroup **ppNewGroup ) /*++ Routine name : CFaxOutboundRoutingGroups::AddGroup Routine description: Create new Group Object and add it to the Collection. If ppNewGroup is NOT NULL, return in it ptr to the new Group Object. Author: Iv Garber (IvG), Jun, 2000 Arguments: pInfo [in] - Ptr to the Group's Data ppNewGroup [out] - Ptr to the new Group Object Return Value: Standard HRESULT code --*/ { HRESULT hr = S_OK; DBG_ENTER(_T("CFaxOutboundRoutingGroups::AddGroup"), hr); // // Create Group Object // CComObject<CFaxOutboundRoutingGroup> *pClass = NULL; hr = CComObject<CFaxOutboundRoutingGroup>::CreateInstance(&pClass); if (FAILED(hr) || (!pClass)) { if (!pClass) { hr = E_OUTOFMEMORY; CALL_FAIL(MEM_ERR, _T("CComObject<CFaxOutboundRoutingGroup>::CreateInstance(&pClass)"), hr); } else { CALL_FAIL(GENERAL_ERR, _T("CComObject<CFaxOutboundRoutingGroup>::CreateInstance(&pClass)"), hr); } AtlReportError(CLSID_FaxOutboundRoutingGroups, GetErrorMsgId(hr), IID_IFaxOutboundRoutingGroups, hr); return hr; } // // Init the Group Object // hr = pClass->Init(pInfo, m_pIFaxServerInner); if (FAILED(hr)) { CALL_FAIL(GENERAL_ERR, _T("pClass->Init(pInfo, m_pIFaxServerInner)"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, GetErrorMsgId(hr), IID_IFaxOutboundRoutingGroups, hr); delete pClass; return hr; } // // Get Interface from the pClass. // This will make AddRef() on the Interface. // This is the Collection's AddRef, which is freed at Collection's Dtor. // CComPtr<IFaxOutboundRoutingGroup> pObject = NULL; hr = pClass->QueryInterface(&pObject); if (FAILED(hr) || (!pObject)) { if (!pObject) { hr = E_FAIL; } CALL_FAIL(GENERAL_ERR, _T("pClass->QueryInterface(&pObject)"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, GetErrorMsgId(hr), IID_IFaxOutboundRoutingGroups, hr); delete pClass; return hr; } // // Put the Object in the collection // try { m_coll.push_back(pObject); } catch (exception &) { hr = E_OUTOFMEMORY; AtlReportError(CLSID_FaxOutboundRoutingGroups, IDS_ERROR_OUTOFMEMORY, IID_IFaxOutboundRoutingGroups, hr); CALL_FAIL(MEM_ERR, _T("m_coll.push_back(pObject)"), hr); // // pObject will call Release(), which will delete the pClass // return hr; } // // We want to save the current AddRef() to Collection // pObject.Detach(); // // Return new Group Object, if required // if (ppNewGroup) { if (::IsBadWritePtr(ppNewGroup, sizeof(IFaxOutboundRoutingGroup *))) { hr = E_POINTER; CALL_FAIL(GENERAL_ERR, _T("::IsBadWritePtr(ppNewGroup, sizeof(IFaxOutboundRoutingGroup *))"), hr); return hr; } else { *ppNewGroup = m_coll.back(); (*ppNewGroup)->AddRef(); } } return hr; } // //================= ADD ======================================================= // STDMETHODIMP CFaxOutboundRoutingGroups::Add( /*[in]*/ BSTR bstrName, /*[out, retval]*/ IFaxOutboundRoutingGroup **ppGroup ) /*++ Routine name : CFaxOutboundRoutingGroups::Add Routine description: Add new Group to the Groups Collection Author: Iv Garber (IvG), Jun, 2000 Arguments: bstrName [in] - Name of the new Group ppGroup [out] - the Group Object Return Value: Standard HRESULT code --*/ { HRESULT hr = S_OK; DBG_ENTER(_T("CFaxOutboundRoutingGroups::Add"), hr, _T("Name=%s"), bstrName); // // Check if the Name is valid // if (!bstrName) { hr = E_INVALIDARG; CALL_FAIL(GENERAL_ERR, _T("Empty Group Name"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, IDS_ERROR_INVALID_ARGUMENT, IID_IFaxOutboundRoutingGroups, hr); return hr; } if (_tcsicmp(bstrName, ROUTING_GROUP_ALL_DEVICES) == 0) { // // Cannot Add the "All Devices" Group // hr = E_INVALIDARG; CALL_FAIL(GENERAL_ERR, _T("All Devices Group"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, IDS_ERROR_ALLDEVICESGROUP, IID_IFaxOutboundRoutingGroups, hr); return hr; } // // Get Fax Server Handle // HANDLE faxHandle; hr = m_pIFaxServerInner->GetHandle(&faxHandle); ATLASSERT(SUCCEEDED(hr)); if (faxHandle == NULL) { // // Fax Server is not connected // hr = Fax_HRESULT_FROM_WIN32(ERROR_NOT_CONNECTED); CALL_FAIL(GENERAL_ERR, _T("faxHandle == NULL"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, IDS_ERROR_INVALID_ARGUMENT, IID_IFaxOutboundRoutingGroups, hr); return hr; } // // Add the Group to the Fax Server // if (!FaxAddOutboundGroup(faxHandle, bstrName)) { hr = Fax_HRESULT_FROM_WIN32(GetLastError()); CALL_FAIL(GENERAL_ERR, _T("FaxAddOutboundGroup(faxHandle, bstrName)"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, GetErrorMsgId(hr), IID_IFaxOutboundRoutingGroups, hr); return hr; } // // Add the Group to the Collection // FAX_OUTBOUND_ROUTING_GROUP groupData; groupData.dwNumDevices = 0; groupData.dwSizeOfStruct = sizeof(FAX_OUTBOUND_ROUTING_GROUP); groupData.lpctstrGroupName = bstrName; groupData.lpdwDevices = NULL; groupData.Status = FAX_GROUP_STATUS_EMPTY; hr = AddGroup(&groupData, ppGroup); return hr; } // //================= REMOVE ======================================================= // STDMETHODIMP CFaxOutboundRoutingGroups::Remove( /*[in]*/ VARIANT vIndex ) /*++ Routine name : CFaxOutboundRoutingGroups::Remove Routine description: Remove Group by the given key Author: Iv Garber (IvG), Jun, 2000 Arguments: vIndex [in] - the Key to Find the Group to Remove Return Value: Standard HRESULT code --*/ { HRESULT hr = S_OK; DBG_ENTER(_T("CFaxOutboundRoutingGroups::Remove"), hr); // // Find the Group // ContainerType::iterator it; hr = FindGroup(vIndex, it); if (FAILED(hr)) { return hr; } // // Take the Name of the Group // CComBSTR bstrName; hr = (*it)->get_Name(&bstrName); if (FAILED(hr)) { AtlReportError(CLSID_FaxOutboundRoutingGroups, GetErrorMsgId(hr), IID_IFaxOutboundRoutingGroups, hr); CALL_FAIL(GENERAL_ERR, _T("(*it)->get_Name(&bstrName)"), hr); return hr; } // // Check that Name is valid // if (_tcsicmp(bstrName, ROUTING_GROUP_ALL_DEVICES) == 0) { // // Cannot Remove "All Devices" Group // hr = E_INVALIDARG; CALL_FAIL(GENERAL_ERR, _T("All Devices Group"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, IDS_ERROR_ALLDEVICESGROUP, IID_IFaxOutboundRoutingGroups, hr); return hr; } // // Get Fax Server Handle // HANDLE faxHandle; hr = m_pIFaxServerInner->GetHandle(&faxHandle); ATLASSERT(SUCCEEDED(hr)); if (faxHandle == NULL) { // // Fax Server is not connected // hr = Fax_HRESULT_FROM_WIN32(ERROR_NOT_CONNECTED); CALL_FAIL(GENERAL_ERR, _T("faxHandle == NULL"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, IDS_ERROR_INVALID_ARGUMENT, IID_IFaxOutboundRoutingGroups, hr); return hr; } // // Remove from Fax Server // if (!FaxRemoveOutboundGroup(faxHandle, bstrName)) { hr = Fax_HRESULT_FROM_WIN32(GetLastError()); CALL_FAIL(GENERAL_ERR, _T("FaxRemoveOutboundGroup(faxHandle, bstrName)"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, GetErrorMsgId(hr), IID_IFaxOutboundRoutingGroups, hr); return hr; } // // If successed, remove from our collection as well // try { m_coll.erase(it); } catch(exception &) { // // Failed to remove the Group // hr = E_OUTOFMEMORY; AtlReportError(CLSID_FaxOutboundRoutingGroups, GetErrorMsgId(hr), IID_IFaxOutboundRoutingGroups, hr); CALL_FAIL(MEM_ERR, _T("m_coll.erase(it)"), hr); return hr; } return hr; } // //==================== GET ITEM =================================================== // STDMETHODIMP CFaxOutboundRoutingGroups::get_Item( /*[in]*/ VARIANT vIndex, /*[out, retval]*/ IFaxOutboundRoutingGroup **ppGroup ) /*++ Routine name : CFaxOutboundRoutingGroups::get_Item Routine description: Return Item from the Collection either by Group Name either by its Index inside the Collection. Author: Iv Garber (IvG), Jun, 2000 Arguments: vIndex [in] - Group Name or Item Index ppGroup [out] - the resultant Group Object Return Value: Standard HRESULT code --*/ { HRESULT hr = S_OK; DBG_ENTER(_T("CFaxOutboundRoutingGroups::get_Item"), hr); // // Check the Ptr we have got // if (::IsBadWritePtr(ppGroup, sizeof(IFaxOutboundRoutingGroup *))) { hr = E_POINTER; AtlReportError(CLSID_FaxOutboundRoutingGroups, IDS_ERROR_INVALID_ARGUMENT, IID_IFaxOutboundRoutingGroups, hr); CALL_FAIL(GENERAL_ERR, _T("::IsBadWritePtr(ppGroup, sizeof(IFaxOutboundRoutingGroup *))"), hr); return hr; } // // Find the Group // ContainerType::iterator it; hr = FindGroup(vIndex, it); if (FAILED(hr)) { return hr; }; // // Return it to Caller // (*it)->AddRef(); *ppGroup = *it; return hr; } // //==================== INIT =================================================== // STDMETHODIMP CFaxOutboundRoutingGroups::Init( /*[in]*/ IFaxServerInner *pServer ) /*++ Routine name : CFaxOutboundRoutingGroups::Init Routine description: Initialize the Groups Collection : create all Group Objects. Author: Iv Garber (IvG), Jun, 2000 Arguments: pServer [in] - Ptr to the Fax Server Object. Return Value: Standard HRESULT code --*/ { HRESULT hr = S_OK; DBG_ENTER(_T("CFaxOutboundRoutingGroups::Init"), hr); // // First, set the Ptr to the Server // hr = CFaxInitInnerAddRef::Init(pServer); if (FAILED(hr)) { return hr; } // // Get Fax Handle // HANDLE faxHandle; hr = m_pIFaxServerInner->GetHandle(&faxHandle); ATLASSERT(SUCCEEDED(hr)); if (faxHandle == NULL) { // // Fax Server is not connected // hr = Fax_HRESULT_FROM_WIN32(ERROR_NOT_CONNECTED); CALL_FAIL(GENERAL_ERR, _T("faxHandle == NULL"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, GetErrorMsgId(hr), IID_IFaxOutboundRoutingGroups, hr); return hr; } // // Call Server to Return all OR Groups // CFaxPtr<FAX_OUTBOUND_ROUTING_GROUP> pGroups; DWORD dwNum = 0; if (!FaxEnumOutboundGroups(faxHandle, &pGroups, &dwNum)) { hr = Fax_HRESULT_FROM_WIN32(GetLastError()); CALL_FAIL(GENERAL_ERR, _T("FaxEnumOutboundGroups(faxHandle, &pGroups, &dwNum)"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, GetErrorMsgId(hr), IID_IFaxOutboundRoutingGroups, hr); return hr; } // // Fill the Collection with Objects // for (DWORD i=0 ; i<dwNum ; i++ ) { hr = AddGroup(&pGroups[i]); if (FAILED(hr)) { return hr; } } return hr; } // //==================== CREATE ======================================== // HRESULT CFaxOutboundRoutingGroups::Create ( /*[out, retval]*/IFaxOutboundRoutingGroups **ppGroups ) /*++ Routine name : CFaxOutboundRoutingGroups::Create Routine description: Static function to create the Fax Outbound Routing Groups Collection Object Author: Iv Garber (IvG), Jun, 2000 Arguments: ppGroups [out] -- the new Fax OR Groups Collection Object Return Value: Standard HRESULT code --*/ { HRESULT hr = S_OK; DBG_ENTER (_T("CFaxOutboundRoutingGroups::Create"), hr); // // Create Instance of the Collection // CComObject<CFaxOutboundRoutingGroups> *pClass; hr = CComObject<CFaxOutboundRoutingGroups>::CreateInstance(&pClass); if (FAILED(hr)) { CALL_FAIL(GENERAL_ERR, _T("CComObject<CFaxOutboundRoutingGroups>::CreateInstance(&pClass)"), hr); return hr; } // // Return the desired Interface Ptr // hr = pClass->QueryInterface(ppGroups); if (FAILED(hr)) { CALL_FAIL(GENERAL_ERR, _T("pClass->QueryInterface(ppGroups)"), hr); return hr; } return hr; } // CFaxOutboundRoutingGroups::Create() // //===================== SUPPORT ERROR INFO ====================================== // STDMETHODIMP CFaxOutboundRoutingGroups::InterfaceSupportsErrorInfo( REFIID riid ) /*++ Routine name : CFaxOutboundRoutingGroups::InterfaceSupportsErrorInfo Routine description: ATL's implementation of the ISupportErrorInfo Interface. Author: Iv Garber (IvG), Jun, 2000 Arguments: riid [in] - Reference to the Interface Return Value: Standard HRESULT code --*/ { static const IID* arr[] = { &IID_IFaxOutboundRoutingGroups }; for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++) { if (InlineIsEqualGUID(*arr[i],riid)) return S_OK; } return S_FALSE; }
24.047749
123
0.585295
npocmaka
cda6db8666468ed40d3b11d3517612e9989016c1
6,262
cpp
C++
DotNetLibrary/src/BitConverter.cpp
lambertlb/CppTranslator
8d9e94f01a0eb099c224fbd9720a0d060a49bda9
[ "MIT" ]
null
null
null
DotNetLibrary/src/BitConverter.cpp
lambertlb/CppTranslator
8d9e94f01a0eb099c224fbd9720a0d060a49bda9
[ "MIT" ]
null
null
null
DotNetLibrary/src/BitConverter.cpp
lambertlb/CppTranslator
8d9e94f01a0eb099c224fbd9720a0d060a49bda9
[ "MIT" ]
null
null
null
// Copyright (c) 2019 LLambert // // 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, sub-license, 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 "BitConverter.h" namespace DotnetLibrary { Boolean BitConverter::IsLittleEndian = AmILittleEndian(); Boolean BitConverter::AmILittleEndian() { Double d = 1.0; Byte* b = (Byte*) &d; return (b[0] == 0); } Array* BitConverter::GetBytes(Byte* ptr, Int32 count) { Array* ret = new Array(ByteType, count); memcpy(ret->Address(0), ptr, count); return ret; } void BitConverter::PutBytes(Byte* dst, Array* src, Int32 start_index, Int32 count) { if (src == nullptr) throw new ArgumentNullException(); if (start_index < 0 || (start_index > src->get_Length() - 1)) throw new ArgumentOutOfRangeException(); // avoid integer overflow (with large pos/neg start_index values) if (src->get_Length() - count < start_index) throw new ArgumentException(); memcpy(dst, src->Address(start_index), count); } Int64 BitConverter::DoubleToInt64Bits(Double value) { return *(Int64*) &value; } Double BitConverter::Int64BitsToDouble(Int64 value) { return *(Double*) &value; } Array* BitConverter::GetBytes(Boolean value) { return GetBytes((Byte*) &value, 1); } Array* BitConverter::GetBytes(Char value) { // treat Char as Int16 because on some systems Char is 4 bytes but .Net isn't Int16 val = (Int16) value; return GetBytes((Byte*) &val, sizeof(Int16)); } Array* BitConverter::GetBytes(Double value) { return GetBytes((Byte*) &value, sizeof(Double)); } Array* BitConverter::GetBytes(Int16 value) { return GetBytes((Byte*) &value, sizeof(Int16)); } Array* BitConverter::GetBytes(Int32 value) { return GetBytes((Byte*) &value, sizeof(Int32)); } Array* BitConverter::GetBytes(Int64 value) { return GetBytes((Byte*) &value, sizeof(Int64)); } Array* BitConverter::GetBytes(Single value) { return GetBytes((Byte*) &value, sizeof(Single)); } Array* BitConverter::GetBytes(UInt16 value) { return GetBytes((Byte*) &value, sizeof(UInt16)); } Array* BitConverter::GetBytes(UInt32 value) { return GetBytes((Byte*) &value, sizeof(UInt32)); } Array* BitConverter::GetBytes(UInt64 value) { return GetBytes((Byte*) &value, sizeof(UInt64)); } Boolean BitConverter::ToBoolean(Array* value, Int32 startIndex) { if (value == nullptr) throw new ArgumentNullException(); if (startIndex < 0 || (startIndex > value->get_Length() - 1)) throw new ArgumentOutOfRangeException(); if (*(Byte*) value->Address(startIndex) != 0) return true; return false; } Char BitConverter::ToChar(Array* value, Int32 startIndex) { Int16 ret; // treat Char as Int16 because on some systems Char is 4 bytes but .Net isn't PutBytes((Byte*) &ret, value, startIndex, sizeof(Int16)); return (Char) ret; } Double BitConverter::ToDouble(Array* value, Int32 startIndex) { Double ret; PutBytes((Byte*) &ret, value, startIndex, sizeof(Double)); return ret; } Int16 BitConverter::ToInt16(Array* value, Int32 startIndex) { Int16 ret; PutBytes((Byte*) &ret, value, startIndex, sizeof(Int16)); return ret; } Int32 BitConverter::ToInt32(Array* value, Int32 startIndex) { Int32 ret; PutBytes((Byte*) &ret, value, startIndex, sizeof(Int32)); return ret; } Int64 BitConverter::ToInt64(Array* value, Int32 startIndex) { Int64 ret; PutBytes((Byte*) &ret, value, startIndex, sizeof(Int64)); return ret; } Single BitConverter::ToSingle(Array* value, Int32 startIndex) { Single ret; PutBytes((Byte*) &ret, value, startIndex, sizeof(Single)); return ret; } UInt16 BitConverter::ToUInt16(Array* value, Int32 startIndex) { UInt16 ret; PutBytes((Byte*) &ret, value, startIndex, sizeof(UInt16)); return ret; } UInt32 BitConverter::ToUInt32(Array* value, Int32 startIndex) { UInt32 ret; PutBytes((Byte*) &ret, value, startIndex, sizeof(UInt32)); return ret; } UInt64 BitConverter::ToUInt64(Array* value, Int32 startIndex) { UInt64 ret; PutBytes((Byte*) &ret, value, startIndex, sizeof(UInt64)); return ret; } String* BitConverter::ToString(Array* value, Int32 startIndex, Int32 length) { if (value == nullptr) throw new ArgumentNullException(); if (length == -1) length = value->get_Length() - startIndex; if (startIndex < 0 || startIndex >= value->get_Length()) { // special (but valid) case (e.g. new byte [0]) if ((startIndex == 0) && (value->get_Length() == 0)) return String::Empty; throw new ArgumentOutOfRangeException(); } if (length < 0) throw new ArgumentOutOfRangeException(); // note: re-ordered to avoid possible integer overflow if (startIndex > value->get_Length() - length) throw new ArgumentException(); if (length == 0) return String::Empty; StringBuilder builder(length * 3 - 1); Int32 end = startIndex + length; for (Int32 i = startIndex; i < end; i++) { if (i > startIndex) builder.Append(L'-'); Byte byte = *(Byte*) value->Address(i); Char high = (Char) ((byte >> 4) & 0x0f); Char low = (Char) (byte & 0x0f); if (high < 10) high += L'0'; else { high -= (Char) 10; high += L'A'; } if (low < 10) low += L'0'; else { low -= (Char) 10; low += L'A'; } builder.Append(high); builder.Append(low); } return builder.ToString(); } }
34.218579
94
0.691313
lambertlb
cda7aed90e850c335048ee2a4c87e655c90a0d98
6,233
cc
C++
cpp/baseline/common/numbered-command-receiver_test.cc
nathanawmk/SPARTA
6eeb28b2dd147088b6e851876b36eeba3e700f16
[ "BSD-2-Clause" ]
37
2017-06-09T13:55:23.000Z
2022-01-28T12:51:17.000Z
cpp/baseline/common/numbered-command-receiver_test.cc
nathanawmk/SPARTA
6eeb28b2dd147088b6e851876b36eeba3e700f16
[ "BSD-2-Clause" ]
null
null
null
cpp/baseline/common/numbered-command-receiver_test.cc
nathanawmk/SPARTA
6eeb28b2dd147088b6e851876b36eeba3e700f16
[ "BSD-2-Clause" ]
5
2017-06-09T13:55:26.000Z
2021-11-11T03:51:56.000Z
//***************************************************************** // Copyright 2015 MIT Lincoln Laboratory // Project: SPAR // Authors: OMD // Description: Unit tests for NumberedCommandReceiver // // Modifications: // Date Name Modification // ---- ---- ------------ // 09 May 2012 omd Original Version //***************************************************************** #include "numbered-command-receiver.h" #define BOOST_TEST_MODULE NumberedCommandReceiverTest #include "common/test-init.h" #include <boost/thread.hpp> #include <iostream> #include <sstream> #include <string> #include <vector> #include "extensible-ready-handler.h" #include "numbered-command-receiver-fixture.h" #include "common/logging.h" #include "common/util.h" using std::string; using std::vector; // Spawns a thread, waits a bit, then calls WriteResults with two lines, the // first line in the command_data passed to Execute and the line "DONE". class DelayedDone : public NumberedCommandHandler { public: virtual ~DelayedDone() {} virtual void Execute(LineRawData<Knot>* command_data) { // Schedule Go() on a new thread. boost::thread runner_thread( boost::bind(&DelayedDone::Go, this, command_data)); } void Go(LineRawData<Knot>* command_data) { // Sleep for a bit and then call ResultReady. boost::this_thread::sleep(boost::posix_time::milliseconds(100)); LineRawData<Knot> output_data; output_data.AddLine(command_data->Get(0)); output_data.AddLine(Knot(new string("DONE"))); WriteResults(output_data); delete command_data; Done(); } }; NumberedCommandHandler* ConstructDelayedDone() { return new DelayedDone; }; const int kBigResultsSize = 100 << 20; // Writes a HUGE results sets to make sure that works. class BigResults : public NumberedCommandHandler { public: virtual ~BigResults() {} virtual void Execute(LineRawData<Knot>* command_data) { boost::thread runner_thread(boost::bind(&BigResults::Go, this)); delete command_data; } void Go() { LineRawData<Knot> results; Knot long_line; // A huge string of 'a' characters. string* long_line_str = new string(kBigResultsSize, 'a'); results.AddLine(Knot(long_line_str)); WriteResults(results); Done(); } }; NumberedCommandHandler* ConstructBigResults() { return new BigResults; } BOOST_FIXTURE_TEST_CASE(NumberedCommandWorks, NumberedCommandReceiverFixture) { FileHandleIStream from_handler(sut_stdout_read_fd); FileHandleOStream to_handler(sut_stdin_write_fd); command_extension->AddHandler("DD", ConstructDelayedDone); // This should block until the stream is written to. string line; getline(from_handler, line); BOOST_CHECK_EQUAL(line, "READY"); line.clear(); // Inputs that should cause DelayedDone to be invoked twice. to_handler << "COMMAND 1\n" "DD foo\n" "ENDCOMMAND\n" "COMMAND 2\n" "DD bar\n" "ENDCOMMAND\n"; to_handler.flush(); // Read lines from the pipe until we see 2 more READY signals and results for // the two command above. vector<string> results; int num_ready = 0; int num_results = 0; while (num_results < 2 && num_results < 2) { getline(from_handler, line); if (line == "READY") { ++num_ready; } else if (line == "ENDRESULTS") { ++num_results; } results.push_back(line); line.clear(); } // This shouldn't have to wait since the above waited for the commands to not // only finish, but the results to arrive at the end of the pipe. command_extension->WaitForAllCommands(); // Now we should have received 2 READY signals, one after each command we // sent. Normally both would happen at once since the results of the commands // are delayed. However, there is no guarantee of that as both threads could // have been delayed until the sleep expired at which point the command might // complete before the READY token was produced. Thus, to be robust, we only // check that we got 2 ready signals. However, if any of them came after a set // of results we write a warning as we don't expect this to happen often. int num_ready_found = 0; for (size_t i = 0; i < results.size(); ++i) { if (results[i] == "READY") { ++num_ready_found; if (i > 1) { LOG(WARNING) << "Found READY after results. Unexpected."; } } } BOOST_CHECK_EQUAL(num_ready_found, 2); // We should also get results for command 1 and command 2. Since these ran in // different threads there is no ordering guarantee. However, for any one set // of results we know what the next few lines should be. int num_results_found = 0; for (size_t i = 0; i < results.size(); ++i) { if (results[i] == "RESULTS 1") { num_results_found += 1; BOOST_REQUIRE_LT(i + 2, results.size()); BOOST_CHECK_EQUAL(results[i + 1], "DD foo"); BOOST_CHECK_EQUAL(results[i + 2], "DONE"); } if (results[i] == "RESULTS 2") { num_results_found += 1; BOOST_REQUIRE_LT(i + 2, results.size()); BOOST_CHECK_EQUAL(results[i + 1], "DD bar"); BOOST_CHECK_EQUAL(results[i + 2], "DONE"); } } BOOST_CHECK_EQUAL(num_results_found, 2); } // Really big results are sent through a slightly different output path since // they are too big to be queued for output. This test ensures that these // commands work. BOOST_FIXTURE_TEST_CASE(BigResultsWork, NumberedCommandReceiverFixture) { FileHandleIStream from_handler(sut_stdout_read_fd); FileHandleOStream to_handler(sut_stdin_write_fd); command_extension->AddHandler("BIG", &ConstructBigResults); string line; getline(from_handler, line); BOOST_CHECK_EQUAL(line, "READY"); line.clear(); to_handler << "COMMAND 107\nBIG\nENDCOMMAND\n"; to_handler.flush(); // Ignore the READY line if that gets sent first. do { getline(from_handler, line); } while (line == "READY"); BOOST_CHECK_EQUAL(line, "RESULTS 107"); getline(from_handler, line); BOOST_CHECK_EQUAL(line, string(kBigResultsSize, 'a')); getline(from_handler, line); BOOST_CHECK_EQUAL(line, "ENDRESULTS"); }
32.295337
80
0.667736
nathanawmk
cda8882bcda65c2a1c71c2f607b23cc4b0f92589
142,674
cpp
C++
private/shell/browseui/menuband.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/shell/browseui/menuband.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/shell/browseui/menuband.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
#include "priv.h" #include "sccls.h" #include "menuband.h" #include "itbar.h" #include "bands.h" #include "isfband.h" #include "menubar.h" #include "../lib/dpastuff.h" // COrderList_* #include "inpobj.h" #include "theater.h" #include "resource.h" #include "oleacc.h" #include "apithk.h" #include "uemapp.h" #include "mnbase.h" #include "mnfolder.h" #include "mnstatic.h" #include "iaccess.h" #include "mluisupp.h" // BUGBUG (lamadio): Conflicts with one defined in winuserp.h #undef WINEVENT_VALID //It's tripping on this... #include "winable.h" #define DM_MISC 0 // miscellany #define PF_USINGNTSD 0x00000400 // set this if you're debugging on ntsd // This must be reset to -1 on any WM_WININICHANGE. We do it in // shbrows2.cpp, but if there are no browser windows open when the // metric changes, we end up running around with a stale value. Oh well. long g_lMenuPopupTimeout = -1; // {AD35F50A-0CC0-11d3-AE2D-00C04F8EEA99} static const CLSID CLSID_MenuBandMetrics = { 0xad35f50a, 0xcc0, 0x11d3, { 0xae, 0x2d, 0x0, 0xc0, 0x4f, 0x8e, 0xea, 0x99 } }; // Registered window messages for the menuband UINT g_nMBPopupOpen = 0; UINT g_nMBFullCancel = 0; UINT g_nMBDragCancel = 0; UINT g_nMBAutomation = 0; UINT g_nMBExecute = 0; UINT g_nMBOpenChevronMenu = 0; HCURSOR g_hCursorArrow = NULL; //UINT g_nMBIgnoreNextDeselect = 0; // Dealt with in menuisf.cpp HRESULT IUnknown_QueryServiceExec(IUnknown* punk, REFGUID guidService, const GUID *guid, DWORD cmdID, DWORD cmdParam, VARIANT* pvarargIn, VARIANT* pvarargOut); BOOL IsAncestor(HWND hwndChild, HWND hwndAncestor) { HWND hwnd = hwndChild; while (hwnd != hwndAncestor && hwnd != NULL) { hwnd = GetParent(hwnd); } return hwndAncestor == hwnd; } //================================================================= // Implementation of menuband message filter //================================================================= extern "C" void DumpMsg(LPCTSTR pszLabel, MSG * pmsg); // Just one of these, b/c we only need one message filter CMBMsgFilter g_msgfilter = { 0 }; void CMBMsgFilter::SetModal(BOOL fModal) { // There was an interesting problem: // Click on the Chevron menu. Right click Delete. // The menus were hosed // Why? // Well, I'll tell you: // We got a deactivate on the subclassed window. We have // 2 menus subclassing it: The Main menu, and the modal // chevron menu. Problem is, the main menu snagged the WM_ACTIVATE // and does a set context. This causes a Pop and releases the Message hook. // Since I still had a menu up, this caused havoc. // So I introduced a concept of a "Modal" menuband. // This says: "Ignore any request to change contexts until I'm done". When // that modal band is done, it sets the old context back in. // Seems like a hack, but we need a better underlying archtecture for // the message passing. _fModal = fModal; } void CMBMsgFilter::ReEngage(void* pvContext) { // We need to make sure that we don't dis/reengage when // switching contexts if (pvContext == _pvContext) _fEngaged = TRUE; } void CMBMsgFilter::DisEngage(void* pvContext) { if (pvContext == _pvContext) _fEngaged = FALSE; } int CMBMsgFilter::GetCount() { return FDSA_GetItemCount(&_fdsa); } int MsgFilter_GetCount() { return g_msgfilter.GetCount(); } CMenuBand * CMBMsgFilter::_GetTopPtr(void) { CMenuBand * pmb = NULL; int cItems = FDSA_GetItemCount(&_fdsa); if (0 < cItems) { MBELEM * pmbelem = FDSA_GetItemPtr(&_fdsa, cItems-1, MBELEM); pmb = pmbelem->pmb; } return pmb; } CMenuBand * CMBMsgFilter::_GetBottomMostSelected(void) { // Ick, I can't believe I just did this. Mix COM and C++ identities... Yuck. CMenuBand* pmb = NULL; if (_pmb) { IUnknown_QueryService(SAFECAST(_pmb, IMenuBand*), SID_SMenuBandBottomSelected, CLSID_MenuBand, (void**)&pmb); // Since we have the C++ identity, release the COM identity. if (pmb) pmb->Release(); } return pmb; } CMenuBand * CMBMsgFilter::_GetWindowOwnerPtr(HWND hwnd) { CMenuBand * pmb = NULL; int cItems = FDSA_GetItemCount(&_fdsa); if (0 < cItems) { // Go thru the list of bands on the stack and return the // one who owns the given window. int i; for (i = 0; i < cItems; i++) { MBELEM * pmbelem = FDSA_GetItemPtr(&_fdsa, i, MBELEM); if (pmbelem->pmb && S_OK == pmbelem->pmb->IsWindowOwner(hwnd)) { pmb = pmbelem->pmb; break; } } } return pmb; } /*---------------------------------------------------------- Purpose: Return menuband or NULL based upon hittest. pt must be in screen coords */ CMenuBand * CMBMsgFilter::_HitTest(POINT pt, HWND * phwnd) { CMenuBand * pmb = NULL; HWND hwnd = NULL; int cItems = FDSA_GetItemCount(&_fdsa); if (0 < cItems) { // Go thru the list of bands on the stack and return the // one who owns the given window. Work backwards since the // later bands are on top (z-order), if the menus ever overlap. int i = cItems - 1; while (0 <= i) { MBELEM * pmbelem = FDSA_GetItemPtr(&_fdsa, i, MBELEM); RECT rc; // Do this dynamically because the hwndBar hasn't been positioned // until after this mbelem has been pushed onto the msg filter stack. GetWindowRect(pmbelem->hwndBar, &rc); if (PtInRect(&rc, pt)) { pmb = pmbelem->pmb; hwnd = pmbelem->hwndTB; break; } i--; } } if (phwnd) *phwnd = hwnd; return pmb; } void CMBMsgFilter::RetakeCapture(void) { // The TrackPopupMenu submenus can steal the capture. Take // it back. Don't take it back if the we're in edit mode, // because the modal drag/drop loop has the capture at that // point. // We do not want to take capture unless we are engaged. // We need to do this because we are not handling mouse messages lower down // in the code. When we set the capture, the messages that we do not handle // trickle up to the top level menu, and can cause weird problems (Such // as signaling a "click out of bounds" or a context menu of the ITBar) if (_hwndCapture && !_fPreventCapture && _fEngaged) { TraceMsg(TF_MENUBAND, "CMBMsgFilter: Setting capture to %#lx", _hwndCapture); SetCapture(_hwndCapture); } } void CMBMsgFilter::SetHook(BOOL fSet, BOOL fDontIgnoreSysChar) { if (fDontIgnoreSysChar) _iSysCharStack += fSet? 1: -1; if (NULL == _hhookMsg && fSet) { TraceMsg(TF_MENUBAND, "CMBMsgFilter: Initialize"); _hhookMsg = SetWindowsHookEx(WH_GETMESSAGE, GetMsgHook, HINST_THISDLL, GetCurrentThreadId()); _fDontIgnoreSysChar = fDontIgnoreSysChar; } else if (!fSet && _iSysCharStack == 0) { TraceMsg(TF_MENUBAND, "CMBMsgFilter: Hook removed"); UnhookWindowsHookEx(_hhookMsg); _hhookMsg = NULL; } } // 1) Set Deskbars on Both Monitors and set to chevron // 2) On Monitor #2 open a chevron // 3) On Monitor #1 open a chevron then open the Start Menu // Result: Start Menu does not work. // The reason is, we set the _fModal of the global message filter. This prevents context switches. Why? // The modal flag was invented to solve context switching problems with the browser frame. So what causes this? // Well, when switching from #2 to #3, we have not switched contexts. But since we got a click out of bounds, we collapse // the previous menu. When switching from #3 to #4, neither have the context, so things get messy. void CMBMsgFilter::ForceModalCollapse() { if (_fModal) { _fModal = FALSE; SetContext(NULL, TRUE); } } void CMBMsgFilter::SetContext(void* pvContext, BOOL fSet) { TraceMsg(TF_MENUBAND, "CMBMsgFilter::SetContext from 0x%x to 0x%x", _pvContext, pvContext); // When changing a menuband context, we need to pop all of the items // in the stack. This is to prevent a race condition that can occur. // We do not want to pop all of the items off the stack if we're setting the same context. // We do a set context on Activation, Both when we switch from one Browser frame to another // but also when right clicking or causing the Rename dialog to be displayed. BOOL fPop = FALSE; if (_fModal) return; // Are we setting a new context? if (fSet) { // Is this different than the one we've got? if (pvContext != _pvContext) { // Yes, then we need to pop off all of the old items. fPop = TRUE; } _pvContext = pvContext; } else { // Then we are trying to unset the message hook. Make sure it still belongs to // this context if (pvContext == _pvContext) { // This context is trying to unset itself, and no other context owns it. // remove all the old items. fPop = TRUE; } } if (fPop) { CMenuBand* pcmb = _GetTopPtr(); if (pcmb) { PostMessage(pcmb->_pmbState->GetSubclassedHWND(), g_nMBFullCancel, 0, 0); // No release. if (FDSA_GetItemCount(&_fdsa) != 0) { while (g_msgfilter.Pop(pvContext)) ; } } } } /*---------------------------------------------------------- Purpose: Push another menuband onto the message filter's stack */ void CMBMsgFilter::Push(void* pvContext, CMenuBand * pmb, IUnknown * punkSite) { ASSERT(IS_VALID_CODE_PTR(pmb, CMenuBand)); TraceMsg(TF_MENUBAND, "CMBMsgFilter::Push called from context 0x%x", pvContext); if (pmb && pvContext == _pvContext) { BOOL bRet = TRUE; HWND hwndBand; pmb->GetWindow(&hwndBand); // If the bar isn't available use the band window HWND hwndBar = hwndBand; IOleWindow * pow; IUnknown_QueryService(punkSite, SID_SMenuPopup, IID_IOleWindow, (LPVOID *)&pow); if (pow) { pow->GetWindow(&hwndBar); pow->Release(); } if (NULL == _hhookMsg) { // We want to ignore the WM_SYSCHAR message in the message filter because // we are using the IsMenuMessage call instead of the global message hook. SetHook(TRUE, FALSE); TraceMsg(TF_MENUBAND, "CMBMsgFilter::push Setting hook from context 0x%x", pvContext); _fSetAtPush = TRUE; } if (!_fInitialized) { ASSERT(NULL == _hwndCapture); _hwndCapture = hwndBar; _fInitialized = TRUE; bRet = FDSA_Initialize(sizeof(MBELEM), CMBELEM_GROW, &_fdsa, _rgmbelem, CMBELEM_INIT); // We need to initialize this for the top level guy so that we have the correct positioning // from the start of this new set of bands. This is used to eliminate spurious WM_MOUSEMOVE // messages which cause problems. See _HandleMouseMessages for more information AcquireMouseLocation(); } if (EVAL(bRet)) { MBELEM mbelem = {0}; TraceMsg(TF_MENUBAND, "CMBMsgFilter: Push (pmp:%#08lx) onto stack", SAFECAST(pmb, IMenuPopup *)); pmb->AddRef(); mbelem.pmb = pmb; mbelem.hwndTB = hwndBand; mbelem.hwndBar = hwndBar; FDSA_AppendItem(&_fdsa, &mbelem); CMenuBand* pmbTop = _GetTopPtr(); ASSERT(pmbTop); if ((pmbTop->GetFlags() & SMINIT_LEGACYMENU) || NULL == GetCapture()) RetakeCapture(); } else { UnhookWindowsHookEx(_hhookMsg); _hhookMsg = NULL; _hwndCapture = NULL; } } } /*---------------------------------------------------------- Purpose: Pop a menuband off the message filter stack Returns the number of bands left on the stack */ int CMBMsgFilter::Pop(void* pvContext) { int nRet = 0; TraceMsg(TF_MENUBAND, "CMBMsgFilter::pop called from context 0x%x", pvContext); // This can be called from a context switch or when we're exiting menu mode, // so we'll switch off the fact that we clear _hhookMsg when we pop the top twice. if (pvContext == _pvContext && _hhookMsg) { int iItem = FDSA_GetItemCount(&_fdsa) - 1; MBELEM * pmbelem; ASSERT(0 <= iItem); pmbelem = FDSA_GetItemPtr(&_fdsa, iItem, MBELEM); if (EVAL(pmbelem->pmb)) { TraceMsg(TF_MENUBAND, "CMBMsgFilter: Pop (pmb=%#08lx) off stack", SAFECAST(pmbelem->pmb, IMenuPopup *)); pmbelem->pmb->Release(); pmbelem->pmb = NULL; } FDSA_DeleteItem(&_fdsa, iItem); if (0 == iItem) { TraceMsg(TF_MENUBAND, "CMBMsgFilter::pop removing hook from context 0x%x", pvContext); if (_fSetAtPush) SetHook(FALSE, FALSE); PreventCapture(FALSE); _fInitialized = FALSE; if (_hwndCapture && GetCapture() == _hwndCapture) { TraceMsg(TF_MENUBAND, "CMBMsgFilter: Releasing capture"); ReleaseCapture(); } _hwndCapture = NULL; } #ifdef UNIX else if (1 == iItem) { CMenuBand * pmb = _GetTopPtr(); if( pmb ) { // Change item count only if we delete successfully. if( pmb->RemoveTopLevelFocus() ) iItem = FDSA_GetItemCount(&_fdsa); } } #endif nRet = iItem; } return nRet; } LRESULT CMBMsgFilter::_HandleMouseMsgs(MSG * pmsg, BOOL bRemove) { LRESULT lRet = 0; CMenuBand * pmb; HWND hwnd = GetCapture(); // Do we still have the capture? if (hwnd != _hwndCapture) { // No; is it b/c a CTrackPopupBar has it? #if 0 // Nuke this trace because I was getting annoyed. //def DEBUG pmb = _GetTopPtr(); if (!EVAL(pmb) || !pmb->IsInSubMenu()) { // No TraceMsg(TF_WARNING, "CMBMsgFilter: someone else has the capture (%#lx)", hwnd); } #endif if (NULL == hwnd) { // There are times that we must retake the capture because // TrackPopupMenuEx has taken it, or some context menu // might have taken it, so take it back. RetakeCapture(); TraceMsg(TF_WARNING, "CMBMsgFilter: taking the capture back"); } } else { // Yes; decide what to do with it POINT pt; HWND hwndPt; MSG msgT; pt.x = GET_X_LPARAM(pmsg->lParam); pt.y = GET_Y_LPARAM(pmsg->lParam); ClientToScreen(pmsg->hwnd, &pt); if (WM_MOUSEMOVE == pmsg->message) { // The mouse cursor can send repeated WM_MOUSEMOVE messages // with the same coordinates. When the user tries to navigate // thru the menus with the keyboard, and the mouse cursor // happens to be over a menu item, these spurious mouse // messages cause us to think the menu has been invoked under // the mouse cursor. // // To avoid this unpleasant rudeness, we eat any gratuitous // WM_MOUSEMOVE messages. if (_ptLastMove.x == pt.x && _ptLastMove.y == pt.y) { pmsg->message = WM_NULL; goto Bail; } // Since this is not a duplicate point, we need to keep it around. // We will use this stored point for the above comparison AcquireMouseLocation(); if (_hcurArrow == NULL) _hcurArrow = LoadCursor(NULL, IDC_ARROW); if (GetCursor() != _hcurArrow) SetCursor(_hcurArrow); } pmb = _HitTest(pt, &hwndPt); if (pmb) { // Forward mouse message onto appropriate menuband. Note // the appropriate menuband's GetMsgFilterCB (below) will call // ScreenToClient to convert the coords correctly. // Use a stack variable b/c we don't want to confuse USER32 // by changing the coords of the real message. msgT = *pmsg; msgT.lParam = MAKELPARAM(pt.x, pt.y); lRet = pmb->GetMsgFilterCB(&msgT, bRemove); // Remember the changed message (if there was one) pmsg->message = msgT.message; } // Debug note: to debug menubands on ntsd, set the prototype // flag accordingly. This will keep menubands from going // away the moment the focus changes to the NTSD window. else if ((WM_LBUTTONDOWN == pmsg->message || WM_RBUTTONDOWN == pmsg->message) && !(g_dwPrototype & PF_USINGNTSD)) { // Mouse down happened outside the menu. Bail. pmb = _GetTopPtr(); if (EVAL(pmb)) { msgT.hwnd = pmsg->hwnd; msgT.message = g_nMBFullCancel; msgT.wParam = 0; msgT.lParam = 0; TraceMsg(TF_MENUBAND, "CMBMsgFilter (pmb=%#08lx): hittest outside, bailing", SAFECAST(pmb, IMenuPopup *)); pmb->GetMsgFilterCB(&msgT, bRemove); } #if 0 // Now send the message to the originally intended window SendMessage(pmsg->hwnd, pmsg->message, pmsg->wParam, pmsg->lParam); #endif } else { pmb = _GetTopPtr(); if (pmb) { IUnknown_QueryServiceExec(SAFECAST(pmb, IOleCommandTarget*), SID_SMenuBandBottom, &CGID_MenuBand, MBANDCID_SELECTITEM, MBSI_NONE, NULL, NULL); } } } Bail: return lRet; } /*---------------------------------------------------------- Purpose: Message hook used to track keyboard and mouse messages while the menuband is "active". The menuband can't steal the focus away -- we use this hook to catch messages. */ LRESULT CMBMsgFilter::GetMsgHook(int nCode, WPARAM wParam, LPARAM lParam) { LRESULT lRet = 0; MSG * pmsg = (MSG *)lParam; BOOL bRemove = (PM_REMOVE == wParam); // The global message filter may be in a state when we are not processing messages, // but the menubands are still displayed. A situation where this will occur is when // a dialog box is displayed because of an interaction with the menus. // Are we engaged? (Are we allowed to process messages?) if (g_msgfilter._fEngaged) { if (WM_SYSCHAR == pmsg->message) { // _fDontIgnoreSysChar is set when the Menubands ONLY want to know about // WM_SYSCHAR and nothing else. if (g_msgfilter._fDontIgnoreSysChar) { CMenuBand * pmb = g_msgfilter.GetTopMostPtr(); if (pmb) lRet = pmb->GetMsgFilterCB(pmsg, bRemove); } } else if (g_msgfilter._fInitialized) // Only filter if we are initalized (have items on the stack) { switch (nCode) { case HC_ACTION: #ifdef DEBUG if (g_dwDumpFlags & DF_GETMSGHOOK) DumpMsg(TEXT("GetMsg"), pmsg); #endif // A lesson about GetMsgHook: it gets the same message // multiple times for as long as someone calls PeekMessage // with the PM_NOREMOVE flag. So we want to take action // only when PM_REMOVE is set (so we don't handle more than // once). If we modify any messages to redirect them (on a // regular basis), we must modify all the time so we don't // confuse the app. // Messages get redirected to different bands in the stack // in this way: // // 1) Keyboard messages go to the currently open submenu // (topmost on the stack). // // 2) The PopupOpen message goes to the hwnd that belongs // to the menu band (via IsWindowOwner). // switch (pmsg->message) { case WM_SYSKEYDOWN: case WM_KEYDOWN: case WM_CHAR: case WM_KEYUP: case WM_CLOSE: // only this message filter gets WM_CLOSE { // There is a situation that can occur when the last selected // menu pane is NOT the bottom most pane. // We need to see if that last selected guy is tracking a context // menu so that we forward the messages correctly. CMenuBand * pmb = g_msgfilter._GetBottomMostSelected(); if (pmb) { // Is it tracking a context menu? if (S_OK == IUnknown_Exec(SAFECAST(pmb, IMenuBand*), &CGID_MenuBand, MBANDCID_ISTRACKING, 0, NULL, NULL)) { // Yes, forward for proper handling. lRet = pmb->GetMsgFilterCB(pmsg, bRemove); } else { // No; Then do the default processing. This can happen if there is no // context menu, but there is a selected parent and not a selected child. goto TopHandler; } } else { TopHandler: pmb = g_msgfilter._GetTopPtr(); if (pmb) lRet = pmb->GetMsgFilterCB(pmsg, bRemove); } } break; case WM_NULL: // Handle this here (we do nothing) to avoid mistaking this for // g_nMBPopupOpen below, in case g_nMBPopupOpen is 0 if // RegisterWindowMessage fails. break; default: if (bRemove && IsInRange(pmsg->message, WM_MOUSEFIRST, WM_MOUSELAST)) { lRet = g_msgfilter._HandleMouseMsgs(pmsg, bRemove); } else if (pmsg->message == g_nMBPopupOpen) { CMenuBand * pmb = g_msgfilter._GetWindowOwnerPtr(pmsg->hwnd); if (pmb) lRet = pmb->GetMsgFilterCB(pmsg, bRemove); } else if (pmsg->message == g_nMBExecute) { CMenuBand * pmb = g_msgfilter._GetWindowOwnerPtr(pmsg->hwnd); if (pmb) { VARIANT var; var.vt = VT_UINT_PTR; var.ullVal = (UINT_PTR)pmsg->hwnd; pmb->Exec(&CGID_MenuBand, MBANDCID_EXECUTE, (DWORD)pmsg->wParam, &var, NULL); } } break; } break; default: if (0 > nCode) return CallNextHookEx(g_msgfilter._hhookMsg, nCode, wParam, lParam); break; } } } // Pass it on to the next hook in the chain if (0 == lRet) return CallNextHookEx(g_msgfilter._hhookMsg, nCode, wParam, lParam); return 0; // Always return 0 } //================================================================= // Implementation of CMenuBand //================================================================= // Struct used by EXEC with a MBANDCID_GETFONTS to return fonts typedef struct tagMBANDFONTS { HFONT hFontMenu; // [out] TopLevelMenuBand's menu font HFONT hFontArrow; // [out] TopLevelMenuBand's font for drawing the cascade arrow int cyArrow; // [out] Height of TopLevelMenuBand's cascade arrow int cxArrow; // [out] Width of TopLevelMenuBand's cascade arrow int cxMargin; // [out] Margin b/t text and arrow } MBANDFONTS; #define THISCLASS CMenuBand #define SUPERCLASS CToolBand #ifdef DEBUG int g_nMenuLevel = 0; #define DBG_THIS _nMenuLevel, SAFECAST(this, IMenuPopup *) #else #define DBG_THIS 0, 0 #endif CMenuBand::CMenuBand() : SUPERCLASS() { _fCanFocus = TRUE; _fAppActive = TRUE; _nItemNew = -1; _nItemCur = -1; _nItemTimer = -1; _uIconSize = ISFBVIEWMODE_SMALLICONS; _uIdAncestor = ANCESTORDEFAULT; _nItemSubMenu = -1; } // The purpose of this method is to finish initializing Menubands, // since it can be initialized in many ways. void CMenuBand::_Initialize(DWORD dwFlags) { _fVertical = !BOOLIFY(dwFlags & SMINIT_HORIZONTAL); _fTopLevel = BOOLIFY(dwFlags & SMINIT_TOPLEVEL); _dwFlags = dwFlags; // We cannot have a horizontal menu if it is not the toplevel menu ASSERT(!_fVertical && _fTopLevel || _fVertical); if (_fTopLevel) { if (!g_nMBPopupOpen) { g_nMBPopupOpen = RegisterWindowMessage(TEXT("CMBPopupOpen")); g_nMBFullCancel = RegisterWindowMessage(TEXT("CMBFullCancel")); g_nMBDragCancel = RegisterWindowMessage(TEXT("CMBDragCancel")); g_nMBAutomation = RegisterWindowMessage(TEXT("CMBAutomation")); g_nMBExecute = RegisterWindowMessage(TEXT("CMBExecute")); g_nMBOpenChevronMenu = RegisterWindowMessage(TEXT("CMBOpenChevronMenu")); g_hCursorArrow = LoadCursor(NULL, IDC_ARROW); TraceMsg(TF_MENUBAND, "CMBPopupOpen message = %#lx", g_nMBPopupOpen); TraceMsg(TF_MENUBAND, "CMBFullCancel message = %#lx", g_nMBFullCancel); } if (!_pmbState) _pmbState = new CMenuBandState; } DEBUG_CODE( _nMenuLevel = -1; ) } CMenuBand::~CMenuBand() { // the message filter does not have a ref'd pointer to us!!! if (g_msgfilter.GetTopMostPtr() == this) g_msgfilter.SetTopMost(NULL); _CallCB(SMC_DESTROY); ATOMICRELEASE(_psmcb); // Cleanup CloseDW(0); if (_pmtbMenu) delete _pmtbMenu; if (_pmtbShellFolder) delete _pmtbShellFolder; ASSERT(_punkSite == NULL); ATOMICRELEASE(_pmpTrackPopup); ATOMICRELEASE(_pmbm); if (_fTopLevel) { if (_pmbState) delete _pmbState; } } /*---------------------------------------------------------- Purpose: Create-instance function for class factory */ HRESULT CMenuBand_CreateInstance(IUnknown* pUnkOuter, IUnknown** ppunk, LPCOBJECTINFO poi) { // aggregation checking is handled in class factory HRESULT hres = E_OUTOFMEMORY; CMenuBand* pObj = new CMenuBand(); if (pObj) { *ppunk = SAFECAST(pObj, IShellMenu*); hres = S_OK; } return hres; } /*---------------------------------------------------------- Purpose: Internal create-instance function */ CMenuBand * CMenuBand_Create(IShellFolder* psf, LPCITEMIDLIST pidl, BOOL bHorizontal) { CMenuBand * pmb = NULL; if (psf || pidl) { DWORD dwFlags = bHorizontal ? (SMINIT_HORIZONTAL | SMINIT_TOPLEVEL) : 0; pmb = new CMenuBand(); if (pmb) { pmb->_Initialize(dwFlags); pmb->SetShellFolder(psf, pidl, NULL, 0); } } return pmb; } #ifdef UNIX BOOL CMenuBand::RemoveTopLevelFocus() { if( _fTopLevel ) { _CancelMode( MPOS_CANCELLEVEL ); return TRUE; } return FALSE; } #endif void CMenuBand::_UpdateButtons() { if (_pmtbMenu) _pmtbMenu->v_UpdateButtons(FALSE); if (_pmtbShellFolder) _pmtbShellFolder->v_UpdateButtons(FALSE); _fForceButtonUpdate = FALSE; } HRESULT CMenuBand::ForwardChangeNotify(LONG lEvent, LPCITEMIDLIST pidl1, LPCITEMIDLIST pidl2) { // Given a change notify from the ShellFolder child, we will forward that notify to each of our // sub menus, but only if they have a shell folder child. HRESULT hres = E_FAIL; BOOL fDone = FALSE; CMenuToolbarBase* pmtb = _pmtbBottom; // Start With the bottom toolbar. This is // is an optimization because typically // menus that have both a Shell Folder portion // and a static portion have the majority // of the change activity in the bottom portion. // This can be NULL on a shutdown, when we're deregistering change notifies if (pmtb) { HWND hwnd = pmtb->_hwndMB; for (int iButton = 0; !fDone; iButton++) { IShellChangeNotify* ptscn; int idCmd = GetButtonCmd(hwnd, iButton); #ifdef DEBUG TCHAR szSubmenuName[MAX_PATH]; SendMessage(hwnd, TB_GETBUTTONTEXT, idCmd, (LPARAM)szSubmenuName); TraceMsg(TF_MENUBAND, "CMenuBand: Forwarding Change notify to %s", szSubmenuName); #endif // If it's not a seperator, see if there is a sub menu with a shell folder child. if (idCmd != -1 && SUCCEEDED(pmtb->v_GetSubMenu(idCmd, &SID_MenuShellFolder, IID_IShellChangeNotify, (void**)&ptscn))) { IShellMenu* psm; // Don't forward this notify if the sub menu has specifically registered for change notify (By not passing // DontRegisterChangeNotify. if (SUCCEEDED(ptscn->QueryInterface(IID_IShellMenu, (void**)&psm))) { UINT uIdParent = 0; DWORD dwFlags = 0; // Get the flags psm->GetShellFolder(&dwFlags, NULL, IID_NULL, NULL); psm->GetMenuInfo(NULL, &uIdParent, NULL, NULL); // If this menupane is an "Optimized" pane, (meaning that we don't register for change notify // and forward from a top level menu down) then we want to forward. We also // forward if this is a child of Menu Folder. If it is a child, // then it also does not register for change notify, but does not explicitly set it in it's flags // (review: Should we set it in it's flags?) // If it is not an optimized pane, then don't forward. if ((dwFlags & SMSET_DONTREGISTERCHANGENOTIFY) || uIdParent == MNFOLDER_IS_PARENT) { // There is!, then pass to the child the change. hres = ptscn->OnChange(lEvent, pidl1, pidl2); // Update Dir on a Recursive change notify forces us to update everyone... Good thing // this does not happen alot and is caused by user interaction most of the time. } psm->Release(); } ptscn->Release(); } // Did we go through all of the buttons on this toolbar? if (iButton >= ToolBar_ButtonCount(hwnd) - 1) { // Yes, then we need to switch to the next toolbar. if (_pmtbTop != _pmtbBottom && pmtb != _pmtbTop) { pmtb = _pmtbTop; hwnd = pmtb->_hwndMB; iButton = -1; // -1 because at the end of the loop the for loop will increment. } else { // No; Then we must be done. fDone = TRUE; } } } } else hres = S_OK; // Return success because we're shutting down. return hres; } // Resize the parent menubar VOID CMenuBand::ResizeMenuBar() { // If we're not shown, then we do not need to do any kind of resize. // NOTE: Horizontal menubands are always shown. Don't do any of the // vertical stuff if we're horizontal. if (!_fShow) return; // If we're horizontal, don't do any Vertical sizing stuff. if (!_fVertical) { // BandInfoChanged is only for Horizontal Menubands. _BandInfoChanged(); return; } // We need to update the buttons before a resize so that the band is the right size. _UpdateButtons(); // Have the menubar think about changing its height IUnknown_QueryServiceExec(_punkSite, SID_SMenuPopup, &CGID_MENUDESKBAR, MBCID_RESIZE, 0, NULL, NULL); } STDMETHODIMP CMenuBand::QueryInterface(REFIID riid, void **ppvObj) { HRESULT hres; static const QITAB qit[] = { QITABENT(CMenuBand, IMenuPopup), QITABENT(CMenuBand, IMenuBand), QITABENT(CMenuBand, IShellMenu), QITABENT(CMenuBand, IWinEventHandler), QITABENT(CMenuBand, IShellMenuAcc), { 0 }, }; hres = QISearch(this, (LPCQITAB)qit, riid, ppvObj); if (FAILED(hres)) hres = SUPERCLASS::QueryInterface(riid, ppvObj); // BUGBUG (lamadio) 8.5.98: Nuke this. We should not expose the this pointer, // this is a bastardization of COM. if (FAILED(hres) && IsEqualGUID(riid, CLSID_MenuBand)) { AddRef(); *ppvObj = (LPVOID)this; hres = S_OK; } return hres; } /*---------------------------------------------------------- Purpose: IServiceProvider::QueryService method */ STDMETHODIMP CMenuBand::QueryService(REFGUID guidService, REFIID riid, void **ppvObj) { HRESULT hres = E_FAIL; *ppvObj = NULL; // assume error if (IsEqualIID(guidService, SID_SMenuPopup) || IsEqualIID(guidService, SID_SMenuBandChild) || IsEqualIID(guidService, SID_SMenuBandParent) || (_fTopLevel && IsEqualIID(guidService, SID_SMenuBandTop))) { if (IsEqualIID(riid, IID_IAccessible) || IsEqualIID(riid, IID_IDispatch)) { hres = E_OUTOFMEMORY; CAccessible* pacc = new CAccessible(SAFECAST(this, IMenuBand*)); if (pacc) { hres = pacc->InitAcc(); if (SUCCEEDED(hres)) { hres = pacc->QueryInterface(riid, ppvObj); } pacc->Release(); } } else hres = QueryInterface(riid, ppvObj); } else if (IsEqualIID(guidService, SID_SMenuBandBottom) || IsEqualIID(guidService, SID_SMenuBandBottomSelected)) { // SID_SMenuBandBottom queries down BOOL fLookingForSelected = IsEqualIID(SID_SMenuBandBottomSelected, guidService); // Are we the leaf node? if (!_fInSubMenu) { if ( fLookingForSelected && (_pmtbTracked == NULL || ToolBar_GetHotItem(_pmtbTracked->_hwndMB) == -1)) { hres = E_FAIL; } else { hres = QueryInterface(riid, ppvObj); // Yes; QI ourselves } } else { // No; QS down... IMenuPopup* pmp = _pmpSubMenu; if (_pmpTrackPopup) pmp = _pmpTrackPopup; ASSERT(pmp); hres = IUnknown_QueryService(pmp, guidService, riid, ppvObj); if (FAILED(hres) && fLookingForSelected && _pmtbTracked != NULL) { hres = QueryInterface(riid, ppvObj); // Yes; QI ourselves } } } else if (IsEqualIID(guidService, SID_MenuShellFolder)) { // This is a method of some other menu in the scheme to get to specifically the MenuShellfolder, // This is for the COM Identity property. if (_pmtbShellFolder) hres = _pmtbShellFolder->QueryInterface(riid, ppvObj); } else hres = SUPERCLASS::QueryService(guidService, riid, ppvObj); return hres; } /*---------------------------------------------------------- Purpose: IWinEventHandler::IsWindowOwner method */ STDMETHODIMP CMenuBand::IsWindowOwner(HWND hwnd) { if (( _pmtbShellFolder && (_pmtbShellFolder->IsWindowOwner(hwnd) == S_OK) ) || (_pmtbMenu && (_pmtbMenu->IsWindowOwner(hwnd) == S_OK))) return S_OK; return S_FALSE; } #define MB_EICH_FLAGS (EICH_SSAVETASKBAR | EICH_SWINDOWMETRICS | EICH_SPOLICY | EICH_SSHELLMENU | EICH_KWINPOLICY) /*---------------------------------------------------------- Purpose: IWinEventHandler::OnWinEvent method Processes messages passed on from the bandsite. */ STDMETHODIMP CMenuBand::OnWinEvent(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT *plres) { HRESULT hres = NOERROR; EnterModeless(); // Could our metrics be changing? (We keep track of this only for the // toplevel menu) BOOL fProcessSettingChange = FALSE; switch (uMsg) { case WM_SETTINGCHANGE: fProcessSettingChange = !lParam || (SHIsExplorerIniChange(wParam, lParam) & MB_EICH_FLAGS); break; case WM_SYSCOLORCHANGE: case WM_DISPLAYCHANGE: fProcessSettingChange = TRUE; break; } if (_fTopLevel && fProcessSettingChange && _pmbState && !_pmbState->IsProcessingChangeNotify()) { // There is a race condition that can occur during a refresh // that's really nasty. It causes another one to get pumped in the // middle of processing this one, Yuck! _pmbState->PushChangeNotify(); // There is a race condiction that can occur when the menuband is created, // but not yet initialized. This has been hit by the IEAK group.... if (_pmtbTop) { // Yes; create a new metrics object and tell the submenus // about it. CMenuBandMetrics* pmbm = new CMenuBandMetrics(_pmtbTop->_hwndMB); if (pmbm) { ATOMICRELEASE(_pmbm); _pmbm = pmbm; if (_pmtbMenu) _pmtbMenu->SetMenuBandMetrics(_pmbm); if (_pmtbShellFolder) _pmtbShellFolder->SetMenuBandMetrics(_pmbm); _CallCB(SMC_REFRESH, wParam, lParam); // We need to force a button update at some point so that the new sizes are calculated // Setting this flag will cause the buttons to be updatted before the next time it // is shown. If, however, the menu is currently displayed, then the ResizeMenuBar will // recalculate immediatly. _fForceButtonUpdate = TRUE; RECT rcOld; RECT rcNew; // Resize the MenuBar GetClientRect(_hwndParent, &rcOld); ResizeMenuBar(); GetClientRect(_hwndParent, &rcNew); // If the rect sizes haven't changed, then we need to re-layout the // band because the button widths may have changed. if (EqualRect(&rcOld, &rcNew) && _fVertical) _pmtbTop->NegotiateSize(); } } if (_pmtbMenu) hres = _pmtbMenu->OnWinEvent(hwnd, uMsg, wParam, lParam, plres); if (_pmtbShellFolder) hres = _pmtbShellFolder->OnWinEvent(hwnd, uMsg, wParam, lParam, plres); _pmbState->PopChangeNotify(); } else { if (_pmtbMenu && (_pmtbMenu->IsWindowOwner(hwnd) == S_OK) ) hres = _pmtbMenu->OnWinEvent(hwnd, uMsg, wParam, lParam, plres); if (_pmtbShellFolder && (_pmtbShellFolder->IsWindowOwner(hwnd) == S_OK) ) hres = _pmtbShellFolder->OnWinEvent(hwnd, uMsg, wParam, lParam, plres); } ExitModeless(); return hres; } /*---------------------------------------------------------- Purpose: IOleWindow::GetWindow method */ STDMETHODIMP CMenuBand::GetWindow(HWND * phwnd) { // We assert that only a real menu can be hosted in a standard // bandsite (we're talking about the horizontal menubar). // So we only return the window associated with the static // menu. if (_pmtbMenu) { *phwnd = _pmtbMenu->_hwndMB; return NOERROR; } else { *phwnd = NULL; return E_FAIL; } } /*---------------------------------------------------------- Purpose: IOleWindow::ContextSensitiveHelp method */ STDMETHODIMP CMenuBand::ContextSensitiveHelp(BOOL bEnterMode) { return SUPERCLASS::ContextSensitiveHelp(bEnterMode); } /*---------------------------------------------------------- Purpose: Handle WM_CHAR for accelerators This is handled for any vertical menu. Since we have two toolbars (potentially), this function determines which toolbar gets the message depending on the accelerator. */ HRESULT CMenuBand::_HandleAccelerators(MSG * pmsg) { TCHAR ch = (TCHAR)pmsg->wParam; HWND hwndTop = _pmtbTop->_hwndMB; HWND hwndBottom = _pmtbBottom->_hwndMB; // Here's how this works: the menu can have one or two toolbars. // // One toolbar: we simply forward the message onto the toolbar // and let it handle any potential accelerators. // // Two toolbars: get the count of accelerators that match the // given char for each toolbar. If only one toolbar has at // least one match, forward the message onto that toolbar. // Otherwise, forward the message onto the currently tracked // toolbar and let it negotiate which accelerator button to // choose (we might get a TBN_WRAPHOTITEM). // // If no match occurs, we beep. Beep beep. // if (!_pmtbTracked) SetTracked(_pmtbTop); ASSERT(_pmtbTracked); if (_pmtbTop != _pmtbBottom) { int iNumBottomAccel; int iNumTopAccel; // Tell the dup handler not to handle this one.... _fProcessingDup = TRUE; ToolBar_HasAccelerator(hwndTop, ch, &iNumTopAccel); ToolBar_HasAccelerator(hwndBottom, ch, &iNumBottomAccel); BOOL bBottom = (0 < iNumBottomAccel); BOOL bTop = (0 < iNumTopAccel); // Does one or the other (but not both) have an accelerator? if (bBottom ^ bTop) { // Yes; do the work here for that specific toolbar HWND hwnd = bBottom ? hwndBottom : hwndTop; int cAccel = bBottom ? iNumBottomAccel : iNumTopAccel; int idCmd; pmsg->message = WM_NULL; // no need to forward the message // This should never really fail since we just checked EVAL( ToolBar_MapAccelerator(hwnd, ch, &idCmd) ); DWORD dwFlags = HICF_ACCELERATOR | HICF_RESELECT; if (cAccel == 1) dwFlags |= HICF_TOGGLEDROPDOWN; int iPos = ToolBar_CommandToIndex(hwnd, idCmd); ToolBar_SetHotItem2(hwnd, iPos, dwFlags); } // No; were there no accelerators? else if ( !bTop ) { // Yes if (_fVertical) { MessageBeep(MB_OK); } else { _CancelMode(MPOS_FULLCANCEL); } } // Else allow the message to go to the top toolbar _fProcessingDup = FALSE; } return NOERROR; } /*---------------------------------------------------------- Purpose: Callback for the get message filter. We handle the keyboard messages here (rather than IInputObject:: TranslateAcceleratorIO) so that we can redirect the message *and* have the message pump still call TranslateMessage to generate WM_CHAR and WM_SYSCHAR messages. */ LRESULT CMenuBand::GetMsgFilterCB(MSG * pmsg, BOOL bRemove) { // (See the note in CMBMsgFilter::GetMsgHook about bRemove.) if (bRemove && !_fVertical && (pmsg->message == g_nMBPopupOpen) && _pmtbTracked) { // Menu is being popped open, send a WM_MENUSELECT equivalent. _pmtbTracked->v_SendMenuNotification((UINT)pmsg->wParam, FALSE); } if (_fTopLevel && // Only do this for the top level _dwFlags & SMINIT_USEMESSAGEFILTER && // They want to use the message filter // instead of IsMenuMessage bRemove && // Only do this if we're removing it. WM_SYSCHAR == pmsg->message) // We only care about WM_SYSCHAR { // We intercept Alt-key combos (when pressed together) here, // to prevent USER from going into a false menu loop check. // There are compatibility problems if we let that happen. // // Sent by USER32 when the user hits an Alt-char combination. // We need to translate this into popping down the correct // menu. Normally we intercept this in the message pump // if (_OnSysChar(pmsg, TRUE) == S_OK) { pmsg->message = WM_NULL; } } // If a user menu is up, then we do not want to intercept those messages. Intercepting // messages intended for the poped up user menu causes havoc with keyboard accessibility. // We also don't want to process messages if we're displaying a sub menu (It should be // handling them). BOOL fTracking = FALSE; if (_pmtbMenu) fTracking = _pmtbMenu->v_TrackingSubContextMenu(); if (_pmtbShellFolder && !fTracking) fTracking = _pmtbShellFolder->v_TrackingSubContextMenu(); if (!_fInSubMenu && !fTracking) { // We don't process these messages when we're in a (modal) submenu switch (pmsg->message) { case WM_SYSKEYDOWN: case WM_KEYDOWN: // Don't process IME message. Restore original VK value. if (g_fRunOnFE && VK_PROCESSKEY == pmsg->wParam) pmsg->wParam = ImmGetVirtualKey(pmsg->hwnd); if (bRemove && (VK_ESCAPE == pmsg->wParam || VK_MENU == pmsg->wParam)) { TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): Received Esc in msg filter", DBG_THIS); DWORD dwSelect = (VK_ESCAPE == pmsg->wParam) ? MPOS_CANCELLEVEL : MPOS_FULLCANCEL; _CancelMode(dwSelect); pmsg->message = WM_NULL; return 1; } // Fall thru case WM_CHAR: // Hitting the spacebar should invoke the system menu if (!_fVertical && WM_CHAR == pmsg->message && TEXT(' ') == (TCHAR)pmsg->wParam) { // We need to leave this modal loop before bringing // up the system menu (otherwise the user would need to // hit Alt twice to get out.) Post the message. TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): Leaving menu mode for system menu", DBG_THIS); UIActivateIO(FALSE, NULL); // Say the Alt-key is down to catch DefWindowProc's attention pmsg->lParam |= 0x20000000; pmsg->message = WM_SYSCHAR; // Use the parent of the toolbar, because toolbar does not // forward WM_SYSCHAR onto DefWindowProc. pmsg->hwnd = GetParent(_pmtbTop->_hwndMB); return 1; } else if (_fVertical && WM_CHAR == pmsg->message && pmsg->wParam != VK_RETURN) { #ifdef UNICODE // Need to do this before we ask the toolbars.. // [msadek], On win9x we get the message thru a chain from explorer /iexplore (ANSI app.). // and pass it to comctl32 (Unicode) so it will fail to match the hot key. // the system sends the message with ANSI char and we treated it as Unicode. // It looks like noone is affected with this bug (US, FE) since they have hot keys always in Latin. // Bidi platforms are affected since they do have hot keys in native language. if(!g_fRunningOnNT) { char szCh[2]; WCHAR wszCh[2]; szCh[0] = (BYTE)pmsg->wParam; szCh[1] = '\0'; if(MultiByteToWideChar(CP_ACP, 0, (LPCSTR)szCh, ARRAYSIZE(szCh), wszCh, ARRAYSIZE(wszCh))) { memcpy(&(pmsg->wParam), wszCh, sizeof(WCHAR)); } } #endif // UNICODE // We do not want to pass VK_RETURN to _HandleAccelerators // because it will try to do a character match. When it fails // it will beep. Then we pass the VK_RETURN to the tracked toolbar // and it executes the command. // Handle accelerators here _HandleAccelerators(pmsg); } // Fall thru case WM_KEYUP: // Collection point for most key messages... if (NULL == _pmtbTracked) { // Normally we default to the top toolbar, unless that toolbar // cannot receive the selection (As is the case on the top level // start menu where the fast items are (Empty). // Can the top toolbar be cycled into? if (!_pmtbTop->DontShowEmpty()) { // Yes; SetTracked(_pmtbTop); // default to the top toolbar } else { // No; Set the tracked to the bottom, and hope that he can.... SetTracked(_pmtbBottom); } } // F10 has special meaning for menus. // - F10 alone, should toggle the selection of the first item // in a horizontal menu // - Shift-F10 should display a context menu. if (VK_F10 == pmsg->wParam) { // Is this the Shift-F10 Case? if (GetKeyState(VK_SHIFT) < 0) { // Yes. We need to force this message into a context menu // message. pmsg->message = WM_CONTEXTMENU; pmsg->lParam = -1; pmsg->wParam = (WPARAM)_pmtbTracked->_hwndMB; return 0; } else if (!_fVertical) //No; Then we need to toggle in the horizontal case { // Set the hot item to the first one. int iHot = 0; if (ToolBar_GetHotItem(_pmtbMenu->_hwndMB) != -1) iHot = -1; // We're toggling the selection off. ToolBar_SetHotItem(_pmtbMenu->_hwndMB, iHot); return 0; } } // Redirect to the toolbar pmsg->hwnd = _pmtbTracked->_hwndMB; return 0; case WM_NULL: // Handle this here (we do nothing) to avoid mistaking this for // g_nMBPopupOpen below, in case g_nMBPopupOpen is 0 if // RegisterWindowMessage fails. return 0; default: // We used to handle g_nMBPopupOpen here. But we can't because calling TrackPopupMenu // (via CTrackPopupBar::Popup) w/in a GetMessageFilter is very bad. break; } } if (bRemove) { // These messages must be processed even when no submenu is open switch (pmsg->message) { case WM_CLOSE: // Being deactivated. Bail out of menus. TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): sending MPOS_FULLCANCEL", DBG_THIS); _CancelMode(MPOS_FULLCANCEL); break; default: if (IsInRange(pmsg->message, WM_MOUSEFIRST, WM_MOUSELAST)) { // If we move the mouse, collapse the tip. Careful not to blow away a balloon tip... if (_pmbState) _pmbState->HideTooltip(FALSE); if (_pmtbShellFolder) _pmtbShellFolder->v_ForwardMouseMessage(pmsg->message, pmsg->wParam, pmsg->lParam); if (_pmtbMenu) _pmtbMenu->v_ForwardMouseMessage(pmsg->message, pmsg->wParam, pmsg->lParam); // Don't let the message be dispatched now that we've // forwarded it. pmsg->message = WM_NULL; } else if (pmsg->message == g_nMBFullCancel) { // Popup TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): Received private full cancel message", DBG_THIS); _SubMenuOnSelect(MPOS_CANCELLEVEL); _CancelMode(MPOS_FULLCANCEL); return 1; } break; } } return 0; } /*---------------------------------------------------------- Purpose: Handle WM_SYSCHAR This is handled for the toplevel menu only. */ HRESULT CMenuBand::_OnSysChar(MSG * pmsg, BOOL bFirstDibs) { TCHAR ch = (TCHAR)pmsg->wParam; // HACKHACK (scotth): I'm only doing all this checking because I don't // understand why the doc-obj case sometimes (and sometimes doesn't) // intercept this in its message filter. if (!bFirstDibs && _fSysCharHandled) { _fSysCharHandled = FALSE; return S_FALSE; } if (TEXT(' ') == (TCHAR)pmsg->wParam) { _fAltSpace = TRUE; // In the words of Spock..."Remember" // start menu alt+space TraceMsg(DM_MISC, "cmb._osc: alt+space _fTopLevel(1)"); UEMFireEvent(&UEMIID_SHELL, UEME_INSTRBROWSER, UEMF_INSTRUMENT, UIBW_UIINPUT, UIBL_INPMENU); } else if (!_fInSubMenu) { int idBtn; ASSERT(_fTopLevel); // There is a brief instant when we're merging a menu and pumping messages // This results in a null _pmtbMenu. if (_pmtbMenu) { // Only a toplevel menubar follows this codepath. This means only // the static menu toolbar will exist (and not the shellfolder toolbar). _pmtbTracked = _pmtbMenu; HWND hwnd = _pmtbTracked->_hwndMB; #ifdef UNICODE // [msadek], On win9x we get the message thru a chain from explorer /iexplore (ANSI app.). // and pass it to comctl32 (Unicode) so it will fail to match the hot key. // the system sends the message with ANSI char and we treated it as Unicode. // It looks like noone is affected with this bug (US, FE) since they have hot keys always in Latin. // Bidi platforms are affected since they do have hot keys in native language. if(!g_fRunningOnNT) { char szCh[2]; WCHAR wszCh[2]; szCh[0] = (BYTE)ch; szCh[1] = '\0'; if(MultiByteToWideChar(CP_ACP, 0, (LPCSTR)szCh, ARRAYSIZE(szCh), wszCh, ARRAYSIZE(wszCh))) { memcpy(&ch, wszCh, sizeof(WCHAR)); } } #endif // UNICODE if (ToolBar_MapAccelerator(hwnd, ch, &idBtn)) { // Post a message since we're already in a menu loop TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): WM_SYSCHAR: Posting CMBPopup message", DBG_THIS); UIActivateIO(TRUE, NULL); _pmtbTracked->PostPopup(idBtn, TRUE, TRUE); // browser menu alt+key, start menu alt+key TraceMsg(DM_MISC, "cmb._osc: alt+key _fTopLevel(1)"); UEMFireEvent(&UEMIID_SHELL, UEME_INSTRBROWSER, UEMF_INSTRUMENT, UIBW_UIINPUT, UIBL_INPMENU); return S_OK; } } } // Set or reset _fSysCharHandled = bFirstDibs ? TRUE : FALSE; return S_FALSE; } HRESULT CMenuBand::_ProcessMenuPaneMessages(MSG* pmsg) { if (pmsg->message == g_nMBPopupOpen) { // Popup the submenu. Since the top-level menuband receives this first, the // command must be piped down the chain to the bottom-most menuband. IOleCommandTarget * poct; QueryService(SID_SMenuBandBottom, IID_IOleCommandTarget, (LPVOID *)&poct); if (poct) { BOOL bSetItem = LOWORD(pmsg->lParam); BOOL bInitialSelect = HIWORD(pmsg->lParam); VARIANTARG vargIn; TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): Received private popup menu message", DBG_THIS); DWORD dwOpt = 0; vargIn.vt = VT_I4; vargIn.lVal = (LONG)pmsg->wParam; if (bSetItem) dwOpt |= MBPUI_SETITEM; if (bInitialSelect) dwOpt |= MBPUI_INITIALSELECT; poct->Exec(&CGID_MenuBand, MBANDCID_POPUPITEM, dwOpt, &vargIn, NULL); poct->Release(); return S_OK; } } else if (pmsg->message == g_nMBDragCancel) { // If we got a drag cancel, make sure that the bottom most // menu does not have the drag enter. IUnknown_QueryServiceExec(SAFECAST(this, IOleCommandTarget*), SID_SMenuBandBottom, &CGID_MenuBand, MBANDCID_DRAGCANCEL, 0, NULL, NULL); return S_OK; } else if (pmsg->message == g_nMBOpenChevronMenu) { VARIANTARG v; v.vt = VT_I4; v.lVal = (LONG)pmsg->wParam; IUnknown_Exec(_punkSite, &CGID_DeskBand, DBID_PUSHCHEVRON, _dwBandID, &v, NULL); } else if (pmsg->message == g_nMBFullCancel) { _SubMenuOnSelect(MPOS_CANCELLEVEL); _CancelMode(MPOS_FULLCANCEL); return S_OK; } return S_FALSE; } /*---------------------------------------------------------- Purpose: IMenuBand::IsMenuMessage method The thread's message pump calls this function to see if any messages need to be redirected to the menu band. This returns S_OK if the message is handled. The message pump should not pass it onto TranslateMessage or DispatchMessage if it does. */ STDMETHODIMP CMenuBand::IsMenuMessage(MSG * pmsg) { HRESULT hres = S_FALSE; ASSERT(IS_VALID_WRITE_PTR(pmsg, MSG)); #ifdef DEBUG if (g_dwDumpFlags & DF_TRANSACCELIO) DumpMsg(TEXT("CMB::IsMM"), pmsg); #endif if (!_fShow) goto Return; switch (pmsg->message) { case WM_SYSKEYDOWN: // blow this off if it's a repeated keystroke if (!(pmsg->lParam & 0x40000000)) { SendMessage(_hwndParent, WM_CHANGEUISTATE ,MAKEWPARAM(UIS_CLEAR, UISF_HIDEACCEL), 0); // Are we pressing the Alt key to activate the menu? if (!_fMenuMode && pmsg->wParam == VK_MENU && _pmbState) { // Yes; The the menu was activated because of a keyboard, // Set the global state to show the keyboard cues. _pmbState->SetKeyboardCue(TRUE); // Since this only happens on the top level menu, // We only have to tell the "Top" menu to update it's state. _pmtbTop->SetKeyboardCue(); } } break; case WM_SYSKEYUP: // If we're in menu mode, ignore this message. // if (_fMenuMode) hres = S_OK; break; case WM_SYSCHAR: // We intercept Alt-key combos (when pressed together) here, // to prevent USER from going into a false menu loop check. // There are compatibility problems if we let that happen. // // Sent by USER32 when the user hits an Alt-char combination. // We need to translate this into popping down the correct // menu. Normally we intercept this in the message pump // // Outlook Express needs a message hook in order to filter this // message for perf we do not use that method. // Athena fix 222185 (lamadio) We also don't want to do this if we are not active! // otherwise when WAB is on top of OE, we'll steal it's messages // BUGBUG: i'm removing GetTopMostPtr check below ... breaks menu accelerators for IE5 (224040) // (lamadio): If the Message filter is "engaged", then we can process accelerators. // Engaged does not mean that the filter is running. if (g_msgfilter.IsEngaged()) { hres = (_OnSysChar(pmsg, TRUE) == S_OK) ? S_OK : S_FALSE; } break; case WM_KEYDOWN: case WM_CHAR: case WM_KEYUP: if (_fMenuMode) { // All keystrokes should be handled or eaten by menubands // if we're engaged. We must do this, otherwise hosted // components like mshtml or word will try to handle the // keystroke in CBaseBrowser. // Also, don't bother forwarding tabs if (VK_TAB != pmsg->wParam) { // Since we're answer S_OK, dispatch it ourselves. TranslateMessage(pmsg); DispatchMessage(pmsg); } hres = S_OK; } break; case WM_CONTEXTMENU: // HACKHACK (lamadio): Since the start button has the keyboard focus, // the start button will handle this. We need to forward this off to the // currently tracked item at the bottom of the chain LRESULT lres; IWinEventHandler* pweh; if (_fMenuMode && SUCCEEDED(QueryService(SID_SMenuBandBottomSelected, IID_IWinEventHandler, (LPVOID *)&pweh))) { // BUGBUG (lamadio): This will only work because only one of the two possible toolbars // handles this pweh->OnWinEvent(HWND_BROADCAST, pmsg->message, pmsg->wParam, pmsg->lParam, &lres); pweh->Release(); hres = S_OK; } break; default: // We only want to process the pane messages in IsMenuMessage when there is no // top level HWND. This is for the Deskbar menus. Outlook Express needs the // TranslateMenuMessage entry point if (_pmbState->GetSubclassedHWND() == NULL) hres = _ProcessMenuPaneMessages(pmsg); break; } Return: if (!_fMenuMode && hres != S_OK) hres = E_FAIL; return hres; } BOOL HasWindowTopmostOwner(HWND hwnd) { HWND hwndOwner = hwnd; while (hwndOwner = GetWindowOwner(hwndOwner)) { if (GetWindowLong(hwndOwner, GWL_EXSTYLE) & WS_EX_TOPMOST) return TRUE; } return FALSE; } /*---------------------------------------------------------- Purpose: IMenuBand::TranslateMenuMessage method The main app's window proc calls this so the menuband catches messages that are dispatched from a different message pump (than the thread's main pump). Translates messages specially for menubands. Some messages are processed while the menuband is active. Others are only processed when it is not. Messages that are not b/t WM_KEYFIRST and WM_KEYLAST are handled here (the browser does not send these messages to IInputObject:: TranslateAcceleratorIO). Returns: S_OK if message is processed */ STDMETHODIMP CMenuBand::TranslateMenuMessage(MSG * pmsg, LRESULT * plRet) { ASSERT(IS_VALID_WRITE_PTR(pmsg, MSG)); #ifdef DEBUG if (g_dwDumpFlags & DF_TRANSACCELIO) DumpMsg(TEXT("CMB::TMM"), pmsg); #endif switch (pmsg->message) { case WM_SYSCHAR: // In certain doc-obj situations, the OLE message filter (??) // grabs this before the main thread's message pump gets a // whack at it. So we handle it here too, in case we're in // this scenario. // // See the comments in IsMenuMessage regarding this message. return _OnSysChar(pmsg, FALSE); case WM_INITMENUPOPUP: // Normally the LOWORD(lParam) is the index of the menu that // is being popped up. TrackPopupMenu (which CMenuISF uses) // always sends this message with an index of 0. This breaks // clients (like DefView) who check this value. We need to // massage this value if we find we're the source of the // WM_INITMENUPOPUP. // // (This is not in TranslateAcceleratorIO b/c TrackPopupMenu's // message pump does not call it. The wndproc must forward // the message to this function for us to get it.) if (_fInSubMenu && _pmtbTracked) { // Massage lParam to use the right index int iPos = ToolBar_CommandToIndex(_pmtbTracked->_hwndMB, _nItemCur); pmsg->lParam = MAKELPARAM(iPos, HIWORD(pmsg->lParam)); // Return S_FALSE so this message will still be handled } break; case WM_UPDATEUISTATE: if (_pmbState) { // we don't care about UISF_HIDEFOCUS if (UISF_HIDEACCEL == HIWORD(pmsg->wParam)) _pmbState->SetKeyboardCue(UIS_CLEAR == LOWORD(pmsg->wParam) ? TRUE : FALSE); } break; case WM_ACTIVATE: // Debug note: to debug menubands on ntsd, set the prototype // flag accordingly. This will keep menubands from going // away the moment the focus changes. // Becomming inactive? if (WA_INACTIVE == LOWORD(pmsg->wParam)) { // Yes; Free up the global object // Athena fix (lamadio) 08.02.1998: Athena uses menubands. Since they // have a band per window in one thread, we needed a mechanism to switch // between them. So we used the Msgfilter to forward messages. Since there // are multiple windows, we need to set correct one. // But, On a deactivate, we need to NULL it out incase a window, // running in the same thread, has normal USER menu. We don't want to steal // their messages. if (g_msgfilter.GetTopMostPtr() == this) g_msgfilter.SetTopMost(NULL); g_msgfilter.DisEngage(_pmbState->GetContext()); HWND hwndLostTo = (HWND)(pmsg->lParam); // We won't bail on the menus if we're loosing activation to a child. if (!IsAncestor(hwndLostTo, _pmbState->GetWorkerWindow(NULL))) { if (_fMenuMode && !(g_dwPrototype & PF_USINGNTSD) && !_fDragEntered) { // Being deactivated. Bail out of menus. // (Only the toplevel band gets this message.) if (_fInSubMenu) { IMenuPopup* pmp = _pmpSubMenu; if (_pmpTrackPopup) pmp = _pmpTrackPopup; ASSERT(pmp); // This should be valid. If not, someone screwed up. pmp->OnSelect(MPOS_FULLCANCEL); } _CancelMode(MPOS_FULLCANCEL); } } } else if (WA_ACTIVE == LOWORD(pmsg->wParam) || WA_CLICKACTIVE == LOWORD(pmsg->wParam)) { // If I have activation, the Worker Window needs to be bottom... // // NOTE: Don't do this if the worker window has a topmost owner // (such as the tray). Setting a window to HWND_NOTOPMOST moves // its owner windows to HWND_NOTOPMOST as well, which in this case // was breaking the tray's "always on top" feature. // HWND hwndWorker = _pmbState->GetWorkerWindow(NULL); if (hwndWorker && !HasWindowTopmostOwner(hwndWorker) && !_fDragEntered) SetWindowPos(hwndWorker, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOMOVE); // Set the context because when a menu heirarchy becomes active because the // subclassed HWND becomes active, we need to reenable the message hook. g_msgfilter.SetContext(this, TRUE); // When we get reactivated, we need to position ourself above the start bar. Exec(&CGID_MenuBand, MBANDCID_REPOSITION, TRUE, NULL, NULL); // Becomming activated. We need to reengage the message hook so that // we get the correct messages. g_msgfilter.ReEngage(_pmbState->GetContext()); // Are we in menu mode? if (_fMenuMode) { // Need to reengage some things. // Take the capture back because we have lost it to context menus or dialogs. g_msgfilter.RetakeCapture(); } g_msgfilter.SetTopMost(this); } // // Memphis and NT5 grey their horizontal menus when the windows is inactive. // if (!_fVertical && (g_bRunOnMemphis || g_bRunOnNT5) && _pmtbMenu) { // This needs to stay here because of the above check... if (WA_INACTIVE == LOWORD(pmsg->wParam)) { _fAppActive = FALSE; } else { _fAppActive = TRUE; } // Reduces flicker by using this instead of an InvalidateWindow/UpdateWindow Pair RedrawWindow(_pmtbMenu->_hwndMB, NULL, NULL, RDW_ERASE | RDW_INVALIDATE); } break; case WM_SYSCOMMAND: if ( !_fMenuMode ) { switch (pmsg->wParam & 0xFFF0) { case SC_KEYMENU: // The user either hit the Alt key by itself or Alt-space. // If it was Alt-space, let DefWindowProc handle it so the // system menu comes up. Otherwise, we'll handle it to // toggle the menuband. // Was it Alt-space? if (_fAltSpace) { // Yes; let it go TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): Caught the Alt-space", DBG_THIS); _fAltSpace = FALSE; } else if (_fShow) { // No; activate the menu TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): Caught the WM_SYSCOMMAND, SC_KEYMENU", DBG_THIS); UIActivateIO(TRUE, NULL); // We sit in a modal loop here because typically // WM_SYSCOMMAND doesn't return until the menu is finished. // while (_fMenuMode) { MSG msg; if (GetMessage(&msg, NULL, 0, 0)) { if ( S_OK != IsMenuMessage(&msg) ) { TranslateMessage(&msg); DispatchMessage(&msg); } } } *plRet = 0; return S_OK; // Caller shouldn't handle this } break; } } break; default: // We only want to process the pane messages in IsMenuMessage when there is no // top level HWND. This is for the Deskbar menus. Outlook Express needs the // TranslateMenuMessage entry point if (_pmbState->GetSubclassedHWND() != NULL) return _ProcessMenuPaneMessages(pmsg); break; } return S_FALSE; } /*---------------------------------------------------------- Purpose: IObjectWithSite::SetSite method Called by the menusite to host this band. Since the menuband contains two toolbars, we set their parent window to be the site's hwnd. */ STDMETHODIMP CMenuBand::SetSite(IUnknown* punkSite) { // Do this first because SetParent needs to query to the top level browser for // sftbar who queries to the top level browser to get the drag and drop window. HRESULT hres = SUPERCLASS::SetSite(punkSite); if (_psmcb && _fTopLevel && !(_dwFlags & SMINIT_NOSETSITE)) IUnknown_SetSite(_psmcb, punkSite); IUnknown_GetWindow(punkSite, &_hwndParent); // Need this for Closing an expanded vertical menu. Start Menu knows to do this when it's top level, // but the Favorites needs to know when it's parent is the horizontal menu. VARIANT var; if (SUCCEEDED(IUnknown_QueryServiceExec(punkSite, SID_SMenuBandParent, &CGID_MenuBand, MBANDCID_ISVERTICAL, 0, NULL, &var)) && var.boolVal == VARIANT_FALSE) { _fParentIsHorizontal = TRUE; } // Tell the toolbars who their new parent is if (_pmtbMenu) _pmtbMenu->SetParent(_hwndParent); if (_pmtbShellFolder) _pmtbShellFolder->SetParent(_hwndParent); return hres; } /*---------------------------------------------------------- Purpose: IShellMenu::Initialize method */ STDMETHODIMP CMenuBand::Initialize(IShellMenuCallback* psmcb, UINT uId, UINT uIdAncestor, DWORD dwFlags) { DEBUG_CODE( _fInitialized = TRUE; ); // Initalized can be called with NULL values to only set some of them. // Default to Vertical if (!(dwFlags & SMINIT_HORIZONTAL) && !(dwFlags & SMINIT_VERTICAL)) dwFlags |= SMINIT_VERTICAL; _Initialize(dwFlags); if (uIdAncestor != ANCESTORDEFAULT) _uIdAncestor = uIdAncestor; if (_uId != -1) _uId = uId; if (psmcb) { if (!SHIsSameObject(psmcb, _psmcb)) { if (_punkSite && _fTopLevel && !(dwFlags & SMINIT_NOSETSITE)) IUnknown_SetSite(_psmcb, NULL); ATOMICRELEASE(_psmcb); _psmcb = psmcb; _psmcb->AddRef(); // We do not set the site in case this callback is shared between 2 bands (Menubar/Chevron menu) if (_punkSite && _fTopLevel && !(dwFlags & SMINIT_NOSETSITE)) IUnknown_SetSite(_psmcb, _punkSite); // Only call this if we're setting a new one. Pass the address of the user associated // data section. This is so that the callback can associate data with this pane only _CallCB(SMC_CREATE, 0, (LPARAM)&_pvUserData); } } return NOERROR; } /*---------------------------------------------------------- Purpose: IShellMenu::GetMenuInfo method */ STDMETHODIMP CMenuBand::GetMenuInfo(IShellMenuCallback** ppsmc, UINT* puId, UINT* puIdAncestor, DWORD* pdwFlags) { if (ppsmc) { *ppsmc = _psmcb; if (_psmcb) ((IShellMenuCallback*)*ppsmc)->AddRef(); } if (puId) *puId = _uId; if (puIdAncestor) *puIdAncestor = _uIdAncestor; if (pdwFlags) *pdwFlags = _dwFlags; return NOERROR; } void CMenuBand::_AddToolbar(CMenuToolbarBase* pmtb, DWORD dwFlags) { pmtb->SetSite(SAFECAST(this, IMenuBand*)); if (_hwndParent) pmtb->CreateToolbar(_hwndParent); // Treat this like a two-element stack, where this function // behaves like a "push". The one additional trick is we // could be pushing onto the top or the bottom of the "stack". if (dwFlags & SMSET_BOTTOM) { if (_pmtbBottom) { // I don't need to release, because _pmtbTop and _pmtbBottom are aliases for // _pmtbShellFolder and _pmtbMenu _pmtbTop = _pmtbBottom; _pmtbTop->SetToTop(TRUE); } _pmtbBottom = pmtb; _pmtbBottom->SetToTop(FALSE); } else // Default to Top... { if (_pmtbTop) { _pmtbBottom = _pmtbTop; _pmtbBottom->SetToTop(FALSE); } _pmtbTop = pmtb; _pmtbTop->SetToTop(TRUE); } // _pmtbBottom should never be the only toolbar that exists in the menuband. if (!_pmtbTop) _pmtbTop = _pmtbBottom; // The menuband determines there is a single toolbar by comparing // the bottom with the top. So make the bottom the same if necessary. if (!_pmtbBottom) _pmtbBottom = _pmtbTop; } /*---------------------------------------------------------- Purpose: IShellMenu::GetShellFolder method */ STDMETHODIMP CMenuBand::GetShellFolder(DWORD* pdwFlags, LPITEMIDLIST* ppidl, REFIID riid, void** ppvObj) { HRESULT hres = E_FAIL; if (_pmtbShellFolder) { *pdwFlags = _pmtbShellFolder->GetFlags(); hres = S_OK; if (ppvObj) { // HACK HACK. this should QI for a mnfolder specific interface to do this. hres = _pmtbShellFolder->GetShellFolder(ppidl, riid, ppvObj); } } return hres; } /*---------------------------------------------------------- Purpose: IShellMenu::SetShellFolder method */ STDMETHODIMP CMenuBand::SetShellFolder(IShellFolder* psf, LPCITEMIDLIST pidlFolder, HKEY hKey, DWORD dwFlags) { ASSERT(_fInitialized); HRESULT hres = E_OUTOFMEMORY; // If we're processing a change notify, we cannot do anything that will modify state. // NOTE: if we don't have a state, we can't possibly processing a change notify if (_pmbState && _pmbState->IsProcessingChangeNotify()) return E_PENDING; // Only one shellfolder menu can exist per menuband. Additionally, // a shellfolder menu can exist either at the top of the menu, or // at the bottom (when it coexists with a static menu). // Is there already a shellfolder menu? if (_pmtbShellFolder) { IShellFolderBand* psfb; EVAL(SUCCEEDED(_pmtbShellFolder->QueryInterface(IID_IShellFolderBand, (void**)&psfb))); hres = psfb->InitializeSFB(psf, pidlFolder); psfb->Release(); } else { _pmtbShellFolder = new CMenuSFToolbar(this, psf, pidlFolder, hKey, dwFlags); if (_pmtbShellFolder) { _AddToolbar(_pmtbShellFolder, dwFlags); hres = NOERROR; } } return hres; } /*---------------------------------------------------------- Purpose: IMenuBand::GetMenu method */ STDMETHODIMP CMenuBand::GetMenu(HMENU* phmenu, HWND* phwnd, DWORD* pdwFlags) { HRESULT hres = E_FAIL; // HACK HACK. this should QI for a menustatic specific interface to do this. if (_pmtbMenu) hres = _pmtbMenu->GetMenu(phmenu, phwnd, pdwFlags); return hres; } /*---------------------------------------------------------- Purpose: IMenuBand::SetMenu method */ STDMETHODIMP CMenuBand::SetMenu(HMENU hmenu, HWND hwnd, DWORD dwFlags) { // Passing a NULL hmenu is valid. It means destroy our menu object. ASSERT(_fInitialized); HRESULT hres = E_FAIL; // Only one static menu can exist per menuband. Additionally, // a static menu can exist either at the top of the menu, or // at the bottom (when it coexists with a shellfolder menu). // Is there already a static menu? if (_pmtbMenu) { // Since we're merging in a new menu, make sure to update the cache... _hmenu = hmenu; // Yes // HACK HACK. this should QI for a menustatic specific interface to do this. return _pmtbMenu->SetMenu(hmenu, hwnd, dwFlags); } else { // BUGBUG (lamadio): This is to work around a problem in the interface definintion: We have // no method of setting the Subclassed HWND outside of a SetMenu. So I'm just piggybacking // off of this. A better fix would be to introduce IMenuBand2::SetSubclass(HWND). IMenuBand // actually implements the "Subclassing", so extending this interface would be worthwhile. _hwndMenuOwner = hwnd; if (_fTopLevel) { _pmbState->SetSubclassedHWND(hwnd); } if (hmenu) { _hmenu = hmenu; _pmtbMenu = new CMenuStaticToolbar(this, hmenu, hwnd, _uId, dwFlags); if (_pmtbMenu) { _AddToolbar(_pmtbMenu, dwFlags); hres = S_OK; } else hres = E_OUTOFMEMORY; } } return hres; } /*---------------------------------------------------------- Purpose: IShellMenu::SetMenuToolbar method */ STDMETHODIMP CMenuBand::SetMenuToolbar(IUnknown* punk, DWORD dwFlags) { CMenuToolbarBase* pmtb; if (punk && SUCCEEDED(punk->QueryInterface(CLSID_MenuToolbarBase, (void**)&pmtb))) { ASSERT(_pmtbShellFolder == NULL); _pmtbShellFolder = pmtb; _AddToolbar(pmtb, dwFlags); return S_OK; } else { return E_INVALIDARG; } } /*---------------------------------------------------------- Purpose: IShellMenu::InvalidateItem method */ STDMETHODIMP CMenuBand::InvalidateItem(LPSMDATA psmd, DWORD dwFlags) { HRESULT hres = S_FALSE; // If psmd is NULL, we need to just dump the toolbars and do a full reset. if (psmd == NULL) { // If we're processing a change notify, we cannot do anything that will modify state. if (_pmbState && _pmbState->IsProcessingChangeNotify()) return E_PENDING; _pmbState->PushChangeNotify(); // Tell the callback we're refreshing so that it can // reset any cached state _CallCB(SMC_REFRESH); _fExpanded = FALSE; // We don't need to refill if the caller only wanted to // refresh the sub menus. // Refresh the Shell Folder first because // It may have no items after it's done, and the // menuband may rely on this to add a seperator if (_pmtbShellFolder) _pmtbShellFolder->v_Refresh(); // Refresh the Static menu if (_pmtbMenu) _pmtbMenu->v_Refresh(); if (_pmpSubMenu) { _fInSubMenu = FALSE; IUnknown_SetSite(_pmpSubMenu, NULL); ATOMICRELEASE(_pmpSubMenu); } _pmbState->PopChangeNotify(); } else { if (_pmtbTop) hres = _pmtbTop->v_InvalidateItem(psmd, dwFlags); // We refresh everything at this level if the psmd is null if (_pmtbBottom && hres != S_OK) hres = _pmtbBottom->v_InvalidateItem(psmd, dwFlags); } return hres; } /*---------------------------------------------------------- Purpose: IShellMenu::GetState method */ STDMETHODIMP CMenuBand::GetState(LPSMDATA psmd) { if (_pmtbTracked) return _pmtbTracked->v_GetState(-1, psmd); // todo: might want to put stuff from _CallCB (below) in here return E_FAIL; } HRESULT CMenuBand::_CallCB(DWORD dwMsg, WPARAM wParam, LPARAM lParam) { if (!_psmcb) return S_FALSE; // We don't need to check callback mask here because these are not maskable events. SMDATA smd = {0}; smd.punk = SAFECAST(this, IShellMenu*); smd.uIdParent = _uId; smd.uIdAncestor = _uIdAncestor; smd.hwnd = _hwnd; smd.hmenu = _hmenu; smd.pvUserData = _pvUserData; if (_pmtbShellFolder) _pmtbShellFolder->GetShellFolder(&smd.pidlFolder, IID_IShellFolder, (void**)&smd.psf); HRESULT hres = _psmcb->CallbackSM(&smd, dwMsg, wParam, lParam); ILFree(smd.pidlFolder); if (smd.psf) smd.psf->Release(); return hres; } /*---------------------------------------------------------- Purpose: IInputObject::TranslateAcceleratorIO This is called by the base browser only when the menuband "has the focus", and only for messages b/t WM_KEYFIRST and WM_KEYLAST. This isn't very useful for menubands. See the explanations in GetMsgFilterCB, IsMenuMessage and TranslateMenuMessage. In addition, menubands cannot ever have the activation, so this method should never be called. Returns S_OK if handled. */ STDMETHODIMP CMenuBand::TranslateAcceleratorIO(LPMSG pmsg) { AssertMsg(0, TEXT("Menuband has the activation but it shouldn't!")); return S_FALSE; } /*---------------------------------------------------------- Purpose: IInputObject::HasFocusIO */ STDMETHODIMP CMenuBand::HasFocusIO() { // We consider a menuband has the focus even if it has submenus // that are currently cascaded out. All menubands in the chain // have the focus. return _fMenuMode ? S_OK : S_FALSE; } /*---------------------------------------------------------- Purpose: IMenuPopup::SetSubMenu method The child menubar calls us with its IMenuPopup pointer. */ STDMETHODIMP CMenuBand::SetSubMenu(IMenuPopup * pmp, BOOL fSet) { ASSERT(IS_VALID_CODE_PTR(pmp, IMenuPopup)); if (fSet) { _fInSubMenu = TRUE; } else { if (_pmtbTracked) { _pmtbTracked->PopupClose(); } _fInSubMenu = FALSE; _nItemSubMenu = -1; } return S_OK; } HRESULT CMenuBand::_SiteSetSubMenu(IMenuPopup * pmp, BOOL bSet) { HRESULT hres; IMenuPopup * pmpSite; hres = IUnknown_QueryService(_punkSite, SID_SMenuPopup, IID_IMenuPopup, (LPVOID *)&pmpSite); if (SUCCEEDED(hres)) { hres = pmpSite->SetSubMenu(pmp, bSet); pmpSite->Release(); } return hres; } /*---------------------------------------------------------- Purpose: Tell the GetMsg filter that this menuband is ready to listen to messages. */ HRESULT CMenuBand::_EnterMenuMode(void) { ASSERT(!_fMenuMode); // Must not push onto stack more than once if (g_dwProfileCAP & 0x00002000) StartCAP(); DEBUG_CODE( _nMenuLevel = g_nMenuLevel++; ) _fMenuMode = TRUE; _fInSubMenu = FALSE; _nItemMove = -1; _fCascadeAnimate = TRUE; _hwndFocusPrev = NULL; if (_fTopLevel) { // BUGBUG (lamadio): this piece should be moved to the shbrowse callback // REVIEW (scotth): some embedded controls (like the surround // video ctl on the carpoint website) have another thread that // eats all the messages when the control has the focus. // This prevents us from getting any messages once we're in // menu mode. I don't understand why USER menus work yet. // One way to work around this bug is to detect this case and // set the focus to our main window for the duration. if (GetWindowThreadProcessId(GetFocus(), NULL) != GetCurrentThreadId()) { IShellBrowser* psb; if (SUCCEEDED(QueryService(SID_STopLevelBrowser, IID_IShellBrowser, (void**)&psb))) { HWND hwndT; psb->GetWindow(&hwndT); _hwndFocusPrev = SetFocus(hwndT); psb->Release(); } } _hCursorOld = GetCursor(); SetCursor(g_hCursorArrow); HideCaret(NULL); } _SiteSetSubMenu(this, TRUE); if (_pmtbTop) { HWND hwnd = _pmtbTop->_hwndMB; if (!_fVertical && -1 == _nItemNew) { // The Alt key always highlights the first menu item initially SetTracked(_pmtbTop); ToolBar_SetHotItem(hwnd, 0); NotifyWinEvent(EVENT_OBJECT_FOCUS, _pmtbTop->_hwndMB, OBJID_CLIENT, GetIndexFromChild(TRUE, 0)); } _pmtbTop->Activate(TRUE); // The toolbar usually tracks mouse events. However, as the mouse // moves over submenus, we still want the parent menubar to // behave as if it has retained the focus (that is, keep the // last selected item highlighted). This also prevents the toolbar // from handling WM_MOUSELEAVE messages unnecessarily. ToolBar_SetAnchorHighlight(hwnd, TRUE); TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): Entering menu mode", DBG_THIS); NotifyWinEvent(_fVertical? EVENT_SYSTEM_MENUPOPUPSTART: EVENT_SYSTEM_MENUSTART, hwnd, OBJID_CLIENT, CHILDID_SELF); } if (_pmtbBottom) { _pmtbBottom->Activate(TRUE); ToolBar_SetAnchorHighlight(_pmtbBottom->_hwndMB, TRUE); // Turn off anchoring } g_msgfilter.Push(_pmbState->GetContext(), this, _punkSite); return S_OK; } void CMenuBand::_ExitMenuMode(void) { _fMenuMode = FALSE; _nItemCur = -1; _fPopupNewMenu = FALSE; _fInitialSelect = FALSE; if (_pmtbTop) { HWND hwnd = _pmtbTop->_hwndMB; ToolBar_SetAnchorHighlight(hwnd, FALSE); // Turn off anchoring if (!_fVertical) { // Use the first item, since we're assuming every menu must have // at least one item _pmtbTop->v_SendMenuNotification(0, TRUE); // The user may have clicked outside the menu, which would have // cancelled it. But since we set the ANCHORHIGHLIGHT attribute, // the toolbar won't receive a message to cause it to // remove the highlight. So do it explicitly now. SetTracked(NULL); UpdateWindow(hwnd); } _pmtbTop->Activate(FALSE); NotifyWinEvent(_fVertical? EVENT_SYSTEM_MENUPOPUPEND: EVENT_SYSTEM_MENUEND, hwnd, OBJID_CLIENT, CHILDID_SELF); } if (_pmtbBottom) { _pmtbBottom->Activate(FALSE); ToolBar_SetAnchorHighlight(_pmtbBottom->_hwndMB, FALSE); // Turn off anchoring } g_msgfilter.Pop(_pmbState->GetContext()); _SiteSetSubMenu(this, FALSE); if (_fTopLevel) { SetCursor(_hCursorOld); ShowCaret(NULL); g_msgfilter.SetContext(this, FALSE); // We do this here, because ShowDW(FALSE) does not get called on the // top level menu band. This resets the state, so that the accelerators // are not shown. if (_pmbState) _pmbState->SetKeyboardCue(FALSE); // Tell the menus to update their state to the current global cue state. _pmtbTop->SetKeyboardCue(); if (_pmtbTop != _pmtbBottom) _pmtbBottom->SetKeyboardCue(); } if (_hwndFocusPrev) SetFocus(_hwndFocusPrev); if (_fTopLevel) { // // The top-level menu has gone away. Win32 focus and ui-activation don't // actually change when this happens, so the browser and focused dude have // no idea that something happened and won't generate any AA event. So, we // do it here for them. Note that if there was a selection inside the focused // dude, we'll lose it. This is the best we can do for now, as we don't // currently have a way to tell the focused/ui-active guy (who knows about the // current selection) to reannounce focus. // HWND hwndFocus = GetFocus(); NotifyWinEvent(EVENT_OBJECT_FOCUS, hwndFocus, OBJID_CLIENT, CHILDID_SELF); } TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): Exited menu mode", DBG_THIS); DEBUG_CODE( g_nMenuLevel--; ) DEBUG_CODE( _nMenuLevel = -1; ) if (g_dwProfileCAP & 0x00002000) StopCAP(); } /*---------------------------------------------------------- Purpose: IInputObject::UIActivateIO Menubands CANNOT take the activation. Normally a band would return S_OK and call the site's OnFocusChangeIS method, so that its TranslateAcceleratorIO method would receive keyboard messages. However, menus are different. The window/toolbar that currently has the activation must retain that activation when the menu pops down. Because of this, menubands use a GetMessage filter to intercept messages. */ STDMETHODIMP CMenuBand::UIActivateIO(BOOL fActivate, LPMSG lpMsg) { HRESULT hres; ASSERT(NULL == lpMsg || IS_VALID_WRITE_PTR(lpMsg, MSG)); if (lpMsg != NULL) { // don't allow TAB to band (or any other 'non-explicit' activation). // (if we just cared about TAB we'd check IsVK_TABCycler). // all kinds of badness would result if we did. // the band can't take focus (see above), so it can't obey the // UIAct/OnFocChg rules (e.g. can't call OnFocusChangeIS), so // our basic activation-tracking assumptions would be broken. return S_FALSE; } if (fActivate) { TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): UIActivateIO(%d)", DBG_THIS, fActivate); if (!_fMenuMode) { _EnterMenuMode(); // BUGBUG (lamadio) : Should go in the Favorites callback. // The toplevel menuband does not set the real activation. // But the children do, so activation can be communicated // with the parent menuband. if (_fVertical) { UnkOnFocusChangeIS(_punkSite, SAFECAST(this, IInputObject*), TRUE); } else { IUnknown_Exec(_punkSite, &CGID_Theater, THID_TOOLBARACTIVATED, 0, NULL, NULL); } } if (_fPopupNewMenu) { _nItemCur = _nItemNew; ASSERT(-1 != _nItemCur); ASSERT(_pmtbTracked); _fPopupNewMenu = FALSE; _nItemNew = -1; // Popup a menu hres = _pmtbTracked->PopupOpen(_nItemCur); if (FAILED(hres)) { // Don't fail the activation TraceMsg(TF_ERROR, "%d (pmb=%#08lx): PopupOpen failed", DBG_THIS); MessageBeep(MB_OK); } else if (S_FALSE == hres) { // The submenu was modal and is finished now _ExitMenuMode(); } } } else if (_fMenuMode) { TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): UIActivateIO(%d)", DBG_THIS, fActivate); ASSERT( !_fInSubMenu ); if (!_fTopLevel) UnkOnFocusChangeIS(_punkSite, SAFECAST(this, IInputObject*), FALSE); _ExitMenuMode(); } return S_FALSE; } /*---------------------------------------------------------- Purpose: IDeskBand::GetBandInfo method */ HRESULT CMenuBand::GetBandInfo(DWORD dwBandID, DWORD fViewMode, DESKBANDINFO* pdbi) { HRESULT hres = NOERROR; _dwBandID = dwBandID; // critical for perf! (BandInfoChanged) pdbi->dwMask &= ~DBIM_TITLE; // no title (ever, for now) // We expect that _pmtbBottom should never be the only toolbar // that exists in the menuband. ASSERT(NULL == _pmtbBottom || _pmtbTop); pdbi->dwModeFlags = DBIMF_USECHEVRON; if (_pmtbTop) { // If the buttons need to be updated in the toolbars, the we should // do this before we start asking them about their sizes.... if (_fForceButtonUpdate) { _UpdateButtons(); } if (_fVertical) { pdbi->ptMaxSize.y = 0; pdbi->ptMaxSize.x = 0; SIZE size = {0}; if (_pmtbMenu) { // size param zero here => it's just an out param _pmtbMenu->GetSize(&size); // HACKHACK (lamadio): On downlevel, LARGE metrics mode causes // Start menu to push the programs menu item off screen. if (size.cy > (3 * GetSystemMetrics(SM_CYSCREEN) / 4)) { Exec(&CGID_MenuBand, MBANDCID_SETICONSIZE, ISFBVIEWMODE_SMALLICONS, NULL, NULL); size.cx = 0; size.cy = 0; _pmtbMenu->GetSize(&size); } pdbi->ptMaxSize.y = size.cy; pdbi->ptMaxSize.x = size.cx; } if (_pmtbShellFolder) { // size param should be non-zero here => it's an in/out param _pmtbShellFolder->GetSize(&size); pdbi->ptMaxSize.y += size.cy + ((_pmtbMenu && !_fExpanded)? 1 : 0); // Minor sizing problem pdbi->ptMaxSize.x = max(size.cx, pdbi->ptMaxSize.x); } pdbi->ptMinSize = pdbi->ptMaxSize; } else { HWND hwnd = _pmtbTop->_hwndMB; ShowDW(TRUE); SIZE rgSize; if ( SendMessage( hwnd, TB_GETMAXSIZE, 0, (LPARAM) &rgSize )) { pdbi->ptActual.y = rgSize.cy; SendMessage(hwnd, TB_GETIDEALSIZE, FALSE, (LPARAM)&pdbi->ptActual); } // make our min size identical to the size of the first button // (we're assuming that the toolbar has at least one button) RECT rc; SendMessage(hwnd, TB_GETITEMRECT, 0, (WPARAM)&rc); pdbi->ptMinSize.x = RECTWIDTH(rc); pdbi->ptMinSize.y = RECTHEIGHT(rc); } } return hres; } /*---------------------------------------------------------- Purpose: IOleService::Exec method */ STDMETHODIMP CMenuBand::Exec(const GUID *pguidCmdGroup, DWORD nCmdID, DWORD nCmdExecOpt, VARIANTARG *pvarargIn, VARIANTARG *pvarargOut) { // Don't do anything if we're closing. if (_fClosing) return E_FAIL; if (pguidCmdGroup == NULL) { /*NOTHING*/ } else if (IsEqualGUID(CGID_MENUDESKBAR, *pguidCmdGroup)) { switch (nCmdID) { case MBCID_GETSIDE: if (pvarargOut) { BOOL fOurChoice = FALSE; pvarargOut->vt = VT_I4; if (!_fTopLevel) { // if we are not the top level menu, we // must continue with the direction our parent was in IMenuPopup* pmpParent; IUnknown_QueryService(_punkSite, SID_SMenuPopup, IID_IMenuPopup, (LPVOID*)&pmpParent); if (pmpParent) { if (FAILED(IUnknown_Exec(pmpParent, pguidCmdGroup, nCmdID, nCmdExecOpt, pvarargIn, pvarargOut))) fOurChoice = TRUE; pmpParent->Release(); } } else fOurChoice = TRUE; if (!fOurChoice) { // only use the parent's side hint if it is in the same orientation (ie, horizontal menubar to vertical popup // means we need to make a new choice) BOOL fParentVertical = (pvarargOut->lVal == MENUBAR_RIGHT || pvarargOut->lVal == MENUBAR_LEFT); if (BOOLIFY(_fVertical) != BOOLIFY(fParentVertical)) fOurChoice = TRUE; } if (fOurChoice) { if (_fVertical) { HWND hWndMenuBand; // // The MenuBand is Mirrored , then start the first Menu Window // as Mirrored. [samera] // if ((SUCCEEDED(GetWindow(&hWndMenuBand))) && (IS_WINDOW_RTL_MIRRORED(hWndMenuBand)) ) pvarargOut->lVal = MENUBAR_LEFT; else pvarargOut->lVal = MENUBAR_RIGHT; } else pvarargOut->lVal = MENUBAR_BOTTOM; } } return S_OK; } } else if (IsEqualGUID(CGID_MenuBand, *pguidCmdGroup)) { switch (nCmdID) { case MBANDCID_GETFONTS: // BUGBUG (lamadio): can I remove this? if (pvarargOut) { if (EVAL(_pmbm)) { // BUGBUG (lamadio): this is not marshal-safe. pvarargOut->vt = VT_UNKNOWN; _pmbm->QueryInterface(IID_IUnknown, (void**)&pvarargOut->punkVal); return S_OK; } else return E_FAIL; } else return E_INVALIDARG; break; case MBANDCID_SETFONTS: if (pvarargIn && VT_UNKNOWN == pvarargIn->vt && pvarargIn->punkVal) { // BUGBUG (lamadio): this is not marshal-safe. ATOMICRELEASE(_pmbm); pvarargIn->punkVal->QueryInterface(CLSID_MenuBandMetrics, (void**)&_pmbm); _fForceButtonUpdate = TRUE; // Force Update of Toolbars: if (_pmtbMenu) _pmtbMenu->SetMenuBandMetrics(_pmbm); if (_pmtbShellFolder) _pmtbShellFolder->SetMenuBandMetrics(_pmbm); } else return E_INVALIDARG; break; case MBANDCID_RECAPTURE: g_msgfilter.RetakeCapture(); break; case MBANDCID_NOTAREALSITE: _fParentIsNotASite = BOOLIFY(nCmdExecOpt); break; case MBANDCID_ITEMDROPPED: { _fDragEntered = FALSE; HWND hwndWorker = _pmbState->GetWorkerWindow(NULL); if (hwndWorker && !HasWindowTopmostOwner(hwndWorker)) SetWindowPos(hwndWorker, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOMOVE); } break; case MBANDCID_DRAGENTER: _fDragEntered = TRUE; break; case MBANDCID_DRAGLEAVE: _fDragEntered = FALSE; break; case MBANDCID_SELECTITEM: { int iPos = nCmdExecOpt; // If they are passing vararg in, then this is an ID, not a position if (pvarargIn && pvarargIn->vt == VT_I4) { _nItemNew = pvarargIn->lVal; _fPopupNewItemOnShow = TRUE; } // This can be called outside of a created band. if (_pmtbTop) { if (iPos == MBSI_NONE) { SetTracked(NULL); } else { CMenuToolbarBase* pmtb = (iPos == MBSI_LASTITEM) ? _pmtbBottom : _pmtbTop; ASSERT(pmtb); SetTracked(pmtb); _pmtbTracked->SetHotItem(1, iPos, -1, HICF_OTHER); // If the new hot item is in the obscured part of the menu, then the // above call will have reentered & nulled out _pmtbTracked (since we // drop down the chevron menu if the new hot item is obscured). So we // need to revalidate _pmtbTracked. if (!_pmtbTracked) break; NotifyWinEvent(EVENT_OBJECT_FOCUS, _pmtbTracked->_hwndMB, OBJID_CLIENT, GetIndexFromChild(TRUE, iPos)); } } } break; case MBANDCID_KEYBOARD: // If we've been executed because of a keyboard, then set the global // state to reflect that. This is sent by MenuBar when it's ::Popup // member is called with the flag MPPF_KEYBOARD. This is for start menu. if (_pmbState) _pmbState->SetKeyboardCue(TRUE); break; case MBANDCID_POPUPITEM: if (pvarargIn && VT_I4 == pvarargIn->vt) { // we don't want to popup a sub menu if we're tracking a context menu... if ( !((_pmtbBottom && _pmtbBottom->v_TrackingSubContextMenu()) || (_pmtbTop && _pmtbTop->v_TrackingSubContextMenu()))) { // No tracked item? Well default to the top (For the chevron menu) if (!_pmtbTracked) { SetTracked(_pmtbTop); } // We don't want to display the sub menu if we're not shown. // We do this because we could have been dismissed before the message // was routed. if (_fShow && _pmtbTracked) { int iItem; int iPos; if (nCmdExecOpt & MBPUI_ITEMBYPOS) { iPos = pvarargIn->lVal; iItem = GetButtonCmd(_pmtbTracked->_hwndMB, pvarargIn->lVal); } else { iPos = ToolBar_CommandToIndex(_pmtbTracked->_hwndMB, pvarargIn->lVal); iItem = pvarargIn->lVal; } if (nCmdExecOpt & MBPUI_SETITEM) { // Set the hot item explicitly since this can be // invoked by the keyboard and the mouse could be // anywhere. _pmtbTracked->SetHotItem(1, iPos, -1, HICF_OTHER); // If the new hot item is in the obscured part of the menu, then the // above call will have reentered & nulled out _pmtbTracked (since we // drop down the chevron menu if the new hot item is obscured). So we // need to revalidate _pmtbTracked. if (!_pmtbTracked) break; NotifyWinEvent(EVENT_OBJECT_FOCUS, _pmtbTracked->_hwndMB, OBJID_CLIENT, GetIndexFromChild(TRUE, iPos) ); } _pmtbTracked->PopupHelper(iItem, nCmdExecOpt & MBPUI_INITIALSELECT); } } } break; case MBANDCID_ISVERTICAL: if (pvarargOut) { pvarargOut->vt = VT_BOOL; pvarargOut->boolVal = (_fVertical)? VARIANT_TRUE: VARIANT_FALSE; } break; case MBANDCID_SETICONSIZE: ASSERT(nCmdExecOpt == ISFBVIEWMODE_SMALLICONS || nCmdExecOpt == ISFBVIEWMODE_LARGEICONS); _uIconSize = nCmdExecOpt; if (_pmtbTop) _pmtbTop->v_UpdateIconSize(nCmdExecOpt, TRUE); if (_pmtbBottom) _pmtbBottom->v_UpdateIconSize(nCmdExecOpt, TRUE); break; case MBANDCID_SETSTATEOBJECT: if (pvarargIn && VT_INT_PTR == pvarargIn->vt) { _pmbState = (CMenuBandState*)pvarargIn->byref; } break; case MBANDCID_ISINSUBMENU: if (_fInSubMenu || (_pmtbTracked && _pmtbTracked->v_TrackingSubContextMenu())) return S_OK; else return S_FALSE; break; case MBANDCID_ISTRACKING: if (_pmtbTracked && _pmtbTracked->v_TrackingSubContextMenu()) return S_OK; else return S_FALSE; break; case MBANDCID_REPOSITION: // Don't reposition unless we're shown (Avoids artifacts onscreen of a bad positioning) if (_fShow) { // Don't forget to reposition US!!! IMenuPopup* pmdb; DWORD dwFlags = MPPF_REPOSITION | MPPF_NOANIMATE; // If we should force a reposition. This is so that we get // the trickle down reposition so things overlap correctly if (nCmdExecOpt) dwFlags |= MPPF_FORCEZORDER; if (SUCCEEDED(IUnknown_QueryService(_punkSite, SID_SMenuPopup, IID_IMenuPopup, (void**)&pmdb))) { pmdb->Popup(NULL, NULL, dwFlags); pmdb->Release(); } // Reposition the Tracked sub menu based on the current popped up item // since this pane has now moved // If they have a sub menu, tell them to reposition as well. if (_fInSubMenu && _pmtbTracked) { IUnknown_QueryServiceExec(_pmpSubMenu, SID_SMenuBandChild, &CGID_MenuBand, MBANDCID_REPOSITION, nCmdExecOpt, NULL, NULL); } _pmbState->PutTipOnTop(); } break; case MBANDCID_REFRESH: InvalidateItem(NULL, SMINV_REFRESH); break; case MBANDCID_EXPAND: if (_pmtbShellFolder) _pmtbShellFolder->Expand(TRUE); if (_pmtbMenu) _pmtbMenu->Expand(TRUE); break; case MBANDCID_DRAGCANCEL: // If one of the Sub bands in the menu heirarchy has the drag // (Either because of Drag enter or because of the drop) then // we do not want to cancel. if (!_pmbState->HasDrag()) _CancelMode(MPOS_FULLCANCEL); break; case MBANDCID_EXECUTE: ASSERT(pvarargIn != NULL); if (_pmtbTop && _pmtbTop->IsWindowOwner((HWND)pvarargIn->ullVal) == S_OK) _pmtbTop->v_ExecItem((int)nCmdExecOpt); else if (_pmtbBottom && _pmtbBottom->IsWindowOwner((HWND)pvarargIn->ullVal) == S_OK) _pmtbBottom->v_ExecItem((int)nCmdExecOpt); _SiteOnSelect(MPOS_EXECUTE); break; } // Don't bother passing CGID_MenuBand commands to CToolBand return S_OK; } return SUPERCLASS::Exec(pguidCmdGroup, nCmdID, nCmdExecOpt, pvarargIn, pvarargOut); } /*---------------------------------------------------------- Purpose: IDockingWindow::CloseDW method. */ STDMETHODIMP CMenuBand::CloseDW(DWORD dw) { // We don't want to destroy the band if it's cached. // That means it's the caller's respocibility to Unset this bit and call CloseDW explicitly if (_dwFlags & SMINIT_CACHED) return S_OK; // Since we're blowing away all of the menus, // Top and bottom are invalid _pmtbTracked = _pmtbTop = _pmtbBottom = NULL; if (_pmtbMenu) { _pmtbMenu->v_Close(); } if (_pmtbShellFolder) { _pmtbShellFolder->v_Close(); } if (_pmpSubMenu) { _fInSubMenu = FALSE; IUnknown_SetSite(_pmpSubMenu, NULL); ATOMICRELEASE(_pmpSubMenu); } // We don't want our base class to blow this window away. It belongs to someone else. _hwnd = NULL; _fClosing = TRUE; return SUPERCLASS::CloseDW(dw); } /*---------------------------------------------------------- Purpose: IDockingWindow::ShowDW method Notes: for the start menu (non-browser) case, we bracket* the top-level popup operation w/ a LockSetForegroundWindow so that another app can't steal the foreground and collapse our menu. (nt5:172813: don't do it for the browser case since a) we don't want to and b) ShowDW(FALSE) isn't called until exit the browser so we'd be permanently locked!) */ STDMETHODIMP CMenuBand::ShowDW(BOOL fShow) { // Prevent rentrancy when we're already shown. ASSERT((int)_fShow == BOOLIFY(_fShow)); if ((int)_fShow == BOOLIFY(fShow)) return NOERROR; HRESULT hres = SUPERCLASS::ShowDW(fShow); if (!fShow) { _fShow = FALSE; if (_fTopLevel) { if (_fVertical) { // (_fTopLevel && _fVertical) => start menu MyLockSetForegroundWindow(FALSE); } else if (_dwFlags & SMINIT_USEMESSAGEFILTER) { g_msgfilter.SetHook(FALSE, TRUE); g_msgfilter.SetTopMost(this); } } if ((_fTopLevel || _fParentIsHorizontal) && _pmbState) { // Reset to not have the drag when we collapse. _pmbState->HasDrag(FALSE); _pmbState->SetExpand(FALSE); _pmbState->SetUEMState(0); } _CallCB(SMC_EXITMENU); } else { _CallCB(SMC_INITMENU); _fClosing = FALSE; _fShow = TRUE; _GetFontMetrics(); if (_fTopLevel) { // We set the context here so that the ReEngage causes the message filter // to start taking messages on a TopLevel::Show. This prevents a problem // where tracking doesn't work when switching between Favorites and Start Menu _pmbState->SetContext(this); g_msgfilter.SetContext(this, TRUE); g_msgfilter.ReEngage(_pmbState->GetContext()); if (_hwndMenuOwner && _fVertical) SetForegroundWindow(_hwndMenuOwner); if (_fVertical) { // (_fTopLevel && _fVertical) => start menu MyLockSetForegroundWindow(TRUE); } else if (_dwFlags & SMINIT_USEMESSAGEFILTER) { g_msgfilter.SetHook(TRUE, TRUE); g_msgfilter.SetTopMost(this); } _pmbState->CreateFader(_hwndParent); } } if (_pmtbShellFolder) _pmtbShellFolder->v_Show(_fShow, _fForceButtonUpdate); // Menu needs to be last so that it can update the seperator. if (_pmtbMenu) _pmtbMenu->v_Show(_fShow, _fForceButtonUpdate); if (_fPopupNewItemOnShow) { HWND hwnd = _pmbState->GetSubclassedHWND(); PostMessage(hwnd? hwnd : _pmtbMenu->_hwndMB, g_nMBPopupOpen, _nItemNew, MAKELPARAM(TRUE, TRUE)); _fPopupNewItemOnShow = FALSE; } _fForceButtonUpdate = FALSE; return hres; } // BUGBUG (lamadio): move this to shlwapi HRESULT IUnknown_QueryServiceExec(IUnknown* punk, REFGUID guidService, const GUID *guid, DWORD cmdID, DWORD cmdParam, VARIANT* pvarargIn, VARIANT* pvarargOut) { HRESULT hres; IOleCommandTarget* poct; hres = IUnknown_QueryService(punk, guidService, IID_IOleCommandTarget, (void**)&poct); if (SUCCEEDED(hres)) { hres = poct->Exec(guid, cmdID, cmdParam, pvarargIn, pvarargOut); poct->Release(); } return hres; } void CMenuBand::_GetFontMetrics() { if (_pmbm) return; if (_fTopLevel) { ASSERT(_pmtbTop); // We need only 1 HWND _pmbm = new CMenuBandMetrics(_pmtbTop->_hwndMB); } else { AssertMsg(0, TEXT("When this menuband was created, someone forgot to set the metrics")); IOleCommandTarget *poct; HRESULT hres = IUnknown_QueryService(_punkSite, SID_SMenuBandTop, IID_IOleCommandTarget, (LPVOID *)&poct); if (SUCCEEDED(hres)) { VARIANTARG vargOut; // Ask the toplevel menuband for their font info if (SUCCEEDED(poct->Exec(&CGID_MenuBand, MBANDCID_GETFONTS, 0, NULL, &vargOut))) { if (vargOut.vt == VT_UNKNOWN && vargOut.punkVal) { vargOut.punkVal->QueryInterface(CLSID_MenuBandMetrics, (void**)&_pmbm); vargOut.punkVal->Release(); } } poct->Release(); } } } /*---------------------------------------------------------- Purpose: IMenuPopup::OnSelect method This allows the child menubar to tell us when and how to bail out of the menu. */ STDMETHODIMP CMenuBand::OnSelect(DWORD dwType) { int iIndex; switch (dwType) { case MPOS_CHILDTRACKING: // this means that our child did get tracked over it, so we should abort any timeout to destroy it if (_pmtbTracked) { HWND hwnd = _pmtbTracked->_hwndMB; if (_nItemTimer) { _pmtbTracked->KillPopupTimer(); // Use the command id of the SubMenu that we actually have cascaded out. iIndex = ToolBar_CommandToIndex(hwnd, _nItemSubMenu); ToolBar_SetHotItem(hwnd, iIndex); } KillTimer(hwnd, MBTIMER_DRAGOVER); _SiteOnSelect(dwType); } break; case MPOS_SELECTLEFT: if (!_fVertical) _OnSelectArrow(-1); else { // Cancel the child submenu. Hitting left arrow is like // hitting escape. _SubMenuOnSelect(MPOS_CANCELLEVEL); } break; case MPOS_SELECTRIGHT: if (!_fVertical) _OnSelectArrow(1); else { // The right arrow gets propagated up to the top, so // a fully cascaded menu will be cancelled and the // top level menuband will move to the next menu to the // right. _SiteOnSelect(dwType); } break; case MPOS_CANCELLEVEL: // Forward onto submenu _SubMenuOnSelect(dwType); break; case MPOS_FULLCANCEL: case MPOS_EXECUTE: DEBUG_CODE( TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): CMenuToolbarBase received %s", DBG_THIS, MPOS_FULLCANCEL == dwType ? TEXT("MPOS_FULLCANCEL") : TEXT("MPOS_EXECUTE")); ) _CancelMode(dwType); break; } return S_OK; } void CMenuBand::SetTrackMenuPopup(IUnknown* punk) { ATOMICRELEASE(_pmpTrackPopup); if (punk) { punk->QueryInterface(IID_IMenuPopup, (void**)&_pmpTrackPopup); } } /*---------------------------------------------------------- Purpose: Set the currently tracked toolbar. Only one of the toolbars can have the "activation" at one time. */ BOOL CMenuBand::SetTracked(CMenuToolbarBase* pmtb) { if (pmtb == _pmtbTracked) return FALSE; if (_pmtbTracked) { // Tell the existing toolbar we're leaving him SendMessage(_pmtbTracked->_hwndMB, TB_SETHOTITEM2, -1, HICF_LEAVING); } _pmtbTracked = pmtb; if (_pmtbTracked) { // This is for accessibility. HWND hwnd = _pmtbTracked->_hwndMB; int iHotItem = ToolBar_GetHotItem(hwnd); if (iHotItem >= 0) { // Toolbar Items are 0 based, Accessibility apps require 1 based NotifyWinEvent(EVENT_OBJECT_FOCUS, hwnd, OBJID_CLIENT, GetIndexFromChild(_pmtbTracked->GetFlags() & SMSET_TOP, iHotItem)); } } return TRUE; } void CMenuBand::_OnSelectArrow(int iDir) { _fKeyboardSelected = TRUE; int iIndex; if (!_pmtbTracked) { if (iDir < 0) { SetTracked(_pmtbBottom); iIndex = ToolBar_ButtonCount(_pmtbTracked->_hwndMB) - 1; } else { SetTracked(_pmtbTop); iIndex = 0; } // This can happen when going to the chevron. if (_pmtbTracked) _pmtbTracked->SetHotItem(iDir, iIndex, -1, HICF_ARROWKEYS); } else { HWND hwnd = _pmtbTracked->_hwndMB; iIndex = ToolBar_GetHotItem(hwnd); int iCount = ToolBar_ButtonCount(hwnd); // Set the hot item explicitly since this is invoked by the // keyboard and the mouse could be anywhere. // cycle iIndex by iDir (add extra iCount to avoid negative number problems iIndex = (iIndex + iCount + iDir) % iCount; ToolBar_SetHotItem(hwnd, iIndex); } if (_pmtbTracked) { NotifyWinEvent(EVENT_OBJECT_FOCUS, _pmtbTracked->_hwndMB, OBJID_CLIENT, GetIndexFromChild(_pmtbTracked->GetFlags() & SMSET_TOP, iIndex)); } _fKeyboardSelected = FALSE; } void CMenuBand::_CancelMode(DWORD dwType) { // Tell the hosting site to cancel this level if (_fParentIsNotASite) UIActivateIO(FALSE, NULL); else _SiteOnSelect(dwType); } HRESULT CMenuBand::OnPosRectChangeDB (LPRECT prc) { // We want the HMENU portion to ALWAYS have the maximum allowed. RECT rcMenu = {0}; SIZE sizeMenu = {0}; SIZE sizeSF = {0}; SIZE sizeMax; if (_pmtbMenu) _pmtbMenu->GetSize(&sizeMenu); if (_pmtbShellFolder) _pmtbShellFolder->GetSize(&sizeSF); if (sizeSF.cx > sizeMenu.cx) sizeMax = sizeSF; else sizeMax = sizeMenu; if (_pmtbMenu) { if (_pmtbMenu->GetFlags() & SMSET_TOP) { rcMenu.bottom = sizeMenu.cy; rcMenu.right = prc->right; } else { rcMenu.bottom = prc->bottom; rcMenu.right = prc->right; rcMenu.top = prc->bottom - sizeMenu.cy; rcMenu.left = 0; } _pmtbMenu->SetWindowPos(&sizeMax, &rcMenu, 0); } if (_pmtbShellFolder) { RECT rc = *prc; if (_pmtbShellFolder->GetFlags() & SMSET_TOP) { rc.bottom = prc->bottom - RECTHEIGHT(rcMenu) + 1; } else { rc.top = prc->top + RECTHEIGHT(rcMenu); } _pmtbShellFolder->SetWindowPos(&sizeMax, &rc, 0); } return NOERROR; } HRESULT IUnknown_OnSelect(IUnknown* punk, DWORD dwType, REFGUID guid) { HRESULT hres; IMenuPopup * pmp; hres = IUnknown_QueryService(punk, guid, IID_IMenuPopup, (LPVOID *)&pmp); if (SUCCEEDED(hres)) { pmp->OnSelect(dwType); pmp->Release(); } return hres; } HRESULT CMenuBand::_SiteOnSelect(DWORD dwType) { return IUnknown_OnSelect(_punkSite, dwType, SID_SMenuPopup); } HRESULT CMenuBand::_SubMenuOnSelect(DWORD dwType) { IMenuPopup* pmp = _pmpSubMenu; if (_pmpTrackPopup) pmp = _pmpTrackPopup; return IUnknown_OnSelect(pmp, dwType, SID_SMenuPopup); } HRESULT CMenuBand::GetTop(CMenuToolbarBase** ppmtbTop) { *ppmtbTop = _pmtbTop; if (*ppmtbTop) { (*ppmtbTop)->AddRef(); return NOERROR; } return E_FAIL; } HRESULT CMenuBand::GetBottom(CMenuToolbarBase** ppmtbBottom) { *ppmtbBottom = _pmtbBottom; if (*ppmtbBottom) { (*ppmtbBottom)->AddRef(); return NOERROR; } return E_FAIL; } HRESULT CMenuBand::GetTracked(CMenuToolbarBase** ppmtbTracked) { *ppmtbTracked = _pmtbTracked; if (*ppmtbTracked) { (*ppmtbTracked)->AddRef(); return NOERROR; } return E_FAIL; } HRESULT CMenuBand::GetParentSite(REFIID riid, void** ppvObj) { if (_punkSite) return _punkSite->QueryInterface(riid, ppvObj); return E_FAIL; } HRESULT CMenuBand::GetState(BOOL* pfVertical, BOOL* pfOpen) { *pfVertical = _fVertical; *pfOpen = _fMenuMode; return NOERROR; } HRESULT CMenuBand::DoDefaultAction(VARIANT* pvarChild) { if (pvarChild->lVal != CHILDID_SELF) { CMenuToolbarBase* pmtb = (pvarChild->lVal & TOOLBAR_MASK)? _pmtbTop : _pmtbBottom; int idCmd = GetButtonCmd(pmtb->_hwndMB, (pvarChild->lVal & ~TOOLBAR_MASK) - 1); SendMessage(pmtb->_hwndMB, TB_SETHOTITEM2, idCmd, HICF_OTHER | HICF_TOGGLEDROPDOWN); } else { _CancelMode(MPOS_CANCELLEVEL); } return NOERROR; } HRESULT CMenuBand::GetSubMenu(VARIANT* pvarChild, REFIID riid, void** ppvObj) { HRESULT hres = E_FAIL; CMenuToolbarBase* pmtb = (pvarChild->lVal & TOOLBAR_MASK)? _pmtbTop : _pmtbBottom; int idCmd = GetButtonCmd(pmtb->_hwndMB, (pvarChild->lVal & ~TOOLBAR_MASK) - 1); *ppvObj = NULL; if (idCmd != -1 && pmtb) { hres = pmtb->v_GetSubMenu(idCmd, &SID_SMenuBandChild, riid, ppvObj); } return hres; } HRESULT CMenuBand::IsEmpty() { BOOL fReturn = TRUE; if (_pmtbShellFolder) fReturn = _pmtbShellFolder->IsEmpty(); if (fReturn && _pmtbMenu) fReturn = _pmtbMenu->IsEmpty(); return fReturn? S_OK : S_FALSE; } //---------------------------------------------------------------------------- // CMenuBandMetrics // //---------------------------------------------------------------------------- COLORREF GetDemotedColor() { WORD iHue; WORD iLum; WORD iSat; COLORREF clr = (COLORREF)GetSysColor(COLOR_MENU); HDC hdc = GetDC(NULL); // Office CommandBars use this same algorithm for their "intellimenus" // colors. We prefer to call them "expando menus"... if (hdc) { int cColors = GetDeviceCaps(hdc, BITSPIXEL); ReleaseDC(NULL, hdc); switch (cColors) { case 4: // 16 Colors case 8: // 256 Colors // Default to using Button Face break; default: // 256+ colors ColorRGBToHLS(clr, &iHue, &iLum, &iSat); if (iLum > 220) iLum -= 20; else if (iLum <= 20) iLum += 40; else iLum += 20; clr = ColorHLSToRGB(iHue, iLum, iSat); break; } } return clr; } ULONG CMenuBandMetrics::AddRef() { return ++_cRef; } ULONG CMenuBandMetrics::Release() { ASSERT(_cRef > 0); if (--_cRef > 0) return _cRef; delete this; return 0; } HRESULT CMenuBandMetrics::QueryInterface(REFIID riid, LPVOID * ppvObj) { if (IsEqualIID(riid, IID_IUnknown)) { *ppvObj = SAFECAST(this, IUnknown*); } else if (IsEqualIID(riid, CLSID_MenuBandMetrics)) { *ppvObj = this; } else { *ppvObj = NULL; return E_FAIL; } AddRef(); return S_OK; } CMenuBandMetrics::CMenuBandMetrics(HWND hwnd) : _cRef(1) { _SetMenuFont(); _SetArrowFont(hwnd); _SetChevronFont(hwnd); #ifndef DRAWEDGE _SetPaintMetrics(hwnd); #endif _SetTextBrush(hwnd); _SetColors(); HIGHCONTRAST hc = {sizeof(HIGHCONTRAST)}; if (SystemParametersInfoA(SPI_GETHIGHCONTRAST, sizeof(hc), &hc, 0)) { _fHighContrastMode = (HCF_HIGHCONTRASTON & hc.dwFlags); } } CMenuBandMetrics::~CMenuBandMetrics() { if (_hFontMenu) DeleteObject(_hFontMenu); if (_hFontArrow) DeleteObject(_hFontArrow); if (_hFontChevron) DeleteObject(_hFontChevron); if (_hbrText) DeleteObject(_hbrText); #ifndef DRAWEDGE if (_hPenHighlight) DeleteObject(_hPenHighlight); if (_hPenShadow) DeleteObject(_hPenShadow); #endif } HFONT CMenuBandMetrics::_CalcFont(HWND hwnd, LPCTSTR pszFont, DWORD dwCharSet, TCHAR ch, int* pcx, int* pcy, int* pcxMargin, int iOrientation, int iWeight) { ASSERT(hwnd); HFONT hFontOld, hFontRet; TEXTMETRIC tm; RECT rect={0}; int cx, cy, cxM; HDC hdc = GetDC(hwnd); hFontOld = (HFONT)SelectObject(hdc, _hFontMenu); GetTextMetrics(hdc, &tm); // Set the font height (based on original USER code) cy = ((tm.tmHeight + tm.tmExternalLeading + GetSystemMetrics(SM_CYBORDER)) & 0xFFFE) - 1; // Use the menu font's avg character width as the margin. cxM = tm.tmAveCharWidth; // Not exactly how USER does it, but close // Shlwapi wraps the ansi/unicode behavior. hFontRet = CreateFontWrap(cy, 0, iOrientation, 0, iWeight, 0, 0, 0, dwCharSet, 0, 0, 0, 0, pszFont); if (EVAL(hFontRet)) { // Calc width of arrow using this new font SelectObject(hdc, hFontRet); if (EVAL(DrawText(hdc, &ch, 1, &rect, DT_CALCRECT | DT_SINGLELINE | DT_LEFT | DT_VCENTER))) cx = rect.right; else cx = tm.tmMaxCharWidth; } else { cx = tm.tmMaxCharWidth; } SelectObject(hdc, hFontOld); ReleaseDC(hwnd, hdc); *pcx = cx; *pcy = cy; *pcxMargin = cxM; return hFontRet; } /* Call after _SetMenuFont() */ void CMenuBandMetrics::_SetChevronFont(HWND hwnd) { ASSERT(!_hFontChevron); TCHAR szPath[MAX_PATH]; NONCLIENTMETRICSA ncm; ncm.cbSize = sizeof(ncm); // Should only fail with bad parameters... EVAL(SystemParametersInfoA(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0)); // Obtain the font's metrics SHAnsiToTChar(ncm.lfMenuFont.lfFaceName, szPath, ARRAYSIZE(szPath)); _hFontChevron = _CalcFont(hwnd, szPath, DEFAULT_CHARSET, CH_MENUARROW, &_cxChevron, &_cyChevron, &_cxChevron, -900, FW_NORMAL); } /* Call after _SetMenuFont() */ void CMenuBandMetrics::_SetArrowFont(HWND hwnd) { ASSERT(!_hFontArrow); ASSERT(_hFontMenu); // Obtain the font's metrics if (_hFontMenu) { _hFontArrow = _CalcFont(hwnd, szfnMarlett, SYMBOL_CHARSET, CH_MENUARROW, &_cxArrow, &_cyArrow, &_cxMargin, 0, FW_NORMAL); } else { _cxArrow = _cyArrow = _cxMargin = 0; } } void CMenuBandMetrics::_SetMenuFont() { NONCLIENTMETRICSA ncm; ncm.cbSize = sizeof(ncm); // Should only fail with bad parameters... EVAL(SystemParametersInfoA(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0)); // Should only fail under low mem conditions... EVAL(_hFontMenu = CreateFontIndirectA(&ncm.lfMenuFont)); } void CMenuBandMetrics::_SetColors() { _clrBackground = GetSysColor(COLOR_MENU); _clrMenuText = GetSysColor(COLOR_MENUTEXT); _clrDemoted = GetDemotedColor(); } #ifndef DRAWEDGE // Office "IntelliMenu" style void CMenuBandMetrics::_SetPaintMetrics(HWND hwnd) { DWORD dwSysHighlight = GetSysColor(COLOR_3DHIGHLIGHT); DWORD dwSysShadow = GetSysColor(COLOR_3DSHADOW); _hPenHighlight = CreatePen(PS_SOLID, 1, dwSysHighlight); _hPenShadow = CreatePen(PS_SOLID, 1, dwSysShadow); } #endif void CMenuBandMetrics::_SetTextBrush(HWND hwnd) { _hbrText = CreateSolidBrush(GetSysColor(COLOR_MENUTEXT)); } CMenuBandState::CMenuBandState() { // We will default to NOT show the keyboard cues. This // is overridden based on the User Settings. _fKeyboardCue = FALSE; } CMenuBandState::~CMenuBandState() { ATOMICRELEASE(_ptFader); ATOMICRELEASE(_pScheduler); if (_hwndToolTip) DestroyWindow(_hwndToolTip); if (_hwndWorker) DestroyWindow(_hwndWorker); } int CMenuBandState::GetKeyboardCue() { return _fKeyboardCue; } void CMenuBandState::SetKeyboardCue(BOOL fKC) { _fKeyboardCue = fKC; } IShellTaskScheduler* CMenuBandState::GetScheduler() { if (!_pScheduler) { CoCreateInstance(CLSID_ShellTaskScheduler, NULL, CLSCTX_INPROC, IID_IShellTaskScheduler, (void **) &_pScheduler); } if (_pScheduler) _pScheduler->AddRef(); return _pScheduler; } BOOL CMenuBandState::FadeRect(PRECT prc, PFNFADESCREENRECT pfn, LPVOID pvParam) { BOOL fFade = FALSE; SystemParametersInfo(SPI_GETSELECTIONFADE, 0, &fFade, 0); if (g_bRunOnNT5 && _ptFader && fFade) { // Set the callback into the fader window. Do this each time, as the pane // may have changed between fades if (_ptFader->FadeRect(prc, pfn, pvParam)) { IShellTaskScheduler* pScheduler = GetScheduler(); if (pScheduler) { fFade = pScheduler->AddTask(_ptFader, TASKID_Fader, ITSAT_DEFAULT_LPARAM, ITSAT_DEFAULT_PRIORITY) == S_OK; } } } return fFade; } void CMenuBandState::CreateFader(HWND hwnd) { // We do this on first show, because in the Constuctor of CMenuBandState, // the Window classes might not be registered yet (As is the case with start menu). if (g_bRunOnNT5 && !_ptFader) { _ptFader = new CFadeTask(); } } void CMenuBandState::CenterOnButton(HWND hwndTB, BOOL fBalloon, int idCmd, LPTSTR pszTitle, LPTSTR pszTip) { // Balloon style holds presidence over info tips if (_fTipShown && _fBalloonStyle) return; if (!_hwndToolTip) { _hwndToolTip = CreateWindow(TOOLTIPS_CLASS, NULL, WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP | TTS_BALLOON, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, g_hinst, NULL); if (_hwndToolTip) { // set the version so we can have non buggy mouse event forwarding SendMessage(_hwndToolTip, CCM_SETVERSION, COMCTL32_VERSION, 0); SendMessage(_hwndToolTip, TTM_SETMAXTIPWIDTH, 0, (LPARAM)300); } } if (_hwndToolTip) { // Collapse the previous tip because we're going to be doing some stuff to it before displaying again. SendMessage(_hwndToolTip, TTM_TRACKACTIVATE, (WPARAM)FALSE, (LPARAM)0); // Balloon tips don't have a border, but regular tips do. Swap now... SHSetWindowBits(_hwndToolTip, GWL_STYLE, TTS_BALLOON | WS_BORDER, (fBalloon) ? TTS_BALLOON : WS_BORDER); if (pszTip && pszTip[0]) { RECT rc; TOOLINFO ti = {0}; ti.cbSize = SIZEOF(ti); // This was pretty bad: I kept adding tools, but never deleteing them. Now we get rid of the current // one then add the new one. if (SendMessage(_hwndToolTip, TTM_ENUMTOOLS, 0, (LPARAM)&ti)) { SendMessage(_hwndToolTip, TTM_DELTOOL, 0, (LPARAM)&ti); // Delete the current tool. } ti.cbSize = SIZEOF(ti); ti.uFlags = TTF_IDISHWND | TTF_TRANSPARENT | (fBalloon? TTF_TRACK : 0); ti.hwnd = hwndTB; ti.uId = (UINT_PTR)hwndTB; SendMessage(_hwndToolTip, TTM_ADDTOOL, 0, (LPARAM)(LPTOOLINFO)&ti); ti.lpszText = pszTip; SendMessage(_hwndToolTip, TTM_UPDATETIPTEXT, 0, (LPARAM)&ti); SendMessage(_hwndToolTip, TTM_SETTITLE, TTI_INFO, (LPARAM)pszTitle); SendMessage(hwndTB, TB_GETRECT, idCmd, (LPARAM)&rc); MapWindowPoints(hwndTB, HWND_DESKTOP, (POINT*)&rc, 2); // Notice the correction for the bottom: gsierra wanted it up a couple of pixels. SendMessage(_hwndToolTip, TTM_TRACKPOSITION, 0, MAKELONG((rc.left + rc.right)/2, rc.bottom - 3)); SetWindowPos(_hwndToolTip, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); SendMessage(_hwndToolTip, TTM_TRACKACTIVATE, (WPARAM)TRUE, (LPARAM)&ti); _fTipShown = TRUE; _fBalloonStyle = fBalloon; } } } void CMenuBandState::HideTooltip(BOOL fAllowBalloonCollapse) { if (_hwndToolTip && _fTipShown) { // Now we're going to latch the Balloon style. The rest of menuband blindly // collapses the tooltip when selection changes. Here's where we say "Don't collapse // the chevron balloon tip because of a selection change." if ((_fBalloonStyle && fAllowBalloonCollapse) || !_fBalloonStyle) { SendMessage(_hwndToolTip, TTM_TRACKACTIVATE, (WPARAM)FALSE, (LPARAM)0); _fTipShown = FALSE; } } } void CMenuBandState::PutTipOnTop() { // Force the tooltip to the topmost. if (_hwndToolTip) { SetWindowPos(_hwndToolTip, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } } HWND CMenuBandState::GetWorkerWindow(HWND hwndParent) { if (!_hwndSubclassed) return NULL; if (!_hwndWorker) { // We need a worker window, so that dialogs show up on top of our menus. // HiddenWndProc is included from sftbar.h _hwndWorker = SHCreateWorkerWindow(HiddenWndProc, _hwndSubclassed, WS_EX_TOOLWINDOW, WS_POPUP, 0, (void*)_hwndSubclassed); } //hwndParent is unused at this time. I plan on using it to prevent the parenting to the subclassed window. return _hwndWorker; }
32.53683
131
0.540961
King0987654
cdae0cdd33558e182f17ccd20ab533b31dad9237
13,763
cc
C++
src/builtins/builtins-generator-gen.cc
EXHades/v8
5fe0aa3bc79c0a9d3ad546b79211f07105f09585
[ "BSD-3-Clause" ]
20,995
2015-01-01T05:12:40.000Z
2022-03-31T21:39:18.000Z
src/builtins/builtins-generator-gen.cc
lws597/v8
3685fd86a9c3871e1b0c820c9ec55912e6d74071
[ "BSD-3-Clause" ]
43
2015-01-21T11:54:36.000Z
2022-03-11T07:48:51.000Z
src/builtins/builtins-generator-gen.cc
lws597/v8
3685fd86a9c3871e1b0c820c9ec55912e6d74071
[ "BSD-3-Clause" ]
4,523
2015-01-01T15:12:34.000Z
2022-03-28T06:23:41.000Z
// Copyright 2016 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/builtins/builtins-utils-gen.h" #include "src/builtins/builtins.h" #include "src/codegen/code-factory.h" #include "src/codegen/code-stub-assembler.h" #include "src/execution/isolate.h" #include "src/objects/js-generator.h" #include "src/objects/objects-inl.h" namespace v8 { namespace internal { class GeneratorBuiltinsAssembler : public CodeStubAssembler { public: explicit GeneratorBuiltinsAssembler(compiler::CodeAssemblerState* state) : CodeStubAssembler(state) {} protected: // Currently, AsyncModules in V8 are built on top of JSAsyncFunctionObjects // with an initial yield. Thus, we need some way to 'resume' the // underlying JSAsyncFunctionObject owned by an AsyncModule. To support this // the body of resume is factored out below, and shared by JSGeneratorObject // prototype methods as well as AsyncModuleEvaluate. The only difference // between AsyncModuleEvaluate and JSGeneratorObject::PrototypeNext is // the expected receiver. void InnerResume(CodeStubArguments* args, TNode<JSGeneratorObject> receiver, TNode<Object> value, TNode<Context> context, JSGeneratorObject::ResumeMode resume_mode, char const* const method_name); void GeneratorPrototypeResume(CodeStubArguments* args, TNode<Object> receiver, TNode<Object> value, TNode<Context> context, JSGeneratorObject::ResumeMode resume_mode, char const* const method_name); }; void GeneratorBuiltinsAssembler::InnerResume( CodeStubArguments* args, TNode<JSGeneratorObject> receiver, TNode<Object> value, TNode<Context> context, JSGeneratorObject::ResumeMode resume_mode, char const* const method_name) { // Check if the {receiver} is running or already closed. TNode<Smi> receiver_continuation = LoadObjectField<Smi>(receiver, JSGeneratorObject::kContinuationOffset); Label if_receiverisclosed(this, Label::kDeferred), if_receiverisrunning(this, Label::kDeferred); TNode<Smi> closed = SmiConstant(JSGeneratorObject::kGeneratorClosed); GotoIf(SmiEqual(receiver_continuation, closed), &if_receiverisclosed); DCHECK_LT(JSGeneratorObject::kGeneratorExecuting, JSGeneratorObject::kGeneratorClosed); GotoIf(SmiLessThan(receiver_continuation, closed), &if_receiverisrunning); // Remember the {resume_mode} for the {receiver}. StoreObjectFieldNoWriteBarrier(receiver, JSGeneratorObject::kResumeModeOffset, SmiConstant(resume_mode)); // Resume the {receiver} using our trampoline. // Close the generator if there was an exception. TVARIABLE(Object, var_exception); Label if_exception(this, Label::kDeferred), if_final_return(this); TNode<Object> result; { compiler::ScopedExceptionHandler handler(this, &if_exception, &var_exception); result = CallStub(CodeFactory::ResumeGenerator(isolate()), context, value, receiver); } // If the generator is not suspended (i.e., its state is 'executing'), // close it and wrap the return value in IteratorResult. TNode<Smi> result_continuation = LoadObjectField<Smi>(receiver, JSGeneratorObject::kContinuationOffset); // The generator function should not close the generator by itself, let's // check it is indeed not closed yet. CSA_DCHECK(this, SmiNotEqual(result_continuation, closed)); TNode<Smi> executing = SmiConstant(JSGeneratorObject::kGeneratorExecuting); GotoIf(SmiEqual(result_continuation, executing), &if_final_return); args->PopAndReturn(result); BIND(&if_final_return); { // Close the generator. StoreObjectFieldNoWriteBarrier( receiver, JSGeneratorObject::kContinuationOffset, closed); // Return the wrapped result. args->PopAndReturn(CallBuiltin(Builtin::kCreateIterResultObject, context, result, TrueConstant())); } BIND(&if_receiverisclosed); { // The {receiver} is closed already. TNode<Object> builtin_result; switch (resume_mode) { case JSGeneratorObject::kNext: builtin_result = CallBuiltin(Builtin::kCreateIterResultObject, context, UndefinedConstant(), TrueConstant()); break; case JSGeneratorObject::kReturn: builtin_result = CallBuiltin(Builtin::kCreateIterResultObject, context, value, TrueConstant()); break; case JSGeneratorObject::kThrow: builtin_result = CallRuntime(Runtime::kThrow, context, value); break; } args->PopAndReturn(builtin_result); } BIND(&if_receiverisrunning); { ThrowTypeError(context, MessageTemplate::kGeneratorRunning); } BIND(&if_exception); { StoreObjectFieldNoWriteBarrier( receiver, JSGeneratorObject::kContinuationOffset, closed); CallRuntime(Runtime::kReThrow, context, var_exception.value()); Unreachable(); } } void GeneratorBuiltinsAssembler::GeneratorPrototypeResume( CodeStubArguments* args, TNode<Object> receiver, TNode<Object> value, TNode<Context> context, JSGeneratorObject::ResumeMode resume_mode, char const* const method_name) { // Check if the {receiver} is actually a JSGeneratorObject. ThrowIfNotInstanceType(context, receiver, JS_GENERATOR_OBJECT_TYPE, method_name); TNode<JSGeneratorObject> generator = CAST(receiver); InnerResume(args, generator, value, context, resume_mode, method_name); } TF_BUILTIN(AsyncModuleEvaluate, GeneratorBuiltinsAssembler) { const int kValueArg = 0; auto argc = UncheckedParameter<Int32T>(Descriptor::kJSActualArgumentsCount); CodeStubArguments args(this, argc); TNode<Object> receiver = args.GetReceiver(); TNode<Object> value = args.GetOptionalArgumentValue(kValueArg); auto context = Parameter<Context>(Descriptor::kContext); // AsyncModules act like JSAsyncFunctions. Thus we check here // that the {receiver} is a JSAsyncFunction. char const* const method_name = "[AsyncModule].evaluate"; ThrowIfNotInstanceType(context, receiver, JS_ASYNC_FUNCTION_OBJECT_TYPE, method_name); TNode<JSAsyncFunctionObject> async_function = CAST(receiver); InnerResume(&args, async_function, value, context, JSGeneratorObject::kNext, method_name); } // ES6 #sec-generator.prototype.next TF_BUILTIN(GeneratorPrototypeNext, GeneratorBuiltinsAssembler) { const int kValueArg = 0; auto argc = UncheckedParameter<Int32T>(Descriptor::kJSActualArgumentsCount); CodeStubArguments args(this, argc); TNode<Object> receiver = args.GetReceiver(); TNode<Object> value = args.GetOptionalArgumentValue(kValueArg); auto context = Parameter<Context>(Descriptor::kContext); GeneratorPrototypeResume(&args, receiver, value, context, JSGeneratorObject::kNext, "[Generator].prototype.next"); } // ES6 #sec-generator.prototype.return TF_BUILTIN(GeneratorPrototypeReturn, GeneratorBuiltinsAssembler) { const int kValueArg = 0; auto argc = UncheckedParameter<Int32T>(Descriptor::kJSActualArgumentsCount); CodeStubArguments args(this, argc); TNode<Object> receiver = args.GetReceiver(); TNode<Object> value = args.GetOptionalArgumentValue(kValueArg); auto context = Parameter<Context>(Descriptor::kContext); GeneratorPrototypeResume(&args, receiver, value, context, JSGeneratorObject::kReturn, "[Generator].prototype.return"); } // ES6 #sec-generator.prototype.throw TF_BUILTIN(GeneratorPrototypeThrow, GeneratorBuiltinsAssembler) { const int kExceptionArg = 0; auto argc = UncheckedParameter<Int32T>(Descriptor::kJSActualArgumentsCount); CodeStubArguments args(this, argc); TNode<Object> receiver = args.GetReceiver(); TNode<Object> exception = args.GetOptionalArgumentValue(kExceptionArg); auto context = Parameter<Context>(Descriptor::kContext); GeneratorPrototypeResume(&args, receiver, exception, context, JSGeneratorObject::kThrow, "[Generator].prototype.throw"); } // TODO(cbruni): Merge with corresponding bytecode handler. TF_BUILTIN(SuspendGeneratorBaseline, GeneratorBuiltinsAssembler) { auto generator = Parameter<JSGeneratorObject>(Descriptor::kGeneratorObject); auto context = LoadContextFromBaseline(); StoreJSGeneratorObjectContext(generator, context); auto suspend_id = SmiTag(UncheckedParameter<IntPtrT>(Descriptor::kSuspendId)); StoreJSGeneratorObjectContinuation(generator, suspend_id); // Store the bytecode offset in the [input_or_debug_pos] field, to be used by // the inspector. auto bytecode_offset = SmiTag(UncheckedParameter<IntPtrT>(Descriptor::kBytecodeOffset)); // Avoid the write barrier by using the generic helper. StoreObjectFieldNoWriteBarrier( generator, JSGeneratorObject::kInputOrDebugPosOffset, bytecode_offset); TNode<JSFunction> closure = LoadJSGeneratorObjectFunction(generator); auto sfi = LoadJSFunctionSharedFunctionInfo(closure); CSA_DCHECK(this, Word32BinaryNot(IsSharedFunctionInfoDontAdaptArguments(sfi))); TNode<IntPtrT> formal_parameter_count = Signed(ChangeUint32ToWord( LoadSharedFunctionInfoFormalParameterCountWithoutReceiver(sfi))); TNode<FixedArray> parameters_and_registers = LoadJSGeneratorObjectParametersAndRegisters(generator); auto parameters_and_registers_length = SmiUntag(LoadFixedArrayBaseLength(parameters_and_registers)); // Copy over the function parameters auto parameter_base_index = IntPtrConstant( interpreter::Register::FromParameterIndex(0, 1).ToOperand() + 1); CSA_CHECK(this, UintPtrLessThan(formal_parameter_count, parameters_and_registers_length)); auto parent_frame_pointer = LoadParentFramePointer(); BuildFastLoop<IntPtrT>( IntPtrConstant(0), formal_parameter_count, [=](TNode<IntPtrT> index) { auto reg_index = IntPtrAdd(parameter_base_index, index); TNode<Object> value = LoadFullTagged(parent_frame_pointer, TimesSystemPointerSize(reg_index)); UnsafeStoreFixedArrayElement(parameters_and_registers, index, value); }, 1, IndexAdvanceMode::kPost); // Iterate over register file and write values into array. // The mapping of register to array index must match that used in // BytecodeGraphBuilder::VisitResumeGenerator. auto register_base_index = IntPtrAdd(formal_parameter_count, IntPtrConstant(interpreter::Register(0).ToOperand())); auto register_count = UncheckedParameter<IntPtrT>(Descriptor::kRegisterCount); auto end_index = IntPtrAdd(formal_parameter_count, register_count); CSA_CHECK(this, UintPtrLessThan(end_index, parameters_and_registers_length)); BuildFastLoop<IntPtrT>( formal_parameter_count, end_index, [=](TNode<IntPtrT> index) { auto reg_index = IntPtrSub(register_base_index, index); TNode<Object> value = LoadFullTagged(parent_frame_pointer, TimesSystemPointerSize(reg_index)); UnsafeStoreFixedArrayElement(parameters_and_registers, index, value); }, 1, IndexAdvanceMode::kPost); // The return value is unused, defaulting to undefined. Return(UndefinedConstant()); } // TODO(cbruni): Merge with corresponding bytecode handler. TF_BUILTIN(ResumeGeneratorBaseline, GeneratorBuiltinsAssembler) { auto generator = Parameter<JSGeneratorObject>(Descriptor::kGeneratorObject); TNode<JSFunction> closure = LoadJSGeneratorObjectFunction(generator); auto sfi = LoadJSFunctionSharedFunctionInfo(closure); CSA_DCHECK(this, Word32BinaryNot(IsSharedFunctionInfoDontAdaptArguments(sfi))); TNode<IntPtrT> formal_parameter_count = Signed(ChangeUint32ToWord( LoadSharedFunctionInfoFormalParameterCountWithoutReceiver(sfi))); TNode<FixedArray> parameters_and_registers = LoadJSGeneratorObjectParametersAndRegisters(generator); // Iterate over array and write values into register file. Also erase the // array contents to not keep them alive artificially. auto register_base_index = IntPtrAdd(formal_parameter_count, IntPtrConstant(interpreter::Register(0).ToOperand())); auto register_count = UncheckedParameter<IntPtrT>(Descriptor::kRegisterCount); auto end_index = IntPtrAdd(formal_parameter_count, register_count); auto parameters_and_registers_length = SmiUntag(LoadFixedArrayBaseLength(parameters_and_registers)); CSA_CHECK(this, UintPtrLessThan(end_index, parameters_and_registers_length)); auto parent_frame_pointer = LoadParentFramePointer(); BuildFastLoop<IntPtrT>( formal_parameter_count, end_index, [=](TNode<IntPtrT> index) { TNode<Object> value = UnsafeLoadFixedArrayElement(parameters_and_registers, index); auto reg_index = IntPtrSub(register_base_index, index); StoreFullTaggedNoWriteBarrier(parent_frame_pointer, TimesSystemPointerSize(reg_index), value); UnsafeStoreFixedArrayElement(parameters_and_registers, index, StaleRegisterConstant(), SKIP_WRITE_BARRIER); }, 1, IndexAdvanceMode::kPost); Return(LoadJSGeneratorObjectInputOrDebugPos(generator)); } } // namespace internal } // namespace v8
43.83121
80
0.725714
EXHades
cdb061bf409c313d4a8d1cbe242e3ecc004e4007
3,045
cpp
C++
test_results/scripts/calculate_map_error.cpp
ethz-asl/crowdbot_active_slam
007f1a730e06cea0aaf653dc2f024da1169b9c9e
[ "MIT" ]
21
2019-10-03T10:05:53.000Z
2022-01-30T06:27:05.000Z
test_results/scripts/calculate_map_error.cpp
ethz-asl/crowdbot_active_slam
007f1a730e06cea0aaf653dc2f024da1169b9c9e
[ "MIT" ]
1
2020-06-07T08:12:40.000Z
2020-06-08T14:40:13.000Z
test_results/scripts/calculate_map_error.cpp
ethz-asl/crowdbot_active_slam
007f1a730e06cea0aaf653dc2f024da1169b9c9e
[ "MIT" ]
5
2019-11-24T15:15:32.000Z
2022-01-20T07:53:01.000Z
#include <fstream> #include <ros/ros.h> #include <ros/package.h> int main(int argc, char **argv) { // Get path and file name std::string package_path = ros::package::getPath("crowdbot_active_slam"); std::string directory_path = package_path + "/" + argv[1]; std::string general_results_path = directory_path + "/general_results.txt"; std::string test_results_path = directory_path + "/occupancy_grid_map.txt"; std::string ground_truth_map_path = package_path + "/worlds/occupancy_maps/occupancy_grid_map_" + argv[2] + "_2000x2000.txt"; std::ifstream test_map_file(test_results_path.c_str()); std::ifstream ground_truth_map_file(ground_truth_map_path.c_str()); std::string line; int i = 0; int j = 0; int k = 0; double map_score = 0; double over_ref_score = 0; if (ground_truth_map_file.is_open()){ if (test_map_file.is_open()){ while (std::getline(test_map_file, line)){ std::stringstream ss_test; ss_test << line; double p_test; ss_test >> p_test; std::getline(ground_truth_map_file, line); std::stringstream ss_ref; ss_ref << line; double p_ref; ss_ref >> p_ref; // Map Scoring if (p_test == -1){ p_test = 0.5; if (p_ref == -1){ p_ref = 0.5; } else { k += 1; p_ref /= 100; } } else { p_test /= 100; i += 1; if (p_ref == -1){ p_ref = 0.5; j += 1; over_ref_score += std::pow(p_ref - p_test, 2); } else { p_ref /= 100; } } map_score += std::pow(p_ref - p_test, 2); } } else { ROS_INFO("Failed to open test_map_file!"); } } else { ROS_INFO("Failed to open ground_truth_map_file!"); } std::ofstream result_file(general_results_path.c_str(), std::ofstream::app); if (result_file.is_open()){ // Add information to file result_file << std::endl; result_file << "Map:" << std::endl; result_file << "map_score: " << map_score << std::endl; result_file << "Number of known cells: " << i << std::endl; result_file << "Number of known test cells, while unknown in ref map: " << j << std::endl; result_file << "score for known test cells, while unkown in ref map: " << over_ref_score << std::endl; result_file << "Number of known ref cells, while unknown in test map: " << k << std::endl; // Close file result_file.close(); } else{ ROS_INFO("Could not open general_results.txt!"); } std::cout << "map_score: " << map_score << std::endl; std::cout << "Number of known cells: " << i << std::endl; std::cout << "Number of known test cells, while unknown in ref map: " << j << std::endl; std::cout << "score for known test cells, while unkown in ref map: " << over_ref_score << std::endl; std::cout << "Number of known ref cells, while unknown in test map: " << k << std::endl; return 0; }
30.45
106
0.582923
ethz-asl
cdb0fd8cfbe154c55903043e024d598995cac966
20,665
cpp
C++
oneEngine/oneGame/source/render2d/object/CRenderable2D.cpp
jonting/1Engine
f22ba31f08fa96fe6405ebecec4f374138283803
[ "BSD-3-Clause" ]
null
null
null
oneEngine/oneGame/source/render2d/object/CRenderable2D.cpp
jonting/1Engine
f22ba31f08fa96fe6405ebecec4f374138283803
[ "BSD-3-Clause" ]
null
null
null
oneEngine/oneGame/source/render2d/object/CRenderable2D.cpp
jonting/1Engine
f22ba31f08fa96fe6405ebecec4f374138283803
[ "BSD-3-Clause" ]
null
null
null
#include "CRenderable2D.h" #include "core/utils/string.h" #include "core-ext/system/io/Resources.h" #include "core-ext/system/io/assets/TextureIO.h" #include "gpuw/Device.h" #include "renderer/texture/RrTexture.h" #include "renderer/material/RrShaderProgram.h" #include "renderer/material/RrPass.h" #include "renderer/material/Material.h" #include "render2d/preprocess/PaletteToLUT.h" #include "render2d/preprocess/NormalMapGeneration.h" #include "render2d/preprocess/Conversion.h" #include "render2d/state/WorldPalette.h" CRenderable2D::CRenderable2D ( void ) : CRenderableObject() { // Set up default parameters m_spriteGenerationInfo = rrSpriteGenParams(); m_spriteGenerationInfo.normal_default = Vector3f(0, 0, 1.0F); // Use a default 2D material RrPass spritePass; spritePass.utilSetupAsDefault(); spritePass.m_type = kPassTypeForward; spritePass.m_alphaMode = renderer::kAlphaModeAlphatest; spritePass.m_cullMode = gpu::kCullModeNone; spritePass.m_surface.diffuseColor = Color(1.0F, 1.0F, 1.0F, 1.0F); spritePass.setTexture( TEX_DIFFUSE, RrTexture::Load(renderer::kTextureWhite) ); spritePass.setTexture( TEX_NORMALS, RrTexture::Load(renderer::kTextureNormalN0) ); spritePass.setTexture( TEX_SURFACE, RrTexture::Load(renderer::kTextureBlack) ); spritePass.setTexture( TEX_OVERLAY, RrTexture::Load(renderer::kTextureGrayA0) ); spritePass.setProgram( RrShaderProgram::Load(rrShaderProgramVsPs{"shaders/sys/fullbright_vv.spv", "shaders/sys/fullbright_p.spv"}) ); renderer::shader::Location t_vspec[] = {renderer::shader::Location::kPosition, renderer::shader::Location::kUV0, renderer::shader::Location::kColor}; spritePass.setVertexSpecificationByCommonList(t_vspec, 3); spritePass.m_primitiveType = gpu::kPrimitiveTopologyTriangleStrip; PassInitWithInput(0, &spritePass); // Start off with empty model data memset(&m_modeldata, 0, sizeof(m_modeldata)); m_modeldata.indexNum = 0; m_modeldata.vertexNum = 0; } CRenderable2D::~CRenderable2D () { m_meshBuffer.FreeMeshBuffers(); // Material reference released automatically } // SetSpriteFile ( c-string sprite filename ) // Sets the sprite filename to load or convert. Uses resource manager to cache data. void CRenderable2D::SetSpriteFile ( const char* n_sprite_resname, rrSpriteSetResult* o_set_result ) { SetSpriteFileAnimated( n_sprite_resname, NULL, o_set_result ); } // SetSpriteFileAnimated ( c-string sprite filename ) // Sets the sprite filename to load and possibly convert, but provides returns for additional information. void CRenderable2D::SetSpriteFileAnimated ( const char* n_sprite_resname, core::gfx::tex::arSpriteInfo* o_sprite_info, rrSpriteSetResult* o_set_result ) { //// Create the filename for the files. //std::string filename_palette = core::utils::string::GetFileStemLeaf(n_sprite_filename) + "_pal"; //std::string filename_sprite = core::utils::string::GetFileStemLeaf(n_sprite_filename); //std::string filename_normals = core::utils::string::GetFileStemLeaf(n_sprite_filename) + "_normal"; //std::string filename_surface = core::utils::string::GetFileStemLeaf(n_sprite_filename) + "_surface"; //if (n_palette_filename != NULL) //{ // filename_palette = core::utils::string::GetFileStemLeaf(n_palette_filename); //} //std::string resource_palette; //std::string resource_sprite; //std::string resource_normals; //std::string resource_surface; arstring256 resource_sprite (n_sprite_resname); arstring256 resource_palette = resource_sprite + "_palette"; arstring256 resource_normals = resource_sprite + "_normals"; arstring256 resource_surface = resource_sprite + "_surface"; arstring256 resource_illumin = resource_sprite + "_illumin"; render2d::preprocess::rrConvertSpriteResults convert_results = {}; bool conversionResult = render2d::preprocess::ConvertSprite(n_sprite_resname, &convert_results); ARCORE_ASSERT(conversionResult == true); //#if 1 // DEVELOPER_MODE // // Check for a JPG: // { // // Convert the resource files to engine's format (if the JPGs exist) // if ( core::Resources::MakePathTo(filename_sprite + ".jpg", resource_sprite) ) // { // Textures::ConvertFile(resource_sprite, core::utils::string::GetFileStemLeaf(resource_sprite) + ".bpd"); // } // } // // Check for the PNGs: // { // // Convert the resource files to engine's format (if the PNGs exist) // if ( core::Resources::MakePathTo(filename_sprite + ".png", resource_sprite) ) // { // Textures::ConvertFile(resource_sprite, core::utils::string::GetFileStemLeaf(resource_sprite) + ".bpd"); // } // if ( core::Resources::MakePathTo(filename_palette + ".png", resource_palette) ) // { // Textures::ConvertFile(resource_palette, core::utils::string::GetFileStemLeaf(resource_palette) + ".bpd"); // } // if ( core::Resources::MakePathTo(filename_normals + ".png", resource_normals) ) // { // Textures::ConvertFile(resource_normals, core::utils::string::GetFileStemLeaf(resource_normals) + ".bpd"); // } // if ( core::Resources::MakePathTo(filename_surface + ".png", resource_surface) ) // { // Textures::ConvertFile(resource_surface, core::utils::string::GetFileStemLeaf(resource_surface) + ".bpd"); // } // } // // Check for the GALs: // { // // Convert the resource files to engine's format (if the GALs exist) // if ( core::Resources::MakePathTo(filename_sprite + ".gal", resource_sprite) ) // { // Textures::timgInfo image_info; // pixel_t* image; // if (o_img_info != NULL && o_img_frametimes != NULL) // image = Textures::loadGAL_Animation(resource_sprite, image_info, NULL); // else // image = Textures::loadGAL(resource_sprite, image_info); // Textures::ConvertData(image, &image_info, core::utils::string::GetFileStemLeaf(resource_sprite) + ".bpd"); // delete [] image; // // image = Textures::loadGAL_Layer(resource_sprite, "normals", image_info); // if (image != NULL) // { // Textures::ConvertData(image, &image_info, core::utils::string::GetFileStemLeaf(resource_sprite) + "_normal.bpd"); // delete [] image; // } // // image = Textures::loadGAL_Layer(resource_sprite, "surface", image_info); // if (image != NULL) // { // Textures::ConvertData(image, &image_info, core::utils::string::GetFileStemLeaf(resource_sprite) + "_surface.bpd"); // delete [] image; // } // } // if ( core::Resources::MakePathTo(filename_palette + ".gal", resource_palette) ) // { // Textures::timgInfo image_info; // pixel_t* image = Textures::loadGAL(resource_palette, image_info); // Textures::ConvertData(image, &image_info, core::utils::string::GetFileStemLeaf(resource_palette) + ".bpd"); // delete [] image; // } // } //#endif// DEVELOPER_MODE //arstring256 name_sprite = resource_sprite; //core::utils::string::ToResourceName(name_sprite.data, 256); ////name_sprite = arstring256("rr2d_") + name_sprite; ////arstring256 name_palette = name_sprite + "_palette"; ////arstring256 name_normals = name_sprite + "_normals"; ////arstring256 name_surface = name_sprite + "_surface"; ////arstring256 name_illumin = name_sprite + "_illumin"; //// Load the sprite procedurally for the albedo/palette: //m_textureAlbedo = RrTexture::Find(name_sprite); //if (m_textureAlbedo == NULL) //{ // m_textureAlbedo = RrTexture::CreateUnitialized(name_sprite); // // load the bpd now // // // pull the info? // m_textureAlbedo->Upload(false, // NULL, // 1, 1, // core::gfx::tex::kColorFormatRGBA8, // core::gfx::tex::kWrappingRepeat, core::gfx::tex::kWrappingRepeat, // core::gfx::tex::kMipmapGenerationNone, // core::gfx::tex::kSamplingPoint); //} //else //{ // //o_sprite_info-> //} //// Load up the paletted texture //if (m_texturePalette == NULL) //{ // m_texturePalette = RrTexture::Find(name_palette); // // Load a new palette and add it to the world. // if (m_texturePalette == NULL) // { // m_texturePalette = RrTexture::Load(resource_palette); // // Some things need a palette, some things dont. // // Push the palette to the world (possibly?? improve this???) // /*if (m_texturePalette != NULL) // { // // Load the raw data from the palette first // Textures::timgInfo imginfo_palette; // pixel_t* raw_palette = Textures::LoadRawImageData(resource_palette, imginfo_palette); // if ( raw_palette == NULL ) throw core::MissingDataException(); // // Set all data in the palette to have 255 alpha (opaque) // for (int i = 0; i < imginfo_palette.width * imginfo_palette.height; ++i) // raw_palette[i].a = 255; // // Add the palette to the world's palette // render2d::WorldPalette::Active()->AddPalette( raw_palette, imginfo_palette.height, imginfo_palette.width ); // // Save dummy value // renderer::Resources::AddTexture(filename_palette); // }*/ // } //} // Load the palette: if (core::Resources::Exists(resource_palette)) { m_texturePalette = RrTexture::Load(resource_palette); m_textureAlbedo = RrTexture::Load(resource_sprite); } else { // The palette may be part of the bitmap: m_textureAlbedo = RrTexture::Load(resource_sprite); if (m_textureAlbedo) { //m_texturePalette = m_textureAlbedo->GetPalette(); //TODO } } // Load the other textures using the normal sequence m_textureNormals = RrTexture::Load(resource_normals); m_textureSurface = RrTexture::Load(resource_surface); m_textureIllumin = RrTexture::Load(resource_illumin); // Output the sprite info if (o_sprite_info != NULL) { if (m_textureAlbedo->GetExtraInfo().spriteInfo != NULL) { *o_sprite_info = *m_textureAlbedo->GetExtraInfo().spriteInfo; } } // Set the palette texture as the sprite if (m_textureAlbedo) PassAccess(0).setTexture(TEX_DIFFUSE, m_textureAlbedo); if (m_textureNormals) PassAccess(0).setTexture(TEX_NORMALS, m_textureNormals); if (m_textureSurface) PassAccess(0).setTexture(TEX_SURFACE, m_textureSurface); if (m_textureIllumin) PassAccess(0).setTexture(TEX_OVERLAY, m_textureIllumin); // Set output result if (o_set_result != NULL) { o_set_result->textureAlbedo = m_textureAlbedo; o_set_result->textureNormals = m_textureNormals; o_set_result->textureSurface = m_textureSurface; o_set_result->textureIllumin = m_textureIllumin; o_set_result->texturePalette = m_texturePalette; } /*m_material->setTexture(TEX_DIFFUSE, new_texture); // Set the normal map up as well if (loaded_normals) m_material->setTexture(TEX_NORMALS, loaded_normals); // Set the surface map up as well if (loaded_surface) m_material->setTexture(TEX_SURFACE, loaded_surface);*/ // Now create BPD paths: // Require the sprite //if ( !core::Resources::MakePathTo(filename_sprite + ".bpd", resource_sprite) ) //{ // throw core::MissingFileException(); //} //// If no palette, then load the object in forward mode. //if ( !core::Resources::MakePathTo(filename_palette + ".bpd", resource_palette) ) //{ // // Remove deferred pass from the shader so it only renders in forward mode // m_material->deferredinfo.clear(); // // Load up the texture // RrTexture* new_texture = RESOURCE_GET_TEXTURE( // n_sprite_filename, // new RrTexture ( // n_sprite_filename, // Texture2D, RGBA8, // 1024,1024, Clamp,Clamp, // MipmapNone,SamplingPoint // ) // ); // // Set output texture info // if (o_img_info) *o_img_info = new_texture->GetIOImgInfo(); // // Set sprite info // m_spriteInfo.fullsize.x = new_texture->GetWidth(); // m_spriteInfo.fullsize.y = new_texture->GetHeight(); // m_spriteInfo.framesize.x = new_texture->GetWidth(); // m_spriteInfo.framesize.y = new_texture->GetHeight(); // // Set the material based on the input file. // m_material->setTexture(TEX_DIFFUSE, new_texture); // // No longer need the texture in this object // new_texture->RemoveReference(); // // Not a palette'd sprite. // return; //} //// Check for paletted textures: //RrTexture* loaded_palette = NULL;//renderer::Resources::GetTexture(filename_palette); //RrTexture* loaded_sprite = RrTexture::Load(resource_sprite.c_str()); //RrTexture* loaded_normals = RrTexture::Load(resource_normals.c_str()); //RrTexture* loaded_surface = RrTexture::Load(resource_surface.c_str()); ////RrTexture* loaded_sprite = renderer::Resources::GetTexture(filename_sprite); ////RrTexture* loaded_normals = renderer::Resources::GetTexture(filename_normals); ////RrTexture* loaded_surface = renderer::Resources::GetTexture(filename_surface); //if ( loaded_palette == NULL ) //{ // // Load the raw data from the palette first // Textures::timgInfo imginfo_palette; // pixel_t* raw_palette = Textures::LoadRawImageData(resource_palette, imginfo_palette); // if ( raw_palette == NULL ) throw core::MissingDataException(); // // Set all data in the palette to have 255 alpha (opaque) // for (int i = 0; i < imginfo_palette.width * imginfo_palette.height; ++i) // raw_palette[i].a = 255; // // Add the palette to the world's palette // Render2D::WorldPalette::Active()->AddPalette( raw_palette, imginfo_palette.height, imginfo_palette.width ); // // // No longer need local palette // delete [] raw_palette; // // Save dummy value // renderer::Resources::AddTexture(filename_palette); //} ////if ( loaded_sprite == NULL ) ////{ //// // Load the raw data from the sprite //// Textures::timgInfo imginfo_sprite; //// pixel_t* raw_sprite = Textures::LoadRawImageData(resource_sprite, imginfo_sprite); //// if ( raw_sprite == NULL ) throw core::MissingDataException(); //// // Set output texture info //// if (o_img_info) *o_img_info = imginfo_sprite; //// // Convert the colors to the internal world's palette //// render2d::preprocess::DataToLUT( //// raw_sprite, imginfo_sprite.width * imginfo_sprite.height, //// Render2D::WorldPalette::Active()->palette_data, Render2D::WorldPalette::MAX_HEIGHT, Render2D::WorldPalette::Active()->palette_width); //// // Create empty texture to upload data into //// RrTexture* new_texture = new RrTexture(""); //// // Upload the data //// new_texture->Upload( //// raw_sprite, //// imginfo_sprite.width, imginfo_sprite.height, //// Clamp, Clamp, //// MipmapNone, SamplingPoint //// ); //// // Set sprite info //// m_spriteInfo.fullsize.x = new_texture->GetWidth(); //// m_spriteInfo.fullsize.y = new_texture->GetHeight(); //// m_spriteInfo.framesize.x = new_texture->GetWidth(); //// m_spriteInfo.framesize.y = new_texture->GetHeight(); //// // Set the palette texture as the sprite //// m_material->setTexture(TEX_DIFFUSE, new_texture); //// // No longer need the texture in this object //// new_texture->RemoveReference(); //// // Add it to manager //// renderer::Resources::AddTexture(filename_sprite, new_texture); //// // Create normal map texture //// if ( core::Resources::MakePathTo(filename_normals + ".bpd", resource_normals) ) //// { //// RrTexture* new_texture = new RrTexture ( //// resource_normals, //// Texture2D, RGBA8, //// 1024,1024, Clamp,Clamp, //// MipmapNone,SamplingPoint //// ); //// m_material->setTexture(TEX_NORMALS, new_texture); //// // No longer need the texture in this object //// new_texture->RemoveReference(); //// // Add it to manager //// renderer::Resources::AddTexture(filename_normals, new_texture); //// } //// else //// { //// RrTexture* new_texture = new RrTexture(""); //// // Generate a normal map based on input parameters //// pixel_t* raw_normalmap = new pixel_t [imginfo_sprite.width * imginfo_sprite.height]; //// render2d::preprocess::GenerateNormalMap( raw_sprite, raw_normalmap, imginfo_sprite.width, imginfo_sprite.height, m_spriteGenerationInfo.normal_default ); //// // Upload the data //// new_texture->Upload( //// raw_normalmap, //// imginfo_sprite.width, imginfo_sprite.height, //// Clamp, Clamp, //// MipmapNone, SamplingPoint //// ); //// // Set this new normal map //// m_material->setTexture(TEX_NORMALS, new_texture); //// // Clear off the data now that it's on the GPU //// delete [] raw_normalmap; //// // No longer need the texture in this object //// new_texture->RemoveReference(); //// // Add it to manager //// renderer::Resources::AddTexture(filename_normals, new_texture); //// } //// // Clear off the data now that it's on the GPU and we're done using it for generation //// delete [] raw_sprite; //// // Create surface map texture //// if ( core::Resources::MakePathTo(filename_surface + ".bpd", resource_surface) ) //// { //// RrTexture* new_texture = new RrTexture ( //// resource_surface, //// Texture2D, RGBA8, //// 1024,1024, Clamp,Clamp, //// MipmapNone,SamplingPoint //// ); //// // Set this new surface map //// m_material->setTexture(TEX_SURFACE, new_texture); //// // No longer need the texture in this object //// new_texture->RemoveReference(); //// // Add it to manager //// renderer::Resources::AddTexture(filename_surface, new_texture); //// } ////} ////else //{ // RrTexture* new_texture = loaded_sprite; // // Set sprite info // m_spriteInfo.fullsize.x = new_texture->GetWidth(); // m_spriteInfo.fullsize.y = new_texture->GetHeight(); // m_spriteInfo.framesize.x = new_texture->GetWidth(); // m_spriteInfo.framesize.y = new_texture->GetHeight(); // // Set the palette texture as the sprite // m_material->setTexture(TEX_DIFFUSE, new_texture); // // Set the normal map up as well // if (loaded_normals) m_material->setTexture(TEX_NORMALS, loaded_normals); // // Set the surface map up as well // if (loaded_surface) m_material->setTexture(TEX_SURFACE, loaded_surface); //} //// Remove forward pass to save memory //m_material->passinfo.clear(); } // GetSpriteInfo () // Returns read-only reference to the current sprite information structure. const render2d::rrSpriteInfo& CRenderable2D::GetSpriteInfo ( void ) { return m_spriteInfo; } // SpriteGenParams () // Returns read-write reference to the sprite generation parameters rrSpriteGenParams& CRenderable2D::SpriteGenParams ( void ) { return m_spriteGenerationInfo; } // PushModelData() // Takes the information inside of m_modeldata and pushes it to the GPU so that it may be rendered. void CRenderable2D::PushModeldata ( void ) { m_meshBuffer.InitMeshBuffers(&m_modeldata); } // PreRender() // Push the uniform properties bool CRenderable2D::PreRender ( rrCameraPass* cameraPass ) { PushCbufferPerObject(transform.world, cameraPass); return true; } // Render() // Render the model using the 2D engine's style bool CRenderable2D::Render ( const rrRenderParams* params ) { //// Do not render if no buffer to render with //if ( m_buffer_verts == 0 || m_buffer_tris == 0 ) //{ // return true; //} //// For now, we will render the same way as the 3d meshes render ////GL.Transform( &(transform.world) ); //m_material->m_bufferSkeletonSize = 0; //m_material->m_bufferMatricesSkinning = 0; //m_material->bindPass(pass); ////parent->SendShaderUniforms(this); //BindVAO( pass, m_buffer_verts, m_buffer_tris ); //GL.DrawElements( GL_TRIANGLES, m_modeldata.triangleNum*3, GL_UNSIGNED_INT, 0 ); ////GL.endOrtho(); //// Success! // otherwise we will render the same way 3d meshes render { if ( !m_meshBuffer.m_mesh_uploaded ) return true; // Only render when have a valid mesh and rendering enabled gpu::GraphicsContext* gfx = gpu::getDevice()->getContext(); gpu::Pipeline* pipeline = GetPipeline( params->pass ); gfx->setPipeline(pipeline); // Set up the material helper... renderer::Material(this, gfx, params->pass, pipeline) // set the depth & blend state registers .setDepthStencilState() .setRasterizerState() // bind the samplers & textures .setBlendState() .setTextures(); // bind the vertex buffers for (int i = 0; i < renderer::shader::kVBufferSlotMaxCount; ++i) if (m_meshBuffer.m_bufferEnabled[i]) gfx->setVertexBuffer(i, &m_meshBuffer.m_buffer[i], 0); // bind the index buffer gfx->setIndexBuffer(&m_meshBuffer.m_indexBuffer, gpu::kIndexFormatUnsigned16); // bind the cbuffers gfx->setShaderCBuffer(gpu::kShaderStageVs, renderer::CBUFFER_PER_OBJECT_MATRICES, &m_cbufPerObjectMatrices); gfx->setShaderCBuffer(gpu::kShaderStageVs, renderer::CBUFFER_PER_OBJECT_EXTENDED, &m_cbufPerObjectSurfaces[params->pass]); gfx->setShaderCBuffer(gpu::kShaderStageVs, renderer::CBUFFER_PER_CAMERA_INFORMATION, params->cbuf_perCamera); gfx->setShaderCBuffer(gpu::kShaderStageVs, renderer::CBUFFER_PER_PASS_INFORMATION, params->cbuf_perPass); gfx->setShaderCBuffer(gpu::kShaderStageVs, renderer::CBUFFER_PER_FRAME_INFORMATION, params->cbuf_perFrame); // draw now gfx->drawIndexed(m_modeldata.indexNum, 0, 0); } return true; }
36.064572
160
0.71188
jonting
cdb7ef72726dc5ee1391185155d0b9b34a71f269
13,734
hpp
C++
309551047_np_project3/cgi_server.hpp
Ksld154/Network-Programming
9b92ba9118ecd11de801e1ac4f062ebcce8386f0
[ "MIT" ]
1
2021-09-16T01:15:33.000Z
2021-09-16T01:15:33.000Z
309551047_np_project3/cgi_server.hpp
Ksld154/Network-Programming
9b92ba9118ecd11de801e1ac4f062ebcce8386f0
[ "MIT" ]
null
null
null
309551047_np_project3/cgi_server.hpp
Ksld154/Network-Programming
9b92ba9118ecd11de801e1ac4f062ebcce8386f0
[ "MIT" ]
null
null
null
#include <cstdlib> #include <cstdio> #include <iostream> #include <fstream> #include <unistd.h> #include <boost/asio.hpp> #include <boost/algorithm/string.hpp> #define PANEL_ENTRY_NUM 5 #define SERVER_NUM 12 #define TESTCASE_NUM 10 #define ONE_SECOND 1000000 #define MAX_CONSOLE_RESULT_LEN 15000 using boost::asio::ip::tcp; using namespace std; string get_server_list() { string server_list = ""; string domain = ".cs.nctu.edu.tw"; for(int i = 0; i < SERVER_NUM; i++) { string host = "nplinux" + to_string(i+1); server_list = server_list + "\"<option value=\"" + host + domain + "\">" + host + "</option>"; } return server_list; } string get_testcase_list() { string testcase_list = ""; for(int i = 0; i < TESTCASE_NUM; i++) { string testcase_file = "t" + to_string(i+1) + ".txt"; testcase_list += "<option value=\"" + testcase_file + "\">" + testcase_file + "</option>"; } return testcase_list; } string get_panel_html() { string panel_http = ""; panel_http = panel_http \ + "Content-type: text/html\r\n\r\n" + "<!DOCTYPE html>" + "<html lang=\"en\">" + " <head>" + " <title>NP Project 3 Panel</title>" + " <link" + " rel=\"stylesheet\"" + " href=\"https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css\"" + " integrity=\"sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2\"" + " crossorigin=\"anonymous\"" + " />" + " <link" + " href=\"https://fonts.googleapis.com/css?family=Source+Code+Pro\"" + " rel=\"stylesheet\"" + " />" + " <link" + " rel=\"icon\"" + " type=\"image/png\"" + " href=\"https://cdn4.iconfinder.com/data/icons/iconsimple-setting-time/512/dashboard-512.png\"" + " />" + " <style>" + " * {" + " font-family: \'Source Code Pro\', monospace;" + " }" + " </style>" + " </head>" + " <body class=\"bg-secondary pt-5\">"; panel_http = panel_http \ + " <form action=\"console.cgi\" method=\"GET\">" + " <table class=\"table mx-auto bg-light\" style=\"width: inherit\">" + " <thead class=\"thead-dark\">" + " <tr>" + " <th scope=\"col\">#</th>" + " <th scope=\"col\">Host</th>" + " <th scope=\"col\">Port</th>" + " <th scope=\"col\">Input File</th>" + " </tr>" + " </thead>" + " <tbody>"; for(int i = 0; i < PANEL_ENTRY_NUM; i++) { panel_http = panel_http \ + " <tr>" + " <th scope=\"row\" class=\"align-middle\">Session " + to_string(i+1) + "</th>" + " <td>" + " <div class=\"input-group\">" + " <select name=\"h" + to_string(i) + "\" class=\"custom-select\">" + " <option></option>"; panel_http += get_server_list(); panel_http = panel_http \ + " </select>" + " <div class=\"input-group-append\">" + " <span class=\"input-group-text\">.cs.nctu.edu.tw</span>" + " </div>" + " </div>" + " </td>" + " <td>" + "<input name=\"p" + to_string(i) + "\" type=\"text\" class=\"form-control\" size=\"5\" />" + "</td>" + " <td>" + "<select name=\"f" + to_string(i) + "\" class=\"custom-select\">" + "<option></option>"; panel_http += get_testcase_list(); } panel_http = panel_http \ + " <tr>" + " <td colspan=\"3\"></td>" + " <td>" + " <button type=\"submit\" class=\"btn btn-info btn-block\">Run</button>" + " </td>" + " </tr>" + " </tbody>" + " </table>" + " </form>" + " </body>" + "</html>"; return panel_http; } struct query { string server_id; string hostname; string port; string input_file; string server_endpoint; }; vector<query> parse_query_str(string query_str) { vector<query> queryList; cout << query_str << endl; vector<string> args; boost::split(args, query_str, boost::is_any_of("&")); for(int i = 0; i < args.size(); i+=3) { query q; q.hostname = args.at(i).substr(args.at(i).find("=") + 1); q.port = args.at(i+1).substr(args.at(i+1).find("=") + 1); q.input_file = args.at(i+2).substr(args.at(i+2).find("=") + 1); // q.server_endpoint = ""; // cout << q.hostname << endl; // cout << q.port << endl; // cout << q.input_file << endl; if(q.hostname != "" && q.port != ""){ queryList.push_back(q); } } return queryList; } string get_console_html(vector<query>& queryList) { string payload = ""; payload = payload \ + "Content-type: text/html\r\n\r\n" + "<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + " <head>\n" + " <meta charset=\"UTF-8\" />\n" + " <title>NP Project 3 Sample Console</title>\n" + " <link\n" + " rel=\"stylesheet\"\n" + " href=\"https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css\"\n" + " integrity=\"sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2\"\n" + " crossorigin=\"anonymous\"\n" + " />\n" + " <link\n" + " href=\"https://fonts.googleapis.com/css?family=Source+Code+Pro\"\n" + " rel=\"stylesheet\"\n" + " />\n" + " <link\n" + " rel=\"icon\"\n" + " type=\"image/png\"\n" + " href=\"https://cdn0.iconfinder.com/data/icons/small-n-flat/24/678068-terminal-512.png\"\n" + " />\n" + " <style>\n" + " * {\n" + " font-family: 'Source Code Pro', monospace;\n" + " font-size: 1rem !important;\n" + " }\n" + " body {\n" + " background-color: #212529;\n" + " }\n" + " pre {\n" + " color: #cccccc;\n" + " }\n" + " b {\n" + " color: #01b468;\n" + " }\n" + " </style>\n" + " </head>\n"; payload = payload \ + "<body>\n" + " <table class=\"table table-dark table-bordered\">\n" + " <thead>\n" + " <tr>\n"; for(vector<query>::iterator q = queryList.begin(); q != queryList.end(); q++) { string server = q->hostname + ":" + q->port; payload = payload + " <th scope=\"col\">" + server + "</th>\n"; } payload = payload \ + " </tr>\n" + " </thead>\n" + " <tbody>\n" + " <tr>\n"; for(int i = 0; i < queryList.size(); i++) { string server_id = "s" + to_string(i); queryList[i].server_id = server_id; payload = payload + " <td><pre id=\"" + server_id + "\" class=\"mb-0\"></pre></td>\n"; } payload = payload \ + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </body>\n" + "</html>\n"; return payload; } class client : public std::enable_shared_from_this<client> { public: client(boost::asio::io_context& io_context, tcp::socket& browser_socket, string server_id, string input_file) : socket_(io_context), browser_socket_(browser_socket), server_id_(server_id), input_file_stream_("./test_case/" + input_file), stopped_(false) { memset(recv_data_buf_, '\0', MAX_CONSOLE_RESULT_LEN); } void start(tcp::resolver::results_type endpoints) { endpoints_ = endpoints; do_connect(endpoints_.begin()); } void stop() { stopped_ = true; input_file_stream_.close(); boost::system::error_code ignore_ec; socket_.close(ignore_ec); } private: void do_connect(tcp::resolver::results_type::iterator endpoint_iter) { auto self(shared_from_this()); if(endpoint_iter != endpoints_.end()) { socket_.async_connect(endpoint_iter->endpoint(), [this, self](boost::system::error_code ec) { if(stopped_) return; else if(!ec) { do_read(); } else { printf("Coneect error: <script>console.log(\"%s\")</script>", ec.message().c_str()); fflush(stdout); socket_.close(); // do_connect(); } } ); } else { stop(); } } void do_read() { auto self(shared_from_this()); socket_.async_read_some(boost::asio::buffer(recv_data_buf_, MAX_CONSOLE_RESULT_LEN), [this, self](boost::system::error_code ec, std::size_t length) { if(stopped_) return; if(!ec) { string recv_data = recv_data_buf_; outputShell(recv_data); memset(recv_data_buf_, '\0', MAX_CONSOLE_RESULT_LEN); // If recv_data contains the prompt, then we can start sending next cmd to golden_server if(recv_data.find("% ") != recv_data.npos) { do_write(); } else { // otherwise we continue to read server output from current cmd do_read(); } } else { printf("<script>console.log(\"%s\")</script>\n", ec.message().c_str()); fflush(stdout); stop(); } } ); } void do_write() { getline(input_file_stream_, cmd_buf_); cmd_buf_ += '\n'; outputCommand(cmd_buf_); // usleep(0.2 * ONE_SECOND); // write cmd to golden_server auto self(shared_from_this()); boost::asio::async_write(socket_, boost::asio::buffer(cmd_buf_, cmd_buf_.length()), [this, self](const boost::system::error_code& ec, std::size_t) { if(stopped_) return; if(!ec) { cmd_buf_.clear(); do_read(); } else { printf("write error: <script>console.log(\"%s\")</script>", ec.message().c_str()); fflush(stdout); stop(); } } ); } // print cmd_result/welcome_msg to browser's screen void outputShell(string recv_content) { char html_content[100000]; string formatted_recv_content = help_format_into_html(recv_content); sprintf(html_content, "<script>document.getElementById(\'%s\').innerHTML += \'%s\';</script>", server_id_.c_str(), formatted_recv_content.c_str()); string html_string = html_content; help_print_to_browser(html_string); } // print cmd to browser's screen void outputCommand(string cmd) { char html_cmd[100000]; string formatted_cmd = help_format_into_html(cmd); sprintf(html_cmd, "<script>document.getElementById(\'%s\').innerHTML += \'<b>%s</b>\';</script>", server_id_.c_str(), formatted_cmd.c_str()); string html_string = html_cmd; help_print_to_browser(html_string); } string help_format_into_html(string raw_str) { string formatted_str = raw_str; boost::replace_all(formatted_str, "\r", ""); boost::replace_all(formatted_str, "&", "&amp;"); boost::replace_all(formatted_str, "\n", "&NewLine;"); boost::replace_all(formatted_str, "<", "&lt;"); boost::replace_all(formatted_str, ">", "&gt;"); boost::replace_all(formatted_str, "\"", "&quot;"); boost::replace_all(formatted_str, "\'", "&apos;"); return formatted_str; } void help_print_to_browser(string data) { boost::asio::async_write(browser_socket_, boost::asio::buffer(data, data.length()), [this](boost::system::error_code ec, std::size_t) { if(stopped_) return; if(!ec) { } } ); } tcp::resolver::results_type endpoints_; tcp::socket socket_; tcp::socket& browser_socket_; bool stopped_; char recv_data_buf_[MAX_CONSOLE_RESULT_LEN]; string cmd_buf_; string server_id_; ifstream input_file_stream_; };
34.507538
156
0.457623
Ksld154
cdbb05e40c99a20f8581f4372c23b794aa95f046
13,847
cpp
C++
CPP-A.04S_GLDraw2D/src/Geom.cpp
raeffu/cpp
2331efce9fb6d9432542a7286dd5e1f259ba029e
[ "MIT" ]
null
null
null
CPP-A.04S_GLDraw2D/src/Geom.cpp
raeffu/cpp
2331efce9fb6d9432542a7286dd5e1f259ba029e
[ "MIT" ]
null
null
null
CPP-A.04S_GLDraw2D/src/Geom.cpp
raeffu/cpp
2331efce9fb6d9432542a7286dd5e1f259ba029e
[ "MIT" ]
null
null
null
/*///////////////////////////////////////////////////////////////////////////// module: implementation of geom classes (CPP-A.04S_GLDraw2D) purpose: implements all geometrical classes used in the draw application written: U.Kuenzler version: 1.01 history: 1.00 - initial version of OpenGL drawing application /////////////////////////////////////////////////////////////////////////////*/ // system includes //////////////////////////////////////////////////////////// #include <iostream> #include <math.h> #include <algorithm> using namespace std; // OpenGL helper includes ///////////////////////////////////////////////////// #include <GL/glew.h> #include <FL/glut.H> // application includes /////////////////////////////////////////////////////// #include "../inc/Drawing.h" #include "../inc/Geom.h" // static data definitions //////////////////////////////////////////////////// unsigned long CPoint::ulCount = 0; unsigned long CLine::ulCount = 0; unsigned long CRect::ulCount = 0; unsigned long CCircle::ulCount = 0; /////////////////////////////////////////////////////////////////////////////// // class: CPoint // function: copy constructor // purpose: constructs an object using another object of the same class /////////////////////////////////////////////////////////////////////////////// CPoint::CPoint(const CPoint& source) /////////////////////////////////////////////////////////////////////////////// { x = source.x; y = source.y; ulCount++; } /////////////////////////////////////////////////////////////////////////////// // class: CPoint // function: list() // purpose: list coordinates on standard console /////////////////////////////////////////////////////////////////////////////// void CPoint::list( void ) /////////////////////////////////////////////////////////////////////////////// { cout << "CPoint : " << "Px=" << x << " Py=" << y << endl; } /////////////////////////////////////////////////////////////////////////////// // class: CPoint // function: draw() // purpose: draw point as cross using OpenGL commands /////////////////////////////////////////////////////////////////////////////// void CPoint::draw( void ) /////////////////////////////////////////////////////////////////////////////// { // cout << "DEBUG: CPoint::draw() x=" << x << " y=" << y << endl; // define the size of cross static const float crosslength = 5; // draw the cross using two lines glBegin(GL_LINES); glVertex2f(x - crosslength, y); glVertex2f(x + crosslength+1, y ); glVertex2f(x, y - (crosslength+1)); glVertex2f(x, y + crosslength); glEnd(); } /////////////////////////////////////////////////////////////////////////////// // class: CLine // function: constructor // purpose: constructs a object using two coordinate pairs /////////////////////////////////////////////////////////////////////////////// CLine::CLine( float x1, float y1, float x2, float y2 ) /////////////////////////////////////////////////////////////////////////////// { set( x1, y1, x2, y2 ); ulCount++; } /////////////////////////////////////////////////////////////////////////////// // class: CLine // function: constructor // purpose: constructs an object using two points /////////////////////////////////////////////////////////////////////////////// CLine::CLine( const CPoint& ptP1, const CPoint& ptP2 ) /////////////////////////////////////////////////////////////////////////////// { _P1 = ptP1; _P2 = ptP2; ulCount++; } /////////////////////////////////////////////////////////////////////////////// // class: CLine // function: copy constructor // purpose: constructs an object using another object of the same class /////////////////////////////////////////////////////////////////////////////// CLine::CLine( const CLine& source ) /////////////////////////////////////////////////////////////////////////////// { _P1 = source._P1; _P2 = source._P2; ulCount++; } /////////////////////////////////////////////////////////////////////////////// // class: CLine // function: assignment operator // purpose: constructs an object using another object of the same class /////////////////////////////////////////////////////////////////////////////// CLine& CLine::operator=( const CLine& source ) /////////////////////////////////////////////////////////////////////////////// { _P1 = source._P1; _P2 = source._P2; return *this; } /////////////////////////////////////////////////////////////////////////////// // class: CLine // function: operator+() // purpose: constructs a line object by adding two lines /////////////////////////////////////////////////////////////////////////////// CLine CLine::operator+( const CLine& addline ) /////////////////////////////////////////////////////////////////////////////// { // define temporary local object CLine lineTemp; // calculate components of temporary line lineTemp._P1 = _P1; lineTemp._P2 = _P2 + addline._P2 - addline._P1; return lineTemp; } /////////////////////////////////////////////////////////////////////////////// // class: CLine // function: set() // purpose: sets coordinates of line /////////////////////////////////////////////////////////////////////////////// void CLine::set( float x1, float y1, float x2, float y2 ) /////////////////////////////////////////////////////////////////////////////// { _P1.x = x1; _P1.y = y1; _P2.x = x2; _P2.y = y2; } /////////////////////////////////////////////////////////////////////////////// // class: CLine // function: list() // purpose: list coordinates on standard console /////////////////////////////////////////////////////////////////////////////// void CLine::list( void ) /////////////////////////////////////////////////////////////////////////////// { cout << "CLine :" << endl; _P1.list(); _P2.list(); cout << endl; } /////////////////////////////////////////////////////////////////////////////// // class: CLine // function: draw() // purpose: draw line using OpenGL commands /////////////////////////////////////////////////////////////////////////////// void CLine::draw( void ) /////////////////////////////////////////////////////////////////////////////// { glBegin(GL_LINES); glVertex2f(_P1.x, _P1.y); glVertex2f(_P2.x, _P2.y); glEnd(); } /////////////////////////////////////////////////////////////////////////////// // class: CRect // function: constructor // purpose: constructs a object using two coordinate pairs /////////////////////////////////////////////////////////////////////////////// CRect::CRect( float x1, float y1, float x2, float y2 ) /////////////////////////////////////////////////////////////////////////////// { set( x1, y1, x2, y2 ); ulCount++; } /////////////////////////////////////////////////////////////////////////////// // class: CRect // function: constructor // purpose: constructs an object using two points /////////////////////////////////////////////////////////////////////////////// CRect::CRect( const CPoint& ptP1, const CPoint& ptP2 ) /////////////////////////////////////////////////////////////////////////////// { _P1 = ptP1; _P2 = ptP2; ulCount++; } /////////////////////////////////////////////////////////////////////////////// // class: CRect // function: copy constructor // purpose: constructs an object using another object of the same class /////////////////////////////////////////////////////////////////////////////// CRect::CRect( const CRect& source ) /////////////////////////////////////////////////////////////////////////////// { _P1 = source._P1; _P2 = source._P2; ulCount++; } /////////////////////////////////////////////////////////////////////////////// // class: CRect // function: operator+() // purpose: constructs a rectangle object by adding two rectangles /////////////////////////////////////////////////////////////////////////////// CRect CRect::operator+( const CRect& addrect ) /////////////////////////////////////////////////////////////////////////////// { float x1 = _P1.x; float x2 = _P1.x; float y1 = _P1.y; float y2 = _P1.y; if (_P2.x < x1) x1 = _P2.x; if (addrect._P1.x < x1) x1 = addrect._P1.x; if (addrect._P2.x < x1) x1 = addrect._P2.x; if (_P2.y < y1) y1 = _P2.y; if (addrect._P1.y < y1) y1 = addrect._P1.y; if (addrect._P2.y < y1) y1 = addrect._P2.y; if (_P2.x > x2) x2 = _P2.x; if (addrect._P1.x > x2) x2 = addrect._P1.x; if (addrect._P2.x > x2) x2 = addrect._P2.x; if (_P2.y > y2) y2 = _P2.y; if (addrect._P1.y > y2) y2 = addrect._P1.y; if (addrect._P2.y > y2) y2 = addrect._P2.y; return CRect(x1, y1, x2, y2); } /////////////////////////////////////////////////////////////////////////////// // class: CRect // function: set() // purpose: sets the coordinates of the line /////////////////////////////////////////////////////////////////////////////// void CRect::set( float x1, float y1, float x2, float y2 ) /////////////////////////////////////////////////////////////////////////////// { _P1.x = x1; _P1.y = y1; _P2.x = x2; _P2.y = y2; } /////////////////////////////////////////////////////////////////////////////// // class: CRect // function: list() // purpose: list coordinates on standard console /////////////////////////////////////////////////////////////////////////////// void CRect::list( void ) /////////////////////////////////////////////////////////////////////////////// { cout << "CRect :" << endl; _P1.list(); _P2.list(); cout << endl; } /////////////////////////////////////////////////////////////////////////////// // class: CRect // function: draw() // purpose: draw rectangle using OpenGL commands /////////////////////////////////////////////////////////////////////////////// void CRect::draw( void ) /////////////////////////////////////////////////////////////////////////////// { glRectf(_P1.x, _P1.y, _P2.x, _P2.y); } /////////////////////////////////////////////////////////////////////////////// // class: CCircle // function: constructor // purpose: constructs a object using two coordinate pairs /////////////////////////////////////////////////////////////////////////////// CCircle::CCircle( float x1, float y1, float radius ) /////////////////////////////////////////////////////////////////////////////// { set( x1, y1, radius ); ulCount++; } /////////////////////////////////////////////////////////////////////////////// // class: CCircle // function: constructor // purpose: constructs an object using two points /////////////////////////////////////////////////////////////////////////////// CCircle::CCircle( const CPoint& ptP1, float radius ) /////////////////////////////////////////////////////////////////////////////// { _P1 = ptP1; _Radius = radius; ulCount++; } /////////////////////////////////////////////////////////////////////////////// // class: CCircle // function: copy constructor // purpose: constructs an object using another object of the same class /////////////////////////////////////////////////////////////////////////////// CCircle::CCircle( const CCircle& source ) /////////////////////////////////////////////////////////////////////////////// { _P1 = source._P1; _Radius = source._Radius; ulCount++; } /////////////////////////////////////////////////////////////////////////////// // class: CCircle // function: operator+() // purpose: constructs a circle object by adding two circles /////////////////////////////////////////////////////////////////////////////// CCircle CCircle::operator+( const CCircle& addcircle ) /////////////////////////////////////////////////////////////////////////////// { float radius = 0; CPoint center = _P1; CPoint direction = addcircle._P1 - _P1; float delta = sqrtf( (float) (-_P1.x + addcircle._P1.x)*(-_P1.x + addcircle._P1.x) + (-_P1.y + addcircle._P1.y)*(-_P1.y + addcircle._P1.y) ); if (delta < min(_Radius, addcircle._Radius)) { // circles delta smaller than minimal radius, use existing circle if (_Radius < addcircle._Radius) { radius = addcircle._Radius; center = addcircle._P1; } else { radius = _Radius; center = _P1; } } else { // circles delta greater than minimum radius, calculate new circle radius = (delta + _Radius + addcircle._Radius) / 2.0F; direction.x = (direction.x / delta) * (radius - _Radius); direction.y = (direction.y / delta) * (radius - _Radius); center = _P1 + direction; } return CCircle(center, radius); } /////////////////////////////////////////////////////////////////////////////// // class: CCircle // function: set() // purpose: sets the coordinates of the line /////////////////////////////////////////////////////////////////////////////// void CCircle::set( float x1, float y1, float radius ) /////////////////////////////////////////////////////////////////////////////// { _P1.x = x1; _P1.y = y1; _Radius = radius; } /////////////////////////////////////////////////////////////////////////////// // class: CCircle // function: list() // purpose: list coordinates on standard console /////////////////////////////////////////////////////////////////////////////// void CCircle::list( void ) /////////////////////////////////////////////////////////////////////////////// { cout << "CCircle: " << endl; _P1.list(); cout << "Radius : " << _Radius << endl << endl; } /////////////////////////////////////////////////////////////////////////////// // class: CCircle // function: draw() // purpose: draw circle using OpenGL commands /////////////////////////////////////////////////////////////////////////////// void CCircle::draw( void ) /////////////////////////////////////////////////////////////////////////////// { glPushMatrix(); glTranslatef((GLfloat)_P1.x, (GLfloat)_P1.y, 0.0); gluDisk(gluNewQuadric(), _Radius, _Radius, 100, 1); glPopMatrix(); }
31.686499
79
0.354301
raeffu
cdbb439abbbb903703facacce7234ff385c54718
7,122
cpp
C++
Tuvok/IO/StkConverter.cpp
JensDerKrueger/ImageVis3D
699ab32132c899b7ea227bc87a9de80768ab879f
[ "MIT" ]
null
null
null
Tuvok/IO/StkConverter.cpp
JensDerKrueger/ImageVis3D
699ab32132c899b7ea227bc87a9de80768ab879f
[ "MIT" ]
null
null
null
Tuvok/IO/StkConverter.cpp
JensDerKrueger/ImageVis3D
699ab32132c899b7ea227bc87a9de80768ab879f
[ "MIT" ]
null
null
null
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2008 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** \file StkConverter.cpp \author Tom Fogal SCI Institute University of Utah */ #ifndef TUVOK_NO_IO # include "3rdParty/tiff/tiffio.h" #else struct TIFF; #endif #include "StkConverter.h" #include "../Basics/SysTools.h" #include "../Controller/Controller.h" using namespace tuvok; struct stk { uint32_t x,y,z; ///< dimensions uint16_t bpp; ///< bits per pixel uint16_t samples; ///< number of components per pixel }; static bool stk_read_metadata(TIFF*, struct stk&); static void stk_read_write_strips(TIFF*, LargeRAWFile&); StkConverter::StkConverter() { m_vConverterDesc = L"Stk Volume (Metamorph)"; #ifndef TUVOK_NO_IO m_vSupportedExt.push_back(L"STK"); #endif } bool StkConverter::ConvertToRAW(const std::wstring& strSourceFilename, const std::wstring& strTempDir, bool, uint64_t& iHeaderSkip, unsigned& iComponentSize, uint64_t& iComponentCount, bool& bConvertEndianess, bool& bSigned, bool& bIsFloat, UINT64VECTOR3& vVolumeSize, FLOATVECTOR3& vVolumeAspect, std::wstring& strTitle, std::wstring& strIntermediateFile, bool& bDeleteIntermediateFile) { #ifdef TUVOK_NO_IO T_ERROR("Tuvok was not built with IO support!"); return false; #else MESSAGE("Attempting to convert stk file: %s", SysTools::toNarrow(strSourceFilename).c_str()); TIFF *tif = TIFFOpen(SysTools::toNarrow(strSourceFilename).c_str(), "r"); if(tif == NULL) { T_ERROR("Could not open %s", SysTools::toNarrow(strSourceFilename).c_str()); return false; } struct stk metadata; if(!stk_read_metadata(tif, metadata)) { return false; } MESSAGE("%ux%ux%u %s", metadata.x, metadata.y, metadata.z, SysTools::toNarrow(m_vConverterDesc).c_str()); MESSAGE("%hu bits per component.", metadata.bpp); MESSAGE("%hu component%s.", metadata.samples, (metadata.samples == 1) ? "" : "s"); // copy that metadata into Tuvok variables. iComponentSize = metadata.bpp; iComponentCount = metadata.samples; vVolumeSize[0] = metadata.x; vVolumeSize[1] = metadata.y; vVolumeSize[2] = metadata.z; // IIRC libtiff handles all the endian issues for us. bConvertEndianess = false; // One might consider setting the values below explicitly (as opposed // to reading them from somewhere) to be bugs, but we're not quite // sure where to read these from. In any case, we don't have any // data for which these settings are invalid. bSigned = false; bIsFloat = false; vVolumeAspect[0] = 1; vVolumeAspect[1] = 1; vVolumeAspect[2] = 1; strTitle = L"STK Volume"; // Create an intermediate file to hold the data. iHeaderSkip = 0; strIntermediateFile = strTempDir + SysTools::GetFilename(strSourceFilename) + L".binary"; LargeRAWFile binary(strIntermediateFile); binary.Create(iComponentSize/8 * iComponentCount * vVolumeSize.volume()); if(!binary.IsOpen()) { T_ERROR("Could not create binary file %s", SysTools::toNarrow(strIntermediateFile).c_str()); TIFFClose(tif); return false; } // Populate the intermediate file. We just run through each strip and write // it out; technically, this is not kosher for Tuvok, since a single strip // might exceed INCORESIZE. That said, I've never seen a strip which is // larger than 8192 bytes. stk_read_write_strips(tif, binary); bDeleteIntermediateFile = true; binary.Close(); TIFFClose(tif); return true; #endif } // unimplemented! bool StkConverter::ConvertToNative(const std::wstring&, const std::wstring&, uint64_t, unsigned, uint64_t, bool, bool, UINT64VECTOR3, FLOATVECTOR3, bool, bool) { return false; } static bool stk_read_metadata(TIFF* tif, struct stk& metadata) { #ifdef TUVOK_NO_IO return false; #else // read the number of bits per component from the tiff tag. TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &metadata.bpp); TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &metadata.x); TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &metadata.y); // It's common for Stk files not to easily give the depth. if(TIFFGetField(tif, TIFFTAG_IMAGEDEPTH, &metadata.z) == 0) { // Depth not available as a tag; have to read it from the stk metadata. // In particular, we'll look up the UIC3Tag and count the number of values // in there. const ttag_t uic3tag = (ttag_t) 33630; // the tag is private. uint32_t count; void *data; if(TIFFGetField(tif, uic3tag, &count, &data) == 0) { return false; // UIC3 tag does not exist; this is not a stk. } // The data actually gives the per-slice spacing .. but we just ignore // that. All we care about is how many slices there are. metadata.z = count; } metadata.samples = 1; TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &metadata.samples); return true; #endif } static void stk_read_write_strips(TIFF* tif, LargeRAWFile& raw) { #ifndef TUVOK_NO_IO const tstrip_t n_strips = TIFFNumberOfStrips(tif); tdata_t buf = static_cast<tdata_t>(_TIFFmalloc(TIFFStripSize(tif))); for(tstrip_t s=0; s < n_strips; ++s) { /// @todo FIXME: don't assume the strip is raw; could be encoded. /// There's a `compression scheme' tag which probably details this. tsize_t n_bytes = TIFFReadRawStrip(tif, s, buf, static_cast<tsize_t>(-1)); raw.WriteRAW(static_cast<unsigned char*>(buf), n_bytes); } _TIFFfree(buf); #endif }
35.788945
97
0.663016
JensDerKrueger
cdbc315bd20ec9a67ce41e702f42392ef9439d6c
9,017
cpp
C++
source/EliteQuant/Common/Brokerage/brokerage.cpp
xubingyue/EliteQuant_Cpp
7f539c37d19e3208cca573f5a575dc4162b24880
[ "Apache-2.0" ]
null
null
null
source/EliteQuant/Common/Brokerage/brokerage.cpp
xubingyue/EliteQuant_Cpp
7f539c37d19e3208cca573f5a575dc4162b24880
[ "Apache-2.0" ]
null
null
null
source/EliteQuant/Common/Brokerage/brokerage.cpp
xubingyue/EliteQuant_Cpp
7f539c37d19e3208cca573f5a575dc4162b24880
[ "Apache-2.0" ]
1
2018-06-26T09:01:45.000Z
2018-06-26T09:01:45.000Z
#include <mutex> #include <Common/Brokerage/brokerage.h> #include <Common/Order/orderstatus.h> #include <Common/Order/ordermanager.h> #include <Common/Logger/logger.h> #include <Common/Security/portfoliomanager.h> using namespace std; namespace EliteQuant { extern std::atomic<bool> gShutdown; mutex brokerage::mtx_CANCELALL; brokerage::brokerage() : _bkstate(BK_DISCONNECTED) { timeout.tv_sec = 0; timeout.tv_usec = 500 * 1000; // message queue PUB factory if (CConfig::instance()._msgq == MSGQ::ZMQ) { //msgq_pair_ = std::make_unique<CMsgqZmq>(MSGQ_PROTOCOL::PAIR, CConfig::instance().BROKERAGE_PAIR_PORT); msgq_pair_ = std::make_unique<CMsgqNanomsg>(MSGQ_PROTOCOL::PAIR, CConfig::instance().BROKERAGE_PAIR_PORT); } else { msgq_pair_ = std::make_unique<CMsgqNanomsg>(MSGQ_PROTOCOL::PAIR, CConfig::instance().BROKERAGE_PAIR_PORT); } } brokerage::~brokerage() { } void brokerage::processBrokerageMessages() { if (!heatbeat(5)) { disconnectFromBrokerage(); return; } switch (_bkstate) { case BK_GETORDERID: requestNextValidOrderID(); break; case BK_ACCOUNT: requestBrokerageAccountInformation(CConfig::instance().account); break; case BK_ACCOUNTACK: break; case BK_READYTOORDER: monitorClientRequest(); break; case BK_PLACEORDER_ACK: break; case BK_CANCELORDER: cancelOrder(0); //TODO break; case BK_CANCELORDER_ACK: break; } } //Keep calling this function from brokerage::processMessages() void brokerage::monitorClientRequest() { string msg = msgq_pair_->recmsg(); if (msg.empty()) { return; } PRINT_TO_FILE_AND_CONSOLE("INFO:[%s,%d][%s]msg received: %s\n", __FILE__, __LINE__, __FUNCTION__, msg.c_str()); if (startwith(msg, CConfig::instance().close_all_msg)) { // close all positions lock_guard<mutex> g(oid_mtx); PRINT_TO_FILE_AND_CONSOLE("INFO:[%s,%d][%s]Close all positions.\n", __FILE__, __LINE__, __FUNCTION__); for (auto iterator = PortfolioManager::instance()._positions.begin(); iterator != PortfolioManager::instance()._positions.end(); iterator++) { std::shared_ptr<Order> o = make_shared<Order>(); o->fullSymbol = iterator->first; o->orderId = m_orderId; o->createTime = time(nullptr); o->orderSize = (-1) * iterator->second->_size; o->orderType = "MKT"; o->orderStatus = OrderStatus::OS_NewBorn; ++m_orderId; placeOrder(o); } } // endif close all else if (startwith(msg, CConfig::instance().new_order_msg)) { vector<string> v = stringsplit(msg, SERIALIZATION_SEPARATOR); if (v[1] == "MKT") { if (v.size() == 5) // o|mkt|IBM|-500|oid { PRINT_TO_FILE_AND_CONSOLE("INFO[%s,%d][%s]receive market order: %s\n", __FILE__, __LINE__, __FUNCTION__, msg.c_str()); std::shared_ptr<Order> o = make_shared<Order>(); o->fullSymbol = v[2]; o->orderId = stoi(v[4]); o->createTime = time(nullptr); o->orderSize = stoi(v[3]); o->orderType = "MKT"; o->orderStatus = OrderStatus::OS_NewBorn; //++m_orderId; placeOrder(o); } else { PRINT_TO_FILE("ERROR:[%s,%d][%s]market order bad format.\n", __FILE__, __LINE__, __FUNCTION__); } } else if (v[1] == "LMT") //o|lmt|IBM|-500|125.5|oid { if (v.size() == 6) { //lock_guard<mutex> g(oid_mtx); PRINT_TO_FILE_AND_CONSOLE("ERROR:[%s,%d][%s]recieved limit order: %s.\n", __FILE__, __LINE__, __FUNCTION__, msg.c_str()); std::shared_ptr<Order> o = make_shared<Order>(); o->fullSymbol = v[2]; o->orderId = stoi(v[5]); o->createTime = time(nullptr); o->orderSize = stoi(v[3]); o->orderType = "LMT"; o->limitPrice = stof(v[4]); o->orderStatus = OrderStatus::OS_NewBorn; //++m_orderId; placeOrder(o); } else { PRINT_TO_FILE("ERROR:[%s,%d][%s]limit order bad format.\n", __FILE__, __LINE__, __FUNCTION__); } } else { PRINT_TO_FILE("ERROR:[%s,%d][%s]unrecognized order type: %s %s\n", __FILE__, __LINE__, __FUNCTION__); } } // endif new order else if (startwith(msg, CConfig::instance().cancel_order_msg)) { // c|oid vector<string> v = stringsplit(msg, SERIALIZATION_SEPARATOR); if (v.size() == 2) { cancelOrder(atoi(v[1].c_str())); } else { PRINT_TO_FILE("ERROR:[%s,%d][%s]cancel order bad format.\n", __FILE__, __LINE__, __FUNCTION__); } } // endif cancel order // TODO: should this go to data thread? else if (startwith(msg, CConfig::instance().hist_msg)) { vector<string> v = stringsplit(msg, SERIALIZATION_SEPARATOR); if (v.size() == 6) { //shared_ptr<IBBrokerage> ib = std::static_pointer_cast<IBBrokerage>(poms); //ib->requestHistoricalData(v[1], v[2], v[3], v[4], v[5]); } else { PRINT_TO_FILE("ERROR:[%s,%d][%s]historical data request bad format.\n", __FILE__, __LINE__, __FUNCTION__); } } // endif historical data request else if (startwith(msg, CConfig::instance().test_msg)) { static int count = 0; vector<string> v = stringsplit(msg, SERIALIZATION_SEPARATOR); PRINT_TO_FILE("INFO:[%s,%d][%s]TEST :%d,%s\n", __FILE__, __LINE__, __FUNCTION__, ++count, msg.c_str()); if (v.size()>1) { string reverse(v[1].rbegin(), v[1].rend()); msgq_pair_->sendmsg(CConfig::instance().test_msg + SERIALIZATION_SEPARATOR + reverse); } } } bool brokerage::isAllOrdersCancelled() { return OrderManager::instance().retrieveNonFilledOrderPtr().empty(); } //******************************** Message serialization ***********************// void brokerage::sendOrderCreated(long oid) { string msg = CConfig::instance().order_status_msg + SERIALIZATION_SEPARATOR + std::to_string(int(OrderStatus::OS_NewBorn)) + SERIALIZATION_SEPARATOR + std::to_string(oid); msgq_pair_->sendmsg(msg); } void brokerage::sendOrderSubmitted(long oid) { string msg = CConfig::instance().order_status_msg + SERIALIZATION_SEPARATOR + std::to_string(int(OrderStatus::OS_Submitted)) + SERIALIZATION_SEPARATOR + std::to_string(oid); msgq_pair_->sendmsg(msg); } void brokerage::sendOrderAcknowledged(long oid) { string msg = CConfig::instance().order_status_msg + SERIALIZATION_SEPARATOR + std::to_string(int(OrderStatus::OS_Acknowledged)) + SERIALIZATION_SEPARATOR + std::to_string(oid); msgq_pair_->sendmsg(msg); } void brokerage::sendOrderFilled(Fill& t) { string msg = CConfig::instance().order_status_msg + SERIALIZATION_SEPARATOR + std::to_string(int(OrderStatus::OS_Filled)) + SERIALIZATION_SEPARATOR + t.serialize(); msgq_pair_->sendmsg(msg); } void brokerage::sendOrderCancelled(long oid) { string msg = CConfig::instance().order_status_msg + SERIALIZATION_SEPARATOR + std::to_string(int(OrderStatus::OS_Canceled)) + SERIALIZATION_SEPARATOR + std::to_string(oid); msgq_pair_->sendmsg(msg); } void brokerage::sendOrderStatus(long oid) { std::shared_ptr<Order> o = nullptr; /*do { o = OrderManager::instance().retrieveOrder(oid); msleep(50); } while (o == nullptr);*/ o = OrderManager::instance().retrieveOrder(oid); if (o != nullptr) { string msg = CConfig::instance().order_status_msg + SERIALIZATION_SEPARATOR + std::to_string(oid) + SERIALIZATION_SEPARATOR + std::to_string(int(o ? o->orderStatus : -1)); msgq_pair_->sendmsg(msg); } else { sendGeneralMessage("order status request with invalid order id = " + std::to_string(oid)); } } void brokerage::sendOpenPositionMessage(string symbol, int position, double averageCost, double unrealisedPNL, double realisedPNL) { //char str[512]; //sprintf(str, "%d,%.4f,%.4f,%.4f", position, averageCost, unrealisedPNL, realisedPNL); //push(string(str)); string msg = CConfig::instance().position_msg + SERIALIZATION_SEPARATOR + symbol + SERIALIZATION_SEPARATOR + std::to_string(position) + SERIALIZATION_SEPARATOR + std::to_string(averageCost) + SERIALIZATION_SEPARATOR + std::to_string(unrealisedPNL) + SERIALIZATION_SEPARATOR + std::to_string(realisedPNL); msgq_pair_->sendmsg(msg); } void brokerage::sendHistoricalBarMessage(string symbol, string time, double open, double high, double low, double close, int volume, int barcount, double wap) { string msg = CConfig::instance().hist_msg + SERIALIZATION_SEPARATOR + symbol + SERIALIZATION_SEPARATOR + time + SERIALIZATION_SEPARATOR + std::to_string(open) + SERIALIZATION_SEPARATOR + std::to_string(high) + SERIALIZATION_SEPARATOR + std::to_string(low) + SERIALIZATION_SEPARATOR + std::to_string(close) + SERIALIZATION_SEPARATOR + std::to_string(volume) + SERIALIZATION_SEPARATOR + std::to_string(barcount) + SERIALIZATION_SEPARATOR + std::to_string(wap); msgq_pair_->sendmsg(msg); } // comma separated general msg void brokerage::sendGeneralMessage(std::string gm) { string msg = CConfig::instance().general_msg + SERIALIZATION_SEPARATOR + gm; msgq_pair_->sendmsg(msg); } //************************* End of message serialization ***********************// }
32.67029
159
0.678053
xubingyue
cdbd521d24966c84c7653910de392753f21ad316
301
cpp
C++
list9_9/main.cpp
rimever/SuraSuraCPlus
acbc6e1d0d0bb9bf07e28ab02c30ac021b1f6899
[ "MIT" ]
null
null
null
list9_9/main.cpp
rimever/SuraSuraCPlus
acbc6e1d0d0bb9bf07e28ab02c30ac021b1f6899
[ "MIT" ]
null
null
null
list9_9/main.cpp
rimever/SuraSuraCPlus
acbc6e1d0d0bb9bf07e28ab02c30ac021b1f6899
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> using namespace std; int main() { string s; ifstream fin("myFile.txt"); if (!fin.is_open()) { cout << "ファイルをオープンできません!"; return 1; } while (getline(fin, s)) { cout << s << endl; } fin.close(); return 0; }
16.722222
34
0.521595
rimever
cdbeb95aaab15164aa4bfea1701a86cd6bf4de32
4,674
cpp
C++
2018/2018050703.cpp
maku693/daily-snippets
53e3a516eeb293b3c11055db1b87d54284e6ac52
[ "MIT" ]
null
null
null
2018/2018050703.cpp
maku693/daily-snippets
53e3a516eeb293b3c11055db1b87d54284e6ac52
[ "MIT" ]
null
null
null
2018/2018050703.cpp
maku693/daily-snippets
53e3a516eeb293b3c11055db1b87d54284e6ac52
[ "MIT" ]
null
null
null
#include <algorithm> #include <array> #include <iostream> #include <string> #include <utility> #include <variant> #include <vector> enum class token_type { paren_open, paren_close, period, literal_number, symbol, }; std::ostream &operator<<(std::ostream &os, const token_type &type) noexcept { switch (type) { case token_type::paren_open: os << "paren_open"; break; case token_type::paren_close: os << "paren_close"; break; case token_type::period: os << "period"; break; case token_type::literal_number: os << "literal_number"; break; case token_type::symbol: os << "symbol"; break; default: break; } return os; } struct token { token_type type; std::string str; }; std::ostream &operator<<(std::ostream &os, const token &token) noexcept { return os << "type: " << token.type << ",\tstr: " << token.str; } class tokenizer { public: tokenizer() = delete; explicit tokenizer(std::string &&) noexcept; std::vector<token> tokenize() noexcept; private: const std::string src; std::string::const_iterator head; std::string buf; std::vector<token> tokens; bool is_whitespace() noexcept; bool is_paren_open() noexcept; bool is_paren_close() noexcept; bool is_period() noexcept; bool is_digit() noexcept; bool is_symbol() noexcept; void whitespace() noexcept; void paren_open() noexcept; void paren_close() noexcept; void period() noexcept; void literal_number() noexcept; void symbol() noexcept; char peek() noexcept; void consume() noexcept; void flush() noexcept; }; tokenizer::tokenizer(std::string &&src_) noexcept : src(src_), head(src.cbegin()) {} std::vector<token> tokenizer::tokenize() noexcept { while (head < src.cend()) { whitespace(); paren_open(); paren_close(); period(); literal_number(); symbol(); } return tokens; } bool tokenizer::is_whitespace() noexcept { std::array<char, 10> candidates{' ', '\f', '\n', '\r', '\t', '\v'}; const auto result = std::find(candidates.cbegin(), candidates.cend(), peek()); return result != candidates.cend(); } bool tokenizer::is_paren_open() noexcept { return peek() == '('; } bool tokenizer::is_paren_close() noexcept { return peek() == ')'; } bool tokenizer::is_period() noexcept { return peek() == '.'; } bool tokenizer::is_digit() noexcept { std::array<char, 10> candidates{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; const auto result = std::find(candidates.cbegin(), candidates.cend(), peek()); return result != candidates.cend(); } bool tokenizer::is_symbol() noexcept { return !is_whitespace() && !is_paren_open() && !is_paren_close() && !is_digit(); } void tokenizer::whitespace() noexcept { while (is_whitespace()) { consume(); } if (!buf.empty()) { flush(); } } void tokenizer::paren_open() noexcept { if (is_paren_open()) { consume(); tokens.emplace_back(token{token_type::paren_open, buf}); flush(); } } void tokenizer::paren_close() noexcept { if (is_paren_close()) { consume(); tokens.emplace_back(token{token_type::paren_close, buf}); flush(); } } void tokenizer::period() noexcept { if (is_period()) { consume(); tokens.emplace_back(token{token_type::period, buf}); flush(); } } void tokenizer::literal_number() noexcept { while (is_digit()) { consume(); } if (!buf.empty()) { tokens.emplace_back(token{token_type::literal_number, buf}); flush(); } } void tokenizer::symbol() noexcept { while (is_symbol()) { consume(); } if (!buf.empty()) { tokens.emplace_back(token{token_type::symbol, buf}); flush(); } } char tokenizer::peek() noexcept { return *head; } void tokenizer::consume() noexcept { buf.push_back(peek()); head++; } void tokenizer::flush() noexcept { buf.clear(); } std::vector<token> tokenize(std::string &&str) noexcept { tokenizer tokenizer(std::forward<std::string>(str)); return tokenizer.tokenize(); } // class list; // class atom; // using expression = std::variant<list, atom>; // class parser { // public: // parser() = delete; // explicit parser(std::vector<token> &&) noexcept; // private: // std::vector<token>::const_iterator head; // }; // std::vector<expression> parse(std::string &&str) noexcept { return {}; } int main(int argc, char *argv[]) { if (argc < 2) { std::cerr << "error: no program provided\n"; return 1; } const auto tokenize_result = tokenize(argv[1]); std::cerr << "tokens: " << std::endl; for (const auto &token : tokenize_result) { std::cerr << token << std::endl; } }
21.638889
80
0.633077
maku693
cdbf03a070fec594a7ddff44f254cc624bf0aa34
3,473
cpp
C++
@library/@openxlsx/sources/XLAbstractXMLFile.cpp
killvxk/OpenXLSX
416896fa4881020e2cf6927c64d7d554dd826615
[ "BSD-3-Clause-Clear" ]
2
2019-02-14T00:30:32.000Z
2019-05-01T11:07:23.000Z
@library/@openxlsx/sources/XLAbstractXMLFile.cpp
killvxk/OpenXLSX
416896fa4881020e2cf6927c64d7d554dd826615
[ "BSD-3-Clause-Clear" ]
null
null
null
@library/@openxlsx/sources/XLAbstractXMLFile.cpp
killvxk/OpenXLSX
416896fa4881020e2cf6927c64d7d554dd826615
[ "BSD-3-Clause-Clear" ]
1
2019-02-13T03:08:48.000Z
2019-02-13T03:08:48.000Z
// // Created by Troldal on 05/08/16. // #include "XLDocument.h" #include <sstream> #include <pugixml.hpp> using namespace std; using namespace OpenXLSX; /** * @details The constructor creates a new object with the parent XLDocument and the file path as input, with * an optional input being a std::string with the XML data. If the XML data is provided by a string, any file with * the same path in the .zip file will be overwritten upon saving of the document. If no xmlData is provided, * the data will be read from the .zip file, using the given path. */ XLAbstractXMLFile::XLAbstractXMLFile(XLDocument &parent, const std::string &filePath, const std::string &xmlData) : m_xmlDocument(make_unique<XMLDocument>()), m_parentDocument(parent), m_path(filePath), m_childXmlDocuments(), m_isModified(false) { if (xmlData.empty()) SetXmlData(m_parentDocument.GetXMLFile(m_path)); else SetXmlData(xmlData); } XLAbstractXMLFile::~XLAbstractXMLFile() { } /** * @details This method sets the XML data with a std::string as input. The underlying XMLDocument reads the data. */ void XLAbstractXMLFile::SetXmlData(const std::string &xmlData) { m_xmlDocument->load_string(xmlData.c_str()); } /** * @details This method retrieves the underlying XML data as a std::string. */ std::string XLAbstractXMLFile::GetXmlData() const { ostringstream ostr; m_xmlDocument->print(ostr); return ostr.str(); } /** * @details The CommitXMLData method calls the AddOrReplaceXMLFile method for the current object and all child objects. * This, in turn, will add or replace the XML data files in the zipped .xlsx package. */ void XLAbstractXMLFile::CommitXMLData() { m_parentDocument.AddOrReplaceXMLFile(m_path, GetXmlData()); for (auto file : m_childXmlDocuments) { if(file.second) file.second->CommitXMLData(); } } /** * @details The DeleteXMLData method calls the DeleteXMLFile method for the current object and all child objects. * This, in turn, delete the XML data files in the zipped .xlsx package. */ void XLAbstractXMLFile::DeleteXMLData() { m_parentDocument.DeleteXMLFile(m_path); for (auto file : m_childXmlDocuments) { if(file.second) file.second->DeleteXMLData(); } } /** * @details This method returns the path in the .zip file of the XML file as a std::string. */ const string &XLAbstractXMLFile::FilePath() const { return m_path; } /** * @details This method is mainly meant for debugging, by enabling printing of the xml file to cout. */ void XLAbstractXMLFile::Print() const { XmlDocument()->print(cout); } /** * @details This method returns a pointer to the underlying XMLDocument resource. */ XMLDocument * XLAbstractXMLFile::XmlDocument() { return const_cast<XMLDocument *>(static_cast<const XLAbstractXMLFile *>(this)->XmlDocument()); } /** * @details This method returns a pointer to the underlying XMLDocument resource as const. */ const XMLDocument *XLAbstractXMLFile::XmlDocument() const { return m_xmlDocument.get(); } /** * @details Set the XLWorksheet object to 'modified'. This is done by setting the m_is Modified member to true. */ void XLAbstractXMLFile::SetModified() { m_isModified = true; } /** * @details Returns the value of the m_isModified member variable. */ bool XLAbstractXMLFile::IsModified() { return m_isModified; }
27.784
119
0.706882
killvxk
cdc02ba4eb63cdf0f9ef1210a7169eb0f98b89e5
1,950
hpp
C++
EasySDL-objects.hpp
dido11/EasySDL
dda4e325fb1735ae03f13dd75d4a2c53fba36a97
[ "MIT" ]
1
2021-03-29T05:47:18.000Z
2021-03-29T05:47:18.000Z
EasySDL-objects.hpp
dido11/EasySDL
dda4e325fb1735ae03f13dd75d4a2c53fba36a97
[ "MIT" ]
null
null
null
EasySDL-objects.hpp
dido11/EasySDL
dda4e325fb1735ae03f13dd75d4a2c53fba36a97
[ "MIT" ]
null
null
null
#ifndef EASYSDL_OBJECTS_H #define EASYSDL_OBJECTS_H #include "EasySDL.hpp" namespace objects { struct Area { int h; int w; int x=0, y=0; map<string, double> values; SDL_Surface * area=NULL; void areaPlace(SDL_Surface *surf, bool autoDestroySurface, int x, int y, int x0=x_left, int y0=y_top, double angle=0, double scale=1);; void place(); void place(int x0, int y0, double angle=0, double scale=1); Area(); void init(int _w, int _h); Area(int _h, int _w); ~Area(); void ignoreColor(int r, int g, int b); }; struct BasicArea : Area { bool isFocused(int _x, int _y); BasicArea(int _h, int _w); BasicArea(); }; struct Button : Area { bool over=false; string txt=""; void (*action)(int, int)=NULL; // x, y void (*drawContent)(Button*)=NULL; bool isFocused(int _x, int _y); void build(); void press(int screenX, int screenY); }; /** This is a structure for a button. It use a "customPart" struct made by you the "customPart" struct must contain : - bool isInside(int x, int y) where (0, 0) is the top-left corner of the window/container this func must tell if the x and y coords are inside the button - void show() this func will be used by the container to blit it. It must blit something on "dest" his x0 will be in x, and his y0 will be in y. - void clic(int x, int y) where (0, 0) is the top-left corner of the window/container **/ /*template<class customPart> struct Button : customPart { bool over=false; int x, y; int h, w; int x0, y0; SDL_Surface *dest; //bool isInside(int screenX, int screenY); //void show(); //void clic(int screenX, int screenY); };*/ struct Scrollable : Area { BasicArea content; int deltaY=0; int defilementSpeed=5; bool isFocused(int _x, int _y); void initContent(int _h); void shiftDown(); void shiftUp(); void build(); Scrollable(); }; } #endif // EASYSDL_OBJECTS_H
21.910112
137
0.65641
dido11
02cb3aad25d526cb47685b3fbb34bb04b32c4f37
579
cpp
C++
Assignment 4/Assingnment 4/Assingnment 4/NegateBlue.cpp
justin-harper/cs122
83949bc097cf052ffe6b8bd82002377af4d9cede
[ "MIT" ]
null
null
null
Assignment 4/Assingnment 4/Assingnment 4/NegateBlue.cpp
justin-harper/cs122
83949bc097cf052ffe6b8bd82002377af4d9cede
[ "MIT" ]
null
null
null
Assignment 4/Assingnment 4/Assingnment 4/NegateBlue.cpp
justin-harper/cs122
83949bc097cf052ffe6b8bd82002377af4d9cede
[ "MIT" ]
null
null
null
/* Assignment: 4 Description: Paycheck Calculator Author: Justin Harper WSU ID: 10696738 Completion Time: 4hrs In completing this program, I received help from the following people: myself version 1.0 (major relese) I am happy with this version! */ #include "NegateBlue.h" using namespace std; //image processor to negate blue void NegateBlue::processImage(vector<Point>& points) { //pretty stright forward just set the blue value of each pixle to 255 - blue value for (int i = 0; i < points.size(); i++) { points[i].setBlue(255 - points[i].getBlue()); } return; }
19.965517
83
0.727116
justin-harper
02cd6ab0edf2ca988511751c0d0773d551febbbc
340
cpp
C++
books/tech/cpp/std-11/r_lischner-exploring_cpp_11-2_ed/ch_69-overloaded_functions_and_operators/02-overloading_named_with_a_using_declaration/main.cpp
ordinary-developer/education
1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58
[ "MIT" ]
1
2017-05-04T08:23:46.000Z
2017-05-04T08:23:46.000Z
books/techno/cpp/___pre-intermediate/exploring_cpp_11_2_ed_r_lischner/code/exploration_69-OVERLOADED_FUNCTIONS_AND_OPERATORS/02-overloading_named_with_a_using_declaration/main.cpp
ordinary-developer/lin_education
13d65b20cdbc3e5467b2383e5c09c73bbcdcb227
[ "MIT" ]
null
null
null
books/techno/cpp/___pre-intermediate/exploring_cpp_11_2_ed_r_lischner/code/exploration_69-OVERLOADED_FUNCTIONS_AND_OPERATORS/02-overloading_named_with_a_using_declaration/main.cpp
ordinary-developer/lin_education
13d65b20cdbc3e5467b2383e5c09c73bbcdcb227
[ "MIT" ]
null
null
null
#include <iostream> class base { public: void print(int x) { std::cout << "int: " << x << '\n'; } }; class derived : public base { public: void print(double x) { std::cout << "double: " << x << '\n'; } using base::print; }; int main() { derived d{}; d.print(3); d.print(3.0); return 0; }
16.190476
70
0.485294
ordinary-developer
02ce4870a09d197ce3e39c6df8148ffd464344a3
92,211
cpp
C++
dev/Code/CryEngine/CrySoundSystem/implementations/CryAudioImplWwise/AudioSystemImpl_wwise.cpp
raghnarx/lumberyard
1c52b941dcb7d94341fcf21275fe71ff67173ada
[ "AML" ]
8
2019-10-07T16:33:47.000Z
2020-12-07T03:59:58.000Z
dev/Code/CryEngine/CrySoundSystem/implementations/CryAudioImplWwise/AudioSystemImpl_wwise.cpp
29e7e280-0d1c-4bba-98fe-f7cd3ca7500a/lumberyard
1c52b941dcb7d94341fcf21275fe71ff67173ada
[ "AML" ]
null
null
null
dev/Code/CryEngine/CrySoundSystem/implementations/CryAudioImplWwise/AudioSystemImpl_wwise.cpp
29e7e280-0d1c-4bba-98fe-f7cd3ca7500a/lumberyard
1c52b941dcb7d94341fcf21275fe71ff67173ada
[ "AML" ]
4
2019-08-05T07:25:46.000Z
2020-12-07T05:12:55.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include "StdAfx.h" #include "AudioSystemImpl_wwise.h" #include <AzCore/std/containers/set.h> #include <IAudioSystem.h> #include <AudioSourceManager.h> #include <AudioSystemImplCVars.h> #include <Common_wwise.h> #include <FileIOHandler_wwise.h> #include <AK/SoundEngine/Common/AkSoundEngine.h> // Sound engine #include <AK/MusicEngine/Common/AkMusicEngine.h> // Music Engine #include <AK/SoundEngine/Common/AkMemoryMgr.h> // Memory Manager #include <AK/SoundEngine/Common/AkModule.h> // Default memory and stream managers #include <PluginRegistration_wwise.h> // Registration of default set of plugins, customize this header to your needs. #if defined(AZ_RESTRICTED_PLATFORM) #undef AZ_RESTRICTED_SECTION #define AUDIOSYSTEMIMPL_WWISE_CPP_SECTION_1 1 #define AUDIOSYSTEMIMPL_WWISE_CPP_SECTION_2 2 #define AUDIOSYSTEMIMPL_WWISE_CPP_SECTION_3 3 #define AUDIOSYSTEMIMPL_WWISE_CPP_SECTION_4 4 #endif #if !defined(WWISE_FOR_RELEASE) #include <AK/Comm/AkCommunication.h> // Communication between Wwise and the game (excluded in release build) #include <AK/Tools/Common/AkMonitorError.h> #include <AK/Tools/Common/AkPlatformFuncs.h> #endif // WWISE_FOR_RELEASE #if defined(AK_MAX_AUX_PER_OBJ) #define LY_MAX_AUX_PER_OBJ AK_MAX_AUX_PER_OBJ #else #define LY_MAX_AUX_PER_OBJ (4) #endif ///////////////////////////////////////////////////////////////////////////////// // MEMORY HOOKS SETUP // // ##### IMPORTANT ##### // // These custom alloc/free functions are declared as "extern" in AkMemoryMgr.h // and MUST be defined by the game developer. ///////////////////////////////////////////////////////////////////////////////// namespace AK { void* AllocHook(size_t in_size) { return azmalloc(in_size, AUDIO_MEMORY_ALIGNMENT, Audio::AudioImplAllocator, "AudioWwise"); } void FreeHook(void* in_ptr) { azfree(in_ptr, Audio::AudioImplAllocator); } void* VirtualAllocHook(void* in_pMemAddress, size_t in_size, DWORD in_dwAllocationType, DWORD in_dwProtect) { //return VirtualAlloc(in_pMemAddress, in_size, in_dwAllocationType, in_dwProtect); return azmalloc(in_size, AUDIO_MEMORY_ALIGNMENT, Audio::AudioImplAllocator, "AudioWwise"); } void VirtualFreeHook(void* in_pMemAddress, size_t in_size, DWORD in_dwFreeType) { //VirtualFree(in_pMemAddress, in_size, in_dwFreeType); azfree(in_pMemAddress, Audio::AudioImplAllocator); } #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION AUDIOSYSTEMIMPL_WWISE_CPP_SECTION_1 #if defined(AZ_PLATFORM_XENIA) #include "Xenia/AudioSystemImpl_wwise_cpp_xenia.inl" #elif defined(AZ_PLATFORM_PROVO) #include "Provo/AudioSystemImpl_wwise_cpp_provo.inl" #endif #endif } namespace Audio { const char* const CAudioSystemImpl_wwise::sWwiseImplSubPath = "wwise/"; const char* const CAudioSystemImpl_wwise::sWwiseEventTag = "WwiseEvent"; const char* const CAudioSystemImpl_wwise::sWwiseRtpcTag = "WwiseRtpc"; const char* const CAudioSystemImpl_wwise::sWwiseSwitchTag = "WwiseSwitch"; const char* const CAudioSystemImpl_wwise::sWwiseStateTag = "WwiseState"; const char* const CAudioSystemImpl_wwise::sWwiseRtpcSwitchTag = "WwiseRtpc"; const char* const CAudioSystemImpl_wwise::sWwiseFileTag = "WwiseFile"; const char* const CAudioSystemImpl_wwise::sWwiseAuxBusTag = "WwiseAuxBus"; const char* const CAudioSystemImpl_wwise::sWwiseValueTag = "WwiseValue"; const char* const CAudioSystemImpl_wwise::sWwiseNameAttribute = "wwise_name"; const char* const CAudioSystemImpl_wwise::sWwiseValueAttribute = "wwise_value"; const char* const CAudioSystemImpl_wwise::sWwiseMutiplierAttribute = "atl_mult"; const char* const CAudioSystemImpl_wwise::sWwiseShiftAttribute = "atl_shift"; const char* const CAudioSystemImpl_wwise::sWwiseLocalisedAttribute = "wwise_localised"; const char* const CAudioSystemImpl_wwise::sWwiseGlobalAudioObjectName = "LY-GlobalAudioObject"; const float CAudioSystemImpl_wwise::sObstructionOcclusionMin = 0.0f; const float CAudioSystemImpl_wwise::sObstructionOcclusionMax = 1.0f; /////////////////////////////////////////////////////////////////////////////////////////////////// // AK callbacks void WwiseEventCallback(AkCallbackType eType, AkCallbackInfo* pCallbackInfo) { if (eType == AK_EndOfEvent) { auto const pEventData = static_cast<SATLEventData_wwise*>(pCallbackInfo->pCookie); if (pEventData) { SAudioRequest oRequest; SAudioCallbackManagerRequestData<eACMRT_REPORT_FINISHED_EVENT> oRequestData(pEventData->nATLID, true); oRequest.nFlags = eARF_THREAD_SAFE_PUSH; oRequest.pData = &oRequestData; AudioSystemThreadSafeRequestBus::Broadcast(&AudioSystemThreadSafeRequestBus::Events::PushRequestThreadSafe, oRequest); if (pEventData->nSourceId != INVALID_AUDIO_SOURCE_ID) { AkPlayingID playingId = AudioSourceManager::Get().FindPlayingSource(pEventData->nSourceId); AudioSourceManager::Get().DeactivateSource(playingId); } } } else if (eType == AK_Duration) { auto durationInfo = static_cast<AkDurationCallbackInfo*>(pCallbackInfo); auto const eventData = static_cast<SATLEventData_wwise*>(pCallbackInfo->pCookie); if (durationInfo && eventData) { AudioTriggerNotificationBus::QueueEvent(eventData->m_triggerId, &AudioTriggerNotificationBus::Events::ReportDurationInfo, eventData->nATLID, durationInfo->fDuration, durationInfo->fEstimatedDuration); } } } static bool audioDeviceInitializationEvent = false; void AudioDeviceCallback( AK::IAkGlobalPluginContext* context, AkUniqueID audioDeviceSharesetId, AkUInt32 deviceId, AK::AkAudioDeviceEvent deviceEvent, AKRESULT inAkResult ) { if (deviceEvent == AK::AkAudioDeviceEvent_Initialization) { audioDeviceInitializationEvent = true; } } /////////////////////////////////////////////////////////////////////////////////////////////////// void PrepareEventCallback( AkUniqueID nAkEventID, const void* pBankPtr, AKRESULT eLoadResult, AkMemPoolId nMenmPoolID, void* pCookie) { auto const pEventData = static_cast<SATLEventData_wwise*>(pCookie); if (pEventData) { pEventData->nAKID = nAkEventID; SAudioRequest oRequest; SAudioCallbackManagerRequestData<eACMRT_REPORT_FINISHED_EVENT> oRequestData(pEventData->nATLID, eLoadResult == AK_Success); oRequest.nFlags = eARF_THREAD_SAFE_PUSH; oRequest.pData = &oRequestData; AudioSystemThreadSafeRequestBus::Broadcast(&AudioSystemThreadSafeRequestBus::Events::PushRequestThreadSafe, oRequest); } } /////////////////////////////////////////////////////////////////////////////////////////////////// #if !defined(WWISE_FOR_RELEASE) static void ErrorMonitorCallback( AK::Monitor::ErrorCode in_eErrorCode, ///< Error code number value const AkOSChar* in_pszError, ///< Message or error string to be displayed AK::Monitor::ErrorLevel in_eErrorLevel, ///< Specifies whether it should be displayed as a message or an error AkPlayingID in_playingID, ///< Related Playing ID if applicable, AK_INVALID_PLAYING_ID otherwise AkGameObjectID in_gameObjID ///< Related Game Object ID if applicable, AK_INVALID_GAME_OBJECT otherwise ) { char* sTemp = nullptr; CONVERT_OSCHAR_TO_CHAR(in_pszError, sTemp); g_audioImplLogger_wwise.Log( ((in_eErrorLevel & AK::Monitor::ErrorLevel_Error) != 0) ? eALT_ERROR : eALT_COMMENT, "<Wwise> %s ErrorCode: %d PlayingID: %u GameObjID: %" PRISIZE_T, sTemp, in_eErrorCode, in_playingID, in_gameObjID); } #endif // WWISE_FOR_RELEASE static int GetAssetType(const SATLSourceData* sourceData) { if (!sourceData) { return eAAT_NONE; } return sourceData->m_sourceInfo.m_codecType == eACT_STREAM_PCM ? eAAT_STREAM : eAAT_SOURCE; } static int GetAkCodecID(EAudioCodecType codecType) { switch (codecType) { case eACT_AAC: return AKCODECID_AAC; case eACT_ADPCM: return AKCODECID_ADPCM; case eACT_PCM: return AKCODECID_PCM; case eACT_VORBIS: return AKCODECID_VORBIS; case eACT_XMA: return AKCODECID_XMA; case eACT_XWMA: return AKCODECID_XWMA; case eACT_STREAM_PCM: default: AZ_Assert(codecType, "Codec not supported"); return AKCODECID_VORBIS; } } /////////////////////////////////////////////////////////////////////////////////////////////////// CAudioSystemImpl_wwise::CAudioSystemImpl_wwise() : m_globalGameObjectID(static_cast<AkGameObjectID>(GLOBAL_AUDIO_OBJECT_ID)) , m_defaultListenerGameObjectID(AK_INVALID_GAME_OBJECT) , m_nInitBankID(AK_INVALID_BANK_ID) #if !defined(WWISE_FOR_RELEASE) , m_bCommSystemInitialized(false) #endif // !WWISE_FOR_RELEASE { m_sRegularSoundBankFolder = WWISE_IMPL_BANK_FULL_PATH; m_sLocalizedSoundBankFolder = m_sRegularSoundBankFolder; #if defined(INCLUDE_WWISE_IMPL_PRODUCTION_CODE) m_fullImplString = AZStd::string::format("%s (%s)", WWISE_IMPL_VERSION_STRING, m_sRegularSoundBankFolder.c_str()); #endif // INCLUDE_WWISE_IMPL_PRODUCTION_CODE AudioSystemImplementationRequestBus::Handler::BusConnect(); AudioSystemImplementationNotificationBus::Handler::BusConnect(); } /////////////////////////////////////////////////////////////////////////////////////////////////// CAudioSystemImpl_wwise::~CAudioSystemImpl_wwise() { AudioSystemImplementationRequestBus::Handler::BusDisconnect(); AudioSystemImplementationNotificationBus::Handler::BusDisconnect(); } /////////////////////////////////////////////////////////////////////////////////////////////////// // AZ::Component /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioSystemImpl_wwise::Init() { } /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioSystemImpl_wwise::Activate() { } /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioSystemImpl_wwise::Deactivate() { } /////////////////////////////////////////////////////////////////////////////////////////////////// // AudioSystemImplementationNotificationBus /////////////////////////////////////////////////////////////////////////////////////////////////// #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION AUDIOSYSTEMIMPL_WWISE_CPP_SECTION_4 #if defined(AZ_PLATFORM_XENIA) #include "Xenia/AudioSystemImpl_wwise_cpp_xenia.inl" #elif defined(AZ_PLATFORM_PROVO) #include "Provo/AudioSystemImpl_wwise_cpp_provo.inl" #endif #elif !defined(INCLUDE_WWISE_IMPL_PRODUCTION_CODE) #define AUDIOSYSTEMIMPL_WWISE_CPP_TRAIT_USE_SUSPEND #elif defined(AZ_PLATFORM_ANDROID) || defined(AZ_PLATFORM_APPLE_IOS) #define AUDIOSYSTEMIMPL_WWISE_CPP_TRAIT_USE_SUSPEND #endif /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioSystemImpl_wwise::OnAudioSystemLoseFocus() { #if defined(AUDIOSYSTEMIMPL_WWISE_CPP_TRAIT_USE_SUSPEND) AKRESULT akResult = AK::SoundEngine::Suspend(); if (!IS_WWISE_OK(akResult)) { g_audioImplLogger_wwise.Log(eALT_ERROR, "Wwise failed to Suspend, AKRESULT = %d\n", akResult); } #endif // AUDIOSYSTEMIMPL_WWISE_CPP_TRAIT_USE_SUSPEND } /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioSystemImpl_wwise::OnAudioSystemGetFocus() { #if defined(AUDIOSYSTEMIMPL_WWISE_CPP_TRAIT_USE_SUSPEND) AKRESULT akResult = AK::SoundEngine::WakeupFromSuspend(); if (!IS_WWISE_OK(akResult)) { g_audioImplLogger_wwise.Log(eALT_ERROR, "Wwise failed to WakeupFromSuspend, AKRESULT = %d\n", akResult); } #endif // AUDIOSYSTEMIMPL_WWISE_CPP_TRAIT_USE_SUSPEND } /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioSystemImpl_wwise::OnAudioSystemMuteAll() { // With Wwise we drive this via events. } /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioSystemImpl_wwise::OnAudioSystemUnmuteAll() { // With Wwise we drive this via events. } /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioSystemImpl_wwise::OnAudioSystemRefresh() { AKRESULT eResult = AK_Fail; if (m_nInitBankID != AK_INVALID_BANK_ID) { eResult = AK::SoundEngine::UnloadBank(m_nInitBankID, nullptr); if (!IS_WWISE_OK(eResult)) { g_audioImplLogger_wwise.Log(eALT_ERROR, "Wwise failed to unload Init.bnk, returned the AKRESULT: %d", eResult); AZ_Assert(false, "<Wwise> Failed to unload Init.bnk!"); } } eResult = AK::SoundEngine::LoadBank(AKTEXT("init.bnk"), AK_DEFAULT_POOL_ID, m_nInitBankID); if (!IS_WWISE_OK(eResult)) { g_audioImplLogger_wwise.Log(eALT_ERROR, "Wwise failed to load Init.bnk, returned the AKRESULT: %d", eResult); m_nInitBankID = AK_INVALID_BANK_ID; AZ_Assert(false, "<Wwise> Failed to load Init.bnk!"); } } /////////////////////////////////////////////////////////////////////////////////////////////////// // AudioSystemImplementationRequestBus /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioSystemImpl_wwise::Update(const float fUpdateIntervalMS) { if (AK::SoundEngine::IsInitialized()) { #if defined(INCLUDE_WWISE_IMPL_PRODUCTION_CODE) AKRESULT eResult = AK_Fail; static int nEnableOutputCapture = 0; if (g_audioImplCVars_wwise.m_nEnableOutputCapture == 1 && nEnableOutputCapture == 0) { // This file ends up in the cache folder // Need to disable this on LTX, it produces garbage output. But there's no way to "IsLTX()" yet. eResult = AK::SoundEngine::StartOutputCapture(AKTEXT("../wwise_audio_capture.wav")); AZ_Assert(IS_WWISE_OK(eResult), "AK::SoundEngine::StartOutputCapture failed!"); nEnableOutputCapture = g_audioImplCVars_wwise.m_nEnableOutputCapture; } else if (g_audioImplCVars_wwise.m_nEnableOutputCapture == 0 && nEnableOutputCapture == 1) { eResult = AK::SoundEngine::StopOutputCapture(); AZ_Assert(IS_WWISE_OK(eResult), "AK::SoundEngine::StopOutputCapture failed!"); nEnableOutputCapture = g_audioImplCVars_wwise.m_nEnableOutputCapture; } if (audioDeviceInitializationEvent) { AkChannelConfig channelConfig = AK::SoundEngine::GetSpeakerConfiguration(); int surroundSpeakers = channelConfig.uNumChannels; int lfeSpeakers = 0; if (AK::HasLFE(channelConfig.uChannelMask)) { --surroundSpeakers; ++lfeSpeakers; } m_speakerConfigString = AZStd::string::format("Output: %d.%d", surroundSpeakers, lfeSpeakers); m_fullImplString = AZStd::string::format("%s (%s) %s", WWISE_IMPL_VERSION_STRING, m_sRegularSoundBankFolder.c_str(), m_speakerConfigString.c_str()); audioDeviceInitializationEvent = false; } #endif // INCLUDE_WWISE_IMPL_PRODUCTION_CODE AK::SoundEngine::RenderAudio(); } } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::Initialize() { // If something fails so severely during initialization that we need to fall back to the NULL implementation // we will need to shut down what has been initialized so far. Therefore make sure to call Shutdown() before returning eARS_FAILURE! AkMemSettings oMemSettings; oMemSettings.uMaxNumPools = 20; AKRESULT eResult = AK::MemoryMgr::Init(&oMemSettings); if (!IS_WWISE_OK(eResult)) { g_audioImplLogger_wwise.Log(eALT_ERROR, "AK::MemoryMgr::Init() returned AKRESULT %d", eResult); ShutDown(); return eARS_FAILURE; } const AkMemPoolId nPrepareMemPoolID = AK::MemoryMgr::CreatePool(nullptr, g_audioImplCVars_wwise.m_nPrepareEventMemoryPoolSize << 10, 16, AkMalloc, 16); if (nPrepareMemPoolID == AK_INVALID_POOL_ID) { g_audioImplLogger_wwise.Log(eALT_ERROR, "AK::MemoryMgr::CreatePool() PrepareEventMemoryPool failed!\n"); ShutDown(); return eARS_FAILURE; } eResult = AK::MemoryMgr::SetPoolName(nPrepareMemPoolID, "PrepareEventMemoryPool"); if (eResult != AK_Success) { g_audioImplLogger_wwise.Log(eALT_ERROR, "AK::MemoryMgr::SetPoolName() could not set name of event prepare memory pool!\n"); ShutDown(); return eARS_FAILURE; } eResult = AK::SoundEngine::RegisterAudioDeviceStatusCallback(AudioDeviceCallback); if (eResult != AK_Success) { g_audioImplLogger_wwise.Log(eALT_WARNING, "AK::SoundEngine::RegisterAudioDeviceStatusCallback failed!\n"); } AkStreamMgrSettings oStreamSettings; AK::StreamMgr::GetDefaultSettings(oStreamSettings); oStreamSettings.uMemorySize = g_audioImplCVars_wwise.m_nStreamManagerMemoryPoolSize << 10; // 64 KiB is the default value! if (AK::StreamMgr::Create(oStreamSettings) == nullptr) { g_audioImplLogger_wwise.Log(eALT_ERROR, "AK::StreamMgr::Create() failed!\n"); ShutDown(); return eARS_FAILURE; } AkDeviceSettings oDeviceSettings; AK::StreamMgr::GetDefaultDeviceSettings(oDeviceSettings); oDeviceSettings.uIOMemorySize = g_audioImplCVars_wwise.m_nStreamDeviceMemoryPoolSize << 10; // 2 MiB is the default value! #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION AUDIOSYSTEMIMPL_WWISE_CPP_SECTION_2 #if defined(AZ_PLATFORM_XENIA) #include "Xenia/AudioSystemImpl_wwise_cpp_xenia.inl" #elif defined(AZ_PLATFORM_PROVO) #include "Provo/AudioSystemImpl_wwise_cpp_provo.inl" #endif #endif eResult = m_oFileIOHandler.Init(oDeviceSettings); if (!IS_WWISE_OK(eResult)) { g_audioImplLogger_wwise.Log(eALT_ERROR, "m_oFileIOHandler.Init() returned AKRESULT %d", eResult); ShutDown(); return eARS_FAILURE; } CryFixedStringT<MAX_AUDIO_FILE_PATH_LENGTH> sTemp(WWISE_IMPL_BASE_PATH); const AkOSChar* pTemp = nullptr; CONVERT_CHAR_TO_OSCHAR(sTemp.c_str(), pTemp); m_oFileIOHandler.SetBankPath(pTemp); AkInitSettings oInitSettings; AK::SoundEngine::GetDefaultInitSettings(oInitSettings); oInitSettings.uDefaultPoolSize = g_audioImplCVars_wwise.m_nSoundEngineDefaultMemoryPoolSize << 10; oInitSettings.uCommandQueueSize = g_audioImplCVars_wwise.m_nCommandQueueMemoryPoolSize << 10; #if defined(INCLUDE_WWISE_IMPL_PRODUCTION_CODE) oInitSettings.uMonitorPoolSize = g_audioImplCVars_wwise.m_nMonitorMemoryPoolSize << 10; oInitSettings.uMonitorQueuePoolSize = g_audioImplCVars_wwise.m_nMonitorQueueMemoryPoolSize << 10; #endif // INCLUDE_WWISE_IMPL_PRODUCTION_CODE oInitSettings.uPrepareEventMemoryPoolID = nPrepareMemPoolID; oInitSettings.bEnableGameSyncPreparation = false;//TODO: ??? AkPlatformInitSettings oPlatformInitSettings; AK::SoundEngine::GetDefaultPlatformInitSettings(oPlatformInitSettings); oPlatformInitSettings.uLEngineDefaultPoolSize = g_audioImplCVars_wwise.m_nLowerEngineDefaultPoolSize << 10; #if defined(AZ_PLATFORM_WINDOWS) // Turn off XAudio2 output type due to rare startup crashes. Prefers WASAPI or DirectSound. oPlatformInitSettings.eAudioAPI = static_cast<AkAudioAPI>(oPlatformInitSettings.eAudioAPI & ~AkAPI_XAudio2); oPlatformInitSettings.threadBankManager.dwAffinityMask = 0; oPlatformInitSettings.threadLEngine.dwAffinityMask = 0; oPlatformInitSettings.threadMonitor.dwAffinityMask = 0; #define AZ_RESTRICTED_SECTION_IMPLEMENTED #elif defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION AUDIOSYSTEMIMPL_WWISE_CPP_SECTION_3 #if defined(AZ_PLATFORM_XENIA) #include "Xenia/AudioSystemImpl_wwise_cpp_xenia.inl" #elif defined(AZ_PLATFORM_PROVO) #include "Provo/AudioSystemImpl_wwise_cpp_provo.inl" #endif #endif #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) #undef AZ_RESTRICTED_SECTION_IMPLEMENTED #elif defined(AZ_PLATFORM_APPLE_OSX) #elif defined(AZ_PLATFORM_APPLE_IOS) || defined(AZ_PLATFORM_APPLE_TV) oInitSettings.uDefaultPoolSize = 1.5 * 1024 * 1024; oPlatformInitSettings.uLEngineDefaultPoolSize = 1.5 * 1024 * 1024; #elif defined(AZ_PLATFORM_ANDROID) JNIEnv* jniEnv = AZ::Android::AndroidEnv::Get()->GetJniEnv(); jobject javaActivity = AZ::Android::AndroidEnv::Get()->GetActivityRef(); JavaVM* javaVM = nullptr; if (jniEnv) { jniEnv->GetJavaVM(&javaVM); } oPlatformInitSettings.pJavaVM = javaVM; oPlatformInitSettings.jNativeActivity = javaActivity; #elif defined(AZ_PLATFORM_LINUX_X64) #else #error "Unsupported platform." #endif eResult = AK::SoundEngine::Init(&oInitSettings, &oPlatformInitSettings); if (!IS_WWISE_OK(eResult)) { g_audioImplLogger_wwise.Log(eALT_ERROR, "AK::SoundEngine::Init() returned AKRESULT %d", eResult); ShutDown(); return eARS_FAILURE; } AkMusicSettings oMusicInit; AK::MusicEngine::GetDefaultInitSettings(oMusicInit); eResult = AK::MusicEngine::Init(&oMusicInit); if (!IS_WWISE_OK(eResult)) { g_audioImplLogger_wwise.Log(eALT_ERROR, "AK::MusicEngine::Init() returned AKRESULT %d", eResult); ShutDown(); return eARS_FAILURE; } #if !defined(WWISE_FOR_RELEASE) if (g_audioImplCVars_wwise.m_nEnableCommSystem == 1) { m_bCommSystemInitialized = true; AkCommSettings oCommSettings; AK::Comm::GetDefaultInitSettings(oCommSettings); eResult = AK::Comm::Init(oCommSettings); if (!IS_WWISE_OK(eResult)) { g_audioImplLogger_wwise.Log(eALT_ERROR, "AK::Comm::Init() returned AKRESULT %d. Communication between the Wwise authoring application and the game will not be possible\n", eResult); m_bCommSystemInitialized = false; } eResult = AK::Monitor::SetLocalOutput(AK::Monitor::ErrorLevel_All, ErrorMonitorCallback); if (!IS_WWISE_OK(eResult)) { AK::Comm::Term(); g_audioImplLogger_wwise.Log(eALT_ERROR, "AK::Monitor::SetLocalOutput() returned AKRESULT %d", eResult); m_bCommSystemInitialized = false; } } #endif // !WWISE_FOR_RELEASE // Initialize the AudioSourceManager AudioSourceManager::Get().Initialize(); // Register the DummyGameObject used for the events that don't need a location in the game world eResult = AK::SoundEngine::RegisterGameObj(m_globalGameObjectID, sWwiseGlobalAudioObjectName); if (!IS_WWISE_OK(eResult)) { g_audioImplLogger_wwise.Log(eALT_WARNING, "AK::SoundEngine::RegisterGameObject() failed for '%s' with AKRESULT %d", sWwiseGlobalAudioObjectName, eResult); } // Load Init.bnk before making the system available to the users eResult = AK::SoundEngine::LoadBank(AKTEXT("init.bnk"), AK_DEFAULT_POOL_ID, m_nInitBankID); if (!IS_WWISE_OK(eResult)) { // This does not qualify for a fallback to the NULL implementation! // Still notify the user about this failure! g_audioImplLogger_wwise.Log(eALT_ERROR, "Wwise failed to load Init.bnk, returned the AKRESULT: %d", eResult); m_nInitBankID = AK_INVALID_BANK_ID; } #if defined(INCLUDE_WWISE_IMPL_PRODUCTION_CODE) // Set up memory pool information... AkInt32 numPools = AK::MemoryMgr::GetNumPools(); m_debugMemoryPoolInfo.reserve(numPools); g_audioImplLogger_wwise.Log(eALT_COMMENT, "Number of AK Memory Pools: %d", numPools); for (AkInt32 poolId = 0; poolId < numPools; ++poolId) { eResult = AK::MemoryMgr::CheckPoolId(poolId); if (IS_WWISE_OK(eResult)) { AudioImplMemoryPoolInfo poolInfo; AkOSChar* poolName = AK::MemoryMgr::GetPoolName(poolId); char* nameTemp = nullptr; CONVERT_OSCHAR_TO_CHAR(poolName, nameTemp); AKPLATFORM::SafeStrCpy(poolInfo.m_poolName, nameTemp, AZ_ARRAY_SIZE(poolInfo.m_poolName)); poolInfo.m_poolId = poolId; g_audioImplLogger_wwise.Log(eALT_COMMENT, "Found Wwise Memory Pool: %d - '%s'", poolId, poolInfo.m_poolName); m_debugMemoryPoolInfo.push_back(poolInfo); } } #endif // INCLUDE_WWISE_IMPL_PRODUCTION_CODE return eARS_SUCCESS; } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::ShutDown() { AKRESULT eResult = AK_Fail; #if !defined(WWISE_FOR_RELEASE) if (m_bCommSystemInitialized) { AK::Comm::Term(); eResult = AK::Monitor::SetLocalOutput(0, nullptr); if (!IS_WWISE_OK(eResult)) { g_audioImplLogger_wwise.Log(eALT_WARNING, "AK::Monitor::SetLocalOutput() returned AKRESULT %d", eResult); } m_bCommSystemInitialized = false; } #endif // !WWISE_FOR_RELEASE eResult = AK::SoundEngine::UnregisterAudioDeviceStatusCallback(); if (eResult != AK_Success) { g_audioImplLogger_wwise.Log(eALT_WARNING, "AK::SoundEngine::UnregisterAudioDeviceStatusCallback failed!\n"); } // Shutdown the AudioSourceManager AudioSourceManager::Get().Shutdown(); AK::MusicEngine::Term(); if (AK::SoundEngine::IsInitialized()) { // UnRegister the DummyGameObject eResult = AK::SoundEngine::UnregisterGameObj(m_globalGameObjectID); if (!IS_WWISE_OK(eResult)) { g_audioImplLogger_wwise.Log(eALT_WARNING, "AK::SoundEngine::UnregisterGameObject() failed for '%s' with AKRESULT %d", sWwiseGlobalAudioObjectName, eResult); } eResult = AK::SoundEngine::ClearBanks(); if (!IS_WWISE_OK(eResult)) { g_audioImplLogger_wwise.Log(eALT_ERROR, "Failed to clear sound banks!"); } AK::SoundEngine::Term(); } // Terminate the streaming device and streaming manager // CAkFilePackageLowLevelIOBlocking::Term() destroys its associated streaming device // that lives in the Stream Manager, and unregisters itself as the File Location Resolver. if (AK::IAkStreamMgr::Get()) { m_oFileIOHandler.ShutDown(); AK::IAkStreamMgr::Get()->Destroy(); } // Terminate the Memory Manager if (AK::MemoryMgr::IsInitialized()) { eResult = AK::MemoryMgr::DestroyPool(0); AK::MemoryMgr::Term(); } return eARS_SUCCESS; } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::Release() { azdestroy(this, Audio::AudioImplAllocator, CAudioSystemImpl_wwise); if (AZ::AllocatorInstance<Audio::AudioImplAllocator>::IsReady()) { AZ::AllocatorInstance<Audio::AudioImplAllocator>::Destroy(); } g_audioImplCVars_wwise.UnregisterVariables(); return eARS_SUCCESS; } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::StopAllSounds() { AK::SoundEngine::StopAll(); return eARS_SUCCESS; } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::RegisterAudioObject( IATLAudioObjectData* const pObjectData, const char* const sObjectName) { if (pObjectData) { auto const pAKObjectData = static_cast<SATLAudioObjectData_wwise*>(pObjectData); const AKRESULT eAKResult = AK::SoundEngine::RegisterGameObj(pAKObjectData->nAKID, sObjectName); const bool bAKSuccess = IS_WWISE_OK(eAKResult); if (!bAKSuccess) { g_audioImplLogger_wwise.Log(eALT_WARNING, "Wwise RegisterGameObj failed with AKRESULT: %d", eAKResult); } return BoolToARS(bAKSuccess); } else { g_audioImplLogger_wwise.Log(eALT_WARNING, "Wwise RegisterGameObj failed, pObjectData was null"); return eARS_FAILURE; } } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::UnregisterAudioObject(IATLAudioObjectData* const pObjectData) { if (pObjectData) { auto const pAKObjectData = static_cast<SATLAudioObjectData_wwise*>(pObjectData); const AKRESULT eAKResult = AK::SoundEngine::UnregisterGameObj(pAKObjectData->nAKID); const bool bAKSuccess = IS_WWISE_OK(eAKResult); if (!bAKSuccess) { g_audioImplLogger_wwise.Log(eALT_WARNING, "Wwise UnregisterGameObj failed with AKRESULT: %d", eAKResult); } return BoolToARS(bAKSuccess); } else { g_audioImplLogger_wwise.Log(eALT_WARNING, "Wwise UnregisterGameObj failed, pObjectData was null"); return eARS_FAILURE; } } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::ResetAudioObject(IATLAudioObjectData* const pObjectData) { if (pObjectData) { auto const pAKObjectData = static_cast<SATLAudioObjectData_wwise*>(pObjectData); pAKObjectData->cEnvironmentImplAmounts.clear(); pAKObjectData->bNeedsToUpdateEnvironments = false; return eARS_SUCCESS; } else { g_audioImplLogger_wwise.Log(eALT_WARNING, "Resetting Audio object failed, pObjectData was null"); return eARS_FAILURE; } } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::UpdateAudioObject(IATLAudioObjectData* const pObjectData) { EAudioRequestStatus eResult = eARS_FAILURE; if (pObjectData) { auto const pAKObjectData = static_cast<SATLAudioObjectData_wwise*>(pObjectData); if (pAKObjectData->bNeedsToUpdateEnvironments) { eResult = PostEnvironmentAmounts(pAKObjectData); } } return eResult; } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::PrepareTriggerSync( IATLAudioObjectData* const pAudioObjectData, const IATLTriggerImplData* const pTriggerData) { return PrepUnprepTriggerSync(pTriggerData, true); } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::UnprepareTriggerSync( IATLAudioObjectData* const pAudioObjectData, const IATLTriggerImplData* const pTriggerData) { return PrepUnprepTriggerSync(pTriggerData, false); } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::PrepareTriggerAsync( IATLAudioObjectData* const pAudioObjectData, const IATLTriggerImplData* const pTriggerData, IATLEventData* const pEventData) { return PrepUnprepTriggerAsync(pTriggerData, pEventData, true); } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::UnprepareTriggerAsync( IATLAudioObjectData* const pAudioObjectData, const IATLTriggerImplData* const pTriggerData, IATLEventData* const pEventData) { return PrepUnprepTriggerAsync(pTriggerData, pEventData, false); } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::ActivateTrigger( IATLAudioObjectData* const pAudioObjectData, const IATLTriggerImplData* const pTriggerData, IATLEventData* const pEventData, const SATLSourceData* const pSourceData) { EAudioRequestStatus eResult = eARS_FAILURE; auto const pAKObjectData = static_cast<SATLAudioObjectData_wwise*>(pAudioObjectData); auto const pAKTriggerImplData = static_cast<const SATLTriggerImplData_wwise*>(pTriggerData); auto const pAKEventData = static_cast<SATLEventData_wwise*>(pEventData); if (pAKObjectData && pAKTriggerImplData && pAKEventData) { AkGameObjectID nAKObjectID = AK_INVALID_GAME_OBJECT; if (pAKObjectData->bHasPosition) { nAKObjectID = pAKObjectData->nAKID; PostEnvironmentAmounts(pAKObjectData); } else { nAKObjectID = m_globalGameObjectID; } AkPlayingID nAKPlayingID = AK_INVALID_PLAYING_ID; switch (GetAssetType(pSourceData)) { case eAAT_SOURCE: { AZ_Assert(pSourceData, "SourceData not provided for source type!"); auto sTemp = AZStd::string::format("%s%d/%d/%d.wem", WWISE_IMPL_EXTERNAL_PATH, pSourceData->m_sourceInfo.m_collectionId, pSourceData->m_sourceInfo.m_languageId, pSourceData->m_sourceInfo.m_fileId); AkOSChar* pTemp = nullptr; CONVERT_CHAR_TO_OSCHAR(sTemp.c_str(), pTemp); AkExternalSourceInfo sources[1]; sources[0].iExternalSrcCookie = static_cast<AkUInt32>(pSourceData->m_sourceInfo.m_sourceId); sources[0].szFile = pTemp; sources[0].idCodec = GetAkCodecID(pSourceData->m_sourceInfo.m_codecType); nAKPlayingID = AK::SoundEngine::PostEvent( pAKTriggerImplData->nAKID, nAKObjectID, AK_EndOfEvent | AK_Duration, &WwiseEventCallback, pAKEventData, 1, sources); if (nAKPlayingID != AK_INVALID_PLAYING_ID) { pAKEventData->audioEventState = eAES_PLAYING; pAKEventData->nAKID = nAKPlayingID; eResult = eARS_SUCCESS; } else { // if Posting an Event failed, try to prepare it, if it isn't prepared already g_audioImplLogger_wwise.Log(eALT_WARNING, "Failed to Post Wwise event %u with external source '%s'", pAKTriggerImplData->nAKID, sTemp.c_str()); } break; } case eAAT_STREAM: //[[fallthrough]] case eAAT_NONE: //[[fallthrough]] default: { nAKPlayingID = AK::SoundEngine::PostEvent( pAKTriggerImplData->nAKID, nAKObjectID, AK_EndOfEvent | AK_Duration, &WwiseEventCallback, pAKEventData); if (nAKPlayingID != AK_INVALID_PLAYING_ID) { if (pSourceData) { TAudioSourceId sourceId = pSourceData->m_sourceInfo.m_sourceId; if (sourceId != INVALID_AUDIO_SOURCE_ID) { // Activate the audio input source (associates sourceId w/ playingId)... AudioSourceManager::Get().ActivateSource(sourceId, nAKPlayingID); pAKEventData->nSourceId = sourceId; } } pAKEventData->audioEventState = eAES_PLAYING; pAKEventData->nAKID = nAKPlayingID; eResult = eARS_SUCCESS; } else { // if Posting an Event failed, try to prepare it, if it isn't prepared already g_audioImplLogger_wwise.Log(eALT_WARNING, "Failed to Post Wwise event %u", pAKTriggerImplData->nAKID); } break; } } } else { g_audioImplLogger_wwise.Log(eALT_ERROR, "Invalid AudioObjectData, ATLTriggerData or EventData passed to the Wwise implementation of ActivateTrigger."); } return eResult; } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::StopEvent( IATLAudioObjectData* const pAudioObjectData, const IATLEventData* const pEventData) { EAudioRequestStatus eResult = eARS_FAILURE; auto const pAKEventData = static_cast<const SATLEventData_wwise*>(pEventData); if (pAKEventData) { switch (pAKEventData->audioEventState) { case eAES_PLAYING: { AK::SoundEngine::StopPlayingID(pAKEventData->nAKID, 10); eResult = eARS_SUCCESS; break; } default: { g_audioImplLogger_wwise.Log(eALT_ERROR, "Stopping an event of this type is not supported yet"); break; } } } else { g_audioImplLogger_wwise.Log(eALT_ERROR, "Invalid EventData passed to the Wwise implementation of StopEvent."); } return eResult; } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::StopAllEvents(IATLAudioObjectData* const pAudioObjectData) { EAudioRequestStatus eResult = eARS_FAILURE; auto const pAKObjectData = static_cast<SATLAudioObjectData_wwise*>(pAudioObjectData); if (pAKObjectData) { const AkGameObjectID nAKObjectID = pAKObjectData->bHasPosition ? pAKObjectData->nAKID : m_globalGameObjectID; AK::SoundEngine::StopAll(nAKObjectID); eResult = eARS_SUCCESS; } else { g_audioImplLogger_wwise.Log(eALT_ERROR, "Invalid AudioObjectData passed to the Wwise implementation of StopAllEvents."); } return eResult; } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::SetPosition( IATLAudioObjectData* const pAudioObjectData, const SATLWorldPosition& sWorldPosition) { EAudioRequestStatus eResult = eARS_FAILURE; auto const pAKObjectData = static_cast<SATLAudioObjectData_wwise*>(pAudioObjectData); if (pAKObjectData) { AkSoundPosition sAkSoundPos; ATLTransformToAkTransform(sWorldPosition, sAkSoundPos); const AKRESULT eAKResult = AK::SoundEngine::SetPosition(pAKObjectData->nAKID, sAkSoundPos); if (IS_WWISE_OK(eAKResult)) { eResult = eARS_SUCCESS; } else { g_audioImplLogger_wwise.Log(eALT_WARNING, "Wwise SetPosition failed with AKRESULT: %d", eAKResult); } } else { g_audioImplLogger_wwise.Log(eALT_ERROR, "Invalid AudioObjectData passed to the Wwise implementation of SetPosition."); } return eResult; } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::SetMultiplePositions( IATLAudioObjectData* const pAudioObjectData, const MultiPositionParams& multiPositionParams) { EAudioRequestStatus eResult = eARS_FAILURE; auto const pAKObjectData = static_cast<SATLAudioObjectData_wwise*>(pAudioObjectData); if (pAKObjectData) { AZStd::vector<AkSoundPosition> akPositions; AZStd::for_each(multiPositionParams.m_positions.begin(), multiPositionParams.m_positions.end(), [&akPositions](const auto& position) { akPositions.emplace_back(AZVec3ToAkTransform(position)); } ); AK::SoundEngine::MultiPositionType type = AK::SoundEngine::MultiPositionType_MultiDirections; // default 'Blended' if (multiPositionParams.m_type == MultiPositionBehaviorType::Separate) { type = AK::SoundEngine::MultiPositionType_MultiSources; } const AKRESULT akResult = AK::SoundEngine::SetMultiplePositions(pAKObjectData->nAKID, akPositions.data(), static_cast<AkUInt16>(akPositions.size()), type); if (IS_WWISE_OK(akResult)) { eResult = eARS_SUCCESS; } else { g_audioImplLogger_wwise.Log(eALT_WARNING, "Wwise SetMultiplePositions failed with AKRESULT: %d\n", akResult); } } else { g_audioImplLogger_wwise.Log(eALT_ERROR, "Invalid AudioObjectData passed to the Wwise implementation of SetMultiplePositions."); } return eResult; } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::SetEnvironment( IATLAudioObjectData* const pAudioObjectData, const IATLEnvironmentImplData* const pEnvironmentImplData, const float fAmount) { static const float sEnvEpsilon = 0.0001f; EAudioRequestStatus eResult = eARS_FAILURE; auto const pAKObjectData = static_cast<SATLAudioObjectData_wwise*>(pAudioObjectData); auto const pAKEnvironmentData = static_cast<const SATLEnvironmentImplData_wwise*>(pEnvironmentImplData); if (pAKObjectData && pAKEnvironmentData) { switch (pAKEnvironmentData->eType) { case eWAET_AUX_BUS: { const float fCurrentAmount = stl::find_in_map( pAKObjectData->cEnvironmentImplAmounts, pAKEnvironmentData->nAKBusID, -1.0f); if ((fCurrentAmount == -1.0f) || (fabs(fCurrentAmount - fAmount) > sEnvEpsilon)) { pAKObjectData->cEnvironmentImplAmounts[pAKEnvironmentData->nAKBusID] = fAmount; pAKObjectData->bNeedsToUpdateEnvironments = true; } eResult = eARS_SUCCESS; break; } case eWAET_RTPC: { auto fAKValue = static_cast<AkRtpcValue>(pAKEnvironmentData->fMult * fAmount + pAKEnvironmentData->fShift); const AKRESULT eAKResult = AK::SoundEngine::SetRTPCValue(pAKEnvironmentData->nAKRtpcID, fAKValue, pAKObjectData->nAKID); if (IS_WWISE_OK(eAKResult)) { eResult = eARS_SUCCESS; } else { g_audioImplLogger_wwise.Log( eALT_WARNING, "Wwise failed to set the Rtpc %u to value %f on object %u in SetEnvironement()", pAKEnvironmentData->nAKRtpcID, fAKValue, pAKObjectData->nAKID); } break; } default: { AZ_Assert(false, "<Wwise> Unknown AudioEnvironmentImplementation type!"); } } } else { g_audioImplLogger_wwise.Log(eALT_ERROR, "Invalid AudioObjectData or EnvironmentData passed to the Wwise implementation of SetEnvironment"); } return eResult; } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::SetRtpc( IATLAudioObjectData* const pAudioObjectData, const IATLRtpcImplData* const pRtpcData, const float fValue) { EAudioRequestStatus eResult = eARS_FAILURE; auto const pAKObjectData = static_cast<SATLAudioObjectData_wwise*>(pAudioObjectData); auto const pAKRtpcData = static_cast<const SATLRtpcImplData_wwise*>(pRtpcData); if (pAKObjectData && pAKRtpcData) { auto fAKValue = static_cast<AkRtpcValue>(pAKRtpcData->m_fMult * fValue + pAKRtpcData->m_fShift); const AKRESULT eAKResult = AK::SoundEngine::SetRTPCValue(pAKRtpcData->nAKID, fAKValue, pAKObjectData->nAKID); if (IS_WWISE_OK(eAKResult)) { eResult = eARS_SUCCESS; } else { g_audioImplLogger_wwise.Log( eALT_WARNING, "Wwise failed to set the Rtpc %" PRISIZE_T " to value %f on object %" PRISIZE_T, pAKRtpcData->nAKID, static_cast<AkRtpcValue>(fValue), pAKObjectData->nAKID); } } else { g_audioImplLogger_wwise.Log(eALT_ERROR, "Invalid AudioObjectData or RtpcData passed to the Wwise implementation of SetRtpc"); } return eResult; } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::SetSwitchState( IATLAudioObjectData* const pAudioObjectData, const IATLSwitchStateImplData* const pSwitchStateData) { EAudioRequestStatus eResult = eARS_FAILURE; auto const pAKObjectData = static_cast<SATLAudioObjectData_wwise*>(pAudioObjectData); auto const pAKSwitchStateData = static_cast<const SATLSwitchStateImplData_wwise*>(pSwitchStateData); if (pAKObjectData && pAKSwitchStateData) { switch (pAKSwitchStateData->eType) { case eWST_SWITCH: { const AkGameObjectID nAKObjectID = pAKObjectData->bHasPosition ? pAKObjectData->nAKID : m_globalGameObjectID; const AKRESULT eAKResult = AK::SoundEngine::SetSwitch( pAKSwitchStateData->nAKSwitchID, pAKSwitchStateData->nAKStateID, nAKObjectID); if (IS_WWISE_OK(eAKResult)) { eResult = eARS_SUCCESS; } else { g_audioImplLogger_wwise.Log( eALT_WARNING, "Wwise failed to set the switch group %" PRISIZE_T " to state %" PRISIZE_T " on object %" PRISIZE_T, pAKSwitchStateData->nAKSwitchID, pAKSwitchStateData->nAKStateID, nAKObjectID); } break; } case eWST_STATE: { const AKRESULT eAKResult = AK::SoundEngine::SetState( pAKSwitchStateData->nAKSwitchID, pAKSwitchStateData->nAKStateID); if (IS_WWISE_OK(eAKResult)) { eResult = eARS_SUCCESS; } else { g_audioImplLogger_wwise.Log( eALT_WARNING, "Wwise failed to set the state group %" PRISIZE_T "to state %" PRISIZE_T, pAKSwitchStateData->nAKSwitchID, pAKSwitchStateData->nAKStateID); } break; } case eWST_RTPC: { const AkGameObjectID nAKObjectID = pAKObjectData->nAKID; const AKRESULT eAKResult = AK::SoundEngine::SetRTPCValue( pAKSwitchStateData->nAKSwitchID, static_cast<AkRtpcValue>(pAKSwitchStateData->fRtpcValue), nAKObjectID); if (IS_WWISE_OK(eAKResult)) { eResult = eARS_SUCCESS; } else { g_audioImplLogger_wwise.Log( eALT_WARNING, "Wwise failed to set the Rtpc %" PRISIZE_T " to value %f on object %" PRISIZE_T, pAKSwitchStateData->nAKSwitchID, static_cast<AkRtpcValue>(pAKSwitchStateData->fRtpcValue), nAKObjectID); } break; } case eWST_NONE: { break; } default: { g_audioImplLogger_wwise.Log(eALT_WARNING, "Unknown EWwiseSwitchType: %" PRISIZE_T, pAKSwitchStateData->eType); AZ_Assert(false, "<Wwise> Unknown EWwiseSwitchType"); break; } } } else { g_audioImplLogger_wwise.Log(eALT_ERROR, "Invalid AudioObjectData or RtpcData passed to the Wwise implementation of SetRtpc"); } return eResult; } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::SetObstructionOcclusion( IATLAudioObjectData* const pAudioObjectData, const float fObstruction, const float fOcclusion) { if (fObstruction < sObstructionOcclusionMin || fObstruction > sObstructionOcclusionMax) { g_audioImplLogger_wwise.Log( eALT_WARNING, "Obstruction value %f is out of range, fObstruction should be between %f and %f.", fObstruction, sObstructionOcclusionMin, sObstructionOcclusionMax); } if (fOcclusion < sObstructionOcclusionMin || fOcclusion > sObstructionOcclusionMax) { g_audioImplLogger_wwise.Log( eALT_WARNING, "Occlusion value %f is out of range, fOcclusion should be between %f and %f " PRISIZE_T, fOcclusion, sObstructionOcclusionMin, sObstructionOcclusionMax); } EAudioRequestStatus eResult = eARS_FAILURE; auto const pAKObjectData = static_cast<SATLAudioObjectData_wwise*>(pAudioObjectData); if (pAKObjectData) { const AKRESULT eAKResult = AK::SoundEngine::SetObjectObstructionAndOcclusion( pAKObjectData->nAKID, m_defaultListenerGameObjectID, // only set the obstruction/occlusion for the default listener for now static_cast<AkReal32>(fObstruction), static_cast<AkReal32>(fOcclusion)); if (IS_WWISE_OK(eAKResult)) { eResult = eARS_SUCCESS; } else { g_audioImplLogger_wwise.Log( eALT_WARNING, "Wwise failed to set Obstruction %f and Occlusion %f on object %" PRISIZE_T, fObstruction, fOcclusion, pAKObjectData->nAKID); } } else { g_audioImplLogger_wwise.Log(eALT_ERROR, "Invalid AudioObjectData passed to the Wwise implementation of SetObjectObstructionAndOcclusion"); } return eResult; } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::SetListenerPosition( IATLListenerData* const pListenerData, const SATLWorldPosition& oNewPosition) { EAudioRequestStatus eResult = eARS_FAILURE; auto const pAKListenerData = static_cast<SATLListenerData_wwise*>(pListenerData); if (pAKListenerData) { AkListenerPosition oAKListenerPos; ATLTransformToAkTransform(oNewPosition, oAKListenerPos); const AKRESULT eAKResult = AK::SoundEngine::SetPosition(pAKListenerData->nAKListenerObjectId, oAKListenerPos); if (IS_WWISE_OK(eAKResult)) { eResult = eARS_SUCCESS; } else { g_audioImplLogger_wwise.Log(eALT_WARNING, "Wwise SetListenerPosition failed with AKRESULT: %" PRISIZE_T, eAKResult); } } else { g_audioImplLogger_wwise.Log(eALT_ERROR, "Invalid ATLListenerData passed to the Wwise implementation of SetListenerPosition"); } return eResult; } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::ResetRtpc(IATLAudioObjectData* const pAudioObjectData, const IATLRtpcImplData* const pRtpcData) { EAudioRequestStatus eResult = eARS_FAILURE; auto const pAKObjectData = static_cast<SATLAudioObjectData_wwise*>(pAudioObjectData); auto const pAKRtpcData = static_cast<const SATLRtpcImplData_wwise*>(pRtpcData); if (pAKObjectData && pAKRtpcData) { const AKRESULT eAKResult = AK::SoundEngine::ResetRTPCValue(pAKRtpcData->nAKID, pAKObjectData->nAKID); if (IS_WWISE_OK(eAKResult)) { eResult = eARS_SUCCESS; } else { g_audioImplLogger_wwise.Log( eALT_WARNING, "Wwise failed to reset the Rtpc %" PRISIZE_T " on object %" PRISIZE_T, pAKRtpcData->nAKID, pAKObjectData->nAKID); } } else { g_audioImplLogger_wwise.Log(eALT_ERROR, "Invalid AudioObjectData or RtpcData passed to the Wwise implementation of ResetRtpc"); } return eResult; } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::RegisterInMemoryFile(SATLAudioFileEntryInfo* const pFileEntryInfo) { EAudioRequestStatus eRegisterResult = eARS_FAILURE; if (pFileEntryInfo) { auto const pFileDataWwise = static_cast<SATLAudioFileEntryData_wwise*>(pFileEntryInfo->pImplData); if (pFileDataWwise) { AkBankID nBankID = AK_INVALID_BANK_ID; const AKRESULT eAKResult = AK::SoundEngine::LoadBank( pFileEntryInfo->pFileData, static_cast<AkUInt32>(pFileEntryInfo->nSize), nBankID); if (IS_WWISE_OK(eAKResult)) { pFileDataWwise->nAKBankID = nBankID; eRegisterResult = eARS_SUCCESS; } else { pFileDataWwise->nAKBankID = AK_INVALID_BANK_ID; g_audioImplLogger_wwise.Log(eALT_ERROR, "Failed to load file %s\n", pFileEntryInfo->sFileName); } } else { g_audioImplLogger_wwise.Log(eALT_ERROR, "Invalid AudioFileEntryData passed to the Wwise implementation of RegisterInMemoryFile"); } } return eRegisterResult; } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::UnregisterInMemoryFile(SATLAudioFileEntryInfo* const pFileEntryInfo) { EAudioRequestStatus eResult = eARS_FAILURE; if (pFileEntryInfo) { auto const pFileDataWwise = static_cast<SATLAudioFileEntryData_wwise*>(pFileEntryInfo->pImplData); if (pFileDataWwise) { const AKRESULT eAKResult = AK::SoundEngine::UnloadBank(pFileDataWwise->nAKBankID, pFileEntryInfo->pFileData); if (IS_WWISE_OK(eAKResult)) { eResult = eARS_SUCCESS; } else { g_audioImplLogger_wwise.Log(eALT_ERROR, "Wwise Failed to unregister in memory file %s\n", pFileEntryInfo->sFileName); } } else { g_audioImplLogger_wwise.Log(eALT_ERROR, "Invalid AudioFileEntryData passed to the Wwise implementation of UnregisterInMemoryFile"); } } return eResult; } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::ParseAudioFileEntry(const XmlNodeRef pAudioFileEntryNode, SATLAudioFileEntryInfo* const pFileEntryInfo) { static CryFixedStringT<MAX_AUDIO_FILE_PATH_LENGTH> sPath; EAudioRequestStatus eResult = eARS_FAILURE; if (pFileEntryInfo && azstricmp(pAudioFileEntryNode->getTag(), sWwiseFileTag) == 0) { const char* const sWwiseAudioFileEntryName = pAudioFileEntryNode->getAttr(sWwiseNameAttribute); if (sWwiseAudioFileEntryName && sWwiseAudioFileEntryName[0] != '\0') { const char* const sWwiseLocalised = pAudioFileEntryNode->getAttr(sWwiseLocalisedAttribute); pFileEntryInfo->bLocalized = (sWwiseLocalised != nullptr) && (azstricmp(sWwiseLocalised, "true") == 0); pFileEntryInfo->sFileName = sWwiseAudioFileEntryName; pFileEntryInfo->nMemoryBlockAlignment = AK_BANK_PLATFORM_DATA_ALIGNMENT; pFileEntryInfo->pImplData = azcreate(SATLAudioFileEntryData_wwise, (), Audio::AudioImplAllocator, "ATLAudioFileEntryData_wwise"); eResult = eARS_SUCCESS; } else { pFileEntryInfo->sFileName = nullptr; pFileEntryInfo->nMemoryBlockAlignment = 0; pFileEntryInfo->pImplData = nullptr; } } return eResult; } /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioSystemImpl_wwise::DeleteAudioFileEntryData(IATLAudioFileEntryData* const pOldAudioFileEntry) { azdestroy(pOldAudioFileEntry, Audio::AudioImplAllocator, SATLAudioFileEntryData_wwise); } /////////////////////////////////////////////////////////////////////////////////////////////////// const char* const CAudioSystemImpl_wwise::GetAudioFileLocation(SATLAudioFileEntryInfo* const pFileEntryInfo) { const char* sResult = nullptr; if (pFileEntryInfo) { sResult = pFileEntryInfo->bLocalized ? m_sLocalizedSoundBankFolder.c_str() : m_sRegularSoundBankFolder.c_str(); } return sResult; } /////////////////////////////////////////////////////////////////////////////////////////////////// SATLAudioObjectData_wwise* CAudioSystemImpl_wwise::NewGlobalAudioObjectData(const TAudioObjectID nObjectID) { AZ_UNUSED(nObjectID); auto pNewObjectData = azcreate(SATLAudioObjectData_wwise, (AK_INVALID_GAME_OBJECT, false), Audio::AudioImplAllocator, "ATLAudioObjectData_wwise-Global"); return pNewObjectData; } /////////////////////////////////////////////////////////////////////////////////////////////////// SATLAudioObjectData_wwise* CAudioSystemImpl_wwise::NewAudioObjectData(const TAudioObjectID nObjectID) { auto pNewObjectData = azcreate(SATLAudioObjectData_wwise, (static_cast<AkGameObjectID>(nObjectID), true), Audio::AudioImplAllocator, "ATLAudioObjectData_wwise"); return pNewObjectData; } /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioSystemImpl_wwise::DeleteAudioObjectData(IATLAudioObjectData* const pOldObjectData) { azdestroy(pOldObjectData, Audio::AudioImplAllocator, SATLAudioObjectData_wwise); } /////////////////////////////////////////////////////////////////////////////////////////////////// SATLListenerData_wwise* CAudioSystemImpl_wwise::NewDefaultAudioListenerObjectData(const TATLIDType nListenerID) { auto pNewObject = azcreate(SATLListenerData_wwise, (static_cast<AkGameObjectID>(nListenerID)), Audio::AudioImplAllocator, "ATLListenerData_wwise-Default"); if (pNewObject) { auto listenerName = AZStd::string::format("DefaultAudioListener(%" PRISIZE_T ")", pNewObject->nAKListenerObjectId); AKRESULT eAKResult = AK::SoundEngine::RegisterGameObj(pNewObject->nAKListenerObjectId, listenerName.c_str()); if (IS_WWISE_OK(eAKResult)) { eAKResult = AK::SoundEngine::SetDefaultListeners(&pNewObject->nAKListenerObjectId, 1); if (IS_WWISE_OK(eAKResult)) { m_defaultListenerGameObjectID = pNewObject->nAKListenerObjectId; } else { g_audioImplLogger_wwise.Log(eALT_WARNING, "Wwise failed in SetDefaultListeners to set AkGameObjectID %" PRISIZE_T " as default with AKRESULT: %d", pNewObject->nAKListenerObjectId, eAKResult); } } else { g_audioImplLogger_wwise.Log(eALT_WARNING, "Wwise failed in RegisterGameObj registering a DefaultAudioListener with AKRESULT: %d", eAKResult); } } return pNewObject; } /////////////////////////////////////////////////////////////////////////////////////////////////// SATLListenerData_wwise* CAudioSystemImpl_wwise::NewAudioListenerObjectData(const TATLIDType nListenerID) { auto pNewObject = azcreate(SATLListenerData_wwise, (static_cast<AkGameObjectID>(nListenerID)), Audio::AudioImplAllocator, "ATLListenerData_wwise"); if (pNewObject) { auto listenerName = AZStd::string::format("AudioListener(%" PRISIZE_T ")", pNewObject->nAKListenerObjectId); AKRESULT eAKResult = AK::SoundEngine::RegisterGameObj(pNewObject->nAKListenerObjectId, listenerName.c_str()); if (!IS_WWISE_OK(eAKResult)) { g_audioImplLogger_wwise.Log(eALT_WARNING, "Wwise failed in RegisterGameObj registering an AudioListener with AKRESULT: %d", eAKResult); } } return pNewObject; } /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioSystemImpl_wwise::DeleteAudioListenerObjectData(IATLListenerData* const pOldListenerData) { auto listenerData = static_cast<SATLListenerData_wwise*>(pOldListenerData); if (listenerData) { AKRESULT eAKResult = AK::SoundEngine::UnregisterGameObj(listenerData->nAKListenerObjectId); if (IS_WWISE_OK(eAKResult)) { if (listenerData->nAKListenerObjectId == m_defaultListenerGameObjectID) { m_defaultListenerGameObjectID = AK_INVALID_GAME_OBJECT; } } else { g_audioImplLogger_wwise.Log(eALT_WARNING, "Wwise failed in UnregisterGameObj unregistering an AudioListener(%" PRISIZE_T ") with AKRESULT: %d", listenerData->nAKListenerObjectId, eAKResult); } } azdestroy(pOldListenerData, Audio::AudioImplAllocator, SATLListenerData_wwise); } /////////////////////////////////////////////////////////////////////////////////////////////////// SATLEventData_wwise* CAudioSystemImpl_wwise::NewAudioEventData(const TAudioEventID nEventID) { auto pNewEvent = azcreate(SATLEventData_wwise, (nEventID), Audio::AudioImplAllocator, "ATLEventData_wwise"); return pNewEvent; } /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioSystemImpl_wwise::DeleteAudioEventData(IATLEventData* const pOldEventData) { azdestroy(pOldEventData, Audio::AudioImplAllocator, SATLEventData_wwise); } /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioSystemImpl_wwise::ResetAudioEventData(IATLEventData* const pEventData) { auto const pAKEventData = static_cast<SATLEventData_wwise*>(pEventData); if (pAKEventData) { pAKEventData->audioEventState = eAES_NONE; pAKEventData->nAKID = AK_INVALID_UNIQUE_ID; pAKEventData->nSourceId = INVALID_AUDIO_SOURCE_ID; } } /////////////////////////////////////////////////////////////////////////////////////////////////// const SATLTriggerImplData_wwise* CAudioSystemImpl_wwise::NewAudioTriggerImplData(const XmlNodeRef pAudioTriggerImplNode) { SATLTriggerImplData_wwise* pNewTriggerImpl = nullptr; if (azstricmp(pAudioTriggerImplNode->getTag(), sWwiseEventTag) == 0) { const char* const sWwiseEventName = pAudioTriggerImplNode->getAttr(sWwiseNameAttribute); const AkUniqueID nAKID = AK::SoundEngine::GetIDFromString(sWwiseEventName);//Does not check if the string represents an event!!!! if (nAKID != AK_INVALID_UNIQUE_ID) { pNewTriggerImpl = azcreate(SATLTriggerImplData_wwise, (nAKID), Audio::AudioImplAllocator, "ATLTriggerImplData_wwise"); } else { AZ_Assert(false, "<Wwise> Failed to get a unique ID from string '%s'.", sWwiseEventName); } } return pNewTriggerImpl; } /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioSystemImpl_wwise::DeleteAudioTriggerImplData(const IATLTriggerImplData* const pOldTriggerImplData) { azdestroy(const_cast<IATLTriggerImplData*>(pOldTriggerImplData), Audio::AudioImplAllocator, SATLTriggerImplData_wwise); } /////////////////////////////////////////////////////////////////////////////////////////////////// const SATLRtpcImplData_wwise* CAudioSystemImpl_wwise::NewAudioRtpcImplData(const XmlNodeRef pAudioRtpcNode) { SATLRtpcImplData_wwise* pNewRtpcImpl = nullptr; AkRtpcID nAKRtpcID = AK_INVALID_RTPC_ID; float fMult = 1.0f; float fShift = 0.0f; ParseRtpcImpl(pAudioRtpcNode, nAKRtpcID, fMult, fShift); if (nAKRtpcID != AK_INVALID_RTPC_ID) { pNewRtpcImpl = azcreate(SATLRtpcImplData_wwise, (nAKRtpcID, fMult, fShift), Audio::AudioImplAllocator, "ATLRtpcImplData_wwise"); } return pNewRtpcImpl; } /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioSystemImpl_wwise::DeleteAudioRtpcImplData(const IATLRtpcImplData* const pOldRtpcImplData) { azdestroy(const_cast<IATLRtpcImplData*>(pOldRtpcImplData), Audio::AudioImplAllocator, SATLRtpcImplData_wwise); } /////////////////////////////////////////////////////////////////////////////////////////////////// const SATLSwitchStateImplData_wwise* CAudioSystemImpl_wwise::NewAudioSwitchStateImplData(const XmlNodeRef pAudioSwitchNode) { const char* const sWwiseSwitchNodeTag = pAudioSwitchNode->getTag(); const SATLSwitchStateImplData_wwise* pNewSwitchImpl = nullptr; if (azstricmp(sWwiseSwitchNodeTag, sWwiseSwitchTag) == 0) { pNewSwitchImpl = ParseWwiseSwitchOrState(pAudioSwitchNode, eWST_SWITCH); } else if (azstricmp(sWwiseSwitchNodeTag, sWwiseStateTag) == 0) { pNewSwitchImpl = ParseWwiseSwitchOrState(pAudioSwitchNode, eWST_STATE); } else if (azstricmp(sWwiseSwitchNodeTag, sWwiseRtpcSwitchTag) == 0) { pNewSwitchImpl = ParseWwiseRtpcSwitch(pAudioSwitchNode); } else { // Unknown Wwise switch tag! g_audioImplLogger_wwise.Log(eALT_WARNING, "Unknown Wwise Switch Tag: %s" PRISIZE_T, sWwiseSwitchNodeTag); AZ_Assert(false, "<Wwise> Unknown Wwise Switch Tag."); } return pNewSwitchImpl; } /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioSystemImpl_wwise::DeleteAudioSwitchStateImplData(const IATLSwitchStateImplData* const pOldAudioSwitchStateImplData) { azdestroy(const_cast<IATLSwitchStateImplData*>(pOldAudioSwitchStateImplData), Audio::AudioImplAllocator, SATLSwitchStateImplData_wwise); } /////////////////////////////////////////////////////////////////////////////////////////////////// const SATLEnvironmentImplData_wwise* CAudioSystemImpl_wwise::NewAudioEnvironmentImplData(const XmlNodeRef pAudioEnvironmentNode) { SATLEnvironmentImplData_wwise* pNewEnvironmentImpl = nullptr; if (azstricmp(pAudioEnvironmentNode->getTag(), sWwiseAuxBusTag) == 0) { const char* const sWwiseAuxBusName = pAudioEnvironmentNode->getAttr(sWwiseNameAttribute); const AkUniqueID nAKBusID = AK::SoundEngine::GetIDFromString(sWwiseAuxBusName); //Does not check if the string represents an event!!!! if (nAKBusID != AK_INVALID_AUX_ID) { pNewEnvironmentImpl = azcreate(SATLEnvironmentImplData_wwise, (eWAET_AUX_BUS, static_cast<AkAuxBusID>(nAKBusID)), Audio::AudioImplAllocator, "ATLEnvironmentImplData_wwise"); } else { AZ_Assert(false, "<Wwise> Unknown Aux Bus ID."); } } else if (azstricmp(pAudioEnvironmentNode->getTag(), sWwiseRtpcTag) == 0) { AkRtpcID nAKRtpcID = AK_INVALID_RTPC_ID; float fMult = 1.0f; float fShift = 0.0f; ParseRtpcImpl(pAudioEnvironmentNode, nAKRtpcID, fMult, fShift); if (nAKRtpcID != AK_INVALID_RTPC_ID) { pNewEnvironmentImpl = azcreate(SATLEnvironmentImplData_wwise, (eWAET_RTPC, nAKRtpcID, fMult, fShift), Audio::AudioImplAllocator, "ATLEnvironmentImplData_wwise"); } else { AZ_Assert(false, "<Wwise> Unknown RTPC ID."); } } return pNewEnvironmentImpl; } /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioSystemImpl_wwise::DeleteAudioEnvironmentImplData(const IATLEnvironmentImplData* const pOldEnvironmentImplData) { azdestroy(const_cast<IATLEnvironmentImplData*>(pOldEnvironmentImplData), Audio::AudioImplAllocator, SATLEnvironmentImplData_wwise); } /////////////////////////////////////////////////////////////////////////////////////////////////// const char* const CAudioSystemImpl_wwise::GetImplementationNameString() const { #if defined(INCLUDE_WWISE_IMPL_PRODUCTION_CODE) return m_fullImplString.c_str(); #else return nullptr; #endif // INCLUDE_WWISE_IMPL_PRODUCTION_CODE } /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioSystemImpl_wwise::GetMemoryInfo(SAudioImplMemoryInfo& oMemoryInfo) const { oMemoryInfo.nPrimaryPoolSize = AZ::AllocatorInstance<Audio::AudioImplAllocator>::Get().Capacity(); oMemoryInfo.nPrimaryPoolUsedSize = AZ::AllocatorInstance<Audio::AudioImplAllocator>::Get().NumAllocatedBytes(); oMemoryInfo.nPrimaryPoolAllocations = 0; #if defined(PROVIDE_WWISE_IMPL_SECONDARY_POOL) oMemoryInfo.nSecondaryPoolSize = g_audioImplMemoryPoolSecondary_wwise.MemSize(); oMemoryInfo.nSecondaryPoolUsedSize = oMemoryInfo.nSecondaryPoolSize - g_audioImplMemoryPoolSecondary_wwise.MemFree(); oMemoryInfo.nSecondaryPoolAllocations = g_audioImplMemoryPoolSecondary_wwise.FragmentCount(); #else oMemoryInfo.nSecondaryPoolSize = 0; oMemoryInfo.nSecondaryPoolUsedSize = 0; oMemoryInfo.nSecondaryPoolAllocations = 0; #endif // PROVIDE_WWISE_IMPL_SECONDARY_POOL } /////////////////////////////////////////////////////////////////////////////////////////////////// AZStd::vector<AudioImplMemoryPoolInfo> CAudioSystemImpl_wwise::GetMemoryPoolInfo() { #if defined(INCLUDE_WWISE_IMPL_PRODUCTION_CODE) // Update pools... for (auto& poolInfo : m_debugMemoryPoolInfo) { AKRESULT akResult = AK::MemoryMgr::CheckPoolId(poolInfo.m_poolId); if (IS_WWISE_OK(akResult)) { AK::MemoryMgr::PoolStats poolStats; akResult = AK::MemoryMgr::GetPoolStats(poolInfo.m_poolId, poolStats); if (IS_WWISE_OK(akResult)) { poolInfo.m_memoryReserved = poolStats.uReserved; poolInfo.m_memoryUsed = poolStats.uUsed; poolInfo.m_peakUsed = poolStats.uPeakUsed; poolInfo.m_numAllocs = poolStats.uAllocs; poolInfo.m_numFrees = poolStats.uFrees; } } } // return the pool infos... return m_debugMemoryPoolInfo; #else return AZStd::vector<AudioImplMemoryPoolInfo>(); #endif // INCLUDE_WWISE_IMPL_PRODUCTION_CODE } /////////////////////////////////////////////////////////////////////////////////////////////////// bool CAudioSystemImpl_wwise::CreateAudioSource(const SAudioInputConfig& sourceConfig) { return AudioSourceManager::Get().CreateSource(sourceConfig); } /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioSystemImpl_wwise::DestroyAudioSource(TAudioSourceId sourceId) { AudioSourceManager::Get().DestroySource(sourceId); } /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioSystemImpl_wwise::SetPanningMode(PanningMode mode) { AkPanningRule panningRule; switch (mode) { case PanningMode::Speakers: panningRule = AkPanningRule_Speakers; break; case PanningMode::Headphones: panningRule = AkPanningRule_Headphones; break; default: return; } AKRESULT akResult = AK::SoundEngine::SetPanningRule(panningRule); if (!IS_WWISE_OK(akResult)) { g_audioImplLogger_wwise.Log(eALT_ERROR, "Wwise failed to set Panning Rule to [%s]\n", panningRule == AkPanningRule_Speakers ? "Speakers" : "Headphones"); } } /////////////////////////////////////////////////////////////////////////////////////////////////// const SATLSwitchStateImplData_wwise* CAudioSystemImpl_wwise::ParseWwiseSwitchOrState( XmlNodeRef pNode, EWwiseSwitchType eType) { SATLSwitchStateImplData_wwise* pSwitchStateImpl = nullptr; const char* const sWwiseSwitchNodeName = pNode->getAttr(sWwiseNameAttribute); if (sWwiseSwitchNodeName && (sWwiseSwitchNodeName[0] != '\0') && (pNode->getChildCount() == 1)) { const XmlNodeRef pValueNode(pNode->getChild(0)); if (pValueNode && azstricmp(pValueNode->getTag(), sWwiseValueTag) == 0) { const char* sWwiseSwitchStateName = pValueNode->getAttr(sWwiseNameAttribute); if (sWwiseSwitchStateName && (sWwiseSwitchStateName[0] != '\0')) { const AkUniqueID nAKSwitchID = AK::SoundEngine::GetIDFromString(sWwiseSwitchNodeName); const AkUniqueID nAKSwitchStateID = AK::SoundEngine::GetIDFromString(sWwiseSwitchStateName); pSwitchStateImpl = azcreate(SATLSwitchStateImplData_wwise, (eType, nAKSwitchID, nAKSwitchStateID), Audio::AudioImplAllocator, "ATLSwitchStateImplData_wwise"); } } } else { g_audioImplLogger_wwise.Log( eALT_WARNING, "A Wwise Switch or State %s inside ATLSwitchState needs to have exactly one WwiseValue.", sWwiseSwitchNodeName); } return pSwitchStateImpl; } /////////////////////////////////////////////////////////////////////////////////////////////////// const SATLSwitchStateImplData_wwise* CAudioSystemImpl_wwise::ParseWwiseRtpcSwitch(XmlNodeRef pNode) { SATLSwitchStateImplData_wwise* pSwitchStateImpl = nullptr; const char* const sWwiseRtpcNodeName = pNode->getAttr(sWwiseNameAttribute); if (sWwiseRtpcNodeName && sWwiseRtpcNodeName[0] != '\0' && pNode->getChildCount() == 0) { float fRtpcValue = 0.f; if (pNode->getAttr(sWwiseValueAttribute, fRtpcValue)) { const AkUniqueID nAKRtpcID = AK::SoundEngine::GetIDFromString(sWwiseRtpcNodeName); pSwitchStateImpl = azcreate(SATLSwitchStateImplData_wwise, (eWST_RTPC, nAKRtpcID, nAKRtpcID, fRtpcValue), Audio::AudioImplAllocator, "ATLSwitchStateImplData_wwise"); } } else { g_audioImplLogger_wwise.Log( eALT_WARNING, "A Wwise Rtpc '%s' inside ATLSwitchState shouldn't have any children.", sWwiseRtpcNodeName); } return pSwitchStateImpl; } /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioSystemImpl_wwise::ParseRtpcImpl(XmlNodeRef pNode, AkRtpcID& rAkRtpcID, float& rMult, float& rShift) { SATLRtpcImplData_wwise* pNewRtpcImpl = nullptr; if (azstricmp(pNode->getTag(), sWwiseRtpcTag) == 0) { const char* const sWwiseRtpcName = pNode->getAttr(sWwiseNameAttribute); rAkRtpcID = static_cast<AkRtpcID>(AK::SoundEngine::GetIDFromString(sWwiseRtpcName)); if (rAkRtpcID != AK_INVALID_RTPC_ID) { //the Wwise name is supplied pNode->getAttr(sWwiseMutiplierAttribute, rMult); pNode->getAttr(sWwiseShiftAttribute, rShift); } else { // Invalid Wwise RTPC name! AZ_Assert(false, "<Wwise> Invalid RTPC name: '%s'", sWwiseRtpcName); } } else { // Unknown Wwise RTPC tag! AZ_Assert(false, "<Wwise> Unknown RTPC tag: '%s'", sWwiseRtpcTag); } } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::PrepUnprepTriggerSync( const IATLTriggerImplData* const pTriggerData, bool bPrepare) { EAudioRequestStatus eResult = eARS_FAILURE; auto const pAKTriggerImplData = static_cast<const SATLTriggerImplData_wwise*>(pTriggerData); if (pAKTriggerImplData) { AkUniqueID nImplAKID = pAKTriggerImplData->nAKID; const AKRESULT eAKResult = AK::SoundEngine::PrepareEvent( bPrepare ? AK::SoundEngine::Preparation_Load : AK::SoundEngine::Preparation_Unload, &nImplAKID, 1); if (IS_WWISE_OK(eAKResult)) { eResult = eARS_SUCCESS; } else { g_audioImplLogger_wwise.Log( eALT_WARNING, "Wwise PrepareEvent with %s failed for Wwise event %" PRISIZE_T " with AKRESULT: %" PRISIZE_T, bPrepare ? "Preparation_Load" : "Preparation_Unload", nImplAKID, eAKResult); } } else { g_audioImplLogger_wwise.Log(eALT_ERROR, "Invalid ATLTriggerData or EventData passed to the Wwise implementation of %sTriggerSync", bPrepare ? "Prepare" : "Unprepare"); } return eResult; } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::PrepUnprepTriggerAsync( const IATLTriggerImplData* const pTriggerData, IATLEventData* const pEventData, bool bPrepare) { EAudioRequestStatus eResult = eARS_FAILURE; auto const pAKTriggerImplData = static_cast<const SATLTriggerImplData_wwise*>(pTriggerData); auto const pAKEventData = static_cast<SATLEventData_wwise*>(pEventData); if (pAKTriggerImplData && pAKEventData) { AkUniqueID nImplAKID = pAKTriggerImplData->nAKID; const AKRESULT eAKResult = AK::SoundEngine::PrepareEvent( bPrepare ? AK::SoundEngine::Preparation_Load : AK::SoundEngine::Preparation_Unload, &nImplAKID, 1, &PrepareEventCallback, pAKEventData); if (IS_WWISE_OK(eAKResult)) { pAKEventData->nAKID = nImplAKID; pAKEventData->audioEventState = eAES_UNLOADING; eResult = eARS_SUCCESS; } else { g_audioImplLogger_wwise.Log( eALT_WARNING, "Wwise PrepareEvent with %s failed for Wwise event %" PRISIZE_T " with AKRESULT: %d", bPrepare ? "Preparation_Load" : "Preparation_Unload", nImplAKID, eAKResult); } } else { g_audioImplLogger_wwise.Log(eALT_ERROR, "Invalid ATLTriggerData or EventData passed to the Wwise implementation of %sTriggerAsync", bPrepare ? "Prepare" : "Unprepare"); } return eResult; } /////////////////////////////////////////////////////////////////////////////////////////////////// bool CAudioSystemImpl_wwise::SEnvPairCompare::operator()(const AZStd::pair<const AkAuxBusID, float>& pair1, const AZStd::pair<const AkAuxBusID, float>& pair2) const { return (pair1.second > pair2.second); } /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::PostEnvironmentAmounts(IATLAudioObjectData* const pAudioObjectData) { EAudioRequestStatus eResult = eARS_FAILURE; auto const pAKObjectData = static_cast<SATLAudioObjectData_wwise*>(pAudioObjectData); if (pAKObjectData) { AkAuxSendValue aAuxValues[LY_MAX_AUX_PER_OBJ]; uint32 nAuxCount = 0; SATLAudioObjectData_wwise::TEnvironmentImplMap::iterator iEnvPair = pAKObjectData->cEnvironmentImplAmounts.begin(); const SATLAudioObjectData_wwise::TEnvironmentImplMap::const_iterator iEnvStart = pAKObjectData->cEnvironmentImplAmounts.begin(); const SATLAudioObjectData_wwise::TEnvironmentImplMap::const_iterator iEnvEnd = pAKObjectData->cEnvironmentImplAmounts.end(); if (pAKObjectData->cEnvironmentImplAmounts.size() <= LY_MAX_AUX_PER_OBJ) { for (; iEnvPair != iEnvEnd; ++nAuxCount) { const float fAmount = iEnvPair->second; aAuxValues[nAuxCount].auxBusID = iEnvPair->first; aAuxValues[nAuxCount].fControlValue = fAmount; aAuxValues[nAuxCount].listenerID = m_defaultListenerGameObjectID; // TODO: Expand api to allow specify listeners // If an amount is zero, we still want to send it to the middleware, but we also want to remove it from the map. if (fAmount == 0.0f) { iEnvPair = pAKObjectData->cEnvironmentImplAmounts.erase(iEnvPair); } else { ++iEnvPair; } } } else { // sort the environments in order of decreasing amounts and take the first LY_MAX_AUX_PER_OBJ worth using TEnvPairSet = AZStd::set<SATLAudioObjectData_wwise::TEnvironmentImplMap::value_type, SEnvPairCompare, Audio::AudioImplStdAllocator>; TEnvPairSet cEnvPairs(iEnvStart, iEnvEnd); TEnvPairSet::const_iterator iSortedEnvPair = cEnvPairs.begin(); const TEnvPairSet::const_iterator iSortedEnvEnd = cEnvPairs.end(); for (; (iSortedEnvPair != iSortedEnvEnd) && (nAuxCount < LY_MAX_AUX_PER_OBJ); ++iSortedEnvPair, ++nAuxCount) { aAuxValues[nAuxCount].auxBusID = iSortedEnvPair->first; aAuxValues[nAuxCount].fControlValue = iSortedEnvPair->second; aAuxValues[nAuxCount].listenerID = m_defaultListenerGameObjectID; // TODO: Expand api to allow specify listeners } // remove all Environments with 0.0 amounts while (iEnvPair != iEnvEnd) { if (iEnvPair->second == 0.0f) { iEnvPair = pAKObjectData->cEnvironmentImplAmounts.erase(iEnvPair); } else { ++iEnvPair; } } } AZ_Assert(nAuxCount <= LY_MAX_AUX_PER_OBJ, "WwiseImpl PostEnvironmentAmounts - Exceeded the allowed number of aux environments that can be set!"); const AKRESULT eAKResult = AK::SoundEngine::SetGameObjectAuxSendValues(pAKObjectData->nAKID, aAuxValues, nAuxCount); if (IS_WWISE_OK(eAKResult)) { eResult = eARS_SUCCESS; } else { g_audioImplLogger_wwise.Log(eALT_WARNING, "Wwise SetGameObjectAuxSendValues failed on object %" PRISIZE_T " with AKRESULT: %d", pAKObjectData->nAKID, eAKResult); } pAKObjectData->bNeedsToUpdateEnvironments = false; } return eResult; } ////////////////////////////////////////////////////////////////////////// const char* const CAudioSystemImpl_wwise::GetImplSubPath() const { return sWwiseImplSubPath; } ////////////////////////////////////////////////////////////////////////// void CAudioSystemImpl_wwise::SetLanguage(const char* const sLanguage) { if (sLanguage) { CryFixedStringT<MAX_AUDIO_FILE_NAME_LENGTH> sLanguageFolder; if (azstricmp(sLanguage, "english") == 0) { sLanguageFolder = "english(us)"; } else { sLanguageFolder = sLanguage;// TODO: handle the other possible language variations } sLanguageFolder += "/"; m_sLocalizedSoundBankFolder = m_sRegularSoundBankFolder; m_sLocalizedSoundBankFolder += sLanguageFolder.c_str(); const AkOSChar* pTemp = nullptr; CONVERT_CHAR_TO_OSCHAR(sLanguageFolder.c_str(), pTemp); m_oFileIOHandler.SetLanguageFolder(pTemp); } } } // namespace Audio
41.368775
216
0.567329
raghnarx
02cf4f796d4eb430db9264a6ce3e6efec0bc9c3c
9,786
hpp
C++
include/steam/problem/NoiseModel.hpp
utiasASRL/steam
0905736fa356ce743636453b37e952580d40d425
[ "BSD-3-Clause" ]
38
2019-10-17T01:37:41.000Z
2022-03-31T03:55:47.000Z
include/steam/problem/NoiseModel.hpp
utiasASRL/steam
0905736fa356ce743636453b37e952580d40d425
[ "BSD-3-Clause" ]
2
2019-12-21T21:25:48.000Z
2021-01-01T23:08:57.000Z
include/steam/problem/NoiseModel.hpp
utiasASRL/steam
0905736fa356ce743636453b37e952580d40d425
[ "BSD-3-Clause" ]
5
2019-12-21T21:13:01.000Z
2022-02-28T23:42:14.000Z
////////////////////////////////////////////////////////////////////////////////////////////// /// \file NoiseModel.hpp /// /// \author Sean Anderson, ASRL ////////////////////////////////////////////////////////////////////////////////////////////// #ifndef STEAM_NOISE_MODEL_HPP #define STEAM_NOISE_MODEL_HPP #include <Eigen/Dense> #include <mutex> namespace steam { /// @class NoiseEvaluator evaluates uncertainty based on a derived model. template <int MEAS_DIM> class NoiseEvaluator { public: /// Convenience typedefs typedef std::shared_ptr<NoiseEvaluator<MEAS_DIM> > Ptr; typedef std::shared_ptr<const NoiseEvaluator<MEAS_DIM> > ConstPtr; /// \brief Default constructor. NoiseEvaluator()=default; /// \brief Default destructor. virtual ~NoiseEvaluator()=default; /// \brief mutex locked public exposure of the virtual evaluate() function. virtual Eigen::Matrix<double,MEAS_DIM,MEAS_DIM> evaluateCovariance() { std::lock_guard<std::mutex> lock(eval_mutex_); return evaluate(); } protected: /// \brief Evaluates the uncertainty based on a derived model. /// \return the uncertainty, in the form of a covariance matrix. virtual Eigen::Matrix<double,MEAS_DIM,MEAS_DIM> evaluate()=0; private: std::mutex eval_mutex_; }; /// Enumeration of ways to set the noise enum MatrixType { COVARIANCE, INFORMATION, SQRT_INFORMATION }; /// @class BaseNoiseModel Base class for the steam noise models template <int MEAS_DIM> class BaseNoiseModel { public: /// \brief Default constructor. BaseNoiseModel()=default; /// \brief Constructor /// \brief A noise matrix, determined by the type parameter. /// \brief The type of noise matrix set in the previous paramter. BaseNoiseModel(const Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& matrix, MatrixType type = COVARIANCE); /// \brief Deault destructor virtual ~BaseNoiseModel() = default; /// Convenience typedefs typedef std::shared_ptr<BaseNoiseModel<MEAS_DIM> > Ptr; typedef std::shared_ptr<const BaseNoiseModel<MEAS_DIM> > ConstPtr; ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Set by covariance matrix ////////////////////////////////////////////////////////////////////////////////////////////// void setByCovariance(const Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& matrix) const; ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Set by information matrix ////////////////////////////////////////////////////////////////////////////////////////////// void setByInformation(const Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& matrix) const ; ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Set by square root of information matrix ////////////////////////////////////////////////////////////////////////////////////////////// void setBySqrtInformation(const Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& matrix) const ; ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Get a reference to the square root information matrix ////////////////////////////////////////////////////////////////////////////////////////////// virtual const Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& getSqrtInformation() const = 0; ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Get the norm of the whitened error vector, sqrt(rawError^T * info * rawError) ////////////////////////////////////////////////////////////////////////////////////////////// virtual double getWhitenedErrorNorm(const Eigen::Matrix<double,MEAS_DIM,1>& rawError) const = 0; ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Get the whitened error vector, sqrtInformation*rawError ////////////////////////////////////////////////////////////////////////////////////////////// virtual Eigen::Matrix<double,MEAS_DIM,1> whitenError( const Eigen::Matrix<double,MEAS_DIM,1>& rawError) const = 0; protected: ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Assert that the matrix is positive definite ////////////////////////////////////////////////////////////////////////////////////////////// void assertPositiveDefiniteMatrix(const Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& matrix) const; ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief The square root information (found by performing an LLT decomposition on the /// information matrix (inverse covariance matrix). This triangular matrix is /// stored directly for faster error whitening. ////////////////////////////////////////////////////////////////////////////////////////////// mutable Eigen::Matrix<double,MEAS_DIM,MEAS_DIM> sqrtInformation_; private: }; /// @class StaticNoiseModel Noise model for uncertainties that do not change during the /// steam optimization problem. template <int MEAS_DIM> class StaticNoiseModel : public BaseNoiseModel<MEAS_DIM> { public: /// Convenience typedefs typedef std::shared_ptr<StaticNoiseModel<MEAS_DIM> > Ptr; typedef std::shared_ptr<const StaticNoiseModel<MEAS_DIM> > ConstPtr; ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Default constructor ////////////////////////////////////////////////////////////////////////////////////////////// StaticNoiseModel(); ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief General constructor ////////////////////////////////////////////////////////////////////////////////////////////// StaticNoiseModel(const Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& matrix, MatrixType type = COVARIANCE); ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Get a reference to the square root information matrix ////////////////////////////////////////////////////////////////////////////////////////////// virtual const Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& getSqrtInformation() const; ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Get the norm of the whitened error vector, sqrt(rawError^T * info * rawError) ////////////////////////////////////////////////////////////////////////////////////////////// virtual double getWhitenedErrorNorm(const Eigen::Matrix<double,MEAS_DIM,1>& rawError) const; ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Get the whitened error vector, sqrtInformation*rawError ////////////////////////////////////////////////////////////////////////////////////////////// virtual Eigen::Matrix<double,MEAS_DIM,1> whitenError( const Eigen::Matrix<double,MEAS_DIM,1>& rawError) const; private: }; /// \brief DynamicNoiseModel Noise model for uncertainties that change during the steam optimization /// problem. template <int MEAS_DIM> class DynamicNoiseModel : public BaseNoiseModel<MEAS_DIM> { public: /// \brief Constructor /// \param eval a pointer to a noise evaluator. DynamicNoiseModel(std::shared_ptr<NoiseEvaluator<MEAS_DIM>> eval); /// \brief Deault destructor. ~DynamicNoiseModel()=default; ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Get a reference to the square root information matrix ////////////////////////////////////////////////////////////////////////////////////////////// virtual const Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& getSqrtInformation() const; ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Get the norm of the whitened error vector, sqrt(rawError^T * info * rawError) ////////////////////////////////////////////////////////////////////////////////////////////// virtual double getWhitenedErrorNorm(const Eigen::Matrix<double,MEAS_DIM,1>& rawError) const; ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Get the whitened error vector, sqrtInformation*rawError ////////////////////////////////////////////////////////////////////////////////////////////// virtual Eigen::Matrix<double,MEAS_DIM,1> whitenError( const Eigen::Matrix<double,MEAS_DIM,1>& rawError) const; private: /// \brief A pointer to a noise evaluator. std::shared_ptr<NoiseEvaluator<MEAS_DIM>> eval_; }; ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Typedef for the general base noise model ////////////////////////////////////////////////////////////////////////////////////////////// typedef BaseNoiseModel<Eigen::Dynamic> BaseNoiseModelX; ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Typedef for the general static noise model ////////////////////////////////////////////////////////////////////////////////////////////// typedef StaticNoiseModel<Eigen::Dynamic> StaticNoiseModelX; ////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Typedef for the general dynamic noise model ////////////////////////////////////////////////////////////////////////////////////////////// typedef DynamicNoiseModel<Eigen::Dynamic> DynamicNoiseModelX; } // steam #include <steam/problem/NoiseModel-inl.hpp> #endif // STEAM_NOISE_MODEL_HPP
45.096774
100
0.452279
utiasASRL
02cf532d01e690c3f2cad14f25bdb78d6a67a00a
901
hpp
C++
eagleeye/engine/nano/dataflow/edge.hpp
jianzfb/eagleeye
e28810033eb656b181b6291ca702da825c4946c2
[ "Apache-2.0" ]
12
2020-09-21T02:24:11.000Z
2022-03-10T03:02:03.000Z
eagleeye/engine/nano/dataflow/edge.hpp
jianzfb/eagleeye
e28810033eb656b181b6291ca702da825c4946c2
[ "Apache-2.0" ]
1
2020-11-30T08:22:50.000Z
2020-11-30T08:22:50.000Z
eagleeye/engine/nano/dataflow/edge.hpp
jianzfb/eagleeye
e28810033eb656b181b6291ca702da825c4946c2
[ "Apache-2.0" ]
3
2020-03-16T12:10:55.000Z
2021-07-20T09:58:15.000Z
#ifndef _EAGLEEYE_EDGE_H_ #define _EAGLEEYE_EDGE_H_ #include "eagleeye/common/EagleeyeMacro.h" #include <atomic> #include <memory> namespace eagleeye{ namespace dataflow { class Node; class Edge { public: Edge(Node & prev,int prev_slot, Node & next, int next_slot) noexcept : prev_(prev), next_(next), prev_slot_(prev_slot), next_slot_(next_slot) { lock_ = false; } Node & next() noexcept { return next_; } Node & prev() noexcept { return prev_; } int pre_slot() noexcept{ return prev_slot_; } int next_slot() noexcept{ return next_slot_; } bool lock() noexcept { bool f = lock_; lock_ = true; return f; } void unlock() noexcept { lock_ = false; } bool is_locked() const noexcept { return lock_; } private: std::atomic_bool lock_; Node & prev_; int prev_slot_; Node & next_; int next_slot_; }; } } #endif
15.534483
76
0.654828
jianzfb
02d11b00ed9f12293827bdb5794aa8c352b25e60
11,728
cpp
C++
Lab1/task/Source.cpp
ChernichenkoStephan/ProductionPractices
c3bd544d0cac56a801923e705a685fd2f9fcf247
[ "MIT" ]
null
null
null
Lab1/task/Source.cpp
ChernichenkoStephan/ProductionPractices
c3bd544d0cac56a801923e705a685fd2f9fcf247
[ "MIT" ]
null
null
null
Lab1/task/Source.cpp
ChernichenkoStephan/ProductionPractices
c3bd544d0cac56a801923e705a685fd2f9fcf247
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; /* g++ -w -o out Source.cpp && ./out g++ -o out Source.cpp */ int main() { srand(time(NULL)); int n1, m1, n2, m2, k, l = 2; system("chcp 1251"); cout << "��� ������������ ���������" << endl << "�������� ������������ ������ ������� ���������\n\n"; /////////////////////////////////////////////////////////////////////////////// ////////////////////���� �������� ������� �������������//////////////////////// /////////////////////////////////////////////////////////////////////////////// do { cout << "������� ������� ������ �������\n"; cin >> n1 >> m1; } while (n1 <= 0 || m1 <= 0); do { cout << "������� ������� ������ �������\n"; cin >> n2 >> m2; } while (n2 <= 0 || m2 <= 0); int** M1 = new int* [n1]; for (int i = 0; i < n1; i++) M1[i] = new int[m1]; int** M2 = new int* [n2]; for (int i = 0; i < n2; i++) M2[i] = new int[m2]; /////////////////////////////////////////////////////////////////////////////// ////////////////����� ������� ���������� � ���������� ������/////////////////// /////////////////////////////////////////////////////////////////////////////// do { cout << "�������� ������ ���������� ������\n" << "1 - ������� \n2 - ��������� �������\n"; cin >> k; } while (k < 1 || k > 2); switch (k) { case 1: for (int i = 0; i < n1; i++) for (int j = 0; j < m1; j++) cin >> M1[i][j]; for (int i = 0; i < n2; i++) for (int j = 0; j < m2; j++) cin >> M2[i][j]; cout << "\n������� 1\n\n"; for (int i = 0; i < n1; i++) { for (int j = 0; j < m1; j++) cout << M1[i][j] << " "; cout << endl; } cout << "\n������� 2\n\n"; for (int i = 0; i < n2; i++) { for (int j = 0; j < m2; j++) cout << M2[i][j] << " "; cout << endl; } break; case 2: for (int i = 0; i < n1; i++) for (int j = 0; j < m1; j++) M1[i][j] = rand() % 10; for (int i = 0; i < n2; i++) for (int j = 0; j < m2; j++) M2[i][j] = rand() % 10; cout << "\n������� 1\n\n"; for (int i = 0; i < n1; i++) { for (int j = 0; j < m1; j++) cout << M1[i][j] << " "; cout << endl; } cout << "\n������� 2\n\n"; for (int i = 0; i < n2; i++) { for (int j = 0; j < m2; j++) cout << M2[i][j] << " "; cout << endl; } break; } /////////////////////////////////////////////////////////////////////////////// /////////////////���������� ������ � ���������� �������//////////////////////// /////////////////////////////////////////////////////////////////////////////// while (l < n1 || l < n2 || l < m1 || l < m2) l *= 2; int** M3 = new int* [l]; for (int i = 0; i < l; i++) { M3[i] = new int[l]; for (int j = 0; j < l; j++) M3[i][j] = 0; } int** M4 = new int* [l]; for (int i = 0; i < l; i++) { M4[i] = new int[l]; for (int j = 0; j < l; j++) M4[i][j] = 0; } for (int i = 0; i < n1; i++) { for (int j = 0; j < m1; j++) M3[i][j] = M1[i][j]; } for (int i = 0; i < n2; i++) { for (int j = 0; j < m2; j++) M4[i][j] = M2[i][j]; } cout << "����������� �������\n"; cout << "\n������� 1\n\n"; for (int i = 0; i < l; i++) { for (int j = 0; j < l; j++) cout << M3[i][j] << " "; cout << endl; } cout << "\n������� 2\n\n"; for (int i = 0; i < l; i++) { for (int j = 0; j < l; j++) cout << M4[i][j] << " "; cout << endl; } /////////////////////////////////////////////////////////////////////////////// ///////////////��������� ������ �� ���������� � �� ����������////////////////// /////////////////////////////////////////////////////////////////////////////// int** mat1 = new int* [l / 2]; for (int i = 0; i < l / 2; i++) { mat1[i] = new int[l / 2]; for (int j = 0; j < l / 2; j++) mat1[i][j] = M3[i][j]; } int** mat2 = new int* [l / 2]; for (int i = 0; i < l / 2; i++) { mat2[i] = new int[l / 2]; for (int j = 0; j < l / 2; j++) mat2[i][j] = M3[i][j + l / 2]; } int** mat3 = new int* [l / 2]; for (int i = 0; i < l / 2; i++) { mat3[i] = new int[l / 2]; for (int j = 0; j < l / 2; j++) mat3[i][j] = M3[i + l / 2][j]; } int** mat4 = new int* [l / 2]; for (int i = 0; i < l / 2; i++) { mat4[i] = new int[l / 2]; for (int j = 0; j < l / 2; j++) mat4[i][j] = M3[i + l / 2][j + l / 2]; } int** mat5 = new int* [l / 2]; for (int i = 0; i < l / 2; i++) { mat5[i] = new int[l / 2]; for (int j = 0; j < l / 2; j++) mat5[i][j] = M4[i][j]; } int** mat6 = new int* [l / 2]; for (int i = 0; i < l / 2; i++) { mat6[i] = new int[l / 2]; for (int j = 0; j < l / 2; j++) mat6[i][j] = M4[i][j + l / 2]; } int** mat7 = new int* [l / 2]; for (int i = 0; i < l / 2; i++) { mat7[i] = new int[l / 2]; for (int j = 0; j < l / 2; j++) mat7[i][j] = M4[i + l / 2][j]; } int** mat8 = new int* [l / 2]; for (int i = 0; i < l / 2; i++) { mat8[i] = new int[l / 2]; for (int j = 0; j < l / 2; j++) mat8[i][j] = M4[i + l / 2][j + l / 2]; } /////////////////////////////////////////////////////////////////////////////// ////////////////////////�������� ������������� ������////////////////////////// /////////////////////////////////////////////////////////////////////////////// int** p1 = new int* [l / 2]; for (int i = 0; i < l / 2; i++) { p1[i] = new int[l / 2]; } int** p2 = new int* [l / 2]; for (int i = 0; i < l / 2; i++) { p2[i] = new int[l / 2]; } int** p3 = new int* [l / 2]; for (int i = 0; i < l / 2; i++) { p3[i] = new int[l / 2]; } int** p4 = new int* [l / 2]; for (int i = 0; i < l / 2; i++) { p4[i] = new int[l / 2]; } int** p5 = new int* [l / 2]; for (int i = 0; i < l / 2; i++) { p5[i] = new int[l / 2]; } int** p6 = new int* [l / 2]; for (int i = 0; i < l / 2; i++) { p6[i] = new int[l / 2]; } int** p7 = new int* [l / 2]; for (int i = 0; i < l / 2; i++) { p7[i] = new int[l / 2]; } /////////////////////////////////////////////////////////////////////////////// ////////////////////���������� �������� ������������� ������/////////////////// /////////////////////////////////////////////////////////////////////////////// for (int i = 0; i < l / 2; i++) { for (int j = 0; j < l / 2; j++) { p1[i][j] = 0; for (int z = 0; z < l / 2; z++) { p1[i][j] += (mat1[i][z] + mat4[i][z]) * (mat5[z][j] + mat8[z][j]); } p2[i][j] = 0; for (int z = 0; z < l / 2; z++) { p2[i][j] += (mat3[i][z] + mat4[i][z]) * mat5[z][j]; } p3[i][j] = 0; for (int z = 0; z < l / 2; z++) { p3[i][j] += mat1[i][z] * (mat6[z][j] - mat8[z][j]); } p4[i][j] = 0; for (int z = 0; z < l / 2; z++) { p4[i][j] += mat4[i][z] * (mat7[z][j] - mat5[z][j]); } p5[i][j] = 0; for (int z = 0; z < l / 2; z++) { p5[i][j] += (mat1[i][z] + mat2[i][z]) * mat8[z][j]; } p6[i][j] = 0; for (int z = 0; z < l / 2; z++) { p6[i][j] += (mat3[i][z] - mat1[i][z]) * (mat5[z][j] + mat6[z][j]); } p7[i][j] = 0; for (int z = 0; z < l / 2; z++) { p7[i][j] += (mat2[i][z] - mat4[i][z]) * (mat7[z][j] + mat8[z][j]); } } } /////////////////////////////////////////////////////////////////////////////// ///////////////////////�������� ��������������� ������///////////////////////// /////////////////////////////////////////////////////////////////////////////// int** mat9 = new int* [l / 2]; for (int i = 0; i < l / 2; i++) { mat9[i] = new int[l / 2]; } int** mat10 = new int* [l / 2]; for (int i = 0; i < l / 2; i++) { mat10[i] = new int[l / 2]; } int** mat11 = new int* [l / 2]; for (int i = 0; i < l / 2; i++) { mat11[i] = new int[l / 2]; } int** mat12 = new int* [l / 2]; for (int i = 0; i < l / 2; i++) { mat12[i] = new int[l / 2]; } /////////////////////////////////////////////////////////////////////////////// ////////////������� �������� ��������������� ������ �� �������������/////////// /////////////////////////////////////////////////////////////////////////////// for (int i = 0; i < l / 2; i++) { for (int j = 0; j < l / 2; j++) { mat9[i][j] = p1[i][j] + p4[i][j] - p5[i][j] + p7[i][j]; mat10[i][j] = p3[i][j] + p5[i][j]; mat11[i][j] = p2[i][j] + p4[i][j]; mat12[i][j] = p1[i][j] - p2[i][j] + p3[i][j] + p6[i][j]; } } /////////////////////////////////////////////////////////////////////////////// ///////////////////�������� �������������� �������///////////////////////////// /////////////////////////////////////////////////////////////////////////////// int** M5 = new int* [l]; for (int i = 0; i < l; i++) { M5[i] = new int[l]; } /////////////////////////////////////////////////////////////////////////////// ///////��������� ���������� �� ��������������� ������ � ��������������///////// /////////////////////////////////////////////////////////////////////////////// for (int i = 0; i < l / 2; i++) { for (int j = 0; j < l / 2; j++) { M5[i][j] = mat9[i][j]; M5[i][j + l / 2] = mat10[i][j]; M5[i + l / 2][j] = mat11[i][j]; M5[i + l / 2][j + l / 2] = mat12[i][j]; } } /////////////////////////////////////////////////////////////////////////////// ////////////////������������ ������ �������������� �������///////////////////// /////////////////////////////////////////////////////////////////////////////// int x = 0, f = 100, s = 100; for (int i = 0; i < l; i++) { x = 0; for (int j = 0; j < l; j++) { if (M5[i][j] != 0) { x++; f = 100; } } if (x == 0 && i < f) { f = i; } } for (int i = 0; i < l; i++) { x = 0; for (int j = 0; j < l; j++) { if (M5[j][i] != 0) { x++; s = 100; } } if (x == 0 && i < s) { s = i; } } int** M6 = new int* [f]; for (int i = 0; i < f; i++) { M6[i] = new int[s]; for (int j = 0; j < s; j++) M6[i][j] = M5[i][j]; } /////////////////////////////////////////////////////////////////////////////// ///////////////////����� �������������� �������//////////////////////////////// /////////////////////////////////////////////////////////////////////////////// cout << "\n�������������� �������\n\n"; for (int i = 0; i < f; i++) { for (int j = 0; j < s; j++) cout << M6[i][j] << " "; cout << endl; } system("pause"); /////////////////////////////////////////////////////////////////////////////// /////////////////////������� ������������ ������/////////////////////////////// /////////////////////////////////////////////////////////////////////////////// for (int i = 0; i < n1; i++) delete[] M1[i]; for (int i = 0; i < n2; i++) delete[] M2[i]; for (int i = 0; i < l; i++) { delete[] M3[i]; delete[] M4[i]; delete[] M5[i]; } for (int i = 0; i < f; i++) delete[] M6[i]; for (int i = 0; i < l / 2; i++) { delete[] mat1[i]; delete[] mat2[i]; delete[] mat3[i]; delete[] mat4[i]; delete[] mat5[i]; delete[] mat6[i]; delete[] mat7[i]; delete[] mat8[i]; delete[] mat9[i]; delete[] mat10[i]; delete[] mat11[i]; delete[] mat12[i]; delete[] p1[i]; delete[] p2[i]; delete[] p3[i]; delete[] p4[i]; delete[] p5[i]; delete[] p6[i]; delete[] p7[i]; } delete[] M1, M2, M3, M4, M5, M6; delete[] mat1, mat2, mat3, mat4, mat5, mat6, mat7, mat8, mat9, mat10, mat11, mat12; delete[] p1, p2, p3, p4, p5, p6, p7; return 0; }
25.11349
85
0.255286
ChernichenkoStephan
02d180afd06642b3b4302d112e23071fd11023cd
29,393
cpp
C++
dep/acelite/ace/SOCK_Dgram_Mcast.cpp
forgottenlands/ForgottenCore406
5dbbef6b3b0b17c277fde85e40ec9fdab0b51ad1
[ "OpenSSL" ]
42
2015-01-05T10:00:07.000Z
2022-02-18T14:51:33.000Z
dep/acelite/ace/SOCK_Dgram_Mcast.cpp
Frankenhooker/ArkCORE
0a7be7fc0b67e9ef3de421ab5de6012eac7dec6d
[ "OpenSSL" ]
null
null
null
dep/acelite/ace/SOCK_Dgram_Mcast.cpp
Frankenhooker/ArkCORE
0a7be7fc0b67e9ef3de421ab5de6012eac7dec6d
[ "OpenSSL" ]
31
2015-01-09T02:04:29.000Z
2021-09-01T13:20:20.000Z
// $Id: SOCK_Dgram_Mcast.cpp 92580 2010-11-15 09:48:02Z johnnyw $ #include "ace/SOCK_Dgram_Mcast.h" #include "ace/OS_Memory.h" #include "ace/OS_NS_string.h" #include "ace/OS_NS_errno.h" #include "ace/os_include/net/os_if.h" #include "ace/os_include/arpa/os_inet.h" #if defined (__linux__) && defined (ACE_HAS_IPV6) #include "ace/OS_NS_sys_socket.h" #endif #if defined (ACE_HAS_IPV6) && defined (ACE_WIN32) #include /**/ <iphlpapi.h> #endif #if !defined (__ACE_INLINE__) #include "ace/SOCK_Dgram_Mcast.inl" #endif /* __ACE_INLINE__ */ #include "ace/Log_Msg.h" // This is a workaround for platforms with non-standard // definitions of the ip_mreq structure #if ! defined (IMR_MULTIADDR) #define IMR_MULTIADDR imr_multiaddr #endif /* ! defined (IMR_MULTIADDR) */ ACE_BEGIN_VERSIONED_NAMESPACE_DECL // Helper (inline) functions. class ACE_SDM_helpers { public: // Convert ACE_INET_Addr to string, using local formatting rules. static void addr_to_string (const ACE_INET_Addr &ip_addr, ACE_TCHAR *ret_string, // results here. size_t len, int clip_portnum) // clip port# info? { if (ip_addr.addr_to_string (ret_string, len, 1) == -1) ACE_OS::strcpy (ret_string, ACE_TEXT ("<?>")); else { ACE_TCHAR *pc = ACE_OS::strrchr (ret_string, ACE_TEXT (':')); if (clip_portnum && pc) *pc = ACE_TEXT ('\0'); // clip port# info. } } // op== for ip_mreq structs. static int is_equal (const ip_mreq &m1, const ip_mreq &m2) { return m1.IMR_MULTIADDR.s_addr == m2.IMR_MULTIADDR.s_addr && m1.imr_interface.s_addr == m2.imr_interface.s_addr; } }; ACE_ALLOC_HOOK_DEFINE (ACE_SOCK_Dgram_Mcast) void ACE_SOCK_Dgram_Mcast::dump (void) const { #if defined (ACE_HAS_DUMP) ACE_TRACE ("ACE_SOCK_Dgram_Mcast::dump"); ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); # if defined (ACE_SOCK_DGRAM_MCAST_DUMPABLE) ACE_TCHAR addr_string[MAXNAMELEN + 1]; ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nOptions: bindaddr=%s, nulliface=%s\n"), ACE_BIT_ENABLED (this->opts_, OPT_BINDADDR_YES) ? ACE_TEXT ("<Bound>") : ACE_TEXT ("<Not Bound>"), ACE_BIT_ENABLED (this->opts_, OPT_NULLIFACE_ALL) ? ACE_TEXT ("<All Ifaces>") : ACE_TEXT ("<Default Iface>"))); // Show default send addr, port#, and interface. ACE_SDM_helpers::addr_to_string (this->send_addr_, addr_string, sizeof addr_string, 0); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Send addr=%s iface=%s\n"), addr_string, this->send_net_if_ ? this->send_net_if_ : ACE_TEXT ("<default>"))); // Show list of subscribed addresses. ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Subscription list:\n"))); ACE_MT (ACE_GUARD (ACE_SDM_LOCK, guard, this->subscription_list_lock_)); subscription_list_iter_t iter (this->subscription_list_); for ( ; !iter.done (); iter.advance ()) { ACE_TCHAR iface_string[MAXNAMELEN + 1]; ip_mreq *pm = iter.next (); // Get subscribed address (w/out port# info - not relevant). ACE_INET_Addr ip_addr (static_cast<u_short> (0), ACE_NTOHL (pm->IMR_MULTIADDR.s_addr)); ACE_SDM_helpers::addr_to_string (ip_addr, addr_string, sizeof addr_string, 1); // Get interface address/specification. ACE_INET_Addr if_addr (static_cast<u_short> (0), ACE_NTOHL (pm->imr_interface.s_addr)); ACE_SDM_helpers::addr_to_string (if_addr, iface_string, sizeof iface_string, 1); if (ACE_OS::strcmp (iface_string, ACE_TEXT ("0.0.0.0")) == 0) // Receives on system default iface. (Note that null_iface_opt_ // option processing has already occurred.) ACE_OS::strcpy (iface_string, ACE_TEXT ("<default>")); // Dump info. ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\taddr=%s iface=%s\n"), addr_string, iface_string)); } # endif /* ACE_SOCK_DGRAM_MCAST_DUMPABLE */ ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); #endif /* ACE_HAS_DUMP */ } // Constructor. ACE_SOCK_Dgram_Mcast::ACE_SOCK_Dgram_Mcast (ACE_SOCK_Dgram_Mcast::options opts) : opts_ (opts), send_net_if_ (0) { ACE_TRACE ("ACE_SOCK_Dgram_Mcast::ACE_SOCK_Dgram_Mcast"); } // Destructor. ACE_SOCK_Dgram_Mcast::~ACE_SOCK_Dgram_Mcast (void) { ACE_TRACE ("ACE_SOCK_Dgram_Mcast::~ACE_SOCK_Dgram_Mcast"); // Free memory and optionally unsubscribe from currently subscribed group(s). delete [] this->send_net_if_; this->clear_subs_list (); } int ACE_SOCK_Dgram_Mcast::open (const ACE_INET_Addr &mcast_addr, const ACE_TCHAR *net_if, int reuse_addr) { ACE_TRACE ("ACE_SOCK_Dgram_Mcast::open"); // Only perform the <open> initialization if we haven't been opened // earlier. // No sanity check? We should probably flag an error if the user // makes multiple calls to open(). if (this->get_handle () != ACE_INVALID_HANDLE) return 0; // Invoke lower-layer ::open. if (ACE_SOCK::open (SOCK_DGRAM, mcast_addr.get_type (), 0, // always use 0 reuse_addr) == -1) return -1; return this->open_i (mcast_addr, net_if, reuse_addr); } int ACE_SOCK_Dgram_Mcast::open_i (const ACE_INET_Addr &mcast_addr, const ACE_TCHAR *net_if, int reuse_addr) { ACE_TRACE ("ACE_SOCK_Dgram_Mcast::open_i"); // ACE_SOCK::open calls this if reuse_addr is set, so we only need to // process port reuse option. if (reuse_addr) { #if defined (SO_REUSEPORT) int one = 1; if (this->ACE_SOCK::set_option (SOL_SOCKET, SO_REUSEPORT, &one, sizeof one) == -1) return -1; #endif /* SO_REUSEPORT */ } // Create an address/port# to bind the socket to. Use mcast_addr to // initialize bind_addy to pick up the correct protocol family. If // OPT_BINDADDR_YES is set, then we're done. Else use mcast_addr's // port number and use the "any" address. ACE_INET_Addr bind_addy (mcast_addr); if (ACE_BIT_DISABLED (this->opts_, OPT_BINDADDR_YES)) { #if defined (ACE_HAS_IPV6) if (mcast_addr.get_type () == PF_INET6) { if (bind_addy.set (mcast_addr.get_port_number (), "::", 1, AF_INET6) == -1) return -1; } else // Bind to "any" address and explicit port#. if (bind_addy.set (mcast_addr.get_port_number ()) == -1) return -1; #else // Bind to "any" address and explicit port#. if (bind_addy.set (mcast_addr.get_port_number ()) == -1) return -1; #endif /* ACE_HAS_IPV6 */ } // Bind to the address (which may be INADDR_ANY) and port# (which may be 0) if (ACE_SOCK_Dgram::shared_open (bind_addy, bind_addy.get_type ()) == -1) return -1; // Cache the actual bound address (which may be INADDR_ANY) // and the actual bound port# (which will be a valid, non-zero port#). ACE_INET_Addr bound_addy; if (this->get_local_addr (bound_addy) == -1) { // (Unexpected failure - should be bound to something) if (bound_addy.set (bind_addy) == -1) { // (Shouldn't happen - bind_addy is a valid addy; punt.) return -1; } } this->send_addr_ = mcast_addr; this->send_addr_.set_port_number (bound_addy.get_port_number ()); if (net_if) { if (this->set_nic (net_if, mcast_addr.get_type ())) return -1; this->send_net_if_ = new ACE_TCHAR[ACE_OS::strlen (net_if) + 1]; ACE_OS::strcpy (this->send_net_if_, net_if); } return 0; } int ACE_SOCK_Dgram_Mcast::subscribe_ifs (const ACE_INET_Addr &mcast_addr, const ACE_TCHAR *net_if, int reuse_addr) { ACE_TRACE ("ACE_SOCK_Dgram_Mcast::subscribe_ifs"); if (ACE_BIT_ENABLED (this->opts_, OPT_NULLIFACE_ALL) && net_if == 0) { #if defined (ACE_HAS_IPV6) if (mcast_addr.get_type () == AF_INET6) { size_t nr_subscribed = 0; # if defined(__linux__) struct if_nameindex *intf = 0; intf = ACE_OS::if_nameindex (); if (intf == 0) return -1; int index = 0; while (intf[index].if_index != 0 || intf[index].if_name != 0) { if (this->join (mcast_addr, reuse_addr, ACE_TEXT_CHAR_TO_TCHAR(intf[index].if_name)) == 0) ++nr_subscribed; ++index; } ACE_OS::if_freenameindex (intf); # elif defined (ACE_WIN32) IP_ADAPTER_ADDRESSES tmp_addrs; // Initial call to determine actual memory size needed DWORD dwRetVal; ULONG bufLen = 0; if ((dwRetVal = ::GetAdaptersAddresses (AF_INET6, 0, 0, &tmp_addrs, &bufLen)) != ERROR_BUFFER_OVERFLOW) return -1; // With output bufferlength 0 this can't be right. // Get required output buffer and retrieve info for real. PIP_ADAPTER_ADDRESSES pAddrs; char *buf; ACE_NEW_RETURN (buf, char[bufLen], -1); pAddrs = reinterpret_cast<PIP_ADAPTER_ADDRESSES> (buf); if ((dwRetVal = ::GetAdaptersAddresses (AF_INET6, 0, 0, pAddrs, &bufLen)) != NO_ERROR) { delete[] buf; // clean up return -1; } while (pAddrs) { if (this->join (mcast_addr, reuse_addr, ACE_TEXT_CHAR_TO_TCHAR(pAddrs->AdapterName)) == 0) ++nr_subscribed; pAddrs = pAddrs->Next; } delete[] buf; // clean up # endif /* ACE_WIN32 */ if (nr_subscribed == 0) { errno = ENODEV; return -1; } return 1; } else { // Subscribe on all local multicast-capable network interfaces, by // doing recursive calls with specific interfaces. ACE_INET_Addr *if_addrs = 0; size_t if_cnt; if (ACE::get_ip_interfaces (if_cnt, if_addrs) != 0) return -1; size_t nr_subscribed = 0; if (if_cnt < 2) { if (this->join (mcast_addr, reuse_addr, ACE_TEXT ("0.0.0.0")) == 0) ++nr_subscribed; } else { // Iterate through all the interfaces, figure out which ones // offer multicast service, and subscribe to them. while (if_cnt > 0) { --if_cnt; // Convert to 0-based for indexing, next loop check. if (if_addrs[if_cnt].get_type () != AF_INET || if_addrs[if_cnt].is_loopback ()) continue; char addr_buf[INET6_ADDRSTRLEN]; if (this->join (mcast_addr, reuse_addr, ACE_TEXT_CHAR_TO_TCHAR (if_addrs[if_cnt].get_host_addr (addr_buf, INET6_ADDRSTRLEN))) == 0) ++nr_subscribed; } } delete [] if_addrs; if (nr_subscribed == 0) { errno = ENODEV; return -1; } // 1 indicates a "short-circuit" return. This handles the // recursive behavior of checking all the interfaces. return 1; } #else // Subscribe on all local multicast-capable network interfaces, by // doing recursive calls with specific interfaces. ACE_INET_Addr *if_addrs = 0; size_t if_cnt; if (ACE::get_ip_interfaces (if_cnt, if_addrs) != 0) return -1; size_t nr_subscribed = 0; if (if_cnt < 2) { if (this->join (mcast_addr, reuse_addr, ACE_TEXT ("0.0.0.0")) == 0) ++nr_subscribed; } else { // Iterate through all the interfaces, figure out which ones // offer multicast service, and subscribe to them. while (if_cnt > 0) { --if_cnt; // Convert to 0-based for indexing, next loop check. if (if_addrs[if_cnt].is_loopback ()) continue; char addr_buf[INET6_ADDRSTRLEN]; if (this->join (mcast_addr, reuse_addr, ACE_TEXT_CHAR_TO_TCHAR (if_addrs[if_cnt].get_host_addr (addr_buf, INET6_ADDRSTRLEN))) == 0) ++nr_subscribed; } } delete [] if_addrs; if (nr_subscribed == 0) { errno = ENODEV; return -1; } // 1 indicates a "short-circuit" return. This handles the // recursive behavior of checking all the interfaces. return 1; #endif /* ACE_HAS_IPV6 */ } #if defined (ACE_HAS_IPV6) if (mcast_addr.get_type () == AF_INET6) { if (this->make_multicast_ifaddr6 (0, mcast_addr, net_if) == -1) return -1; } else { // Validate passed multicast addr and iface specifications. if (this->make_multicast_ifaddr (0, mcast_addr, net_if) == -1) return -1; } #else // Validate passed multicast addr and iface specifications. if (this->make_multicast_ifaddr (0, mcast_addr, net_if) == -1) return -1; #endif /* ACE_HAS_IPV6 */ return 0; } int ACE_SOCK_Dgram_Mcast::join (const ACE_INET_Addr &mcast_addr, int reuse_addr, const ACE_TCHAR *net_if) { ACE_TRACE ("ACE_SOCK_Dgram_Mcast::join"); ACE_INET_Addr subscribe_addr = mcast_addr; // If port# is 0, insert bound port# if it is set. (To satisfy lower-level // port# validation.) u_short def_port_number = this->send_addr_.get_port_number (); if (subscribe_addr.get_port_number () == 0 && def_port_number != 0) { subscribe_addr.set_port_number (def_port_number); } // Check for port# different than bound port#. u_short sub_port_number = mcast_addr.get_port_number (); if (sub_port_number != 0 && def_port_number != 0 && sub_port_number != def_port_number) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("Subscribed port# (%u) different than bound ") ACE_TEXT ("port# (%u).\n"), (u_int) sub_port_number, (u_int) def_port_number)); errno = ENXIO; return -1; } // If bind_addr_opt_ is enabled, check for address different than // bound address. ACE_INET_Addr tmp_addr (this->send_addr_); tmp_addr.set_port_number (mcast_addr.get_port_number ()); // force equal port numbers if (ACE_BIT_ENABLED (this->opts_, OPT_BINDADDR_YES) && !this->send_addr_.is_any () && this->send_addr_ != mcast_addr) { ACE_TCHAR sub_addr_string[MAXNAMELEN + 1]; ACE_TCHAR bound_addr_string[MAXNAMELEN + 1]; ACE_SDM_helpers::addr_to_string (mcast_addr, sub_addr_string, sizeof sub_addr_string, 1); ACE_SDM_helpers::addr_to_string (this->send_addr_, bound_addr_string, sizeof bound_addr_string, 1); ACE_ERROR ((LM_ERROR, ACE_TEXT ("Subscribed address (%s) different than ") ACE_TEXT ("bound address (%s).\n"), sub_addr_string, bound_addr_string)); errno = ENXIO; return -1; } // Attempt subscription. int result = this->subscribe_i (subscribe_addr, reuse_addr, net_if); #if defined (ACE_SOCK_DGRAM_MCAST_DUMPABLE) if (result == 0) { // Add this addr/iface info to the list of subscriptions. // (Assumes this is unique addr/iface combo - most systems don't allow // re-sub to same addr/iface.) ip_mreq *pmreq = new ip_mreq; // (should not fail) if (this->make_multicast_ifaddr (pmreq, subscribe_addr, net_if) != -1) { ACE_MT (ACE_GUARD_RETURN (ACE_SDM_LOCK, guard, this->subscription_list_lock_, -1)); this->subscription_list_.insert_tail (pmreq); return 0; } // this still isn't really right. If ACE_GUARD_RETURN fails, we leak. // Need to add one of Chris' fancy ace auto pointers (bound?). delete pmreq; } #endif /* ACE_SOCK_DGRAM_MCAST_DUMPABLE */ return result >= 0 ? 0 : result; } // Attempt subscribe and return status. int ACE_SOCK_Dgram_Mcast::subscribe_i (const ACE_INET_Addr &mcast_addr, int reuse_addr, const ACE_TCHAR *net_if) { ACE_TRACE ("ACE_SOCK_Dgram_Mcast::subscribe_i"); ip_mreq mreq; #if defined (ACE_HAS_IPV6) ipv6_mreq mreq6; #endif /* __linux__ && ACE_HAS_IPV6 */ // Open the socket IFF this is the first ::subscribe and ::open // was not explicitly invoked. if (this->open (mcast_addr, net_if, reuse_addr) == -1) return -1; // Only do this if net_if == 0, i.e., INADDR_ANY if (net_if == 0) { int result = this->subscribe_ifs (mcast_addr, net_if, reuse_addr); // Check for error or "short-circuit" return. if (result != 0) return result; } #if defined (ACE_HAS_IPV6) if (mcast_addr.get_type () == AF_INET6) { if (this->make_multicast_ifaddr6 (&mreq6, mcast_addr, net_if) == -1) return -1; // Tell IP stack to pass messages sent to this group. else if (this->ACE_SOCK::set_option (IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq6, sizeof mreq6) == -1) return -1; return 0; } // Fall through for IPv4 case #endif /* ACE_HAS_IPV6 */ // Create multicast addr/if struct. if (this->make_multicast_ifaddr (&mreq, mcast_addr, net_if) == -1) return -1; // Tell IP stack to pass messages sent to this group. else if (this->ACE_SOCK::set_option (IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof mreq) == -1) return -1; return 0; } int ACE_SOCK_Dgram_Mcast::unsubscribe_ifs (const ACE_INET_Addr &mcast_addr, const ACE_TCHAR *net_if) { ACE_TRACE ("ACE_SOCK_Dgram_Mcast::unsubscribe_ifs"); if (ACE_BIT_ENABLED (this->opts_, OPT_NULLIFACE_ALL) && net_if == 0) { #if defined (ACE_HAS_IPV6) if (mcast_addr.get_type () == AF_INET6) { size_t nr_unsubscribed = 0; # if defined(__linux__) struct if_nameindex *intf; intf = ACE_OS::if_nameindex (); if (intf == 0) return -1; int index = 0; while (intf[index].if_index != 0 || intf[index].if_name != 0) { if (this->leave (mcast_addr, ACE_TEXT_CHAR_TO_TCHAR(intf[index].if_name)) == 0) ++nr_unsubscribed; ++index; } ACE_OS::if_freenameindex (intf); # elif defined (ACE_WIN32) IP_ADAPTER_ADDRESSES tmp_addrs; // Initial call to determine actual memory size needed DWORD dwRetVal; ULONG bufLen = 0; if ((dwRetVal = ::GetAdaptersAddresses (AF_INET6, 0, 0, &tmp_addrs, &bufLen)) != ERROR_BUFFER_OVERFLOW) return -1; // With output bufferlength 0 this can't be right. // Get required output buffer and retrieve info for real. PIP_ADAPTER_ADDRESSES pAddrs; char *buf; ACE_NEW_RETURN (buf, char[bufLen], -1); pAddrs = reinterpret_cast<PIP_ADAPTER_ADDRESSES> (buf); if ((dwRetVal = ::GetAdaptersAddresses (AF_INET6, 0, 0, pAddrs, &bufLen)) != NO_ERROR) { delete[] buf; // clean up return -1; } while (pAddrs) { if (this->leave (mcast_addr, ACE_TEXT_CHAR_TO_TCHAR(pAddrs->AdapterName)) == 0) ++nr_unsubscribed; pAddrs = pAddrs->Next; } delete[] buf; // clean up # endif /* ACE_WIN32 */ if (nr_unsubscribed == 0) { errno = ENODEV; return -1; } return 1; } else { // Unsubscribe on all local multicast-capable network interfaces, by // doing recursive calls with specific interfaces. ACE_INET_Addr *if_addrs = 0; size_t if_cnt; // NOTE - <get_ip_interfaces> doesn't always get all of the // interfaces. In particular, it may not get a PPP interface. This // is a limitation of the way <get_ip_interfaces> works with // old versions of MSVC. The reliable way of getting the interface // list is available only with MSVC 5 and newer. if (ACE::get_ip_interfaces (if_cnt, if_addrs) != 0) return -1; size_t nr_unsubscribed = 0; if (if_cnt < 2) { if (this->leave (mcast_addr, ACE_TEXT ("0.0.0.0")) == 0) ++nr_unsubscribed; } else { while (if_cnt > 0) { --if_cnt; // Convert to 0-based for indexing, next loop check if (if_addrs[if_cnt].get_type () != AF_INET || if_addrs[if_cnt].is_loopback ()) continue; char addr_buf[INET6_ADDRSTRLEN]; if (this->leave (mcast_addr, ACE_TEXT_CHAR_TO_TCHAR (if_addrs[if_cnt].get_host_addr (addr_buf, INET6_ADDRSTRLEN))) == 0) ++nr_unsubscribed; } } delete [] if_addrs; if (nr_unsubscribed == 0) { errno = ENODEV; return -1; } return 1; } #else /* ACE_HAS_IPV6 */ // Unsubscribe on all local multicast-capable network interfaces, by // doing recursive calls with specific interfaces. ACE_INET_Addr *if_addrs = 0; size_t if_cnt; // NOTE - <get_ip_interfaces> doesn't always get all of the // interfaces. In particular, it may not get a PPP interface. This // is a limitation of the way <get_ip_interfaces> works with // old versions of MSVC. The reliable way of getting the interface list // is available only with MSVC 5 and newer. if (ACE::get_ip_interfaces (if_cnt, if_addrs) != 0) return -1; size_t nr_unsubscribed = 0; if (if_cnt < 2) { if (this->leave (mcast_addr, ACE_TEXT ("0.0.0.0")) == 0) ++nr_unsubscribed; } else { while (if_cnt > 0) { --if_cnt; // Convert to 0-based for indexing, next loop check if (if_addrs[if_cnt].is_loopback ()) continue; char addr_buf[INET6_ADDRSTRLEN]; if (this->leave (mcast_addr, ACE_TEXT_CHAR_TO_TCHAR (if_addrs[if_cnt].get_host_addr (addr_buf, INET6_ADDRSTRLEN))) == 0) ++nr_unsubscribed; } } delete [] if_addrs; if (nr_unsubscribed == 0) { errno = ENODEV; return -1; } return 1; #endif /* !ACE_HAS_IPV6 */ } return 0; } int ACE_SOCK_Dgram_Mcast::leave (const ACE_INET_Addr &mcast_addr, const ACE_TCHAR *net_if) { ACE_TRACE ("ACE_SOCK_Dgram_Mcast::leave"); // Unsubscribe. int result = this->unsubscribe_i (mcast_addr, net_if); #if defined (ACE_SOCK_DGRAM_MCAST_DUMPABLE) // (Unconditionally) Remove this addr/if from subscription list. // (Addr/if is removed even if unsubscribe failed) ip_mreq tgt_mreq; if (this->make_multicast_ifaddr (&tgt_mreq, mcast_addr, net_if) != -1) { ACE_MT (ACE_GUARD_RETURN (ACE_SDM_LOCK, guard, this->subscription_list_lock_, -1)); subscription_list_iter_t iter (this->subscription_list_); for (; !iter.done (); iter.advance ()) { ip_mreq *pm = iter.next (); if (ACE_SDM_helpers::is_equal (*pm, tgt_mreq)) { iter.remove (); delete pm; break; } } } #endif /* ACE_SOCK_DGRAM_MCAST_DUMPABLE */ return result >= 0 ? 0 : result; } // Attempt unsubscribe and return status. int ACE_SOCK_Dgram_Mcast::unsubscribe_i (const ACE_INET_Addr &mcast_addr, const ACE_TCHAR *net_if) { ACE_TRACE ("ACE_SOCK_Dgram_Mcast::unsubscribe_i"); int result = this->unsubscribe_ifs (mcast_addr, net_if); // Check for error or "short-circuit" return. if (result != 0) return result; #if defined (ACE_HAS_IPV6) if (mcast_addr.get_type () == AF_INET6) { // Validate addr/if specifications and create addr/if struct. ipv6_mreq mreq; if (this->make_multicast_ifaddr6 (&mreq, mcast_addr, net_if) == -1) { return -1; } // Tell network device driver to stop reading datagrams with the // <mcast_addr>. else if (ACE_SOCK::set_option (IPPROTO_IPV6, IPV6_LEAVE_GROUP, &mreq, sizeof mreq) == -1) { return -1; } } else // IPv4 { // Validate addr/if specifications and create addr/if struct. ip_mreq mreq; if (this->make_multicast_ifaddr (&mreq, mcast_addr, net_if) == -1) { return -1; } // Tell network device driver to stop reading datagrams with the // <mcast_addr>. else if (ACE_SOCK::set_option (IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreq, sizeof mreq) == -1) { return -1; } } #else // Validate addr/if specifications and create addr/if struct. ip_mreq mreq; if (this->make_multicast_ifaddr (&mreq, mcast_addr, net_if) == -1) { return -1; } // Tell network device driver to stop reading datagrams with the // <mcast_addr>. // Note, this is not IPv6 friendly... else if (ACE_SOCK::set_option (IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreq, sizeof mreq) == -1) { return -1; } #endif /* ACE_HAS_IPV6 */ return 0; } int ACE_SOCK_Dgram_Mcast::clear_subs_list (void) { ACE_TRACE ("ACE_SOCK_Dgram_Mcast::clear_subs_list"); int result = 0; #if defined (ACE_SOCK_DGRAM_MCAST_DUMPABLE) ACE_MT (ACE_GUARD_RETURN (ACE_SDM_LOCK, guard, this->subscription_list_lock_, -1)); subscription_list_iter_t iter (this->subscription_list_); for (; !iter.done (); /*Hack: Do _not_ ::advance after remove*/) { ip_mreq *pm = iter.next (); iter.remove (); delete pm; } #endif /* ACE_SOCK_DGRAM_MCAST_DUMPABLE */ return result; } ACE_END_VERSIONED_NAMESPACE_DECL
31.983678
105
0.532746
forgottenlands
02d2c027ad40ad44e9b0183dcfbda42297b28a2c
2,225
cpp
C++
3rdParty/iresearch/core/search/bitset_doc_iterator.cpp
snykiotcubedev/arangodb-3.7.6
fce8f85f1c2f070c8e6a8e76d17210a2117d3833
[ "Apache-2.0" ]
null
null
null
3rdParty/iresearch/core/search/bitset_doc_iterator.cpp
snykiotcubedev/arangodb-3.7.6
fce8f85f1c2f070c8e6a8e76d17210a2117d3833
[ "Apache-2.0" ]
109
2022-01-06T07:05:24.000Z
2022-03-21T01:39:35.000Z
3rdParty/iresearch/core/search/bitset_doc_iterator.cpp
snykiotcubedev/arangodb-3.7.6
fce8f85f1c2f070c8e6a8e76d17210a2117d3833
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2017 ArangoDB GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Andrey Abramov //////////////////////////////////////////////////////////////////////////////// #include "bitset_doc_iterator.hpp" #include "formats/empty_term_reader.hpp" #include "utils/bitset.hpp" #include "utils/math_utils.hpp" namespace iresearch { attribute* bitset_doc_iterator::get_mutable(type_info::type_id id) noexcept { if (type<document>::id() == id) { return &doc_; } return type<cost>::id() == id ? &cost_ : nullptr; } bool bitset_doc_iterator::next() noexcept { while (!word_) { if (next_ >= end_) { if (refill(&begin_, &end_)) { reset(); continue; } doc_.value = doc_limits::eof(); word_ = 0; return false; } word_ = *next_++; base_ += bits_required<word_t>(); } const doc_id_t delta = math::math_traits<word_t>::ctz(word_); irs::unset_bit(word_, delta); doc_.value = base_ + delta; return true; } doc_id_t bitset_doc_iterator::seek(doc_id_t target) noexcept { while (1) { next_ = begin_ + bitset::word(target); if (next_ >= end_) { if (refill(&begin_, &end_)) { reset(); continue; } doc_.value = doc_limits::eof(); word_ = 0; return doc_.value; } break; } base_ = doc_id_t(std::distance(begin_, next_) * bits_required<word_t>()); word_ = (*next_++) & ((~word_t(0)) << bitset::bit(target)); next(); return doc_.value; } } // ROOT
24.184783
80
0.593258
snykiotcubedev