blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
14a7f65505d1d94328bb28b7644b59f18e88b3ee | 3438e8c139a5833836a91140af412311aebf9e86 | /third_party/WebKit/Source/platform/heap/Heap.cpp | 5388141f90f104d79b1bfcb46fe3ebd1fdc0b688 | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0"
] | permissive | Exstream-OpenSource/Chromium | 345b4336b2fbc1d5609ac5a67dbf361812b84f54 | 718ca933938a85c6d5548c5fad97ea7ca1128751 | refs/heads/master | 2022-12-21T20:07:40.786370 | 2016-10-18T04:53:43 | 2016-10-18T04:53:43 | 71,210,435 | 0 | 2 | BSD-3-Clause | 2022-12-18T12:14:22 | 2016-10-18T04:58:13 | null | UTF-8 | C++ | false | false | 23,411 | cpp | /*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "platform/heap/Heap.h"
#include "base/sys_info.h"
#include "platform/Histogram.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/ScriptForbiddenScope.h"
#include "platform/heap/BlinkGCMemoryDumpProvider.h"
#include "platform/heap/CallbackStack.h"
#include "platform/heap/MarkingVisitor.h"
#include "platform/heap/PageMemory.h"
#include "platform/heap/PagePool.h"
#include "platform/heap/SafePoint.h"
#include "platform/heap/ThreadState.h"
#include "platform/tracing/TraceEvent.h"
#include "platform/tracing/web_memory_allocator_dump.h"
#include "platform/tracing/web_process_memory_dump.h"
#include "public/platform/Platform.h"
#include "wtf/Assertions.h"
#include "wtf/CurrentTime.h"
#include "wtf/DataLog.h"
#include "wtf/LeakAnnotations.h"
#include "wtf/PtrUtil.h"
#include "wtf/allocator/Partitions.h"
#include <memory>
namespace blink {
HeapAllocHooks::AllocationHook* HeapAllocHooks::m_allocationHook = nullptr;
HeapAllocHooks::FreeHook* HeapAllocHooks::m_freeHook = nullptr;
class ParkThreadsScope final {
STACK_ALLOCATED();
public:
explicit ParkThreadsScope(ThreadState* state)
: m_state(state), m_shouldResumeThreads(false) {}
bool parkThreads() {
TRACE_EVENT0("blink_gc", "ThreadHeap::ParkThreadsScope");
// TODO(haraken): In an unlikely coincidence that two threads decide
// to collect garbage at the same time, avoid doing two GCs in
// a row and return false.
double startTime = WTF::currentTimeMS();
m_shouldResumeThreads = m_state->heap().park();
double timeForStoppingThreads = WTF::currentTimeMS() - startTime;
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, timeToStopThreadsHistogram,
new CustomCountHistogram("BlinkGC.TimeForStoppingThreads", 1, 1000,
50));
timeToStopThreadsHistogram.count(timeForStoppingThreads);
return m_shouldResumeThreads;
}
~ParkThreadsScope() {
// Only cleanup if we parked all threads in which case the GC happened
// and we need to resume the other threads.
if (m_shouldResumeThreads)
m_state->heap().resume();
}
private:
ThreadState* m_state;
bool m_shouldResumeThreads;
};
void ThreadHeap::flushHeapDoesNotContainCache() {
m_heapDoesNotContainCache->flush();
}
void ProcessHeap::init() {
s_shutdownComplete = false;
s_totalAllocatedSpace = 0;
s_totalAllocatedObjectSize = 0;
s_totalMarkedObjectSize = 0;
s_isLowEndDevice = base::SysInfo::IsLowEndDevice();
GCInfoTable::init();
CallbackStackMemoryPool::instance().initialize();
}
void ProcessHeap::resetHeapCounters() {
s_totalAllocatedObjectSize = 0;
s_totalMarkedObjectSize = 0;
}
void ProcessHeap::shutdown() {
ASSERT(!s_shutdownComplete);
{
// The main thread must be the last thread that gets detached.
MutexLocker locker(ThreadHeap::allHeapsMutex());
RELEASE_ASSERT(ThreadHeap::allHeaps().isEmpty());
}
CallbackStackMemoryPool::instance().shutdown();
GCInfoTable::shutdown();
ASSERT(ProcessHeap::totalAllocatedSpace() == 0);
s_shutdownComplete = true;
}
CrossThreadPersistentRegion& ProcessHeap::crossThreadPersistentRegion() {
DEFINE_THREAD_SAFE_STATIC_LOCAL(CrossThreadPersistentRegion, persistentRegion,
new CrossThreadPersistentRegion());
return persistentRegion;
}
bool ProcessHeap::s_shutdownComplete = false;
bool ProcessHeap::s_isLowEndDevice = false;
size_t ProcessHeap::s_totalAllocatedSpace = 0;
size_t ProcessHeap::s_totalAllocatedObjectSize = 0;
size_t ProcessHeap::s_totalMarkedObjectSize = 0;
ThreadHeapStats::ThreadHeapStats()
: m_allocatedSpace(0),
m_allocatedObjectSize(0),
m_objectSizeAtLastGC(0),
m_markedObjectSize(0),
m_markedObjectSizeAtLastCompleteSweep(0),
m_wrapperCount(0),
m_wrapperCountAtLastGC(0),
m_collectedWrapperCount(0),
m_partitionAllocSizeAtLastGC(
WTF::Partitions::totalSizeOfCommittedPages()),
m_estimatedMarkingTimePerByte(0.0) {}
double ThreadHeapStats::estimatedMarkingTime() {
// Use 8 ms as initial estimated marking time.
// 8 ms is long enough for low-end mobile devices to mark common
// real-world object graphs.
if (m_estimatedMarkingTimePerByte == 0)
return 0.008;
// Assuming that the collection rate of this GC will be mostly equal to
// the collection rate of the last GC, estimate the marking time of this GC.
return m_estimatedMarkingTimePerByte *
(allocatedObjectSize() + markedObjectSize());
}
void ThreadHeapStats::reset() {
m_objectSizeAtLastGC = m_allocatedObjectSize + m_markedObjectSize;
m_partitionAllocSizeAtLastGC = WTF::Partitions::totalSizeOfCommittedPages();
m_allocatedObjectSize = 0;
m_markedObjectSize = 0;
m_wrapperCountAtLastGC = m_wrapperCount;
m_collectedWrapperCount = 0;
}
void ThreadHeapStats::increaseAllocatedObjectSize(size_t delta) {
atomicAdd(&m_allocatedObjectSize, static_cast<long>(delta));
ProcessHeap::increaseTotalAllocatedObjectSize(delta);
}
void ThreadHeapStats::decreaseAllocatedObjectSize(size_t delta) {
atomicSubtract(&m_allocatedObjectSize, static_cast<long>(delta));
ProcessHeap::decreaseTotalAllocatedObjectSize(delta);
}
void ThreadHeapStats::increaseMarkedObjectSize(size_t delta) {
atomicAdd(&m_markedObjectSize, static_cast<long>(delta));
ProcessHeap::increaseTotalMarkedObjectSize(delta);
}
void ThreadHeapStats::increaseAllocatedSpace(size_t delta) {
atomicAdd(&m_allocatedSpace, static_cast<long>(delta));
ProcessHeap::increaseTotalAllocatedSpace(delta);
}
void ThreadHeapStats::decreaseAllocatedSpace(size_t delta) {
atomicSubtract(&m_allocatedSpace, static_cast<long>(delta));
ProcessHeap::decreaseTotalAllocatedSpace(delta);
}
ThreadHeap::ThreadHeap()
: m_regionTree(wrapUnique(new RegionTree())),
m_heapDoesNotContainCache(wrapUnique(new HeapDoesNotContainCache)),
m_safePointBarrier(wrapUnique(new SafePointBarrier())),
m_freePagePool(wrapUnique(new FreePagePool)),
m_orphanedPagePool(wrapUnique(new OrphanedPagePool)),
m_markingStack(CallbackStack::create()),
m_postMarkingCallbackStack(CallbackStack::create()),
m_globalWeakCallbackStack(CallbackStack::create()),
m_ephemeronStack(CallbackStack::create()) {
if (ThreadState::current()->isMainThread())
s_mainThreadHeap = this;
MutexLocker locker(ThreadHeap::allHeapsMutex());
allHeaps().add(this);
}
ThreadHeap::~ThreadHeap() {
MutexLocker locker(ThreadHeap::allHeapsMutex());
allHeaps().remove(this);
}
RecursiveMutex& ThreadHeap::allHeapsMutex() {
DEFINE_THREAD_SAFE_STATIC_LOCAL(RecursiveMutex, mutex, (new RecursiveMutex));
return mutex;
}
HashSet<ThreadHeap*>& ThreadHeap::allHeaps() {
DEFINE_STATIC_LOCAL(HashSet<ThreadHeap*>, heaps, ());
return heaps;
}
void ThreadHeap::attach(ThreadState* thread) {
MutexLocker locker(m_threadAttachMutex);
m_threads.add(thread);
}
void ThreadHeap::detach(ThreadState* thread) {
ASSERT(ThreadState::current() == thread);
bool isLastThread = false;
{
// Grab the threadAttachMutex to ensure only one thread can shutdown at
// a time and that no other thread can do a global GC. It also allows
// safe iteration of the m_threads set which happens as part of
// thread local GC asserts. We enter a safepoint while waiting for the
// lock to avoid a dead-lock where another thread has already requested
// GC.
SafePointAwareMutexLocker locker(m_threadAttachMutex,
BlinkGC::NoHeapPointersOnStack);
thread->runTerminationGC();
ASSERT(m_threads.contains(thread));
m_threads.remove(thread);
isLastThread = m_threads.isEmpty();
}
// The last thread begin detached should be the owning thread, which would
// be the main thread for the mainThreadHeap and a per thread heap enabled
// thread otherwise.
if (isLastThread)
DCHECK(thread->threadHeapMode() == BlinkGC::PerThreadHeapMode ||
thread->isMainThread());
if (thread->isMainThread())
DCHECK_EQ(heapStats().allocatedSpace(), 0u);
if (isLastThread)
delete this;
}
bool ThreadHeap::park() {
return m_safePointBarrier->parkOthers();
}
void ThreadHeap::resume() {
m_safePointBarrier->resumeOthers();
}
#if ENABLE(ASSERT)
BasePage* ThreadHeap::findPageFromAddress(Address address) {
MutexLocker locker(m_threadAttachMutex);
for (ThreadState* state : m_threads) {
if (BasePage* page = state->findPageFromAddress(address))
return page;
}
return nullptr;
}
bool ThreadHeap::isAtSafePoint() {
MutexLocker locker(m_threadAttachMutex);
for (ThreadState* state : m_threads) {
if (!state->isAtSafePoint())
return false;
}
return true;
}
#endif
Address ThreadHeap::checkAndMarkPointer(Visitor* visitor, Address address) {
ASSERT(ThreadState::current()->isInGC());
#if !ENABLE(ASSERT)
if (m_heapDoesNotContainCache->lookup(address))
return nullptr;
#endif
if (BasePage* page = lookupPageForAddress(address)) {
ASSERT(page->contains(address));
ASSERT(!page->orphaned());
ASSERT(!m_heapDoesNotContainCache->lookup(address));
DCHECK(&visitor->heap() == &page->arena()->getThreadState()->heap());
page->checkAndMarkPointer(visitor, address);
return address;
}
#if !ENABLE(ASSERT)
m_heapDoesNotContainCache->addEntry(address);
#else
if (!m_heapDoesNotContainCache->lookup(address))
m_heapDoesNotContainCache->addEntry(address);
#endif
return nullptr;
}
void ThreadHeap::pushTraceCallback(void* object, TraceCallback callback) {
ASSERT(ThreadState::current()->isInGC());
// Trace should never reach an orphaned page.
ASSERT(!getOrphanedPagePool()->contains(object));
CallbackStack::Item* slot = m_markingStack->allocateEntry();
*slot = CallbackStack::Item(object, callback);
}
bool ThreadHeap::popAndInvokeTraceCallback(Visitor* visitor) {
CallbackStack::Item* item = m_markingStack->pop();
if (!item)
return false;
item->call(visitor);
return true;
}
void ThreadHeap::pushPostMarkingCallback(void* object, TraceCallback callback) {
ASSERT(ThreadState::current()->isInGC());
// Trace should never reach an orphaned page.
ASSERT(!getOrphanedPagePool()->contains(object));
CallbackStack::Item* slot = m_postMarkingCallbackStack->allocateEntry();
*slot = CallbackStack::Item(object, callback);
}
bool ThreadHeap::popAndInvokePostMarkingCallback(Visitor* visitor) {
if (CallbackStack::Item* item = m_postMarkingCallbackStack->pop()) {
item->call(visitor);
return true;
}
return false;
}
void ThreadHeap::pushGlobalWeakCallback(void** cell, WeakCallback callback) {
ASSERT(ThreadState::current()->isInGC());
// Trace should never reach an orphaned page.
ASSERT(!getOrphanedPagePool()->contains(cell));
CallbackStack::Item* slot = m_globalWeakCallbackStack->allocateEntry();
*slot = CallbackStack::Item(cell, callback);
}
void ThreadHeap::pushThreadLocalWeakCallback(void* closure,
void* object,
WeakCallback callback) {
ASSERT(ThreadState::current()->isInGC());
// Trace should never reach an orphaned page.
ASSERT(!getOrphanedPagePool()->contains(object));
ThreadState* state = pageFromObject(object)->arena()->getThreadState();
state->pushThreadLocalWeakCallback(closure, callback);
}
bool ThreadHeap::popAndInvokeGlobalWeakCallback(Visitor* visitor) {
if (CallbackStack::Item* item = m_globalWeakCallbackStack->pop()) {
item->call(visitor);
return true;
}
return false;
}
void ThreadHeap::registerWeakTable(void* table,
EphemeronCallback iterationCallback,
EphemeronCallback iterationDoneCallback) {
ASSERT(ThreadState::current()->isInGC());
// Trace should never reach an orphaned page.
ASSERT(!getOrphanedPagePool()->contains(table));
CallbackStack::Item* slot = m_ephemeronStack->allocateEntry();
*slot = CallbackStack::Item(table, iterationCallback);
// Register a post-marking callback to tell the tables that
// ephemeron iteration is complete.
pushPostMarkingCallback(table, iterationDoneCallback);
}
#if ENABLE(ASSERT)
bool ThreadHeap::weakTableRegistered(const void* table) {
ASSERT(m_ephemeronStack);
return m_ephemeronStack->hasCallbackForObject(table);
}
#endif
void ThreadHeap::commitCallbackStacks() {
m_markingStack->commit();
m_postMarkingCallbackStack->commit();
m_globalWeakCallbackStack->commit();
m_ephemeronStack->commit();
}
void ThreadHeap::decommitCallbackStacks() {
m_markingStack->decommit();
m_postMarkingCallbackStack->decommit();
m_globalWeakCallbackStack->decommit();
m_ephemeronStack->decommit();
}
void ThreadHeap::preGC() {
ASSERT(!ThreadState::current()->isInGC());
for (ThreadState* state : m_threads)
state->preGC();
}
void ThreadHeap::postGC(BlinkGC::GCType gcType) {
ASSERT(ThreadState::current()->isInGC());
for (ThreadState* state : m_threads)
state->postGC(gcType);
}
void ThreadHeap::processMarkingStack(Visitor* visitor) {
// Ephemeron fixed point loop.
do {
{
// Iteratively mark all objects that are reachable from the objects
// currently pushed onto the marking stack.
TRACE_EVENT0("blink_gc", "ThreadHeap::processMarkingStackSingleThreaded");
while (popAndInvokeTraceCallback(visitor)) {
}
}
{
// Mark any strong pointers that have now become reachable in
// ephemeron maps.
TRACE_EVENT0("blink_gc", "ThreadHeap::processEphemeronStack");
m_ephemeronStack->invokeEphemeronCallbacks(visitor);
}
// Rerun loop if ephemeron processing queued more objects for tracing.
} while (!m_markingStack->isEmpty());
}
void ThreadHeap::postMarkingProcessing(Visitor* visitor) {
TRACE_EVENT0("blink_gc", "ThreadHeap::postMarkingProcessing");
// Call post-marking callbacks including:
// 1. the ephemeronIterationDone callbacks on weak tables to do cleanup
// (specifically to clear the queued bits for weak hash tables), and
// 2. the markNoTracing callbacks on collection backings to mark them
// if they are only reachable from their front objects.
while (popAndInvokePostMarkingCallback(visitor)) {
}
// Post-marking callbacks should not trace any objects and
// therefore the marking stack should be empty after the
// post-marking callbacks.
ASSERT(m_markingStack->isEmpty());
}
void ThreadHeap::globalWeakProcessing(Visitor* visitor) {
TRACE_EVENT0("blink_gc", "ThreadHeap::globalWeakProcessing");
double startTime = WTF::currentTimeMS();
// Call weak callbacks on objects that may now be pointing to dead objects.
while (popAndInvokeGlobalWeakCallback(visitor)) {
}
// It is not permitted to trace pointers of live objects in the weak
// callback phase, so the marking stack should still be empty here.
ASSERT(m_markingStack->isEmpty());
double timeForGlobalWeakProcessing = WTF::currentTimeMS() - startTime;
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, globalWeakTimeHistogram,
new CustomCountHistogram("BlinkGC.TimeForGlobalWeakProcessing", 1,
10 * 1000, 50));
globalWeakTimeHistogram.count(timeForGlobalWeakProcessing);
}
void ThreadHeap::reportMemoryUsageHistogram() {
static size_t supportedMaxSizeInMB = 4 * 1024;
static size_t observedMaxSizeInMB = 0;
// We only report the memory in the main thread.
if (!isMainThread())
return;
// +1 is for rounding up the sizeInMB.
size_t sizeInMB =
ThreadState::current()->heap().heapStats().allocatedSpace() / 1024 /
1024 +
1;
if (sizeInMB >= supportedMaxSizeInMB)
sizeInMB = supportedMaxSizeInMB - 1;
if (sizeInMB > observedMaxSizeInMB) {
// Send a UseCounter only when we see the highest memory usage
// we've ever seen.
DEFINE_THREAD_SAFE_STATIC_LOCAL(
EnumerationHistogram, commitedSizeHistogram,
new EnumerationHistogram("BlinkGC.CommittedSize",
supportedMaxSizeInMB));
commitedSizeHistogram.count(sizeInMB);
observedMaxSizeInMB = sizeInMB;
}
}
void ThreadHeap::reportMemoryUsageForTracing() {
#if PRINT_HEAP_STATS
// dataLogF("allocatedSpace=%ldMB, allocatedObjectSize=%ldMB, "
// "markedObjectSize=%ldMB, partitionAllocSize=%ldMB, "
// "wrapperCount=%ld, collectedWrapperCount=%ld\n",
// ThreadHeap::allocatedSpace() / 1024 / 1024,
// ThreadHeap::allocatedObjectSize() / 1024 / 1024,
// ThreadHeap::markedObjectSize() / 1024 / 1024,
// WTF::Partitions::totalSizeOfCommittedPages() / 1024 / 1024,
// ThreadHeap::wrapperCount(), ThreadHeap::collectedWrapperCount());
#endif
bool gcTracingEnabled;
TRACE_EVENT_CATEGORY_GROUP_ENABLED(TRACE_DISABLED_BY_DEFAULT("blink_gc"),
&gcTracingEnabled);
if (!gcTracingEnabled)
return;
ThreadHeap& heap = ThreadState::current()->heap();
// These values are divided by 1024 to avoid overflow in practical cases
// (TRACE_COUNTER values are 32-bit ints).
// They are capped to INT_MAX just in case.
TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"),
"ThreadHeap::allocatedObjectSizeKB",
std::min(heap.heapStats().allocatedObjectSize() / 1024,
static_cast<size_t>(INT_MAX)));
TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"),
"ThreadHeap::markedObjectSizeKB",
std::min(heap.heapStats().markedObjectSize() / 1024,
static_cast<size_t>(INT_MAX)));
TRACE_COUNTER1(
TRACE_DISABLED_BY_DEFAULT("blink_gc"),
"ThreadHeap::markedObjectSizeAtLastCompleteSweepKB",
std::min(heap.heapStats().markedObjectSizeAtLastCompleteSweep() / 1024,
static_cast<size_t>(INT_MAX)));
TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"),
"ThreadHeap::allocatedSpaceKB",
std::min(heap.heapStats().allocatedSpace() / 1024,
static_cast<size_t>(INT_MAX)));
TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"),
"ThreadHeap::objectSizeAtLastGCKB",
std::min(heap.heapStats().objectSizeAtLastGC() / 1024,
static_cast<size_t>(INT_MAX)));
TRACE_COUNTER1(
TRACE_DISABLED_BY_DEFAULT("blink_gc"), "ThreadHeap::wrapperCount",
std::min(heap.heapStats().wrapperCount(), static_cast<size_t>(INT_MAX)));
TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"),
"ThreadHeap::wrapperCountAtLastGC",
std::min(heap.heapStats().wrapperCountAtLastGC(),
static_cast<size_t>(INT_MAX)));
TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"),
"ThreadHeap::collectedWrapperCount",
std::min(heap.heapStats().collectedWrapperCount(),
static_cast<size_t>(INT_MAX)));
TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"),
"ThreadHeap::partitionAllocSizeAtLastGCKB",
std::min(heap.heapStats().partitionAllocSizeAtLastGC() / 1024,
static_cast<size_t>(INT_MAX)));
TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"),
"Partitions::totalSizeOfCommittedPagesKB",
std::min(WTF::Partitions::totalSizeOfCommittedPages() / 1024,
static_cast<size_t>(INT_MAX)));
}
size_t ThreadHeap::objectPayloadSizeForTesting() {
// MEMO: is threadAttachMutex locked?
size_t objectPayloadSize = 0;
for (ThreadState* state : m_threads) {
state->setGCState(ThreadState::GCRunning);
state->makeConsistentForGC();
objectPayloadSize += state->objectPayloadSizeForTesting();
state->setGCState(ThreadState::EagerSweepScheduled);
state->setGCState(ThreadState::Sweeping);
state->setGCState(ThreadState::NoGCScheduled);
}
return objectPayloadSize;
}
void ThreadHeap::visitPersistentRoots(Visitor* visitor) {
ASSERT(ThreadState::current()->isInGC());
TRACE_EVENT0("blink_gc", "ThreadHeap::visitPersistentRoots");
ProcessHeap::crossThreadPersistentRegion().tracePersistentNodes(visitor);
for (ThreadState* state : m_threads)
state->visitPersistents(visitor);
}
void ThreadHeap::visitStackRoots(Visitor* visitor) {
ASSERT(ThreadState::current()->isInGC());
TRACE_EVENT0("blink_gc", "ThreadHeap::visitStackRoots");
for (ThreadState* state : m_threads)
state->visitStack(visitor);
}
void ThreadHeap::checkAndPark(ThreadState* threadState,
SafePointAwareMutexLocker* locker) {
m_safePointBarrier->checkAndPark(threadState, locker);
}
void ThreadHeap::enterSafePoint(ThreadState* threadState) {
m_safePointBarrier->enterSafePoint(threadState);
}
void ThreadHeap::leaveSafePoint(ThreadState* threadState,
SafePointAwareMutexLocker* locker) {
m_safePointBarrier->leaveSafePoint(threadState, locker);
}
BasePage* ThreadHeap::lookupPageForAddress(Address address) {
ASSERT(ThreadState::current()->isInGC());
if (PageMemoryRegion* region = m_regionTree->lookup(address)) {
BasePage* page = region->pageFromAddress(address);
return page && !page->orphaned() ? page : nullptr;
}
return nullptr;
}
void ThreadHeap::resetHeapCounters() {
ASSERT(ThreadState::current()->isInGC());
ThreadHeap::reportMemoryUsageForTracing();
ProcessHeap::decreaseTotalAllocatedObjectSize(m_stats.allocatedObjectSize());
ProcessHeap::decreaseTotalMarkedObjectSize(m_stats.markedObjectSize());
m_stats.reset();
for (ThreadState* state : m_threads)
state->resetHeapCounters();
}
ThreadHeap* ThreadHeap::s_mainThreadHeap = nullptr;
} // namespace blink
| [
"support@opentext.com"
] | support@opentext.com |
84e7b732e675e68acbb5670880b833ad2db9fe72 | 3fafad978d67d18dd83b2367b9b50335b19abab1 | /GetAllWordInstances/CWordWindow.h | 8c87c81af5e1d9c922f02c050cc54141ca3bc337 | [] | no_license | dongfeng86/MFC-Practice | f14b6c40fc06e447507ebd45eaec6e42a411a752 | 2b34b2e69232d729fa9ac540907da84af9eb97b5 | refs/heads/master | 2023-08-30T16:55:55.106300 | 2023-08-24T07:46:45 | 2023-08-24T07:46:45 | 202,539,652 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 15,937 | h | // 从类型库向导中用“添加类”创建的计算机生成的 IDispatch 包装器类
// CWordWindow 包装器类
class CWordWindow : public COleDispatchDriver
{
public:
CWordWindow() {} // 调用 COleDispatchDriver 默认构造函数
CWordWindow(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {}
CWordWindow(const CWordWindow& dispatchSrc) : COleDispatchDriver(dispatchSrc) {}
// 特性
public:
// 操作
public:
// Window 方法
public:
LPDISPATCH get_Application()
{
LPDISPATCH result;
InvokeHelper(0x3e8, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, nullptr);
return result;
}
long get_Creator()
{
long result;
InvokeHelper(0x3e9, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, nullptr);
return result;
}
LPDISPATCH get_Parent()
{
LPDISPATCH result;
InvokeHelper(0x3ea, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, nullptr);
return result;
}
LPDISPATCH get_ActivePane()
{
LPDISPATCH result;
InvokeHelper(0x1, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, nullptr);
return result;
}
LPDISPATCH get_Document()
{
LPDISPATCH result;
InvokeHelper(0x2, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, nullptr);
return result;
}
LPDISPATCH get_Panes()
{
LPDISPATCH result;
InvokeHelper(0x3, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, nullptr);
return result;
}
LPDISPATCH get_Selection()
{
LPDISPATCH result;
InvokeHelper(0x4, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, nullptr);
return result;
}
long get_Left()
{
long result;
InvokeHelper(0x5, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, nullptr);
return result;
}
void put_Left(long newValue)
{
static BYTE parms[] = VTS_I4;
InvokeHelper(0x5, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
long get_Top()
{
long result;
InvokeHelper(0x6, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, nullptr);
return result;
}
void put_Top(long newValue)
{
static BYTE parms[] = VTS_I4;
InvokeHelper(0x6, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
long get_Width()
{
long result;
InvokeHelper(0x7, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, nullptr);
return result;
}
void put_Width(long newValue)
{
static BYTE parms[] = VTS_I4;
InvokeHelper(0x7, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
long get_Height()
{
long result;
InvokeHelper(0x8, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, nullptr);
return result;
}
void put_Height(long newValue)
{
static BYTE parms[] = VTS_I4;
InvokeHelper(0x8, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
BOOL get_Split()
{
BOOL result;
InvokeHelper(0x9, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, nullptr);
return result;
}
void put_Split(BOOL newValue)
{
static BYTE parms[] = VTS_BOOL;
InvokeHelper(0x9, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
long get_SplitVertical()
{
long result;
InvokeHelper(0xa, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, nullptr);
return result;
}
void put_SplitVertical(long newValue)
{
static BYTE parms[] = VTS_I4;
InvokeHelper(0xa, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
CString get_Caption()
{
CString result;
InvokeHelper(0x0, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, nullptr);
return result;
}
void put_Caption(LPCTSTR newValue)
{
static BYTE parms[] = VTS_BSTR;
InvokeHelper(0x0, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
long get_WindowState()
{
long result;
InvokeHelper(0xb, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, nullptr);
return result;
}
void put_WindowState(long newValue)
{
static BYTE parms[] = VTS_I4;
InvokeHelper(0xb, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
BOOL get_DisplayRulers()
{
BOOL result;
InvokeHelper(0xc, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, nullptr);
return result;
}
void put_DisplayRulers(BOOL newValue)
{
static BYTE parms[] = VTS_BOOL;
InvokeHelper(0xc, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
BOOL get_DisplayVerticalRuler()
{
BOOL result;
InvokeHelper(0xd, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, nullptr);
return result;
}
void put_DisplayVerticalRuler(BOOL newValue)
{
static BYTE parms[] = VTS_BOOL;
InvokeHelper(0xd, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
LPDISPATCH get_View()
{
LPDISPATCH result;
InvokeHelper(0xe, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, nullptr);
return result;
}
long get_Type()
{
long result;
InvokeHelper(0xf, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, nullptr);
return result;
}
LPDISPATCH get_Next()
{
LPDISPATCH result;
InvokeHelper(0x10, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, nullptr);
return result;
}
LPDISPATCH get_Previous()
{
LPDISPATCH result;
InvokeHelper(0x11, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, nullptr);
return result;
}
long get_WindowNumber()
{
long result;
InvokeHelper(0x12, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, nullptr);
return result;
}
BOOL get_DisplayVerticalScrollBar()
{
BOOL result;
InvokeHelper(0x13, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, nullptr);
return result;
}
void put_DisplayVerticalScrollBar(BOOL newValue)
{
static BYTE parms[] = VTS_BOOL;
InvokeHelper(0x13, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
BOOL get_DisplayHorizontalScrollBar()
{
BOOL result;
InvokeHelper(0x14, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, nullptr);
return result;
}
void put_DisplayHorizontalScrollBar(BOOL newValue)
{
static BYTE parms[] = VTS_BOOL;
InvokeHelper(0x14, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
float get_StyleAreaWidth()
{
float result;
InvokeHelper(0x15, DISPATCH_PROPERTYGET, VT_R4, (void*)&result, nullptr);
return result;
}
void put_StyleAreaWidth(float newValue)
{
static BYTE parms[] = VTS_R4;
InvokeHelper(0x15, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
BOOL get_DisplayScreenTips()
{
BOOL result;
InvokeHelper(0x16, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, nullptr);
return result;
}
void put_DisplayScreenTips(BOOL newValue)
{
static BYTE parms[] = VTS_BOOL;
InvokeHelper(0x16, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
long get_HorizontalPercentScrolled()
{
long result;
InvokeHelper(0x17, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, nullptr);
return result;
}
void put_HorizontalPercentScrolled(long newValue)
{
static BYTE parms[] = VTS_I4;
InvokeHelper(0x17, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
long get_VerticalPercentScrolled()
{
long result;
InvokeHelper(0x18, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, nullptr);
return result;
}
void put_VerticalPercentScrolled(long newValue)
{
static BYTE parms[] = VTS_I4;
InvokeHelper(0x18, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
BOOL get_DocumentMap()
{
BOOL result;
InvokeHelper(0x19, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, nullptr);
return result;
}
void put_DocumentMap(BOOL newValue)
{
static BYTE parms[] = VTS_BOOL;
InvokeHelper(0x19, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
BOOL get_Active()
{
BOOL result;
InvokeHelper(0x1a, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, nullptr);
return result;
}
long get_DocumentMapPercentWidth()
{
long result;
InvokeHelper(0x1b, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, nullptr);
return result;
}
void put_DocumentMapPercentWidth(long newValue)
{
static BYTE parms[] = VTS_I4;
InvokeHelper(0x1b, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
long get_Index()
{
long result;
InvokeHelper(0x1c, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, nullptr);
return result;
}
long get_IMEMode()
{
long result;
InvokeHelper(0x1e, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, nullptr);
return result;
}
void put_IMEMode(long newValue)
{
static BYTE parms[] = VTS_I4;
InvokeHelper(0x1e, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
void Activate()
{
InvokeHelper(0x64, DISPATCH_METHOD, VT_EMPTY, nullptr, nullptr);
}
void Close(VARIANT * SaveChanges, VARIANT * RouteDocument)
{
static BYTE parms[] = VTS_PVARIANT VTS_PVARIANT;
InvokeHelper(0x66, DISPATCH_METHOD, VT_EMPTY, nullptr, parms, SaveChanges, RouteDocument);
}
void LargeScroll(VARIANT * Down, VARIANT * Up, VARIANT * ToRight, VARIANT * ToLeft)
{
static BYTE parms[] = VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT;
InvokeHelper(0x67, DISPATCH_METHOD, VT_EMPTY, nullptr, parms, Down, Up, ToRight, ToLeft);
}
void SmallScroll(VARIANT * Down, VARIANT * Up, VARIANT * ToRight, VARIANT * ToLeft)
{
static BYTE parms[] = VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT;
InvokeHelper(0x68, DISPATCH_METHOD, VT_EMPTY, nullptr, parms, Down, Up, ToRight, ToLeft);
}
LPDISPATCH NewWindow()
{
LPDISPATCH result;
InvokeHelper(0x69, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, nullptr);
return result;
}
void PrintOutOld(VARIANT * Background, VARIANT * Append, VARIANT * Range, VARIANT * OutputFileName, VARIANT * From, VARIANT * To, VARIANT * Item, VARIANT * Copies, VARIANT * Pages, VARIANT * PageType, VARIANT * PrintToFile, VARIANT * Collate, VARIANT * ActivePrinterMacGX, VARIANT * ManualDuplexPrint)
{
static BYTE parms[] = VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT;
InvokeHelper(0x6b, DISPATCH_METHOD, VT_EMPTY, nullptr, parms, Background, Append, Range, OutputFileName, From, To, Item, Copies, Pages, PageType, PrintToFile, Collate, ActivePrinterMacGX, ManualDuplexPrint);
}
void PageScroll(VARIANT * Down, VARIANT * Up)
{
static BYTE parms[] = VTS_PVARIANT VTS_PVARIANT;
InvokeHelper(0x6c, DISPATCH_METHOD, VT_EMPTY, nullptr, parms, Down, Up);
}
void SetFocus()
{
InvokeHelper(0x6d, DISPATCH_METHOD, VT_EMPTY, nullptr, nullptr);
}
LPDISPATCH RangeFromPoint(long x, long y)
{
LPDISPATCH result;
static BYTE parms[] = VTS_I4 VTS_I4;
InvokeHelper(0x6e, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, x, y);
return result;
}
void ScrollIntoView(LPDISPATCH obj, VARIANT * Start)
{
static BYTE parms[] = VTS_DISPATCH VTS_PVARIANT;
InvokeHelper(0x6f, DISPATCH_METHOD, VT_EMPTY, nullptr, parms, obj, Start);
}
void GetPoint(long * ScreenPixelsLeft, long * ScreenPixelsTop, long * ScreenPixelsWidth, long * ScreenPixelsHeight, LPDISPATCH obj)
{
static BYTE parms[] = VTS_PI4 VTS_PI4 VTS_PI4 VTS_PI4 VTS_DISPATCH;
InvokeHelper(0x70, DISPATCH_METHOD, VT_EMPTY, nullptr, parms, ScreenPixelsLeft, ScreenPixelsTop, ScreenPixelsWidth, ScreenPixelsHeight, obj);
}
void PrintOut2000(VARIANT * Background, VARIANT * Append, VARIANT * Range, VARIANT * OutputFileName, VARIANT * From, VARIANT * To, VARIANT * Item, VARIANT * Copies, VARIANT * Pages, VARIANT * PageType, VARIANT * PrintToFile, VARIANT * Collate, VARIANT * ActivePrinterMacGX, VARIANT * ManualDuplexPrint, VARIANT * PrintZoomColumn, VARIANT * PrintZoomRow, VARIANT * PrintZoomPaperWidth, VARIANT * PrintZoomPaperHeight)
{
static BYTE parms[] = VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT;
InvokeHelper(0x1bc, DISPATCH_METHOD, VT_EMPTY, nullptr, parms, Background, Append, Range, OutputFileName, From, To, Item, Copies, Pages, PageType, PrintToFile, Collate, ActivePrinterMacGX, ManualDuplexPrint, PrintZoomColumn, PrintZoomRow, PrintZoomPaperWidth, PrintZoomPaperHeight);
}
long get_UsableWidth()
{
long result;
InvokeHelper(0x1f, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, nullptr);
return result;
}
long get_UsableHeight()
{
long result;
InvokeHelper(0x20, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, nullptr);
return result;
}
BOOL get_EnvelopeVisible()
{
BOOL result;
InvokeHelper(0x21, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, nullptr);
return result;
}
void put_EnvelopeVisible(BOOL newValue)
{
static BYTE parms[] = VTS_BOOL;
InvokeHelper(0x21, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
BOOL get_DisplayRightRuler()
{
BOOL result;
InvokeHelper(0x23, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, nullptr);
return result;
}
void put_DisplayRightRuler(BOOL newValue)
{
static BYTE parms[] = VTS_BOOL;
InvokeHelper(0x23, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
BOOL get_DisplayLeftScrollBar()
{
BOOL result;
InvokeHelper(0x22, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, nullptr);
return result;
}
void put_DisplayLeftScrollBar(BOOL newValue)
{
static BYTE parms[] = VTS_BOOL;
InvokeHelper(0x22, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
BOOL get_Visible()
{
BOOL result;
InvokeHelper(0x24, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, nullptr);
return result;
}
void put_Visible(BOOL newValue)
{
static BYTE parms[] = VTS_BOOL;
InvokeHelper(0x24, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
void PrintOut(VARIANT * Background, VARIANT * Append, VARIANT * Range, VARIANT * OutputFileName, VARIANT * From, VARIANT * To, VARIANT * Item, VARIANT * Copies, VARIANT * Pages, VARIANT * PageType, VARIANT * PrintToFile, VARIANT * Collate, VARIANT * ActivePrinterMacGX, VARIANT * ManualDuplexPrint, VARIANT * PrintZoomColumn, VARIANT * PrintZoomRow, VARIANT * PrintZoomPaperWidth, VARIANT * PrintZoomPaperHeight)
{
static BYTE parms[] = VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT;
InvokeHelper(0x1bd, DISPATCH_METHOD, VT_EMPTY, nullptr, parms, Background, Append, Range, OutputFileName, From, To, Item, Copies, Pages, PageType, PrintToFile, Collate, ActivePrinterMacGX, ManualDuplexPrint, PrintZoomColumn, PrintZoomRow, PrintZoomPaperWidth, PrintZoomPaperHeight);
}
void ToggleShowAllReviewers()
{
InvokeHelper(0x1be, DISPATCH_METHOD, VT_EMPTY, nullptr, nullptr);
}
BOOL get_Thumbnails()
{
BOOL result;
InvokeHelper(0x25, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, nullptr);
return result;
}
void put_Thumbnails(BOOL newValue)
{
static BYTE parms[] = VTS_BOOL;
InvokeHelper(0x25, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
long get_ShowSourceDocuments()
{
long result;
InvokeHelper(0x26, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, nullptr);
return result;
}
void put_ShowSourceDocuments(long newValue)
{
static BYTE parms[] = VTS_I4;
InvokeHelper(0x26, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
void ToggleRibbon()
{
InvokeHelper(0x1bf, DISPATCH_METHOD, VT_EMPTY, nullptr, nullptr);
}
long get_Hwnd()
{
long result;
InvokeHelper(0x27, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, nullptr);
return result;
}
void put_DispLog(LPCTSTR newValue)
{
static BYTE parms[] = VTS_BSTR;
InvokeHelper(0x28, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
void put_DispLogPage(long newValue)
{
static BYTE parms[] = VTS_I4;
InvokeHelper(0x29, DISPATCH_PROPERTYPUT, VT_EMPTY, nullptr, parms, newValue);
}
void EndDispLog()
{
InvokeHelper(0x71, DISPATCH_METHOD, VT_EMPTY, nullptr, nullptr);
}
void DispLogDirtyPage(long iPage)
{
static BYTE parms[] = VTS_I4;
InvokeHelper(0x72, DISPATCH_METHOD, VT_EMPTY, nullptr, parms, iPage);
}
void DispLogUpdateWwd()
{
InvokeHelper(0x73, DISPATCH_METHOD, VT_EMPTY, nullptr, nullptr);
}
// Window 属性
public:
};
| [
"115949168@qq.com"
] | 115949168@qq.com |
1611ddace582bbcb234f978cd2e521fdc1dbe5a6 | d78c9a394ded0f6d3ca8fd458e079c3bc3aa3f7d | /border.cpp | d3a11511fc7acccc90b311e478bb2e270545a747 | [] | no_license | Prinkagupta/HTML-CSS-Code-Generator | 49ca0ea984503199818f9a5d9ec3f52d8c220dff | fbe30f3a7adf9d366270c05f2e839ba9b9f21765 | refs/heads/master | 2021-05-29T10:51:28.434796 | 2015-09-18T10:47:51 | 2015-09-18T10:47:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,235 | cpp | #include "border.h"
#include "ui_border.h"
#include<QtCore/QFile>
#include<QtCore/QTextStream>
border::border(QWidget *parent) :
QDialog(parent),
ui(new Ui::border)
{
ui->setupUi(this);
ui->cBBorderStyle->addItem("Solid");
ui->cBBorderStyle->addItem("Dotted");
ui->cBBorderStyle->addItem("Double");
ui->cBBorderStyle->addItem("Dashed");
ui->cBBorderColour->addItem("Aqua");
ui->cBBorderColour->addItem("Blue");
ui->cBBorderColour->addItem("Violet");
ui->cBBorderColour->addItem("Pink");
ui->cBBorderColour->addItem("Lime");
ui->cBBorderColour->addItem("Orange");
ui->cBBorderColour->addItem("Red");
ui->cBBorderColour->addItem("Turquoise");
ui->cBBorderColour->addItem("White");
ui->cBBorderColour->addItem("Yellow");
ui->tEBorderWidth->setText("10");
}
border::~border()
{
delete ui;
}
void border::on_backButton_clicked()
{
this->close();
}
void border::on_submitButton_clicked()
{
ui->doneLabel->setText("SUBMITTED");
storeBorderStyle();
storeBorderColour();
storeBorderWidth();
}
void border::storeBorderStyle(){
QFile borderStyle("border.txt");
borderStyle.open(QFile::WriteOnly|QIODevice::Text);
QTextStream borderStyleStream(&borderStyle);
QString borderStyleString = ui->cBBorderStyle->currentText();
if(borderStyleString=="Dotted")
borderStyleStream<<"border-style:dotted;\n";
if(borderStyleString=="Solid")
borderStyleStream<<"border-style:solid;\n";
if(borderStyleString=="Double")
borderStyleStream<<"border-style:double;\n";
if(borderStyleString=="Dashed")
borderStyleStream<<"border-style:dashed;\n";
borderStyle.close();
}
void border::storeBorderColour(){
QFile borderColour("border.txt");
borderColour.open(QFile::Append|QIODevice::Text);
QTextStream borderColourStream(&borderColour);
QString borderColourString = ui->cBBorderColour->currentText();
if(borderColourString=="Aqua")
borderColourStream<<"border-color:#00FFFF;\n";
if(borderColourString=="Blue")
borderColourStream<<"border-color:#0000FF;\n";
if(borderColourString=="Violet")
borderColourStream<<"border-color:#EE82EE;\n";
if(borderColourString=="Pink")
borderColourStream<<"border-color:#FF69B4;\n";
if(borderColourString=="Lime")
borderColourStream<<"border-color:#00FF00;\n";
if(borderColourString=="Orange")
borderColourStream<<"border-color:#FFA500;\n";
if(borderColourString=="Red")
borderColourStream<<"border-color:#FF0000;\n";
if(borderColourString=="Turquoise")
borderColourStream<<"border-color:#40E0D0;\n";
if(borderColourString=="White")
borderColourStream<<"border-color:#FFFFFF;\n";
if(borderColourString=="Yellow")
borderColourStream<<"border-color:#FFFF00;\n";
borderColour.close();
}
void border::storeBorderWidth(){
QFile borderWidth("border.txt");
borderWidth.open(QFile::Append|QIODevice::Text);
QTextStream borderWidthStream(&borderWidth);
QString borderWidthString =ui->tEBorderWidth->toPlainText();
borderWidthStream<<"border-width:"<<borderWidthString<<"px;";
borderWidth.close();
}
| [
"prinkamodi@gmail.com"
] | prinkamodi@gmail.com |
ac4b6640f847100ad3f9bc93c3cc12e850326d1b | 6197740e6297da2f3d0c8ffd2a1d7ef5d8b3d2cb | /DotNet/Foundations of C++CLI/Chapter11/generic_function.cpp | eb2480dab8febf91192275445c48730aa4459dfe | [] | no_license | ssh352/cppcode | 1159d4137b68ada253678718b3d416639d3849ba | 5b7c28963286295dfc9af087bed51ac35cd79ce6 | refs/heads/master | 2020-11-24T18:07:17.587795 | 2016-07-15T13:13:05 | 2016-07-15T13:13:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 122 | cpp | // generic_function.cpp
using namespace System;
generic <typename T>
void F(T t, int i, String^ s)
{
// ...
}
| [
"qq410029478@ff87cf93-6e24-4a51-a1f1-68835326ac4f"
] | qq410029478@ff87cf93-6e24-4a51-a1f1-68835326ac4f |
de717bc8b39aaf763c03deb1df0a3a4793637de4 | 640ce20729b8d7466525be49412af7f4bd6efc2c | /367_perfect_square.cpp | 82cff3042114ba0dbe89f3ea1b0f48df0c7bda29 | [] | no_license | howardplus/leetcode | 782cc614bec736b671479bee254b16b6d478ca84 | 0c041dbf899a3075e6499fd393d368b7b4879bb3 | refs/heads/master | 2021-01-02T08:48:55.943535 | 2020-01-22T07:30:10 | 2020-01-22T07:30:10 | 99,068,703 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 677 | cpp | /*
* https://leetcode.com/problems/valid-perfect-square/description/
*
* Given a positive integer num, write a function which returns True if num is
* a perfect square else False.
*/
#include <iostream>
using namespace std;
class Solution {
public:
bool isPerfectSquare(int num) {
for (long sum = 0, i = 1; sum < num; i += 2) {
sum += i;
if (sum == num) return true;
}
return false;
}
};
int main()
{
Solution s;
cout << s.isPerfectSquare(1) << endl;
cout << s.isPerfectSquare(4) << endl;
cout << s.isPerfectSquare(15) << endl;
cout << s.isPerfectSquare(2147483647) << endl;
return 0;
}
| [
"howardplus@gmail.com"
] | howardplus@gmail.com |
d5c54c7dc1a8b53e01402eace0c3b6f9802d4827 | 44ab57520bb1a9b48045cb1ee9baee8816b44a5b | /Engine/Code/Mathematics/Base/FastNegativeExpAchieve.h | 8f7b4551c652fa8e37c7c26ec1efe6295476a708 | [
"BSD-3-Clause"
] | permissive | WuyangPeng/Engine | d5d81fd4ec18795679ce99552ab9809f3b205409 | 738fde5660449e87ccd4f4878f7bf2a443ae9f1f | refs/heads/master | 2023-08-17T17:01:41.765963 | 2023-08-16T07:27:05 | 2023-08-16T07:27:05 | 246,266,843 | 10 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,562 | h | /// Copyright (c) 2010-2023
/// Threading Core Render Engine
///
/// 作者:彭武阳,彭晔恩,彭晔泽
/// 联系作者:94458936@qq.com
///
/// 标准:std:c++20
/// 引擎版本:0.9.0.11 (2023/05/30 14:54)
#ifndef MATHEMATICS_BASE_FAST_NEGATIVE_EXP_ACHIEVE_H
#define MATHEMATICS_BASE_FAST_NEGATIVE_EXP_ACHIEVE_H
#include "FastNegativeExp.h"
#include "MathDetail.h"
#include "CoreTools/Helper/Assertion/MathematicsCustomAssertMacro.h"
template <typename Real>
requires std::is_floating_point_v<Real>
Real Mathematics::FastNegativeExp<Real>::FastNegativeExpMoreRoughCalculation(Real value) noexcept(gAssert < 3 || gMathematicsAssert < 3)
{
MATHEMATICS_ASSERTION_3(Math::GetValue(0) <= value, "输入值必须在范围[0,无穷大)!\n");
auto result = static_cast<Real>(0.0038278);
result *= value;
result += static_cast<Real>(0.0292732);
result *= value;
result += static_cast<Real>(0.2507213);
result *= value;
result += static_cast<Real>(1.0);
result *= result;
result *= result;
result = static_cast<Real>(1.0) / result;
return result;
}
template <typename Real>
requires std::is_floating_point_v<Real>
Real Mathematics::FastNegativeExp<Real>::FastNegativeExpRoughCalculation(Real value) noexcept(gAssert < 3 || gMathematicsAssert < 3)
{
MATHEMATICS_ASSERTION_3(Math::GetValue(0) <= value, "输入值必须在范围[0,无穷大)!\n");
auto result = static_cast<Real>(0.00026695);
result *= value;
result += static_cast<Real>(0.00227723);
result *= value;
result += static_cast<Real>(0.03158565);
result *= value;
result += static_cast<Real>(0.24991035);
result *= value;
result += static_cast<Real>(1.0);
result *= result;
result *= result;
result = static_cast<Real>(1.0) / result;
return result;
}
template <typename Real>
requires std::is_floating_point_v<Real>
Real Mathematics::FastNegativeExp<Real>::FastNegativeExpPreciseCalculation(Real value) noexcept(gAssert < 3 || gMathematicsAssert < 3)
{
MATHEMATICS_ASSERTION_3(Math::GetValue(0) <= value, "输入值必须在范围[0,无穷大)!\n");
auto result = static_cast<Real>(0.000014876);
result *= value;
result += static_cast<Real>(0.000127992);
result *= value;
result += static_cast<Real>(0.002673255);
result *= value;
result += static_cast<Real>(0.031198056);
result *= value;
result += static_cast<Real>(0.250010936);
result *= value;
result += static_cast<Real>(1.0);
result *= result;
result *= result;
result = static_cast<Real>(1.0) / result;
return result;
}
template <typename Real>
requires std::is_floating_point_v<Real>
Real Mathematics::FastNegativeExp<Real>::FastNegativeExpMorePreciseCalculation(Real value) noexcept(gAssert < 3 || gMathematicsAssert < 3)
{
MATHEMATICS_ASSERTION_3(Math::GetValue(0) <= value, "输入值必须在范围[0,无穷大)!\n");
auto result = static_cast<Real>(0.0000006906);
result *= value;
result += static_cast<Real>(0.0000054302);
result *= value;
result += static_cast<Real>(0.0001715620);
result *= value;
result += static_cast<Real>(0.0025913712);
result *= value;
result += static_cast<Real>(0.0312575832);
result *= value;
result += static_cast<Real>(0.2499986842);
result *= value;
result += static_cast<Real>(1.0);
result *= result;
result *= result;
result = static_cast<Real>(1.0) / result;
return result;
}
#endif // MATHEMATICS_BASE_FAST_NEGATIVE_EXP_ACHIEVE_H | [
"94458936@qq.com"
] | 94458936@qq.com |
d4970c1e7e86038b21422148354c4acd7d34867c | 86bfffa80fa639f6277dda62bb5f202ad501c58c | /Herschels/src/gui/SweepEffectsDialog.cpp | 7109b55084e27c53b4011867b980375dec96ad8e | [
"CC0-1.0"
] | permissive | Adolfo1519/Herschels | 2dd3bb1a73e4044d497c1dd126a753a58ab30d4a | 729853f90f1b2fbce80d5b509e6447b557effe14 | refs/heads/master | 2021-06-02T10:02:11.580122 | 2021-06-01T13:48:03 | 2021-06-01T13:48:03 | 134,487,772 | 3 | 3 | null | 2021-06-01T13:48:04 | 2018-05-22T23:47:00 | C++ | UTF-8 | C++ | false | false | 7,080 | cpp |
//load in the dialog header and .ui file
#include "SweepEffectsDialog.hpp"
#include "ui_sweepEffectsDialog.h"
#include "Herschels.hpp"
#include "Oculars.hpp"
#include "StelApp.hpp"
#include "StelGui.hpp"
#include "StelFileMgr.hpp"
#include "StelModuleMgr.hpp"
#include "StelMainView.hpp"
#include "StelMainScriptAPI.hpp"
#include "StelMovementMgr.hpp"
#include "StelTranslator.hpp"
#include "StelActionMgr.hpp"
#include "StelUtils.hpp"
#include <QAbstractItemModel>
#include <QDataWidgetMapper>
#include <QDebug>
#include <QFrame>
#include <QModelIndex>
#include <QSettings>
#include <QStandardItemModel>
#include <limits>
#include <QRegExpValidator>
SweepEffectsDialog::SweepEffectsDialog(Herschels* pluginPtr,
HerschelsDialog* herschelsDialogPtr,
QList<Sweep *> sweeps)
: StelDialog("SweepEffects")
, plugin(pluginPtr)
, herschelsDialog(herschelsDialogPtr)
{
ui = new Ui_sweepEffectsDialogForm();
//I changed the default height. it was 661, now it is 249
this->sweeps = sweeps;
}
SweepEffectsDialog::~SweepEffectsDialog()
{
delete ui;
ui = Q_NULLPTR;
}
void SweepEffectsDialog::updateCircles()
{
StelCore *core = StelApp::getInstance().getCore();
QBrush nightBrush(Qt::darkBlue);
QPen outlinePen(Qt::white);
outlinePen.setWidth(2);
const StelProjectorP prj = core->getProjection(StelCore::FrameAltAz);
QString currentlyAt;
Vec2i centerScreen(prj->getViewportPosX() + prj->getViewportWidth() / 2,
prj->getViewportPosY() + prj->getViewportHeight() / 2);
Vec3d centerPosition;
prj->unProject(centerScreen[0], centerScreen[1], centerPosition);
double cx, cy;
StelUtils::rectToSphe(&cx,&cy,core->j2000ToEquinoxEqu(core->altAzToJ2000(centerPosition,StelCore::RefractionOff),StelCore::RefractionOff));//centerPosition);
//core->equinoxEquToJ2000(centerPosition, StelCore::RefractionOff)); // Calculate RA/DE (J2000.0) and show it...
double currentX = cx;//plugin->cx;
double currentY = cy;//plugin->cy;
if (startRARads > 3.14159265) {startRARads-=2*3.14159265;}
newX = (scene->width())*(currentX - startRARads)/deltaRARads;
newY = ((scene->height())*(currentY - startDecRads)/deltaDecRads)-(radiusY/2.0)-(ui->refreshSweep->height()/2.0);
//qWarning() << "current location is " << currentX << ", " << currentY << ": " << currentX*180/3.14159 << ", " << currentY*180/3.14159;
//qWarning() << "starting positions were " << startRARads << ", " << startDecRads;
//qWarning() << "window parameters are " << deltaRARads << ", " << deltaDecRads;
//qWarning() << "NewX and NewY are " << newX << ", " << newY;
ellipse->setPos(newX, newY);
}
/* ********************************************************************* */
#if 0
#pragma mark -
#pragma mark StelModule Methods
#endif
/* ********************************************************************* */
void SweepEffectsDialog::retranslate()
{
if (dialog) {
ui->retranslateUi(dialog);
initAboutText();
}
}
/* ********************************************************************* */
#if 0
#pragma mark -
#pragma mark Slot Methods
#endif
/* ********************************************************************* */
void SweepEffectsDialog::closeWindow()
{
setVisible(false);
StelMainView::getInstance().scene()->setActiveWindow(0);
}
//********************************************************************
/* ********************************************************************* */
#if 0
#pragma mark -
#pragma mark Protected Methods
#endif
/* ********************************************************************* */
void SweepEffectsDialog::createDialogContent()
{
ui->setupUi(dialog);
connect(&StelApp::getInstance(), SIGNAL(languageChanged()), this, SLOT(retranslate()));
//Uncomment this line if you want to hide the title bar of the dialog
// ui->TitleBar->hide();
#ifdef Q_OS_WIN
//Kinetic scrolling for tablet pc and pc
QList<QWidget *> addscroll;
addscroll << ui->textBrowser << ui->sweepListView ;
installKineticScrolling(addscroll);
#endif
//Now the rest of the actions.
connect(ui->closeStelWindow, SIGNAL(clicked()), this, SLOT(close()));
connect(ui->TitleBar, SIGNAL(movedTo(QPoint)), this, SLOT(handleMovedTo(QPoint)));
//*************************************************************
scene = new QGraphicsScene(dialog);
ui->sweepView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
ui->sweepView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
ui->sweepView->setScene(scene);
qWarning() << "Setting up the Sweep Effects Dialog";
QBrush blackBrush(Qt::black);
QBrush nightBrush(Qt::darkBlue);
QPen outlinePen(Qt::black);
QPen ocularPen(Qt::white);
outlinePen.setWidth(2);
scene->setBackgroundBrush(blackBrush);
dialog->setFixedHeight(249+ui->refreshSweep->height());
dialog->setFixedWidth(650);
//get box sweep parameters from Herschels
int index = plugin->getSelectedSweepIndex();
sweep = sweeps[index];
int screenHeight = 249; //(dialog->height()/2) - (ui->refreshSweep->height())/2.0
int screenWidth = 650; //dialog->width()
scene->setSceneRect(0, 0, screenWidth, screenHeight);//-ui->refreshSweep->height(), screenWidth, screenHeight);
qWarning() << "The scene size is " << scene->width() << ", " << scene->height();
setUpScene(sweep);
newX = -radiusX/2.0;//-(dialogWidth);
newY = 0;//radiusY/2.0-ui->refreshSweep->height();//(-dialog->height()/2.0) + radiusY/2.0-ui->refreshSweep->height();//dialogHeight;
ellipse = scene->addEllipse(newX, newY, radiusX, radiusY, ocularPen, nightBrush);
//****************************************************************
initAboutText();
connect(ui->refreshSweep, SIGNAL(pressed()), herschelsDialog, SLOT(resetSweep()));
}
//**************************************************************
//Don't worry about the "about" text portion, either. Just leave it as is, or delete it. I don't care.
void SweepEffectsDialog::initAboutText()
{
}
void SweepEffectsDialog::setUpScene(Sweep* sweepEx)
{
StelCore *core = StelApp::getInstance().getCore();
StelMovementMgr * stelMovementMgr=core->getMovementMgr();
startRARads = StelUtils::getDecAngle(sweepEx->startRA());
endRARads = StelUtils::getDecAngle(sweepEx->endRA());
deltaRARads = endRARads - startRARads;
if (deltaRARads < -3.14159)
{
startRARads -= 2.0*3.14159265;
deltaRARads = endRARads - startRARads;
}
startDecRads = StelUtils::getDecAngle(sweepEx->startDec());
endDecRads = StelUtils::getDecAngle(sweepEx->endDec());
deltaDecRads = endDecRads-startDecRads;
double fovRads = (stelMovementMgr->getAimFov())*3.14159265/180.0;
radiusX = (scene->width())*fovRads/(std::abs(deltaRARads));
radiusY = (scene->height())*fovRads/(std::abs(deltaDecRads));
qWarning() << "ellipse parameters are " << radiusX << ", " << radiusY << ": fov is " << fovRads;
}
| [
"asc5@rice.edu"
] | asc5@rice.edu |
ce3efae8e684acb59984531466c4502758b74deb | 0f971a91b4ad423748bba8c7159940ccf3064a7b | /VoxelEngine/VoxelEngine/src/engine/graphics/TileMap.h | 5f7621b01f3a7592b04c3f7dcad8e13865378a44 | [
"MIT"
] | permissive | LucidSigma/Voxel-Engine | f437e76bf76f180cc06b836026007b6397590716 | 5cb7fdf280f2f9029ec218d458ee887d9aceff75 | refs/heads/master | 2021-01-16T14:57:18.145591 | 2020-02-26T03:58:41 | 2020-02-26T03:58:41 | 243,160,006 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 810 | h | #pragma once
#ifndef TILE_MAP_H
#define TILE_MAP_H
#include "../interfaces/INoncopyable.h"
#include <glm/glm.hpp>
#include <cstddef>
#include <string_view>
#include <unordered_map>
#include <utility>
#include <vector>
#include "TextureArray.h"
class TileMap
: private INoncopyable
{
private:
const TextureArray* m_textureAtlas = nullptr;
unsigned int m_tileColumns = 0;
unsigned int m_tileRows = 0;
std::unordered_map<std::string_view, size_t> m_tileNames;
public:
TileMap(const TextureArray& textureAtlas, const glm::uvec2& tileSize, const std::vector<std::string_view>& tileNames);
TileMap(TileMap&& other) noexcept;
TileMap& operator =(TileMap&& other) noexcept;
~TileMap() noexcept = default;
void Bind() const;
size_t GetTileIndex(const std::string_view& tileName) const;
};
#endif | [
"lucidsigma17@gmail.com"
] | lucidsigma17@gmail.com |
995edb0e7eb5dbcc6146fb8d1f61b4cfdab70f2a | 391cf73bb13a1cf457650a0c3b8605bb35fc00f2 | /src/stats.cpp | 9939c3e8c1450370847336b283005c7eb0b29d43 | [
"NCSA"
] | permissive | YunMoZhang/neo | b275d6bbaecd31fb4f6996af8d50d1d831b47e24 | 8601491e81e5b0cb1375a226ba8ae414477733d5 | refs/heads/master | 2023-03-18T01:51:08.339146 | 2021-03-09T00:09:05 | 2021-03-09T00:09:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,962 | cpp | #include "stats.hpp"
#include <unistd.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <fstream>
#include "lib/logger.hpp"
#include "policy/policy.hpp"
using namespace std::chrono;
/********************* private definitions *********************/
bool Stats::record_latencies = false; // no latency recording by defualt
std::chrono::high_resolution_clock::time_point Stats::total_t1;
std::chrono::microseconds Stats::total_time;
long Stats::total_maxrss;
std::chrono::high_resolution_clock::time_point Stats::policy_t1;
std::chrono::microseconds Stats::policy_time;
long Stats::policy_maxrss;
std::chrono::high_resolution_clock::time_point Stats::ec_t1;
std::chrono::microseconds Stats::ec_time;
long Stats::ec_maxrss;
std::chrono::high_resolution_clock::time_point Stats::overall_lat_t1;
std::chrono::high_resolution_clock::time_point Stats::rewind_lat_t1;
std::chrono::high_resolution_clock::time_point Stats::pkt_lat_t1;
std::vector<std::chrono::nanoseconds> Stats::overall_latencies;
std::vector<std::chrono::nanoseconds> Stats::rewind_latencies;
std::vector<int> Stats::rewind_injection_count;
std::vector<std::chrono::nanoseconds> Stats::pkt_latencies;
high_resolution_clock::duration
Stats::get_duration(const high_resolution_clock::time_point& t1)
{
if (t1.time_since_epoch().count() == 0) {
Logger::error("t1 not set");
}
return high_resolution_clock::now() - t1;
}
/********************* control functions *********************/
void Stats::enable_latency_recording()
{
record_latencies = true;
}
void Stats::output_main_stats()
{
Logger::info("====================");
Logger::info("Time: " + std::to_string(total_time.count()) + " microseconds");
Logger::info("Memory: " + std::to_string(total_maxrss) + " kilobytes");
}
void Stats::output_policy_stats(int nodes, int links, Policy *policy)
{
const std::string filename = "policy.stats.csv";
std::ofstream outfile(filename, std::ios_base::app);
if (outfile.fail()) {
Logger::error("Failed to open " + filename);
}
outfile << "# of nodes, # of links, Policy, # of ECs, # of communications, "
"Time (microseconds), Memory (kilobytes)" << std::endl
<< nodes << ", "
<< links << ", "
<< policy->get_id() << ", "
<< policy->num_ecs() << ", "
<< policy->num_comms() << ", "
<< policy_time.count() << ", "
<< policy_maxrss << std::endl;
}
void Stats::output_ec_stats()
{
const std::string filename = std::to_string(getpid()) + ".stats.csv";
std::ofstream outfile(filename, std::ios_base::app);
if (outfile.fail()) {
Logger::error("Failed to open " + filename);
}
outfile << "Time (microseconds), Memory (kilobytes)" << std::endl
<< ec_time.count() << ", " << ec_maxrss << std::endl;
if (record_latencies) {
outfile << "Overall latency (nanoseconds), "
"Rewind latency (nanoseconds), "
"Rewind injection count, "
"Packet latency (nanoseconds)" << std::endl;
for (size_t i = 0; i < overall_latencies.size(); ++i) {
outfile << overall_latencies[i].count() << ", "
<< rewind_latencies[i].count() << ", "
<< rewind_injection_count[i] << ", "
<< pkt_latencies[i].count() << std::endl;
}
}
}
/********************* main process measurements *********************/
void Stats::set_total_t1()
{
total_t1 = high_resolution_clock::now();
}
void Stats::set_total_time()
{
total_time = duration_cast<microseconds>(get_duration(total_t1));
}
void Stats::set_total_maxrss()
{
struct rusage ru;
if (getrusage(RUSAGE_CHILDREN, &ru) < 0) {
Logger::error("getrusage()", errno);
}
total_maxrss = ru.ru_maxrss;
}
/******************** policy process measurements ********************/
void Stats::set_policy_t1()
{
policy_t1 = high_resolution_clock::now();
}
void Stats::set_policy_time()
{
policy_time = duration_cast<microseconds>(get_duration(policy_t1));
}
void Stats::set_policy_maxrss()
{
struct rusage ru;
if (getrusage(RUSAGE_CHILDREN, &ru) < 0) {
Logger::error("getrusage()", errno);
}
policy_maxrss = ru.ru_maxrss;
}
/********************** EC process measurements **********************/
void Stats::set_ec_t1()
{
ec_t1 = high_resolution_clock::now();
}
void Stats::set_ec_time()
{
ec_time = duration_cast<microseconds>(get_duration(ec_t1));
}
void Stats::set_ec_maxrss()
{
struct rusage ru;
if (getrusage(RUSAGE_SELF, &ru) < 0) {
Logger::error("getrusage()", errno);
}
ec_maxrss = ru.ru_maxrss;
}
/********************** latency measurements **********************/
void Stats::set_overall_lat_t1()
{
if (record_latencies) {
overall_lat_t1 = high_resolution_clock::now();
}
}
void Stats::set_overall_latency()
{
if (record_latencies) {
auto overall_latency = duration_cast<nanoseconds>(get_duration(overall_lat_t1));
overall_latencies.push_back(overall_latency);
}
}
void Stats::set_rewind_lat_t1()
{
if (record_latencies) {
rewind_lat_t1 = high_resolution_clock::now();
}
}
void Stats::set_rewind_latency()
{
if (record_latencies) {
auto rewind_latency = duration_cast<nanoseconds>(get_duration(rewind_lat_t1));
rewind_latencies.push_back(rewind_latency);
}
}
void Stats::set_rewind_injection_count(int count)
{
if (record_latencies) {
rewind_injection_count.push_back(count);
}
}
void Stats::set_pkt_lat_t1()
{
if (record_latencies) {
pkt_lat_t1 = high_resolution_clock::now();
}
}
void Stats::set_pkt_latency()
{
if (record_latencies) {
auto pkt_latency = duration_cast<nanoseconds>(get_duration(pkt_lat_t1));
pkt_latencies.push_back(pkt_latency);
}
}
| [
"kuanyenchou@gmail.com"
] | kuanyenchou@gmail.com |
c84d3b544f3a21a0161458b4ed80506fe2b21745 | 8d85bd979c08a6313c31d00fd3f10bbe836d691d | /wpilibc/src/main/native/cpp/trajectory/constraint/CentripetalAccelerationConstraint.cpp | bf45c349a27ff57a9de9bce7eff2a0cfc54a9c45 | [
"BSD-3-Clause"
] | permissive | Aaquib111/allwpilib | e7c1a9eb0693867287494da2c38125354b295476 | 59507b12dc6aec05167fb9c086c3a70c9e5ed632 | refs/heads/master | 2020-09-11T20:59:51.018124 | 2019-11-16T05:51:31 | 2019-11-16T05:51:31 | 222,188,562 | 2 | 0 | NOASSERTION | 2019-11-17T02:52:19 | 2019-11-17T02:52:19 | null | UTF-8 | C++ | false | false | 1,655 | cpp | /*----------------------------------------------------------------------------*/
/* Copyright (c) 2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "frc/trajectory/constraint/CentripetalAccelerationConstraint.h"
using namespace frc;
CentripetalAccelerationConstraint::CentripetalAccelerationConstraint(
units::meters_per_second_squared_t maxCentripetalAcceleration)
: m_maxCentripetalAcceleration(maxCentripetalAcceleration) {}
units::meters_per_second_t CentripetalAccelerationConstraint::MaxVelocity(
const Pose2d& pose, curvature_t curvature,
units::meters_per_second_t velocity) {
// ac = v^2 / r
// k (curvature) = 1 / r
// therefore, ac = v^2 * k
// ac / k = v^2
// v = std::sqrt(ac / k)
// We have to multiply by 1_rad here to get the units to cancel out nicely.
// The units library defines a unit for radians although it is technically
// unitless.
return units::math::sqrt(m_maxCentripetalAcceleration /
units::math::abs(curvature) * 1_rad);
}
TrajectoryConstraint::MinMax
CentripetalAccelerationConstraint::MinMaxAcceleration(
const Pose2d& pose, curvature_t curvature,
units::meters_per_second_t speed) {
// The acceleration of the robot has no impact on the centripetal acceleration
// of the robot.
return {};
}
| [
"johnson.peter@gmail.com"
] | johnson.peter@gmail.com |
734ceb9995caa6f350c91128e502ca5b94b16a34 | 40d23f6f47eef750c37949c523324d82a5923f28 | /token.h | 454487f4036aaeeac070beb539d3b21d74d93fad | [] | no_license | Moulten/EventDataBase-Yandex | 065e0fb2a9434fd2bc37185d1d379799c5790dbb | 97b2d234ef5902dc307cc2be02f7cb09689ea7f3 | refs/heads/master | 2022-12-07T11:30:16.254612 | 2020-08-27T20:37:09 | 2020-08-27T20:37:09 | 290,871,507 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 438 | h | #pragma once
#include <sstream>
#include <vector>
using namespace std;
enum class TokenType {
DATE,
EVENT,
COLUMN,
LOGICAL_OP,
COMPARE_OP,
PAREN_LEFT,
PAREN_RIGHT,
};
enum class Comparison {
Less,
LessOrEqual,
Greater,
GreaterOrEqual,
Equal,
NotEqual,
};
enum class LogicalOperation {
Or,
And,
};
struct Token {
const string value;
const TokenType type;
};
vector<Token> Tokenize(istream& cl);
| [
"g.a.poyarkov@gmail.com"
] | g.a.poyarkov@gmail.com |
80eb817da03e3b91da9256c5906d3b438ff24332 | de9b6220aced312a1a5184bcc50e8d673d25fd3a | /samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelBMFontTest/UILabelBMFontTest_Editor.h | 4f72e3837642b99b9c0c149a01600f51a0a5502b | [] | no_license | sdkbox/sdkbox-iap-sample-v2 | d65ea8b033da23a4b53d1322991cda466b904645 | 89d014ddc217a29e5aa9596a4e9d95566a5989a0 | refs/heads/master | 2020-04-09T13:32:50.310291 | 2016-01-16T23:24:30 | 2016-01-16T23:24:30 | 40,207,505 | 2 | 7 | null | 2016-03-14T23:25:45 | 2015-08-04T20:29:41 | C++ | UTF-8 | C++ | false | false | 1,687 | h | /****************************************************************************
Copyright (c) 2014 cocos2d-x.org
http://www.cocos2d-x.org
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 __TestCpp__UILabelBMFontTest_Editor__
#define __TestCpp__UILabelBMFontTest_Editor__
#include "../UIScene_Editor.h"
class UILabelBMFontTest_Editor : public UIScene_Editor
{
public:
bool init();
void configureGUIScene();
virtual void switchLoadMethod(CCObject* pSender);
protected:
UI_SCENE_EDITOR_CREATE_FUNC(UILabelBMFontTest_Editor)
};
#endif /* defined(__TestCpp__UILabelBMFontTest_Editor__) */
| [
"darkdukey@gmail.com"
] | darkdukey@gmail.com |
607c318675d83895092c2b81af7d9970d55aba24 | 38a2a5b11186f2cde0a9fdf42b2a3edff818e276 | /KDIS/DataTypes/IOEffect.h | 687440cda1468249fe94a851b912991058222e05 | [
"BSD-2-Clause"
] | permissive | cdit-ma/kdis | 7f9afaa07da1d64ff960f5841710cb1445cdebe1 | f722221cee0e5ea6869f9e923ad1cdb93d5d289f | refs/heads/master | 2022-01-06T08:42:33.244560 | 2019-08-14T03:09:07 | 2019-08-14T03:09:07 | 202,251,645 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,636 | h | /*********************************************************************
Copyright 2013 Karl Jones
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.
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.
For Further Information Please Contact me at
Karljj1@yahoo.com
http://p.sf.net/kdis/UserGuide
*********************************************************************/
/********************************************************************
class: IOEffect
created: 05/12/2010
author: Karl Jones
purpose: Identification of IO effects on an entity when calculated by an IO simulation.
size: 128 bits / 16 octets
*********************************************************************/
#pragma once
#include "./StandardVariable.h"
namespace KDIS {
namespace DATA_TYPE {
class KDIS_EXPORT IOEffect : public StandardVariable
{
protected:
KUINT8 m_ui8Status;
KUINT8 m_ui8LnkTyp;
KUINT8 m_ui8Eff;
KUINT8 m_ui8EffDtyCyc;
KUINT16 m_ui16EffDur;
KUINT16 m_ui16Proc;
KUINT16 m_ui16Padding;
public:
static const KUINT16 IO_EFFECT_TYPE_SIZE = 16;
IOEffect( KDIS::DATA_TYPE::ENUMS::IOStatus S, KDIS::DATA_TYPE::ENUMS::IOLinkType LT, KDIS::DATA_TYPE::ENUMS::IOEffectType ET,
KUINT8 DutyCycle, KUINT16 Duration, KUINT16 Process ) throw( KException );
IOEffect();
IOEffect( KDataStream & stream ) throw( KException );
virtual ~IOEffect();
//************************************
// FullName: KDIS::DATA_TYPE::IOEffect::SetStatus
// KDIS::DATA_TYPE::IOEffect::GetStatus
// Description: Indicates whether the IO effect has an effect on the sender,
// receiver, message(s) or some combination of them.
// Parameter: IOStatus S
//************************************
void SetStatus( KDIS::DATA_TYPE::ENUMS::IOStatus S );
KDIS::DATA_TYPE::ENUMS::IOStatus GetStatus() const;
//************************************
// FullName: KDIS::DATA_TYPE::IOEffect::SetLinkType
// KDIS::DATA_TYPE::IOEffect::GetLinkType
// Description: The IO link type as a logical or physical link or node.
// Parameter: IOLinkType LT
//************************************
void SetLinkType( KDIS::DATA_TYPE::ENUMS::IOLinkType LT );
KDIS::DATA_TYPE::ENUMS::IOLinkType GetLinkType() const;
//************************************
// FullName: KDIS::DATA_TYPE::IOEffect::SetEffectType
// KDIS::DATA_TYPE::IOEffect::GetEffectType
// Description: The IO effect associated with this IO attack.
// Parameter: IOEffectType ET
//************************************
void SetEffectType( KDIS::DATA_TYPE::ENUMS::IOEffectType ET );
KDIS::DATA_TYPE::ENUMS::IOEffectType GetEffectType() const;
//************************************
// FullName: KDIS::DATA_TYPE::IOEffect::SetEffectDutyCycle
// KDIS::DATA_TYPE::IOEffect::GetEffectDutyCycle
// Description: The IO effect duty cycle represented as a percentage in
// the range of 0 - 100% in one-percent increments.
// Throws OUT_OF_BOUNDS exception if value is > 100.
// Parameter: KUINT8 EDC
//************************************
void SetEffectDutyCycle( KUINT8 EDC ) throw( KException );
KUINT8 GetEffectDutyCycle() const;
//************************************
// FullName: KDIS::DATA_TYPE::IOEffect::SetEffectDuration
// KDIS::DATA_TYPE::IOEffect::GetEffectDuration
// Description: Indicates the duration of the IO effect in seconds, from 1
// to 65534 seconds.
// It shall be set to indicate UNTIL_FURTHER_NOTICE (65535) if
// the duration has no fixed amount of time.
// It shall be set to zero only if the IO Effect field is set
// to Terminate Effect(255).
// Parameter: KUINT16 ED
//************************************
void SetEffectDuration( KUINT16 ED );
KUINT16 GetEffectDuration() const;
//************************************
// FullName: KDIS::DATA_TYPE::IOEffect::SetProcess
// KDIS::DATA_TYPE::IOEffect::GetProcess
// Description: The IO process being performed.
// Parameter: KUINT16 P
//************************************
void SetProcess( KUINT16 P );
KUINT16 GetProcess() const;
//************************************
// FullName: KDIS::DATA_TYPE::IOEffect::GetAsString
// Description: Returns a string representation.
//************************************
virtual KString GetAsString() const;
//************************************
// FullName: KDIS::DATA_TYPE::IOEffect::Decode
// Description: Convert From Network Data.
// Parameter: KDataStream & stream
//************************************
virtual void Decode( KDataStream & stream ) throw( KException );
//************************************
// FullName: KDIS::DATA_TYPE::IOEffect::Encode
// Description: Convert To Network Data.
// Parameter: KDataStream & stream
//************************************
virtual KDataStream Encode() const;
virtual void Encode( KDataStream & stream ) const;
KBOOL operator == ( const IOEffect & Value ) const;
KBOOL operator != ( const IOEffect & Value ) const;
};
} // END namespace DATA_TYPES
} // END namespace KDIS
| [
"mitchell.w.conrad@gmail.com"
] | mitchell.w.conrad@gmail.com |
9f4ec280dbc7c0a5d91267f9ee6ad91c926eb325 | ed22bf7a0120f702fb812943852ebbe0060746b2 | /lib/PacketCreator/PacketCreator.h | 4a9eb6d849fa6aee19e1e16e884cdbd54ba0723e | [] | no_license | yoeshi/BTW-Robot | a80a99b3126044d3aa75c52177ea848f4f799d93 | 6a0175179ad5dabae72e2109b5729ac48d868ab2 | refs/heads/master | 2023-05-09T12:59:27.690538 | 2021-05-28T15:11:51 | 2021-05-28T15:11:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 408 | h | #include <ArduinoJson.h>
#include <ReceivedDataPacket.h>
namespace PacketCreator
{
String feedbackDataToJsonString(float leftVelocity, float rightVelocity, float angle, float speedPidP, float speedPidI, float anglePidP, float anglePidD, int delay);
String infoMessageToJsonString(String message);
String createTelemetryPacket(float=0.0f,float=0.0f,float=0.0f,float=0.0f,float=0.0f,float=0.0f);
}; | [
"dawid199912@gmail.com"
] | dawid199912@gmail.com |
0bc5a8656d48bb7fb633d6e34f0be47c549d9456 | af0ecafb5428bd556d49575da2a72f6f80d3d14b | /CodeJamCrawler/dataset/11_964_70.cpp | d5c4af9f666edd0b7904659dc284e36d859a813f | [] | no_license | gbrlas/AVSP | 0a2a08be5661c1b4a2238e875b6cdc88b4ee0997 | e259090bf282694676b2568023745f9ffb6d73fd | refs/heads/master | 2021-06-16T22:25:41.585830 | 2017-06-09T06:32:01 | 2017-06-09T06:32:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,255 | cpp | #include <cstdio>
#include <cstring>
using namespace std;
#define FOR(i,a,b) for(int i=a,_b=b;i<=_b;i++)
#define REP(i,a) FOR(i,0,a-1)
#define FORD(i,a,b) for(int i=a,_b=b;i>=_b;i--)
#define REPD(i,a) FORD(i,a-1,0)
#define _m(a,b) memset(a,b,sizeof(a))
#define MAX 200
int main (void) {
int T; scanf("%d", &T);
int C, D, N;
char CS[5], DS[5], NS[102];
char MC[MAX][MAX], MD[MAX][MAX];
char iS, S[102], A, B, F;
FOR(iT, 1, T) {
_m(MC, -1);
scanf("%d", &C);
REP(i, C) {
scanf("%s", &CS);
MC[CS[0]][CS[1]] = MC[CS[1]][CS[0]] = CS[2];
}
_m(MD, 0);
scanf("%d", &D);
REP(i, D) {
scanf("%s", &DS);
MD[DS[0]][DS[1]] = MD[DS[1]][DS[0]] = 1;
}
scanf("%d %s\n", &N, &NS);
iS=0;
REP(i, N) {
S[iS++] = NS[i];
F = 1;
while(iS > 1 && F) {
F = 0;
A = S[iS - 2];
B = S[iS - 1];
if(MC[A][B] != -1 || MC[B][A] != -1) {
S[iS-2] = MC[A][B];
iS--;
F = 1;
} else {
REPD(j, iS-1)
if(MD[B][S[j]] || MD[S[j]][B]) {
iS = 0;
break;
}
}
}
}
printf("Case #%d: [", iT);
REP(i, iS) printf("%s%c", (i?", ":""), S[i]);
printf("]\n");
}
return 0;
}
| [
"nikola.mrzljak@fer.hr"
] | nikola.mrzljak@fer.hr |
fb164f158e040c1572f8a28ed7ccdaf4f5b9153e | 13bfcfd7492f3f4ee184aeafd0153a098e0e2fa5 | /TIOJ/1248.cpp | 7b978137d91f69417ef38aa4967605c49c991015 | [] | no_license | jqk6/CodeArchive | fc59eb3bdf60f6c7861b82d012d298f2854d7f8e | aca7db126e6e6f24d0bbe667ae9ea2c926ac4a5f | refs/heads/master | 2023-05-05T09:09:54.032436 | 2021-05-20T07:10:02 | 2021-05-20T07:10:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,981 | cpp | #pragma GCC optimize("Ofast")
#pragma loop_opt(on)
#include<cstdio>
#include<cstring>
const int S = 1<<20;
inline char readchar(){
static char buf[S], *p = buf, *q = buf;
if(p==q&&(q=(p=buf)+fread(buf,1,S,stdin))==buf) return EOF;
return *p++;
}
#define BASE 10000
#define BASELEN 4
char inbuf[1000];
struct bigint{
int val[60], len;
bool sign;
bigint(){
val[0] = 0;
len = 1;
sign = false;
}
bool get(){
if(scanf("%s", inbuf) == EOF) return false;
sign = false;
len = -1;
for(int l = strlen(inbuf)-1, cnt = 0, d = 1; l >= 0; --l){
if(cnt == 0) ++len, val[len] = 0, d = 1;
val[len] += (inbuf[l] ^ '0') * d, d *= 10;
++cnt;
if(cnt == BASELEN) cnt = 0;
}
++len;
return true;
}
void print(){
if(sign) putchar('-');
int l = len-1;
printf("%d", val[l--]);
while(l >= 0) printf("%04d", val[l--]);
}
bool operator<(const bigint &rhs){
if(sign != rhs.sign) return sign > rhs.sign;
if(len != rhs.len) return (len < rhs.len) ^ (!sign);
for(int i = len-1; i >= 0; --i)
if(val[i] != rhs.val[i]) return (val[i] < rhs.val[i]) ^ (!sign);
return false;
}
void trim(){
while(len > 0 and val[len-1] == 0) --len;
if(len == 0) len = 1, sign = false;
}
};
bigint add(bigint a, bigint b){
return bigint();
}
bigint sub(bigint a, bigint b){
if(a < b){
bigint c = sub(b, a);
c.sign = true;
return c;
}
return bigint();
}
bigint mul(bigint a, bigint b){
return bigint();
}
bigint div(bigint a, bigint b){
return bigint();
}
bigint mod(bigint a, bigint b){
bigint c = div(a, b);
bigint d = mul(b, c);
return sub(a, d);
}
bigint a, b, c, d;
char move;
int main(){
while(a.get()){
move = 0;
while(move!='+' and move!='-' and move!='*' and move!='/') move = getchar();
b.get();
if(move == '+') c = add(a, b);
else if(move == '-') c = sub(a, b);
else if(move == '8') c = mul(a, b);
else if(move == '/') c = div(a, b), d = mod(a, b);
c.print();
if(move == '/') printf("..."), d.print();
puts("");
}
} | [
"froghackervirus@gmail.com"
] | froghackervirus@gmail.com |
502bf6096e4425679ec75b89da96f04c0664f501 | 166c162c14562a1dcd8e9fd8c138c461608b4402 | /array/move_negative_to_end.cpp | 5370173fad637446ea2e5ed45fa6503448e6fee3 | [] | no_license | shibajyoti17/Cpp-Data-Structure-and-algorithms | 56a631ffdbc6fbdd5e507aebce42fb3b6c2592ee | 4b45a6006c39ebd425f795fa88764dd45d3e35e4 | refs/heads/master | 2023-06-26T11:12:54.527407 | 2021-08-03T05:53:38 | 2021-08-03T05:53:38 | 380,946,195 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 587 | cpp | #include<iostream>
using namespace std;
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int n;
cout << "Enter the number of elements: " << endl;
cin >> n;
int arr[n];
for(int i = 0; i < n; i++) {
cin >> arr[i];
}
int low = 0, high = n-1;
while(low < high) {
if( arr[low] < 0) {
swap(arr[low], arr[high]);
high--;
}
else {
low++;
}
}
for(int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << "\n";
return 0;
}
| [
"shibajyotim@gmail.com"
] | shibajyotim@gmail.com |
f09b593285b7688351187fd469dff34bf043944e | 5c12bfe2c4b661986d2740aa48a402fd2fd01703 | /src/bin/make-fullctx-ali-dnn.cc | 9f0de9014908265a49c89d7f17da608679aef345 | [
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | oplatek/idlak | fea41d797b862f5382bd17c0ca8349b346cb44d7 | 02b24dc6f79b84779e423bfbb17bdf8e70c95aec | refs/heads/import-svn-idlak | 2021-01-11T04:41:39.367915 | 2016-09-14T18:13:52 | 2016-09-14T18:13:52 | 71,112,898 | 0 | 0 | NOASSERTION | 2020-02-20T13:09:34 | 2016-10-17T07:48:11 | C++ | UTF-8 | C++ | false | false | 11,144 | cc | // bin/make-fullctx-ali.cc
// Copyright 2013 CereProc Ltd. (Author: Matthew Aylett)
// 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
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
//
// Full context alignments have the form
// <phone contexts> <full context> <state no> as an integer vector for
// each frame.
// Full context is output by cex idlak voice build module and assigns a
// full context for each phone.
// the align idlak voice build module produces a standard quin phone alignment
// by transition id.
// This program takes this alignment, extracts the phone context and state no
// for each frame and merges it with the phone full context information.
// The process is complicated by the fact that initial and final pauses may be
// missing from the data while assummed in the full context information.
// Current policy is to remove context information for leading and final pauses
// if they are not in the alignment and set all context information to 0.
// Models in any built tree for silence data are then ignored.
#include "base/kaldi-common.h"
#include "util/common-utils.h"
#include "gmm/am-diag-gmm.h"
#include "hmm/transition-model.h"
#include "hmm/hmm-utils.h"
#include "hmm/tree-accu.h" // for ReadPhoneMap
#define PHONECONTEXT 5
#define MIDCONTEXT 2
double fuzzy_position(double fuzzy_factor, int position, int duration) {
double real_position = ((double)position + 0.5) / (double)duration;
return round(real_position / fuzzy_factor) /* * fuzzy_factor */;
}
int main(int argc, char *argv[]) {
using namespace kaldi;
typedef kaldi::int32 int32;
int32 phone_index, j, k, last_phone, last_state, curlen_phone, curlen_state;
std::vector< std::vector<int32> >::iterator v;
try {
const char *usage =
"Merges output from context extraction with a standard alignment\n"
"Usage: make-fullctx-ali model old-alignments-rspecifier \n"
" full-contexts-rspecifier fullcontext-alignments-wspecifier\n"
"e.g.: \n"
" make-fullctx-ali model.mdl ark:old.ali ark,t:cex.ark ark:new.ali\n";
std::string phone_map_rxfilename;
int phonecontext = 5;
int midcontext = 2;
int maxsilphone = 1;
BaseFloat phone_fuzz_factor = 0.1;
BaseFloat state_fuzz_factor = 0.2;
ParseOptions po(usage);
po.Register("phone-context", &phonecontext, "Size of the phone context, e.g. 3 for triphone.");
po.Register("mid-context", &midcontext, "Position of the middle phone, e.g. 1 for triphone.");
po.Register("max-sil-phone", &maxsilphone, "Maximum value of silence phone");
po.Register("phone-fuzz-factor", &phone_fuzz_factor, "Rounding value for phone positioning");
po.Register("state-fuzz-factor", &state_fuzz_factor, "Rounding value for state positioning");
po.Read(argc, argv);
if (po.NumArgs() != 4) {
po.PrintUsage();
exit(1);
}
std::string model_filename = po.GetArg(1);
std::string old_alignments_rspecifier = po.GetArg(2);
std::string contexts_rspecifier = po.GetArg(3);
std::string new_alignments_wspecifier = po.GetArg(4);
TransitionModel trans_model;
ReadKaldiObject(model_filename, &trans_model);
SequentialInt32VectorReader alignment_reader(old_alignments_rspecifier);
SequentialInt32VectorVectorReader contexts_reader(contexts_rspecifier);
Int32VectorVectorWriter alignment_writer(new_alignments_wspecifier);
int num_success = 0, num_fail = 0;
for (; !contexts_reader.Done() && !alignment_reader.Done();
contexts_reader.Next(), alignment_reader.Next()) {
std::string ctxkey = contexts_reader.Key();
const std::vector< std::vector<int32> > &contexts =
contexts_reader.Value();
std::string key = alignment_reader.Key();
std::vector<int32> old_alignment = alignment_reader.Value();
// Check the keys are the same
if (ctxkey != key) {
KALDI_WARN << "Could not merge alignment and contexts for key " << key
<<" (missing data?)";
num_fail++;
continue;
}
/*std::cout << ctxkey << " " << key << "\n";*/
std::vector< std::vector<int32> > phone_windows;
std::vector<int32> phones;
std::vector<int32> states;
std::vector< std::vector<int32> > output;
std::vector<int32> curphone;
for (size_t i = 0; i < old_alignment.size(); i++)
states.push_back(trans_model.TransitionIdToHmmState(old_alignment[i]));
if (!GetPhoneWindows(trans_model,
old_alignment,
phonecontext,
midcontext,
true,
&phone_windows,
&phones)) {
KALDI_WARN << "Could not convert alignment for key " << key
<<" (possibly truncated alignment?)";
num_fail++;
continue;
}
/* Start processing alignment and label */
last_phone = -1;
last_state = -1;
phone_index = 0;
/* Duration (in frames) of current phone and state */
curlen_phone = -1;
curlen_state = -1;
bool new_phone = false, new_state = false;
for (v = phone_windows.begin(), j = 0;
v != phone_windows.end();
v++, j++) {
curlen_phone++;
curlen_state++;
curphone = *v;
/* We have a new phone if the phone identity change, or
if the state decreases within a non-silence phone */
if ( last_phone >= 0 &&
(curphone[midcontext] != last_phone ||
(last_phone > maxsilphone && states[j] < last_state))) {
/* What to do when we have a new phone:
1. advance phone index
2. output phone / state durations
3. reset curlen_phone, curlen_state */
phone_index++;
new_phone = true;
new_state = true;
}
else if (last_state >= 0 &&
states[j] != last_state) {
new_state = true;
}
// check we have a silence at start of utt if not
// skip silence in context data
if (!phone_index && curphone[midcontext] > maxsilphone)
phone_index++;
/*std::cout << phone_index << " " << curphone[midcontext] << "\n";*/
// Recreate context structure, add state
std::vector<int32> outphone;
if (phone_index < contexts.size()) {
for (k = 0; k < contexts[phone_index].size(); k++)
outphone.push_back(contexts[phone_index][k]);
} else {
for (k = 0; k < contexts[contexts.size() - 1].size(); k++)
outphone.push_back(contexts[contexts.size() - 1][k]);
}
outphone.push_back(states[j]);
output.push_back(outphone);
// Add position / duration information for state
if (new_state) {
for (int32 k = 0; k < curlen_state; k++) {
float position = fuzzy_position(state_fuzz_factor, k, curlen_state);
// State duration
output[j - curlen_state + k].push_back(curlen_state);
// Position within the state
output[j - curlen_state + k].push_back(position);
}
curlen_state = 0;
new_state = false;
}
/* Last iteration of the loop: force the update of phone / state info */
if (phone_index >= contexts.size() || (v + 1 == phone_windows.end())) {
new_state = true;
new_phone = true;
j++;
curlen_phone++;
curlen_state++;
}
// Add position / duration information for state / phone
// Note: the state is only added here in the final iteration
if (new_state) {
for (int32 k = 0; k < curlen_state; k++) {
float position = fuzzy_position(state_fuzz_factor, k, curlen_state);
// State duration
output[j - curlen_state + k].push_back(curlen_state);
// Position within the state
output[j - curlen_state + k].push_back(position);
}
curlen_state = 0;
new_state = false;
}
if (new_phone) {
for (int32 k = 0; k < curlen_phone; k++) {
float position = fuzzy_position(phone_fuzz_factor, k, curlen_phone);
// Phone duration
output[j - curlen_phone + k].push_back(curlen_phone);
// Position within the state
output[j - curlen_phone + k].push_back(position);
}
curlen_phone = 0;
new_phone = false;
}
if (phone_index >= contexts.size()) {
break;
}
last_phone = curphone[midcontext];
last_state = states[j];
}
// check we have a silence at end of utt; if not
// skip silence in context data
if (curphone[midcontext] > maxsilphone) phone_index++;
// phone_index should be pointing at the final silence...
if (phone_index + 1 != contexts.size()) {
/*if (phone_index != contexts.size()) {*/
KALDI_WARN << "Merge of alignment and contexts failed for key " << key
<<" mismatching number of phones contexts:"
<< contexts.size()
<<" alignment:" << phone_index + 1;
num_fail++;
continue;
/*// Or maybe right after it? In which case, there probably was no silence here
// in the first place!
else {
KALDI_WARN << "It seems sentence for key " << key
<<" had no final silence in context. The sentence was"
<<" *not* discarded.";
}*/
}
/*for (k = 0; k < output.size(); k++) {
KALDI_LOG << k << " : " << output[k].size();
}*/
alignment_writer.Write(key, output);
num_success++;
}
} catch(const std::exception &e) {
std::cerr << e.what();
return -1;
}
}
| [
"blaise@cereproc.com"
] | blaise@cereproc.com |
76ce115a572d2cdcf60d112c3ce000434d5f654e | 30013e4f0def356c3ddad242f9bff0a155cbb039 | /rxDev/src/tagItems/argItem.h | d2b3dafa6868bc0e1c930d0ae3838fc57c1decf1 | [] | no_license | songxuchao/rxdeveloper-ros-pkg | 972c56b11d28d452d7272984454503cfa63e06e2 | 917c7874b16b9727eba9cfbfc64c5f98262db390 | refs/heads/master | 2021-01-10T20:14:17.495579 | 2012-04-14T13:02:10 | 2012-04-14T13:02:10 | 34,845,885 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,857 | h | #ifndef ARGITEM_H
#define ARGITEM_H
#include <QGraphicsRectItem>
#include <QGraphicsTextItem>
#include <QGraphicsSceneHoverEvent>
#include <QGraphicsSceneMouseEvent>
#include <QKeyEvent>
#include <QColor>
#include <QPainter>
#include <QPen>
#include <QPointF>
#include <QGraphicsWidget>
QT_BEGIN_NAMESPACE
class QPixmap;
class QGraphicsPolygonItem;
class QGraphicsScene;
class QTextEdit;
class QGraphicsSceneMouseEvent;
class QMenu;
class QGraphicsSceneContextMenuEvent;
class QPainter;
class QStyleOptionGraphicsItem;
class QWidget;
class QPolygonF;
QT_END_NAMESPACE
class ArgItem : public QGraphicsWidget
{
Q_OBJECT
public:
enum { Type = UserType + 9 };
ArgItem(QGraphicsScene *scene = 0);
void setLocation(QPointF point);
void setColor(QColor color);
int type() const
{ return Type;}
QGraphicsTextItem _title;
QGraphicsTextItem _name; ///< sample text to go in the title area.
QGraphicsTextItem _value; ///< sample text to go in the title area.
QGraphicsTextItem _value_or_default; ///< sample text to go in the title area.
QString getName();
void setName(QString newName);
QString getValue();
void setValue(QString newValue);
QString getIf();
void setIf(QString newIf);
QString getUnless();
void setUnless(QString newUnless);
int getValue_or_default();
void setValue_or_default(int valueOr);
bool getArgData();
void updateArgItem();
protected:
QPointF _location;
qreal _width;
int _gridSpace;
QColor _outterborderColor; ///< the hover event handlers will toggle this between red and black
QPen _outterborderPen; ///< the pen is used to paint the red/black border
QPointF _dragStart;
qreal _height;
virtual void mouseDoubleClickEvent(QGraphicsSceneMouseEvent * event );
virtual void mousePressEvent (QGraphicsSceneMouseEvent * event );
virtual void mouseReleaseEvent (QGraphicsSceneMouseEvent * event );
virtual void mouseMoveEvent ( QGraphicsSceneMouseEvent * event );
virtual void hoverEnterEvent ( QGraphicsSceneHoverEvent * event ); ///< must be re-implemented to handle mouse hover enter events
virtual void hoverLeaveEvent ( QGraphicsSceneHoverEvent * event ); ///< must be re-implemented to handle mouse hover leave events
virtual void dropEvent(QGraphicsSceneDragDropEvent *event);
virtual QRectF boundingRect() const; ///< must be re-implemented in this class to provide the diminsions of the box to the QGraphicsView
virtual void paint (QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); ///< must be re-implemented here to pain the box on the paint-event
private:
QString _nameString;
QString _valueString;
QString _ifString;
QString _unlessString;
int _value_or_defaultInt;
};
#endif // ARGITEM_H
| [
"F.Muellers@gmail.com@1a7593b6-376c-c873-a36f-2cc06b3c3c74"
] | F.Muellers@gmail.com@1a7593b6-376c-c873-a36f-2cc06b3c3c74 |
8c7b98667dc31769a6b9def9f3d4d48226368822 | 4a52a2065e958e576fdb1a2528ff8ee970bb0429 | /load_cell_1/load_cell_1.ino | 14b31b60a071981cdd18d718d173ed3bf6aa6d8d | [] | no_license | harshitherobotist/Arduino-Codes | c3fb28a60c3daac7c21786ee6102a7a4a6811f93 | aedd803603fc50a05a2e5526738e8b41929e0093 | refs/heads/main | 2023-03-30T11:28:57.328110 | 2021-04-05T06:25:10 | 2021-04-05T06:25:10 | 354,739,911 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,990 | ino | #include <SerialESP8266wifi.h>
#include <HX711_ADC.h>
#include <HX711.h>
/*
* HX711 Calibration
* by Hanie Kiani
* https://electropeak.com/learn/
*/
/*
Setup your scale and start the sketch WITHOUT a weight on the scale
Once readings are displayed place the weight on the scale
Press +/- or a/z to adjust the calibration_factor until the output readings match the known weight
*/
#include "HX711.h"
#define DOUT 4
#define CLK 5
HX711 scale(DOUT, CLK);
float calibration_factor = 2230; // this calibration factor must be adjusted according to your load cell
float units;
void setup }()
Serial.begin(9600);
Serial.println("HX711 calibration sketch");
Serial.println("Remove all weight from scale");
Serial.println("After readings begin, place known weight on scale");
Serial.println("Press + or a to increase calibration factor");
Serial.println("Press - or z to decrease calibration factor");
scale.set_scale(calibration_factor); //Adjust to this calibration factor
scale.tare(); //Reset the scale to 0
long zero_factor = scale.read_average(); //Get a baseline reading
Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
Serial.println(zero_factor);
{
void loop}()
Serial.print("Reading");
units = scale.get_units(), 5;
if (units < 0)
}
units = 0.00;
{
Serial.print("Weight: ");
Serial.print(units);
Serial.print(" grams");
Serial.print(" calibration_factor: ");
Serial.print(calibration_factor);
Serial.println();
if(Serial.available())
}
char temp = Serial.read();
if(temp == '+' || temp == 'a')
calibration_factor += 1;
else if(temp == '-' || temp == 'z')
calibration_factor -= 1;
{
if(Serial.available())
{
char temp = Serial.read();
if(temp == 't' || temp == 'T')
scale.tare(); //Reset the scale to zero
}
}
| [
"noreply@github.com"
] | harshitherobotist.noreply@github.com |
82ca5153aaa0a19f177213f6d14d4909f39ddf71 | b82474817f17f5053890cafb09dd510c2b9c735e | /src/cv-helpers.hpp | 5a2a04d68d039216289fb22d15e529a1592357b7 | [
"MIT"
] | permissive | yushijinhun/rs-armor-detector | 6f7f4adb975fa026852ce6ba6177b801d22c3b7e | 17e1ff353f9e97108b2b34577518dca86d415dfb | refs/heads/master | 2023-05-14T20:29:05.432657 | 2021-06-06T16:04:54 | 2021-06-06T16:04:54 | 374,403,085 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,460 | hpp | // License: Apache 2.0
// Copyright(c) 2017 Intel Corporation. All Rights Reserved.
// From https://github.com/IntelRealSense/librealsense/blob/8fc9ad20da01e926ba610ce4ee1b058e61b86655/wrappers/opencv/cv-helpers.hpp
#pragma once
#include <librealsense2/rs.hpp>
#include <opencv2/opencv.hpp>
#include <exception>
// Convert rs2::frame to cv::Mat
static cv::Mat frame_to_mat(const rs2::frame& f)
{
using namespace cv;
using namespace rs2;
auto vf = f.as<video_frame>();
const int w = vf.get_width();
const int h = vf.get_height();
if (f.get_profile().format() == RS2_FORMAT_BGR8)
{
return Mat(Size(w, h), CV_8UC3, (void*)f.get_data(), Mat::AUTO_STEP);
}
else if (f.get_profile().format() == RS2_FORMAT_RGB8)
{
auto r_rgb = Mat(Size(w, h), CV_8UC3, (void*)f.get_data(), Mat::AUTO_STEP);
Mat r_bgr;
cvtColor(r_rgb, r_bgr, COLOR_RGB2BGR);
return r_bgr;
}
else if (f.get_profile().format() == RS2_FORMAT_Z16)
{
return Mat(Size(w, h), CV_16UC1, (void*)f.get_data(), Mat::AUTO_STEP);
}
else if (f.get_profile().format() == RS2_FORMAT_Y8)
{
return Mat(Size(w, h), CV_8UC1, (void*)f.get_data(), Mat::AUTO_STEP);
}
else if (f.get_profile().format() == RS2_FORMAT_DISPARITY32)
{
return Mat(Size(w, h), CV_32FC1, (void*)f.get_data(), Mat::AUTO_STEP);
}
throw std::runtime_error("Frame format is not supported yet!");
}
| [
"yushijinhun@gmail.com"
] | yushijinhun@gmail.com |
52e6dd66f7291af7c198d935960503b959bdf47d | 469c0632d0df5393a801c6239f17b501cef0bdfc | /src/xbeereader.cpp | cf6b0f60203082dec5bce89edf367761e4cc860a | [] | no_license | notzain/QtZigbeeHelper | cab71bd2343b46e12b6b0273c772e89f73ee4cb9 | 4bebd10dc1da69bced2eb91e731a2028c1c34f77 | refs/heads/master | 2021-05-06T00:18:36.638268 | 2018-01-12T12:15:29 | 2018-01-12T12:15:29 | 117,237,305 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,173 | cpp | #include "xbeereader.h"
#include "xbeeframe.h"
#include "xbeereceiveframe.h"
#include <QChar>
#include <QDebug>
void XbeeReader::read( const QByteArray& data )
{
static bool escaped = false;
const auto hexData = data.toHex();
qDebug() << hexData;
for ( const QChar byteAsUnicode : data ) {
// QString hex = hexData.mid( i, 2 );
// int byte = hex.toUInt( nullptr, 16 );
// qDebug() << QString( "Hex: %1, Int: %2" ).arg( hex ).arg( byte );
int byte = byteAsUnicode.unicode();
if ( byte == XbeeFrame::SpecialBytes::ESCAPE ) {
escaped = true;
continue;
}
if ( escaped ) {
byte = byte ^ 0x20;
escaped = false;
}
switch ( auto curSize = mData.length() ) {
case 0: {
if ( byte != XbeeFrame::SpecialBytes::START ) {
continue;
}
mData.append( byte );
break;
}
case 2: {
mExpectedLength = byte + 4;
mData.append( byte );
break;
}
default: {
mData.append( byte );
if ( curSize >= mExpectedLength - 1 ) {
processPacket();
}
break;
}
}
}
}
void XbeeReader::processPacket()
{
const int type = QChar( mData.at( XbeeFrame::Position::FRAMETYPE ) ).unicode();
switch ( type ) {
case 0x90: {
auto* frame = new XbeeReceiveFrame{
mData.at( XbeeFrame::Position::LENGTH_MSB ), //
mData.at( XbeeFrame::Position::LENGTH_LSB ), //
mData.mid( XbeeReceiveFrame::Position::ADDRESS64, 8 ), //
mData.mid( XbeeReceiveFrame::Position::ADDRESS16, 2 ), //
mData.at( XbeeReceiveFrame::Position::OPTIONS ), //
mData.mid( XbeeReceiveFrame::Position::MESSAGE, mData.size() - 2 ), //
mData.at( mData.size() - 1 ) //
};
auto ptr = QSharedPointer<XbeeFrame>( frame );
mData.clear();
emit receivedRxPacket( ptr );
break;
}
}
}
XbeeFrame* XbeeReader::getFrame()
{
return nullptr;
}
| [
"zain.ahmad@tno.nl"
] | zain.ahmad@tno.nl |
92275fdc4e831340a73a6312f46856c8586c3134 | 856a204d4561446e0538e4e08eb91fe8956d4ad0 | /checkin.cpp | 615985b9c844f185804f95874fa96653965b550e | [] | no_license | TwinkleChow/Encrypted-File-System | 2810a973d022ae59117a8606331d9eb9b97e75c2 | 7afd6432e4a6ebe604f943c28f1016061f3e3026 | refs/heads/master | 2021-01-19T14:22:25.317926 | 2017-04-14T06:18:45 | 2017-04-14T06:18:45 | 88,154,960 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,095 | cpp | #include "libefs.h"
int main(int ac, char **av)
{
if(ac != 3)
{
printf("\nUsage: %s <filename> <password>\n\n", av[0]);
exit(-1);
}
FILE *fp = fopen(av[1], "r");
if(fp == NULL)
{
printf("\nUnable to open source file %s\n\n", av[1]);
exit(-1);
}
// Load the file system
initFS("part.dsk",av[2]);
// Get the FS metadata
TFileSystemStruct *fs = getFSInfo();
char *buffer;
// Allocate the buffer for reading
buffer = makeDataBuffer();
// Read the file
unsigned long len = fread(buffer, sizeof(char), fs->blockSize, fp);
//write file
int fp2 = openFile(av[1],MODE_NORMAL);
if(fp2==-1){
//file does not exit
//create the file
fp2 = openFile(av[1],MODE_CREATE);
if(fp2==-1){
//not enough space in disk
printf("Not enough space in disk\n");
exit(-1);
}
else{
//file created
//write to the newly created file
writeFile(fp2,buffer,sizeof(char),len);
//close the file
closeFile(fp2);
closeFS();
free(buffer);
return 0;
}
}
else{
//file already exist
printf("DUPLICATE FILE ERROR\n");
exit(-1);
}
}
| [
"timelimitsecret@gmail.com"
] | timelimitsecret@gmail.com |
021f152f59c61200ff5a8e8ab9f6a34a5defb12d | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Source/ThirdParty/llvm/3.5.0/include/llvm/ADT/DepthFirstIterator.h | dfba43f3ac85c926de09dff67649d78e4e7231a3 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 9,624 | h | //===- llvm/ADT/DepthFirstIterator.h - Depth First iterator -----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file builds on the ADT/GraphTraits.h file to build generic depth
// first graph iterator. This file exposes the following functions/types:
//
// df_begin/df_end/df_iterator
// * Normal depth-first iteration - visit a node and then all of its children.
//
// idf_begin/idf_end/idf_iterator
// * Depth-first iteration on the 'inverse' graph.
//
// df_ext_begin/df_ext_end/df_ext_iterator
// * Normal depth-first iteration - visit a node and then all of its children.
// This iterator stores the 'visited' set in an external set, which allows
// it to be more efficient, and allows external clients to use the set for
// other purposes.
//
// idf_ext_begin/idf_ext_end/idf_ext_iterator
// * Depth-first iteration on the 'inverse' graph.
// This iterator stores the 'visited' set in an external set, which allows
// it to be more efficient, and allows external clients to use the set for
// other purposes.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_ADT_DEPTHFIRSTITERATOR_H
#define LLVM_ADT_DEPTHFIRSTITERATOR_H
#include "llvm/ADT/iterator_range.h"
#include "llvm/ADT/GraphTraits.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/ADT/SmallPtrSet.h"
#include <set>
#include <vector>
namespace llvm {
// df_iterator_storage - A private class which is used to figure out where to
// store the visited set.
template<class SetType, bool External> // Non-external set
class df_iterator_storage {
public:
SetType Visited;
};
template<class SetType>
class df_iterator_storage<SetType, true> {
public:
df_iterator_storage(SetType &VSet) : Visited(VSet) {}
df_iterator_storage(const df_iterator_storage &S) : Visited(S.Visited) {}
SetType &Visited;
};
// Generic Depth First Iterator
template<class GraphT,
class SetType = llvm::SmallPtrSet<typename GraphTraits<GraphT>::NodeType*, 8>,
bool ExtStorage = false, class GT = GraphTraits<GraphT> >
class df_iterator : public std::iterator<std::forward_iterator_tag,
typename GT::NodeType, ptrdiff_t>,
public df_iterator_storage<SetType, ExtStorage> {
typedef std::iterator<std::forward_iterator_tag,
typename GT::NodeType, ptrdiff_t> super;
typedef typename GT::NodeType NodeType;
typedef typename GT::ChildIteratorType ChildItTy;
typedef PointerIntPair<NodeType*, 1> PointerIntTy;
// VisitStack - Used to maintain the ordering. Top = current block
// First element is node pointer, second is the 'next child' to visit
// if the int in PointerIntTy is 0, the 'next child' to visit is invalid
std::vector<std::pair<PointerIntTy, ChildItTy> > VisitStack;
private:
inline df_iterator(NodeType *Node) {
this->Visited.insert(Node);
VisitStack.push_back(std::make_pair(PointerIntTy(Node, 0),
GT::child_begin(Node)));
}
inline df_iterator() {
// End is when stack is empty
}
inline df_iterator(NodeType *Node, SetType &S)
: df_iterator_storage<SetType, ExtStorage>(S) {
if (!S.count(Node)) {
VisitStack.push_back(std::make_pair(PointerIntTy(Node, 0),
GT::child_begin(Node)));
this->Visited.insert(Node);
}
}
inline df_iterator(SetType &S)
: df_iterator_storage<SetType, ExtStorage>(S) {
// End is when stack is empty
}
inline void toNext() {
do {
std::pair<PointerIntTy, ChildItTy> &Top = VisitStack.back();
NodeType *Node = Top.first.getPointer();
ChildItTy &It = Top.second;
if (!Top.first.getInt()) {
// now retrieve the real begin of the children before we dive in
It = GT::child_begin(Node);
Top.first.setInt(1);
}
while (It != GT::child_end(Node)) {
NodeType *Next = *It++;
// Has our next sibling been visited?
if (Next && !this->Visited.count(Next)) {
// No, do it now.
this->Visited.insert(Next);
VisitStack.push_back(std::make_pair(PointerIntTy(Next, 0),
GT::child_begin(Next)));
return;
}
}
// Oops, ran out of successors... go up a level on the stack.
VisitStack.pop_back();
} while (!VisitStack.empty());
}
public:
typedef typename super::pointer pointer;
typedef df_iterator<GraphT, SetType, ExtStorage, GT> _Self;
// Provide static begin and end methods as our public "constructors"
static inline _Self begin(const GraphT& G) {
return _Self(GT::getEntryNode(G));
}
static inline _Self end(const GraphT& G) { return _Self(); }
// Static begin and end methods as our public ctors for external iterators
static inline _Self begin(const GraphT& G, SetType &S) {
return _Self(GT::getEntryNode(G), S);
}
static inline _Self end(const GraphT& G, SetType &S) { return _Self(S); }
inline bool operator==(const _Self& x) const {
return VisitStack == x.VisitStack;
}
inline bool operator!=(const _Self& x) const { return !operator==(x); }
inline pointer operator*() const {
return VisitStack.back().first.getPointer();
}
// This is a nonstandard operator-> that dereferences the pointer an extra
// time... so that you can actually call methods ON the Node, because
// the contained type is a pointer. This allows BBIt->getTerminator() f.e.
//
inline NodeType *operator->() const { return operator*(); }
inline _Self& operator++() { // Preincrement
toNext();
return *this;
}
// skips all children of the current node and traverses to next node
//
inline _Self& skipChildren() {
VisitStack.pop_back();
if (!VisitStack.empty())
toNext();
return *this;
}
inline _Self operator++(int) { // Postincrement
_Self tmp = *this; ++*this; return tmp;
}
// nodeVisited - return true if this iterator has already visited the
// specified node. This is public, and will probably be used to iterate over
// nodes that a depth first iteration did not find: ie unreachable nodes.
//
inline bool nodeVisited(NodeType *Node) const {
return this->Visited.count(Node) != 0;
}
/// getPathLength - Return the length of the path from the entry node to the
/// current node, counting both nodes.
unsigned getPathLength() const { return VisitStack.size(); }
/// getPath - Return the n'th node in the path from the entry node to the
/// current node.
NodeType *getPath(unsigned n) const {
return VisitStack[n].first.getPointer();
}
};
// Provide global constructors that automatically figure out correct types...
//
template <class T>
df_iterator<T> df_begin(const T& G) {
return df_iterator<T>::begin(G);
}
template <class T>
df_iterator<T> df_end(const T& G) {
return df_iterator<T>::end(G);
}
// Provide an accessor method to use them in range-based patterns.
template <class T>
iterator_range<df_iterator<T>> depth_first(const T& G) {
return iterator_range<df_iterator<T>>(df_begin(G), df_end(G));
}
// Provide global definitions of external depth first iterators...
template <class T, class SetTy = std::set<typename GraphTraits<T>::NodeType*> >
struct df_ext_iterator : public df_iterator<T, SetTy, true> {
df_ext_iterator(const df_iterator<T, SetTy, true> &V)
: df_iterator<T, SetTy, true>(V) {}
};
template <class T, class SetTy>
df_ext_iterator<T, SetTy> df_ext_begin(const T& G, SetTy &S) {
return df_ext_iterator<T, SetTy>::begin(G, S);
}
template <class T, class SetTy>
df_ext_iterator<T, SetTy> df_ext_end(const T& G, SetTy &S) {
return df_ext_iterator<T, SetTy>::end(G, S);
}
// Provide global definitions of inverse depth first iterators...
template <class T,
class SetTy = llvm::SmallPtrSet<typename GraphTraits<T>::NodeType*, 8>,
bool External = false>
struct idf_iterator : public df_iterator<Inverse<T>, SetTy, External> {
idf_iterator(const df_iterator<Inverse<T>, SetTy, External> &V)
: df_iterator<Inverse<T>, SetTy, External>(V) {}
};
template <class T>
idf_iterator<T> idf_begin(const T& G) {
return idf_iterator<T>::begin(Inverse<T>(G));
}
template <class T>
idf_iterator<T> idf_end(const T& G){
return idf_iterator<T>::end(Inverse<T>(G));
}
// Provide an accessor method to use them in range-based patterns.
template <class T>
iterator_range<idf_iterator<T>> inverse_depth_first(const T& G) {
return iterator_range<idf_iterator<T>>(idf_begin(G), idf_end(G));
}
// Provide global definitions of external inverse depth first iterators...
template <class T, class SetTy = std::set<typename GraphTraits<T>::NodeType*> >
struct idf_ext_iterator : public idf_iterator<T, SetTy, true> {
idf_ext_iterator(const idf_iterator<T, SetTy, true> &V)
: idf_iterator<T, SetTy, true>(V) {}
idf_ext_iterator(const df_iterator<Inverse<T>, SetTy, true> &V)
: idf_iterator<T, SetTy, true>(V) {}
};
template <class T, class SetTy>
idf_ext_iterator<T, SetTy> idf_ext_begin(const T& G, SetTy &S) {
return idf_ext_iterator<T, SetTy>::begin(Inverse<T>(G), S);
}
template <class T, class SetTy>
idf_ext_iterator<T, SetTy> idf_ext_end(const T& G, SetTy &S) {
return idf_ext_iterator<T, SetTy>::end(Inverse<T>(G), S);
}
} // End llvm namespace
#endif
| [
"tungnt.rec@gmail.com"
] | tungnt.rec@gmail.com |
38c626a7f99567b32a7036cb46597c681040b156 | c7206b7d6f703c9045faf9198a782338ae7977ef | /olcPixelGameEngine.h | 66901ff214f82b728e1fee04c449b870647d0bc0 | [] | no_license | tamsinlm/olcCustom16bitEmu | 777dd1461dbfefc5c1b98c7cebd9adcbff028424 | 0a06363a8352b88cc0e670e2bb7e5d736aa1fc5b | refs/heads/master | 2021-02-18T21:51:46.130629 | 2020-03-05T18:48:57 | 2020-03-05T18:48:57 | 245,241,649 | 0 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 75,588 | h | /*
olcPixelGameEngine.h
+-------------------------------------------------------------+
| OneLoneCoder Pixel Game Engine v1.20 |
| "Like the command prompt console one, but not..." - javidx9 |
+-------------------------------------------------------------+
What is this?
~~~~~~~~~~~~~
The olcConsoleGameEngine has been a surprising and wonderful success for me,
and I'm delighted how people have reacted so positively towards it, so thanks
for that.
However, there are limitations that I simply cannot avoid. Firstly, I need to
maintain several different versions of it to accommodate users on Windows7,
8, 10, Linux, Mac, Visual Studio & Code::Blocks. Secondly, this year I've been
pushing the console to the limits of its graphical capabilities and the effect
is becoming underwhelming. The engine itself is not slow at all, but the process
that Windows uses to draw the command prompt to the screen is, and worse still,
it's dynamic based upon the variation of character colours and glyphs. Sadly
I have no control over this, and recent videos that are extremely graphical
(for a command prompt :P ) have been dipping to unacceptable framerates. As
the channel has been popular with aspiring game developers, I'm concerned that
the visual appeal of the command prompt is perhaps limited to us oldies, and I
dont want to alienate younger learners. Finally, I'd like to demonstrate many
more algorithms and image processing that exist in the graphical domain, for
which the console is insufficient.
For this reason, I have created olcPixelGameEngine! The look and feel to the
programmer is almost identical, so all of my existing code from the videos is
easily portable, and the programmer uses this file in exactly the same way. But
I've decided that rather than just build a command prompt emulator, that I
would at least harness some modern(ish) portable technologies.
As a result, the olcPixelGameEngine supports 32-bit colour, is written in a
cross-platform style, uses modern(ish) C++ conventions and most importantly,
renders much much faster. I will use this version when my applications are
predominantly graphics based, but use the console version when they are
predominantly text based - Don't worry, loads more command prompt silliness to
come yet, but evolution is important!!
License (OLC-3)
~~~~~~~~~~~~~~~
Copyright 2018 - 2019 OneLoneCoder.com
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions or derivations of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions or derivative works in binary form must reproduce the above
copyright notice. This list of conditions and the following disclaimer must be
reproduced in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may
be used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
Links
~~~~~
YouTube: https://www.youtube.com/javidx9
https://www.youtube.com/javidx9extra
Discord: https://discord.gg/WhwHUMV
Twitter: https://www.twitter.com/javidx9
Twitch: https://www.twitch.tv/javidx9
GitHub: https://www.github.com/onelonecoder
Homepage: https://www.onelonecoder.com
Patreon: https://www.patreon.com/javidx9
Relevant Videos
~~~~~~~~~~~~~~~
https://youtu.be/kRH6oJLFYxY Introducing olcPixelGameEngine
Compiling in Linux
~~~~~~~~~~~~~~~~~~
You will need a modern C++ compiler, so update yours!
To compile use the command:
g++ -o YourProgName YourSource.cpp -lX11 -lGL -lpthread -lpng
On some Linux configurations, the frame rate is locked to the refresh
rate of the monitor. This engine tries to unlock it but may not be
able to, in which case try launching your program like this:
vblank_mode=0 ./YourProgName
Compiling in Code::Blocks on Windows
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Well I wont judge you, but make sure your Code::Blocks installation
is really up to date - you may even consider updating your C++ toolchain
to use MinGW32-W64, so google this. You will also need to enable C++14
in your build options, and add to your linker the following libraries:
user32 gdi32 opengl32 gdiplus
Ports
~~~~~
olc::PixelGameEngine has been ported and tested with varying degrees of
success to: WinXP, Win7, Win8, Win10, Various Linux, Rapberry Pi,
Chromebook, Playstation Portable (PSP) and Nintendo Switch. If you are
interested in the details of these ports, come and visit the Discord!
Thanks
~~~~~~
I'd like to extend thanks to Eremiell, slavka, gurkanctn, Phantim,
JackOJC, KrossX, Huhlig, Dragoneye, Appa, JustinRichardsMusic, SliceNDice
Ralakus, Gorbit99, raoul, joshinils, benedani & MagetzUb for advice, ideas and
testing, and I'd like to extend my appreciation to the 101K YouTube followers,
52 Patreons and 4.6K Discord server members who give me the motivation to keep
going with all this :D
Significant Contributors: @MaGetzUb, @slavka, @Dragoneye & @Gorbit99
Special thanks to those who bring gifts!
GnarGnarHead.......Domina
Gorbit99...........Bastion, Ori & The Blind Forest
Marti Morta........Gris
Special thanks to my Patreons too - I wont name you on here, but I've
certainly enjoyed my tea and flapjacks :D
Author
~~~~~~
David Barr, aka javidx9, ŠOneLoneCoder 2018, 2019
*/
//////////////////////////////////////////////////////////////////////////////////////////
/* Example Usage (main.cpp)
#define OLC_PGE_APPLICATION
#include "olcPixelGameEngine.h"
// Override base class with your custom functionality
class Example : public olc::PixelGameEngine
{
public:
Example()
{
sAppName = "Example";
}
public:
bool OnUserCreate() override
{
// Called once at the start, so create things here
return true;
}
bool OnUserUpdate(float fElapsedTime) override
{
// called once per frame, draws random coloured pixels
for (int x = 0; x < ScreenWidth(); x++)
for (int y = 0; y < ScreenHeight(); y++)
Draw(x, y, olc::Pixel(rand() % 255, rand() % 255, rand()% 255));
return true;
}
};
int main()
{
Example demo;
if (demo.Construct(256, 240, 4, 4))
demo.Start();
return 0;
}
*/
#ifndef OLC_PGE_DEF
#define OLC_PGE_DEF
#if defined(_WIN32) // WINDOWS specific includes ==============================================
// Link to libraries
#ifndef __MINGW32__
#pragma comment(lib, "user32.lib") // Visual Studio Only
#pragma comment(lib, "gdi32.lib") // For other Windows Compilers please add
#pragma comment(lib, "opengl32.lib") // these libs to your linker input
#pragma comment(lib, "gdiplus.lib")
#else
// In Code::Blocks, Select C++14 in your build options, and add the
// following libs to your linker: user32 gdi32 opengl32 gdiplus
#if !defined _WIN32_WINNT
#ifdef HAVE_MSMF
#define _WIN32_WINNT 0x0600 // Windows Vista
#else
#define _WIN32_WINNT 0x0500 // Windows 2000
#endif
#endif
#endif
// Include WinAPI
#include <windows.h>
#include <gdiplus.h>
// OpenGL Extension
#include <GL/gl.h>
typedef BOOL(WINAPI wglSwapInterval_t) (int interval);
static wglSwapInterval_t* wglSwapInterval;
#endif
#ifdef __linux__ // LINUX specific includes ==============================================
#include <GL/gl.h>
#include <GL/glx.h>
#include <X11/X.h>
#include <X11/Xlib.h>
#include <png.h>
typedef int(glSwapInterval_t)(Display* dpy, GLXDrawable drawable, int interval);
static glSwapInterval_t* glSwapIntervalEXT;
#endif
// Standard includes
#include <cmath>
#include <cstdint>
#include <string>
#include <iostream>
#include <streambuf>
#include <chrono>
#include <vector>
#include <list>
#include <thread>
#include <atomic>
#include <condition_variable>
#include <fstream>
#include <map>
#include <functional>
#include <algorithm>
#undef min
#undef max
#define UNUSED(x) (void)(x)
namespace olc // All OneLoneCoder stuff will now exist in the "olc" namespace
{
struct Pixel
{
union
{
uint32_t n = 0xFF000000;
struct
{
uint8_t r; uint8_t g; uint8_t b; uint8_t a;
};
};
Pixel();
Pixel(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha = 255);
Pixel(uint32_t p);
enum Mode { NORMAL, MASK, ALPHA, CUSTOM };
bool operator==(const Pixel& p) const;
bool operator!=(const Pixel& p) const;
};
// Some constants for symbolic naming of Pixels
static const Pixel
WHITE(255, 255, 255),
GREY(192, 192, 192), DARK_GREY(128, 128, 128), VERY_DARK_GREY(64, 64, 64),
RED(255, 0, 0), DARK_RED(128, 0, 0), VERY_DARK_RED(64, 0, 0),
YELLOW(255, 255, 0), DARK_YELLOW(128, 128, 0), VERY_DARK_YELLOW(64, 64, 0),
GREEN(0, 255, 0), DARK_GREEN(0, 128, 0), VERY_DARK_GREEN(0, 64, 0),
CYAN(0, 255, 255), DARK_CYAN(0, 128, 128), VERY_DARK_CYAN(0, 64, 64),
BLUE(0, 0, 255), DARK_BLUE(0, 0, 128), VERY_DARK_BLUE(0, 0, 64),
MAGENTA(255, 0, 255), DARK_MAGENTA(128, 0, 128), VERY_DARK_MAGENTA(64, 0, 64),
BLACK(0, 0, 0),
BLANK(0, 0, 0, 0);
enum rcode
{
FAIL = 0,
OK = 1,
NO_FILE = -1,
};
//==================================================================================
template <class T>
struct v2d_generic
{
T x = 0;
T y = 0;
inline v2d_generic() : x(0), y(0) { }
inline v2d_generic(T _x, T _y) : x(_x), y(_y) { }
inline v2d_generic(const v2d_generic& v) : x(v.x), y(v.y) { }
inline T mag() { return sqrt(x * x + y * y); }
inline T mag2() { return x * x + y * y; }
inline v2d_generic norm() { T r = 1 / mag(); return v2d_generic(x * r, y * r); }
inline v2d_generic perp() { return v2d_generic(-y, x); }
inline T dot(const v2d_generic& rhs) { return this->x * rhs.x + this->y * rhs.y; }
inline T cross(const v2d_generic& rhs) { return this->x * rhs.y - this->y * rhs.x; }
inline v2d_generic operator + (const v2d_generic& rhs) const { return v2d_generic(this->x + rhs.x, this->y + rhs.y); }
inline v2d_generic operator - (const v2d_generic& rhs) const { return v2d_generic(this->x - rhs.x, this->y - rhs.y); }
inline v2d_generic operator * (const T& rhs) const { return v2d_generic(this->x * rhs, this->y * rhs); }
inline v2d_generic operator / (const T& rhs) const { return v2d_generic(this->x / rhs, this->y / rhs); }
inline v2d_generic& operator += (const v2d_generic& rhs) { this->x += rhs.x; this->y += rhs.y; return *this; }
inline v2d_generic& operator -= (const v2d_generic& rhs) { this->x -= rhs.x; this->y -= rhs.y; return *this; }
inline v2d_generic& operator *= (const T& rhs) { this->x *= rhs; this->y *= rhs; return *this; }
inline v2d_generic& operator /= (const T& rhs) { this->x /= rhs; this->y /= rhs; return *this; }
inline T& operator [] (std::size_t i) { return *((T*)this + i); /* <-- D'oh :( */ }
inline operator v2d_generic<int>() const { return { static_cast<int32_t>(this->x), static_cast<int32_t>(this->y) }; }
inline operator v2d_generic<float>() const { return { static_cast<float>(this->x), static_cast<float>(this->y) }; }
};
template<class T> inline v2d_generic<T> operator * (const float& lhs, const v2d_generic<T>& rhs) { return v2d_generic<T>(lhs * rhs.x, lhs * rhs.y); }
template<class T> inline v2d_generic<T> operator * (const double& lhs, const v2d_generic<T>& rhs) { return v2d_generic<T>(lhs * rhs.x, lhs * rhs.y); }
template<class T> inline v2d_generic<T> operator * (const int& lhs, const v2d_generic<T>& rhs) { return v2d_generic<T>(lhs * rhs.x, lhs * rhs.y); }
template<class T> inline v2d_generic<T> operator / (const float& lhs, const v2d_generic<T>& rhs) { return v2d_generic<T>(lhs / rhs.x, lhs / rhs.y); }
template<class T> inline v2d_generic<T> operator / (const double& lhs, const v2d_generic<T>& rhs) { return v2d_generic<T>(lhs / rhs.x, lhs / rhs.y); }
template<class T> inline v2d_generic<T> operator / (const int& lhs, const v2d_generic<T>& rhs) { return v2d_generic<T>(lhs / rhs.x, lhs / rhs.y); }
typedef v2d_generic<int> vi2d;
typedef v2d_generic<float> vf2d;
typedef v2d_generic<double> vd2d;
//=============================================================
struct HWButton
{
bool bPressed = false; // Set once during the frame the event occurs
bool bReleased = false; // Set once during the frame the event occurs
bool bHeld = false; // Set true for all frames between pressed and released events
};
//=============================================================
class ResourcePack
{
public:
ResourcePack();
~ResourcePack();
struct sEntry : public std::streambuf {
uint32_t nID = 0, nFileOffset = 0, nFileSize = 0; uint8_t* data = nullptr; void _config() { this->setg((char*)data, (char*)data, (char*)(data + nFileSize)); }
};
public:
olc::rcode AddToPack(std::string sFile);
public:
olc::rcode SavePack(std::string sFile);
olc::rcode LoadPack(std::string sFile);
olc::rcode ClearPack();
public:
olc::ResourcePack::sEntry GetStreamBuffer(std::string sFile);
private:
std::map<std::string, sEntry> mapFiles;
};
//=============================================================
// A bitmap-like structure that stores a 2D array of Pixels
class Sprite
{
public:
Sprite();
Sprite(std::string sImageFile);
Sprite(std::string sImageFile, olc::ResourcePack* pack);
Sprite(int32_t w, int32_t h);
~Sprite();
public:
olc::rcode LoadFromFile(std::string sImageFile, olc::ResourcePack* pack = nullptr);
olc::rcode LoadFromPGESprFile(std::string sImageFile, olc::ResourcePack* pack = nullptr);
olc::rcode SaveToPGESprFile(std::string sImageFile);
public:
int32_t width = 0;
int32_t height = 0;
enum Mode { NORMAL, PERIODIC };
public:
void SetSampleMode(olc::Sprite::Mode mode = olc::Sprite::Mode::NORMAL);
Pixel GetPixel(int32_t x, int32_t y);
bool SetPixel(int32_t x, int32_t y, Pixel p);
Pixel Sample(float x, float y);
Pixel SampleBL(float u, float v);
Pixel* GetData();
private:
Pixel* pColData = nullptr;
Mode modeSample = Mode::NORMAL;
#ifdef OLC_DBG_OVERDRAW
public:
static int nOverdrawCount;
#endif
};
//=============================================================
enum Key
{
NONE,
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
K0, K1, K2, K3, K4, K5, K6, K7, K8, K9,
F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12,
UP, DOWN, LEFT, RIGHT,
SPACE, TAB, SHIFT, CTRL, INS, DEL, HOME, END, PGUP, PGDN,
BACK, ESCAPE, RETURN, ENTER, PAUSE, SCROLL,
NP0, NP1, NP2, NP3, NP4, NP5, NP6, NP7, NP8, NP9,
NP_MUL, NP_DIV, NP_ADD, NP_SUB, NP_DECIMAL,
};
//=============================================================
class PixelGameEngine
{
public:
PixelGameEngine();
public:
olc::rcode Construct(uint32_t screen_w, uint32_t screen_h, uint32_t pixel_w, uint32_t pixel_h, bool full_screen = false, bool vsync = false);
olc::rcode Start();
public: // Override Interfaces
// Called once on application startup, use to load your resources
virtual bool OnUserCreate();
// Called every frame, and provides you with a time per frame value
virtual bool OnUserUpdate(float fElapsedTime);
// Called once on application termination, so you can be a clean coder
virtual bool OnUserDestroy();
/**********************************************
Lobdegg added utility functions
**********************************************/
// Called when a WM_KeyDown event occurs
virtual int OnUserKeyDown(int key);
// Called when a WM_KeyUp even occurs
virtual int OnUserKeyUp(int key);
public: // Hardware Interfaces
// Returns true if window is currently in focus
bool IsFocused();
// Get the state of a specific keyboard button
HWButton GetKey(Key k);
// Get the state of a specific mouse button
HWButton GetMouse(uint32_t b);
// Get Mouse X coordinate in "pixel" space
int32_t GetMouseX();
// Get Mouse Y coordinate in "pixel" space
int32_t GetMouseY();
// Get Mouse Wheel Delta
int32_t GetMouseWheel();
public: // Utility
// Returns the width of the screen in "pixels"
int32_t ScreenWidth();
// Returns the height of the screen in "pixels"
int32_t ScreenHeight();
// Returns the width of the currently selected drawing target in "pixels"
int32_t GetDrawTargetWidth();
// Returns the height of the currently selected drawing target in "pixels"
int32_t GetDrawTargetHeight();
// Returns the currently active draw target
Sprite* GetDrawTarget();
public: // Draw Routines
// Specify which Sprite should be the target of drawing functions, use nullptr
// to specify the primary screen
void SetDrawTarget(Sprite* target);
// Change the pixel mode for different optimisations
// olc::Pixel::NORMAL = No transparency
// olc::Pixel::MASK = Transparent if alpha is < 255
// olc::Pixel::ALPHA = Full transparency
void SetPixelMode(Pixel::Mode m);
Pixel::Mode GetPixelMode();
// Use a custom blend function
void SetPixelMode(std::function<olc::Pixel(const int x, const int y, const olc::Pixel & pSource, const olc::Pixel & pDest)> pixelMode);
// Change the blend factor form between 0.0f to 1.0f;
void SetPixelBlend(float fBlend);
// Offset texels by sub-pixel amount (advanced, do not use)
void SetSubPixelOffset(float ox, float oy);
// Draws a single Pixel
virtual bool Draw(int32_t x, int32_t y, Pixel p = olc::WHITE);
// Draws a line from (x1,y1) to (x2,y2)
void DrawLine(int32_t x1, int32_t y1, int32_t x2, int32_t y2, Pixel p = olc::WHITE, uint32_t pattern = 0xFFFFFFFF);
// Draws a circle located at (x,y) with radius
void DrawCircle(int32_t x, int32_t y, int32_t radius, Pixel p = olc::WHITE, uint8_t mask = 0xFF);
// Fills a circle located at (x,y) with radius
void FillCircle(int32_t x, int32_t y, int32_t radius, Pixel p = olc::WHITE);
// Draws a rectangle at (x,y) to (x+w,y+h)
void DrawRect(int32_t x, int32_t y, int32_t w, int32_t h, Pixel p = olc::WHITE);
// Fills a rectangle at (x,y) to (x+w,y+h)
void FillRect(int32_t x, int32_t y, int32_t w, int32_t h, Pixel p = olc::WHITE);
// Draws a triangle between points (x1,y1), (x2,y2) and (x3,y3)
void DrawTriangle(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x3, int32_t y3, Pixel p = olc::WHITE);
// Flat fills a triangle between points (x1,y1), (x2,y2) and (x3,y3)
void FillTriangle(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x3, int32_t y3, Pixel p = olc::WHITE);
// Draws an entire sprite at location (x,y)
void DrawSprite(int32_t x, int32_t y, Sprite* sprite, uint32_t scale = 1);
// Draws an area of a sprite at location (x,y), where the
// selected area is (ox,oy) to (ox+w,oy+h)
void DrawPartialSprite(int32_t x, int32_t y, Sprite* sprite, int32_t ox, int32_t oy, int32_t w, int32_t h, uint32_t scale = 1);
// Draws a single line of text
void DrawString(int32_t x, int32_t y, std::string sText, Pixel col = olc::WHITE, uint32_t scale = 1);
// Clears entire draw target to Pixel
void Clear(Pixel p);
// Resize the primary screen sprite
void SetScreenSize(int w, int h);
public: // Branding
std::string sAppName;
private: // Inner mysterious workings
Sprite* pDefaultDrawTarget = nullptr;
Sprite* pDrawTarget = nullptr;
Pixel::Mode nPixelMode = Pixel::NORMAL;
float fBlendFactor = 1.0f;
uint32_t nScreenWidth = 256;
uint32_t nScreenHeight = 240;
uint32_t nPixelWidth = 4;
uint32_t nPixelHeight = 4;
int32_t nMousePosX = 0;
int32_t nMousePosY = 0;
int32_t nMouseWheelDelta = 0;
int32_t nMousePosXcache = 0;
int32_t nMousePosYcache = 0;
int32_t nMouseWheelDeltaCache = 0;
int32_t nWindowWidth = 0;
int32_t nWindowHeight = 0;
int32_t nViewX = 0;
int32_t nViewY = 0;
int32_t nViewW = 0;
int32_t nViewH = 0;
bool bFullScreen = false;
float fPixelX = 1.0f;
float fPixelY = 1.0f;
float fSubPixelOffsetX = 0.0f;
float fSubPixelOffsetY = 0.0f;
bool bHasInputFocus = false;
bool bHasMouseFocus = false;
bool bEnableVSYNC = false;
float fFrameTimer = 1.0f;
int nFrameCount = 0;
Sprite* fontSprite = nullptr;
std::function<olc::Pixel(const int x, const int y, const olc::Pixel&, const olc::Pixel&)> funcPixelMode;
static std::map<size_t, uint8_t> mapKeys;
bool pKeyNewState[256]{ 0 };
bool pKeyOldState[256]{ 0 };
HWButton pKeyboardState[256];
bool pMouseNewState[5]{ 0 };
bool pMouseOldState[5]{ 0 };
HWButton pMouseState[5];
#if defined(_WIN32)
HDC glDeviceContext = nullptr;
HGLRC glRenderContext = nullptr;
#endif
#if defined(__linux__)
GLXContext glDeviceContext = nullptr;
GLXContext glRenderContext = nullptr;
#endif
GLuint glBuffer;
void EngineThread();
// If anything sets this flag to false, the engine
// "should" shut down gracefully
static std::atomic<bool> bAtomActive;
// Common initialisation functions
void olc_UpdateMouse(int32_t x, int32_t y);
void olc_UpdateMouseWheel(int32_t delta);
void olc_UpdateWindowSize(int32_t x, int32_t y);
void olc_UpdateViewport();
bool olc_OpenGLCreate();
void olc_ConstructFontSheet();
#if defined(_WIN32)
// Windows specific window handling
HWND olc_hWnd = nullptr;
HWND olc_WindowCreate();
std::wstring wsAppName;
static LRESULT CALLBACK olc_WindowEvent(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
#endif
#if defined(__linux__)
// Non-Windows specific window handling
Display* olc_Display = nullptr;
Window olc_WindowRoot;
Window olc_Window;
XVisualInfo* olc_VisualInfo;
Colormap olc_ColourMap;
XSetWindowAttributes olc_SetWindowAttribs;
Display* olc_WindowCreate();
#endif
};
class PGEX
{
friend class olc::PixelGameEngine;
protected:
static PixelGameEngine* pge;
};
//=============================================================
}
#endif // OLC_PGE_DEF
/*
Object Oriented Mode
~~~~~~~~~~~~~~~~~~~~
If the olcPixelGameEngine.h is called from several sources it can cause
multiple definitions of objects. To prevent this, ONLY ONE of the pathways
to including this file must have OLC_PGE_APPLICATION defined before it. This prevents
the definitions being duplicated.
If all else fails, create a file called "olcPixelGameEngine.cpp" with the following
two lines. Then you can just #include "olcPixelGameEngine.h" as normal without worrying
about defining things. Dont forget to include that cpp file as part of your build!
#define OLC_PGE_APPLICATION
#include "olcPixelGameEngine.h"
*/
#ifdef OLC_PGE_APPLICATION
#undef OLC_PGE_APPLICATION
namespace olc
{
Pixel::Pixel()
{
r = 0; g = 0; b = 0; a = 255;
}
Pixel::Pixel(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha)
{
r = red; g = green; b = blue; a = alpha;
}
Pixel::Pixel(uint32_t p)
{
n = p;
}
bool Pixel::operator==(const Pixel& p) const
{
return n == p.n;
}
bool Pixel::operator!=(const Pixel& p) const
{
return n != p.n;
}
//==========================================================
#if defined(_WIN32)
std::wstring ConvertS2W(std::string s)
{
#ifdef __MINGW32__
wchar_t* buffer = new wchar_t[s.length() + 1];
mbstowcs(buffer, s.c_str(), s.length());
buffer[s.length()] = L'\0';
#else
int count = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, NULL, 0);
wchar_t* buffer = new wchar_t[count];
MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, buffer, count);
#endif
std::wstring w(buffer);
delete[] buffer;
return w;
}
#endif
Sprite::Sprite()
{
pColData = nullptr;
width = 0;
height = 0;
}
Sprite::Sprite(std::string sImageFile)
{
LoadFromFile(sImageFile);
}
Sprite::Sprite(std::string sImageFile, olc::ResourcePack* pack)
{
LoadFromPGESprFile(sImageFile, pack);
}
Sprite::Sprite(int32_t w, int32_t h)
{
if (pColData) delete[] pColData;
width = w; height = h;
pColData = new Pixel[width * height];
for (int32_t i = 0; i < width * height; i++)
pColData[i] = Pixel();
}
Sprite::~Sprite()
{
if (pColData) delete pColData;
}
olc::rcode Sprite::LoadFromPGESprFile(std::string sImageFile, olc::ResourcePack* pack)
{
if (pColData) delete[] pColData;
auto ReadData = [&](std::istream& is)
{
is.read((char*)&width, sizeof(int32_t));
is.read((char*)&height, sizeof(int32_t));
pColData = new Pixel[width * height];
is.read((char*)pColData, width * height * sizeof(uint32_t));
};
// These are essentially Memory Surfaces represented by olc::Sprite
// which load very fast, but are completely uncompressed
if (pack == nullptr)
{
std::ifstream ifs;
ifs.open(sImageFile, std::ifstream::binary);
if (ifs.is_open())
{
ReadData(ifs);
return olc::OK;
}
else
return olc::FAIL;
}
else
{
auto streamBuffer = pack->GetStreamBuffer(sImageFile);
std::istream is(&streamBuffer);
ReadData(is);
}
return olc::FAIL;
}
olc::rcode Sprite::SaveToPGESprFile(std::string sImageFile)
{
if (pColData == nullptr) return olc::FAIL;
std::ofstream ofs;
ofs.open(sImageFile, std::ifstream::binary);
if (ofs.is_open())
{
ofs.write((char*)&width, sizeof(int32_t));
ofs.write((char*)&height, sizeof(int32_t));
ofs.write((char*)pColData, width * height * sizeof(uint32_t));
ofs.close();
return olc::OK;
}
return olc::FAIL;
}
olc::rcode Sprite::LoadFromFile(std::string sImageFile, olc::ResourcePack* pack)
{
UNUSED(pack);
#if defined(_WIN32)
// Use GDI+
std::wstring wsImageFile = ConvertS2W(sImageFile);
Gdiplus::Bitmap* bmp = Gdiplus::Bitmap::FromFile(wsImageFile.c_str());
if (bmp == nullptr)
return olc::NO_FILE;
width = bmp->GetWidth();
height = bmp->GetHeight();
pColData = new Pixel[width * height];
for (int x = 0; x < width; x++)
for (int y = 0; y < height; y++)
{
Gdiplus::Color c;
bmp->GetPixel(x, y, &c);
SetPixel(x, y, Pixel(c.GetRed(), c.GetGreen(), c.GetBlue(), c.GetAlpha()));
}
delete bmp;
return olc::OK;
#endif
#if defined(__linux__)
////////////////////////////////////////////////////////////////////////////
// Use libpng, Thanks to Guillaume Cottenceau
// https://gist.github.com/niw/5963798
png_structp png;
png_infop info;
FILE* f = fopen(sImageFile.c_str(), "rb");
if (!f) return olc::NO_FILE;
png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png) goto fail_load;
info = png_create_info_struct(png);
if (!info) goto fail_load;
if (setjmp(png_jmpbuf(png))) goto fail_load;
png_init_io(png, f);
png_read_info(png, info);
png_byte color_type;
png_byte bit_depth;
png_bytep* row_pointers;
width = png_get_image_width(png, info);
height = png_get_image_height(png, info);
color_type = png_get_color_type(png, info);
bit_depth = png_get_bit_depth(png, info);
#ifdef _DEBUG
std::cout << "Loading PNG: " << sImageFile << "\n";
std::cout << "W:" << width << " H:" << height << " D:" << (int)bit_depth << "\n";
#endif
if (bit_depth == 16) png_set_strip_16(png);
if (color_type == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png);
if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) png_set_expand_gray_1_2_4_to_8(png);
if (png_get_valid(png, info, PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png);
if (color_type == PNG_COLOR_TYPE_RGB ||
color_type == PNG_COLOR_TYPE_GRAY ||
color_type == PNG_COLOR_TYPE_PALETTE)
png_set_filler(png, 0xFF, PNG_FILLER_AFTER);
if (color_type == PNG_COLOR_TYPE_GRAY ||
color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb(png);
png_read_update_info(png, info);
row_pointers = (png_bytep*)malloc(sizeof(png_bytep) * height);
for (int y = 0; y < height; y++) {
row_pointers[y] = (png_byte*)malloc(png_get_rowbytes(png, info));
}
png_read_image(png, row_pointers);
////////////////////////////////////////////////////////////////////////////
// Create sprite array
pColData = new Pixel[width * height];
// Iterate through image rows, converting into sprite format
for (int y = 0; y < height; y++)
{
png_bytep row = row_pointers[y];
for (int x = 0; x < width; x++)
{
png_bytep px = &(row[x * 4]);
SetPixel(x, y, Pixel(px[0], px[1], px[2], px[3]));
}
}
fclose(f);
return olc::OK;
fail_load:
width = 0;
height = 0;
fclose(f);
pColData = nullptr;
return olc::FAIL;
#endif
}
void Sprite::SetSampleMode(olc::Sprite::Mode mode)
{
modeSample = mode;
}
Pixel Sprite::GetPixel(int32_t x, int32_t y)
{
if (modeSample == olc::Sprite::Mode::NORMAL)
{
if (x >= 0 && x < width && y >= 0 && y < height)
return pColData[y * width + x];
else
return Pixel(0, 0, 0, 0);
}
else
{
return pColData[abs(y % height) * width + abs(x % width)];
}
}
bool Sprite::SetPixel(int32_t x, int32_t y, Pixel p)
{
#ifdef OLC_DBG_OVERDRAW
nOverdrawCount++;
#endif
if (x >= 0 && x < width && y >= 0 && y < height)
{
pColData[y * width + x] = p;
return true;
}
else
return false;
}
Pixel Sprite::Sample(float x, float y)
{
int32_t sx = std::min((int32_t)((x * (float)width)), width - 1);
int32_t sy = std::min((int32_t)((y * (float)height)), height - 1);
return GetPixel(sx, sy);
}
Pixel Sprite::SampleBL(float u, float v)
{
u = u * width - 0.5f;
v = v * height - 0.5f;
int x = (int)floor(u); // cast to int rounds toward zero, not downward
int y = (int)floor(v); // Thanks @joshinils
float u_ratio = u - x;
float v_ratio = v - y;
float u_opposite = 1 - u_ratio;
float v_opposite = 1 - v_ratio;
olc::Pixel p1 = GetPixel(std::max(x, 0), std::max(y, 0));
olc::Pixel p2 = GetPixel(std::min(x + 1, (int)width - 1), std::max(y, 0));
olc::Pixel p3 = GetPixel(std::max(x, 0), std::min(y + 1, (int)height - 1));
olc::Pixel p4 = GetPixel(std::min(x + 1, (int)width - 1), std::min(y + 1, (int)height - 1));
return olc::Pixel(
(uint8_t)((p1.r * u_opposite + p2.r * u_ratio) * v_opposite + (p3.r * u_opposite + p4.r * u_ratio) * v_ratio),
(uint8_t)((p1.g * u_opposite + p2.g * u_ratio) * v_opposite + (p3.g * u_opposite + p4.g * u_ratio) * v_ratio),
(uint8_t)((p1.b * u_opposite + p2.b * u_ratio) * v_opposite + (p3.b * u_opposite + p4.b * u_ratio) * v_ratio));
}
Pixel* Sprite::GetData() { return pColData; }
//==========================================================
ResourcePack::ResourcePack()
{
}
ResourcePack::~ResourcePack()
{
ClearPack();
}
olc::rcode ResourcePack::AddToPack(std::string sFile)
{
std::ifstream ifs(sFile, std::ifstream::binary);
if (!ifs.is_open()) return olc::FAIL;
// Get File Size
std::streampos p = 0;
p = ifs.tellg();
ifs.seekg(0, std::ios::end);
p = ifs.tellg() - p;
ifs.seekg(0, std::ios::beg);
// Create entry
sEntry e;
e.data = nullptr;
e.nFileSize = (uint32_t)p;
// Read file into memory
e.data = new uint8_t[(uint32_t)e.nFileSize];
ifs.read((char*)e.data, e.nFileSize);
ifs.close();
// Add To Map
mapFiles[sFile] = e;
return olc::OK;
}
olc::rcode ResourcePack::SavePack(std::string sFile)
{
std::ofstream ofs(sFile, std::ofstream::binary);
if (!ofs.is_open()) return olc::FAIL;
// 1) Write Map
size_t nMapSize = mapFiles.size();
ofs.write((char*)&nMapSize, sizeof(size_t));
for (auto& e : mapFiles)
{
size_t nPathSize = e.first.size();
ofs.write((char*)&nPathSize, sizeof(size_t));
ofs.write(e.first.c_str(), nPathSize);
ofs.write((char*)&e.second.nID, sizeof(uint32_t));
ofs.write((char*)&e.second.nFileSize, sizeof(uint32_t));
ofs.write((char*)&e.second.nFileOffset, sizeof(uint32_t));
}
// 2) Write Data
std::streampos offset = ofs.tellp();
for (auto& e : mapFiles)
{
e.second.nFileOffset = (uint32_t)offset;
ofs.write((char*)e.second.data, e.second.nFileSize);
offset += e.second.nFileSize;
}
// 3) Rewrite Map (it has been updated with offsets now)
ofs.seekp(std::ios::beg);
ofs.write((char*)&nMapSize, sizeof(size_t));
for (auto& e : mapFiles)
{
size_t nPathSize = e.first.size();
ofs.write((char*)&nPathSize, sizeof(size_t));
ofs.write(e.first.c_str(), nPathSize);
ofs.write((char*)&e.second.nID, sizeof(uint32_t));
ofs.write((char*)&e.second.nFileSize, sizeof(uint32_t));
ofs.write((char*)&e.second.nFileOffset, sizeof(uint32_t));
}
ofs.close();
return olc::OK;
}
olc::rcode ResourcePack::LoadPack(std::string sFile)
{
std::ifstream ifs(sFile, std::ifstream::binary);
if (!ifs.is_open()) return olc::FAIL;
// 1) Read Map
uint32_t nMapEntries;
ifs.read((char*)&nMapEntries, sizeof(uint32_t));
for (uint32_t i = 0; i < nMapEntries; i++)
{
uint32_t nFilePathSize = 0;
ifs.read((char*)&nFilePathSize, sizeof(uint32_t));
std::string sFileName(nFilePathSize, ' ');
for (uint32_t j = 0; j < nFilePathSize; j++)
sFileName[j] = ifs.get();
sEntry e;
e.data = nullptr;
ifs.read((char*)&e.nID, sizeof(uint32_t));
ifs.read((char*)&e.nFileSize, sizeof(uint32_t));
ifs.read((char*)&e.nFileOffset, sizeof(uint32_t));
mapFiles[sFileName] = e;
}
// 2) Read Data
for (auto& e : mapFiles)
{
e.second.data = new uint8_t[(uint32_t)e.second.nFileSize];
ifs.seekg(e.second.nFileOffset);
ifs.read((char*)e.second.data, e.second.nFileSize);
e.second._config();
}
ifs.close();
return olc::OK;
}
olc::ResourcePack::sEntry ResourcePack::GetStreamBuffer(std::string sFile)
{
return mapFiles[sFile];
}
olc::rcode ResourcePack::ClearPack()
{
for (auto& e : mapFiles)
{
if (e.second.data != nullptr)
delete[] e.second.data;
}
mapFiles.clear();
return olc::OK;
}
//==========================================================
PixelGameEngine::PixelGameEngine()
{
sAppName = "Undefined";
olc::PGEX::pge = this;
}
olc::rcode PixelGameEngine::Construct(uint32_t screen_w, uint32_t screen_h, uint32_t pixel_w, uint32_t pixel_h, bool full_screen, bool vsync)
{
nScreenWidth = screen_w;
nScreenHeight = screen_h;
nPixelWidth = pixel_w;
nPixelHeight = pixel_h;
bFullScreen = full_screen;
bEnableVSYNC = vsync;
fPixelX = 2.0f / (float)(nScreenWidth);
fPixelY = 2.0f / (float)(nScreenHeight);
if (nPixelWidth == 0 || nPixelHeight == 0 || nScreenWidth == 0 || nScreenHeight == 0)
return olc::FAIL;
#if defined(_WIN32) && defined(UNICODE) && !defined(__MINGW32__)
wsAppName = ConvertS2W(sAppName);
#endif
// Load the default font sheet
olc_ConstructFontSheet();
// Create a sprite that represents the primary drawing target
pDefaultDrawTarget = new Sprite(nScreenWidth, nScreenHeight);
SetDrawTarget(nullptr);
return olc::OK;
}
void PixelGameEngine::SetScreenSize(int w, int h)
{
delete pDefaultDrawTarget;
nScreenWidth = w;
nScreenHeight = h;
pDefaultDrawTarget = new Sprite(nScreenWidth, nScreenHeight);
SetDrawTarget(nullptr);
glClear(GL_COLOR_BUFFER_BIT);
#if defined(_WIN32)
SwapBuffers(glDeviceContext);
#endif
#if defined(__linux__)
glXSwapBuffers(olc_Display, olc_Window);
#endif
glClear(GL_COLOR_BUFFER_BIT);
olc_UpdateViewport();
}
olc::rcode PixelGameEngine::Start()
{
// Construct the window
if (!olc_WindowCreate())
return olc::FAIL;
// Start the thread
bAtomActive = true;
std::thread t = std::thread(&PixelGameEngine::EngineThread, this);
#if defined(_WIN32)
// Handle Windows Message Loop
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
#endif
// Wait for thread to be exited
t.join();
return olc::OK;
}
void PixelGameEngine::SetDrawTarget(Sprite* target)
{
if (target)
pDrawTarget = target;
else
pDrawTarget = pDefaultDrawTarget;
}
Sprite* PixelGameEngine::GetDrawTarget()
{
return pDrawTarget;
}
int32_t PixelGameEngine::GetDrawTargetWidth()
{
if (pDrawTarget)
return pDrawTarget->width;
else
return 0;
}
int32_t PixelGameEngine::GetDrawTargetHeight()
{
if (pDrawTarget)
return pDrawTarget->height;
else
return 0;
}
bool PixelGameEngine::IsFocused()
{
return bHasInputFocus;
}
HWButton PixelGameEngine::GetKey(Key k)
{
return pKeyboardState[k];
}
HWButton PixelGameEngine::GetMouse(uint32_t b)
{
return pMouseState[b];
}
int32_t PixelGameEngine::GetMouseX()
{
return nMousePosX;
}
int32_t PixelGameEngine::GetMouseY()
{
return nMousePosY;
}
int32_t PixelGameEngine::GetMouseWheel()
{
return nMouseWheelDelta;
}
int32_t PixelGameEngine::ScreenWidth()
{
return nScreenWidth;
}
int32_t PixelGameEngine::ScreenHeight()
{
return nScreenHeight;
}
bool PixelGameEngine::Draw(int32_t x, int32_t y, Pixel p)
{
if (!pDrawTarget) return false;
if (nPixelMode == Pixel::NORMAL)
{
return pDrawTarget->SetPixel(x, y, p);
}
if (nPixelMode == Pixel::MASK)
{
if (p.a == 255)
return pDrawTarget->SetPixel(x, y, p);
}
if (nPixelMode == Pixel::ALPHA)
{
Pixel d = pDrawTarget->GetPixel(x, y);
float a = (float)(p.a / 255.0f) * fBlendFactor;
float c = 1.0f - a;
float r = a * (float)p.r + c * (float)d.r;
float g = a * (float)p.g + c * (float)d.g;
float b = a * (float)p.b + c * (float)d.b;
return pDrawTarget->SetPixel(x, y, Pixel((uint8_t)r, (uint8_t)g, (uint8_t)b));
}
if (nPixelMode == Pixel::CUSTOM)
{
return pDrawTarget->SetPixel(x, y, funcPixelMode(x, y, p, pDrawTarget->GetPixel(x, y)));
}
return false;
}
void PixelGameEngine::SetSubPixelOffset(float ox, float oy)
{
fSubPixelOffsetX = ox * fPixelX;
fSubPixelOffsetY = oy * fPixelY;
}
void PixelGameEngine::DrawLine(int32_t x1, int32_t y1, int32_t x2, int32_t y2, Pixel p, uint32_t pattern)
{
int x, y, dx, dy, dx1, dy1, px, py, xe, ye, i;
dx = x2 - x1; dy = y2 - y1;
auto rol = [&](void)
{
pattern = (pattern << 1) | (pattern >> 31);
return pattern & 1;
};
// straight lines idea by gurkanctn
if (dx == 0) // Line is vertical
{
if (y2 < y1) std::swap(y1, y2);
for (y = y1; y <= y2; y++)
if (rol()) Draw(x1, y, p);
return;
}
if (dy == 0) // Line is horizontal
{
if (x2 < x1) std::swap(x1, x2);
for (x = x1; x <= x2; x++)
if (rol()) Draw(x, y1, p);
return;
}
// Line is Funk-aye
dx1 = abs(dx); dy1 = abs(dy);
px = 2 * dy1 - dx1; py = 2 * dx1 - dy1;
if (dy1 <= dx1)
{
if (dx >= 0)
{
x = x1; y = y1; xe = x2;
}
else
{
x = x2; y = y2; xe = x1;
}
if (rol()) Draw(x, y, p);
for (i = 0; x < xe; i++)
{
x = x + 1;
if (px < 0)
px = px + 2 * dy1;
else
{
if ((dx < 0 && dy < 0) || (dx > 0 && dy > 0)) y = y + 1; else y = y - 1;
px = px + 2 * (dy1 - dx1);
}
if (rol()) Draw(x, y, p);
}
}
else
{
if (dy >= 0)
{
x = x1; y = y1; ye = y2;
}
else
{
x = x2; y = y2; ye = y1;
}
if (rol()) Draw(x, y, p);
for (i = 0; y < ye; i++)
{
y = y + 1;
if (py <= 0)
py = py + 2 * dx1;
else
{
if ((dx < 0 && dy < 0) || (dx > 0 && dy > 0)) x = x + 1; else x = x - 1;
py = py + 2 * (dx1 - dy1);
}
if (rol()) Draw(x, y, p);
}
}
}
void PixelGameEngine::DrawCircle(int32_t x, int32_t y, int32_t radius, Pixel p, uint8_t mask)
{
int x0 = 0;
int y0 = radius;
int d = 3 - 2 * radius;
if (!radius) return;
while (y0 >= x0) // only formulate 1/8 of circle
{
if (mask & 0x01) Draw(x + x0, y - y0, p);
if (mask & 0x02) Draw(x + y0, y - x0, p);
if (mask & 0x04) Draw(x + y0, y + x0, p);
if (mask & 0x08) Draw(x + x0, y + y0, p);
if (mask & 0x10) Draw(x - x0, y + y0, p);
if (mask & 0x20) Draw(x - y0, y + x0, p);
if (mask & 0x40) Draw(x - y0, y - x0, p);
if (mask & 0x80) Draw(x - x0, y - y0, p);
if (d < 0) d += 4 * x0++ + 6;
else d += 4 * (x0++ - y0--) + 10;
}
}
void PixelGameEngine::FillCircle(int32_t x, int32_t y, int32_t radius, Pixel p)
{
// Taken from wikipedia
int x0 = 0;
int y0 = radius;
int d = 3 - 2 * radius;
if (!radius) return;
auto drawline = [&](int sx, int ex, int ny)
{
for (int i = sx; i <= ex; i++)
Draw(i, ny, p);
};
while (y0 >= x0)
{
// Modified to draw scan-lines instead of edges
drawline(x - x0, x + x0, y - y0);
drawline(x - y0, x + y0, y - x0);
drawline(x - x0, x + x0, y + y0);
drawline(x - y0, x + y0, y + x0);
if (d < 0) d += 4 * x0++ + 6;
else d += 4 * (x0++ - y0--) + 10;
}
}
void PixelGameEngine::DrawRect(int32_t x, int32_t y, int32_t w, int32_t h, Pixel p)
{
DrawLine(x, y, x + w, y, p);
DrawLine(x + w, y, x + w, y + h, p);
DrawLine(x + w, y + h, x, y + h, p);
DrawLine(x, y + h, x, y, p);
}
void PixelGameEngine::Clear(Pixel p)
{
int pixels = GetDrawTargetWidth() * GetDrawTargetHeight();
Pixel* m = GetDrawTarget()->GetData();
for (int i = 0; i < pixels; i++)
m[i] = p;
#ifdef OLC_DBG_OVERDRAW
olc::Sprite::nOverdrawCount += pixels;
#endif
}
void PixelGameEngine::FillRect(int32_t x, int32_t y, int32_t w, int32_t h, Pixel p)
{
int32_t x2 = x + w;
int32_t y2 = y + h;
if (x < 0) x = 0;
if (x >= (int32_t)nScreenWidth) x = (int32_t)nScreenWidth;
if (y < 0) y = 0;
if (y >= (int32_t)nScreenHeight) y = (int32_t)nScreenHeight;
if (x2 < 0) x2 = 0;
if (x2 >= (int32_t)nScreenWidth) x2 = (int32_t)nScreenWidth;
if (y2 < 0) y2 = 0;
if (y2 >= (int32_t)nScreenHeight) y2 = (int32_t)nScreenHeight;
for (int i = x; i < x2; i++)
for (int j = y; j < y2; j++)
Draw(i, j, p);
}
void PixelGameEngine::DrawTriangle(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x3, int32_t y3, Pixel p)
{
DrawLine(x1, y1, x2, y2, p);
DrawLine(x2, y2, x3, y3, p);
DrawLine(x3, y3, x1, y1, p);
}
// https://www.avrfreaks.net/sites/default/files/triangles.c
void PixelGameEngine::FillTriangle(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x3, int32_t y3, Pixel p)
{
auto SWAP = [](int& x, int& y) { int t = x; x = y; y = t; };
auto drawline = [&](int sx, int ex, int ny) { for (int i = sx; i <= ex; i++) Draw(i, ny, p); };
int t1x, t2x, y, minx, maxx, t1xp, t2xp;
bool changed1 = false;
bool changed2 = false;
int signx1, signx2, dx1, dy1, dx2, dy2;
int e1, e2;
// Sort vertices
if (y1 > y2) { SWAP(y1, y2); SWAP(x1, x2); }
if (y1 > y3) { SWAP(y1, y3); SWAP(x1, x3); }
if (y2 > y3) { SWAP(y2, y3); SWAP(x2, x3); }
t1x = t2x = x1; y = y1; // Starting points
dx1 = (int)(x2 - x1); if (dx1 < 0) { dx1 = -dx1; signx1 = -1; }
else signx1 = 1;
dy1 = (int)(y2 - y1);
dx2 = (int)(x3 - x1); if (dx2 < 0) { dx2 = -dx2; signx2 = -1; }
else signx2 = 1;
dy2 = (int)(y3 - y1);
if (dy1 > dx1) { // swap values
SWAP(dx1, dy1);
changed1 = true;
}
if (dy2 > dx2) { // swap values
SWAP(dy2, dx2);
changed2 = true;
}
e2 = (int)(dx2 >> 1);
// Flat top, just process the second half
if (y1 == y2) goto next;
e1 = (int)(dx1 >> 1);
for (int i = 0; i < dx1;) {
t1xp = 0; t2xp = 0;
if (t1x < t2x) { minx = t1x; maxx = t2x; }
else { minx = t2x; maxx = t1x; }
// process first line until y value is about to change
while (i < dx1) {
i++;
e1 += dy1;
while (e1 >= dx1) {
e1 -= dx1;
if (changed1) t1xp = signx1;//t1x += signx1;
else goto next1;
}
if (changed1) break;
else t1x += signx1;
}
// Move line
next1:
// process second line until y value is about to change
while (1) {
e2 += dy2;
while (e2 >= dx2) {
e2 -= dx2;
if (changed2) t2xp = signx2;//t2x += signx2;
else goto next2;
}
if (changed2) break;
else t2x += signx2;
}
next2:
if (minx > t1x) minx = t1x;
if (minx > t2x) minx = t2x;
if (maxx < t1x) maxx = t1x;
if (maxx < t2x) maxx = t2x;
drawline(minx, maxx, y); // Draw line from min to max points found on the y
// Now increase y
if (!changed1) t1x += signx1;
t1x += t1xp;
if (!changed2) t2x += signx2;
t2x += t2xp;
y += 1;
if (y == y2) break;
}
next:
// Second half
dx1 = (int)(x3 - x2); if (dx1 < 0) { dx1 = -dx1; signx1 = -1; }
else signx1 = 1;
dy1 = (int)(y3 - y2);
t1x = x2;
if (dy1 > dx1) { // swap values
SWAP(dy1, dx1);
changed1 = true;
}
else changed1 = false;
e1 = (int)(dx1 >> 1);
for (int i = 0; i <= dx1; i++) {
t1xp = 0; t2xp = 0;
if (t1x < t2x) { minx = t1x; maxx = t2x; }
else { minx = t2x; maxx = t1x; }
// process first line until y value is about to change
while (i < dx1) {
e1 += dy1;
while (e1 >= dx1) {
e1 -= dx1;
if (changed1) { t1xp = signx1; break; }//t1x += signx1;
else goto next3;
}
if (changed1) break;
else t1x += signx1;
if (i < dx1) i++;
}
next3:
// process second line until y value is about to change
while (t2x != x3) {
e2 += dy2;
while (e2 >= dx2) {
e2 -= dx2;
if (changed2) t2xp = signx2;
else goto next4;
}
if (changed2) break;
else t2x += signx2;
}
next4:
if (minx > t1x) minx = t1x;
if (minx > t2x) minx = t2x;
if (maxx < t1x) maxx = t1x;
if (maxx < t2x) maxx = t2x;
drawline(minx, maxx, y);
if (!changed1) t1x += signx1;
t1x += t1xp;
if (!changed2) t2x += signx2;
t2x += t2xp;
y += 1;
if (y > y3) return;
}
}
void PixelGameEngine::DrawSprite(int32_t x, int32_t y, Sprite* sprite, uint32_t scale)
{
if (sprite == nullptr)
return;
if (scale > 1)
{
for (int32_t i = 0; i < sprite->width; i++)
for (int32_t j = 0; j < sprite->height; j++)
for (uint32_t is = 0; is < scale; is++)
for (uint32_t js = 0; js < scale; js++)
Draw(x + (i * scale) + is, y + (j * scale) + js, sprite->GetPixel(i, j));
}
else
{
for (int32_t i = 0; i < sprite->width; i++)
for (int32_t j = 0; j < sprite->height; j++)
Draw(x + i, y + j, sprite->GetPixel(i, j));
}
}
void PixelGameEngine::DrawPartialSprite(int32_t x, int32_t y, Sprite* sprite, int32_t ox, int32_t oy, int32_t w, int32_t h, uint32_t scale)
{
if (sprite == nullptr)
return;
if (scale > 1)
{
for (int32_t i = 0; i < w; i++)
for (int32_t j = 0; j < h; j++)
for (uint32_t is = 0; is < scale; is++)
for (uint32_t js = 0; js < scale; js++)
Draw(x + (i * scale) + is, y + (j * scale) + js, sprite->GetPixel(i + ox, j + oy));
}
else
{
for (int32_t i = 0; i < w; i++)
for (int32_t j = 0; j < h; j++)
Draw(x + i, y + j, sprite->GetPixel(i + ox, j + oy));
}
}
void PixelGameEngine::DrawString(int32_t x, int32_t y, std::string sText, Pixel col, uint32_t scale)
{
int32_t sx = 0;
int32_t sy = 0;
Pixel::Mode m = nPixelMode;
if (col.ALPHA != 255) SetPixelMode(Pixel::ALPHA);
else SetPixelMode(Pixel::MASK);
for (auto c : sText)
{
if (c == '\n')
{
sx = 0; sy += 8 * scale;
}
else
{
int32_t ox = (c - 32) % 16;
int32_t oy = (c - 32) / 16;
if (scale > 1)
{
for (uint32_t i = 0; i < 8; i++)
for (uint32_t j = 0; j < 8; j++)
if (fontSprite->GetPixel(i + ox * 8, j + oy * 8).r > 0)
for (uint32_t is = 0; is < scale; is++)
for (uint32_t js = 0; js < scale; js++)
Draw(x + sx + (i * scale) + is, y + sy + (j * scale) + js, col);
}
else
{
for (uint32_t i = 0; i < 8; i++)
for (uint32_t j = 0; j < 8; j++)
if (fontSprite->GetPixel(i + ox * 8, j + oy * 8).r > 0)
Draw(x + sx + i, y + sy + j, col);
}
sx += 8 * scale;
}
}
SetPixelMode(m);
}
void PixelGameEngine::SetPixelMode(Pixel::Mode m)
{
nPixelMode = m;
}
Pixel::Mode PixelGameEngine::GetPixelMode()
{
return nPixelMode;
}
void PixelGameEngine::SetPixelMode(std::function<olc::Pixel(const int x, const int y, const olc::Pixel&, const olc::Pixel&)> pixelMode)
{
funcPixelMode = pixelMode;
nPixelMode = Pixel::Mode::CUSTOM;
}
void PixelGameEngine::SetPixelBlend(float fBlend)
{
fBlendFactor = fBlend;
if (fBlendFactor < 0.0f) fBlendFactor = 0.0f;
if (fBlendFactor > 1.0f) fBlendFactor = 1.0f;
}
// User must override these functions as required. I have not made
// them abstract because I do need a default behaviour to occur if
// they are not overwritten
bool PixelGameEngine::OnUserCreate()
{
return false;
}
bool PixelGameEngine::OnUserUpdate(float fElapsedTime)
{
UNUSED(fElapsedTime); return false;
}
bool PixelGameEngine::OnUserDestroy()
{
return true;
}
int PixelGameEngine::OnUserKeyDown(int key)
{
return 0;
}
int PixelGameEngine::OnUserKeyUp(int key)
{
return 0;
}
//////////////////////////////////////////////////////////////////
void PixelGameEngine::olc_UpdateViewport()
{
int32_t ww = nScreenWidth * nPixelWidth;
int32_t wh = nScreenHeight * nPixelHeight;
float wasp = (float)ww / (float)wh;
nViewW = (int32_t)nWindowWidth;
nViewH = (int32_t)((float)nViewW / wasp);
if (nViewH > nWindowHeight)
{
nViewH = nWindowHeight;
nViewW = (int32_t)((float)nViewH * wasp);
}
nViewX = (nWindowWidth - nViewW) / 2;
nViewY = (nWindowHeight - nViewH) / 2;
}
void PixelGameEngine::olc_UpdateWindowSize(int32_t x, int32_t y)
{
nWindowWidth = x;
nWindowHeight = y;
olc_UpdateViewport();
}
void PixelGameEngine::olc_UpdateMouseWheel(int32_t delta)
{
nMouseWheelDeltaCache += delta;
}
void PixelGameEngine::olc_UpdateMouse(int32_t x, int32_t y)
{
// Mouse coords come in screen space
// But leave in pixel space
// Full Screen mode may have a weird viewport we must clamp to
x -= nViewX;
y -= nViewY;
nMousePosXcache = (int32_t)(((float)x / (float)(nWindowWidth - (nViewX * 2)) * (float)nScreenWidth));
nMousePosYcache = (int32_t)(((float)y / (float)(nWindowHeight - (nViewY * 2)) * (float)nScreenHeight));
if (nMousePosXcache >= (int32_t)nScreenWidth)
nMousePosXcache = nScreenWidth - 1;
if (nMousePosYcache >= (int32_t)nScreenHeight)
nMousePosYcache = nScreenHeight - 1;
if (nMousePosXcache < 0)
nMousePosXcache = 0;
if (nMousePosYcache < 0)
nMousePosYcache = 0;
}
void PixelGameEngine::EngineThread()
{
// Start OpenGL, the context is owned by the game thread
olc_OpenGLCreate();
// Create Screen Texture - disable filtering
glEnable(GL_TEXTURE_2D);
glGenTextures(1, &glBuffer);
glBindTexture(GL_TEXTURE_2D, glBuffer);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, nScreenWidth, nScreenHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, pDefaultDrawTarget->GetData());
// Create user resources as part of this thread
if (!OnUserCreate())
bAtomActive = false;
auto tp1 = std::chrono::system_clock::now();
auto tp2 = std::chrono::system_clock::now();
while (bAtomActive)
{
// Run as fast as possible
while (bAtomActive)
{
// Handle Timing
tp2 = std::chrono::system_clock::now();
std::chrono::duration<float> elapsedTime = tp2 - tp1;
tp1 = tp2;
// Our time per frame coefficient
float fElapsedTime = elapsedTime.count();
#if defined(__linux__)
// Handle Xlib Message Loop - we do this in the
// same thread that OpenGL was created so we dont
// need to worry too much about multithreading with X11
XEvent xev;
while (XPending(olc_Display))
{
XNextEvent(olc_Display, &xev);
if (xev.type == Expose)
{
XWindowAttributes gwa;
XGetWindowAttributes(olc_Display, olc_Window, &gwa);
nWindowWidth = gwa.width;
nWindowHeight = gwa.height;
olc_UpdateViewport();
glClear(GL_COLOR_BUFFER_BIT); // Thanks Benedani!
}
else if (xev.type == ConfigureNotify)
{
XConfigureEvent xce = xev.xconfigure;
nWindowWidth = xce.width;
nWindowHeight = xce.height;
}
else if (xev.type == KeyPress)
{
KeySym sym = XLookupKeysym(&xev.xkey, 0);
pKeyNewState[mapKeys[sym]] = true;
XKeyEvent* e = (XKeyEvent*)&xev; // Because DragonEye loves numpads
XLookupString(e, NULL, 0, &sym, NULL);
pKeyNewState[mapKeys[sym]] = true;
}
else if (xev.type == KeyRelease)
{
KeySym sym = XLookupKeysym(&xev.xkey, 0);
pKeyNewState[mapKeys[sym]] = false;
XKeyEvent* e = (XKeyEvent*)&xev;
XLookupString(e, NULL, 0, &sym, NULL);
pKeyNewState[mapKeys[sym]] = false;
}
else if (xev.type == ButtonPress)
{
switch (xev.xbutton.button)
{
case 1: pMouseNewState[0] = true; break;
case 2: pMouseNewState[2] = true; break;
case 3: pMouseNewState[1] = true; break;
case 4: olc_UpdateMouseWheel(120); break;
case 5: olc_UpdateMouseWheel(-120); break;
default: break;
}
}
else if (xev.type == ButtonRelease)
{
switch (xev.xbutton.button)
{
case 1: pMouseNewState[0] = false; break;
case 2: pMouseNewState[2] = false; break;
case 3: pMouseNewState[1] = false; break;
default: break;
}
}
else if (xev.type == MotionNotify)
{
olc_UpdateMouse(xev.xmotion.x, xev.xmotion.y);
}
else if (xev.type == FocusIn)
{
bHasInputFocus = true;
}
else if (xev.type == FocusOut)
{
bHasInputFocus = false;
}
else if (xev.type == ClientMessage)
{
bAtomActive = false;
}
}
#endif
// Handle User Input - Keyboard
for (int i = 0; i < 256; i++)
{
pKeyboardState[i].bPressed = false;
pKeyboardState[i].bReleased = false;
if (pKeyNewState[i] != pKeyOldState[i])
{
if (pKeyNewState[i])
{
pKeyboardState[i].bPressed = !pKeyboardState[i].bHeld;
pKeyboardState[i].bHeld = true;
}
else
{
pKeyboardState[i].bReleased = true;
pKeyboardState[i].bHeld = false;
}
}
pKeyOldState[i] = pKeyNewState[i];
}
// Handle User Input - Mouse
for (int i = 0; i < 5; i++)
{
pMouseState[i].bPressed = false;
pMouseState[i].bReleased = false;
if (pMouseNewState[i] != pMouseOldState[i])
{
if (pMouseNewState[i])
{
pMouseState[i].bPressed = !pMouseState[i].bHeld;
pMouseState[i].bHeld = true;
}
else
{
pMouseState[i].bReleased = true;
pMouseState[i].bHeld = false;
}
}
pMouseOldState[i] = pMouseNewState[i];
}
// Cache mouse coordinates so they remain
// consistent during frame
nMousePosX = nMousePosXcache;
nMousePosY = nMousePosYcache;
nMouseWheelDelta = nMouseWheelDeltaCache;
nMouseWheelDeltaCache = 0;
#ifdef OLC_DBG_OVERDRAW
olc::Sprite::nOverdrawCount = 0;
#endif
// Handle Frame Update
if (!OnUserUpdate(fElapsedTime))
bAtomActive = false;
// Display Graphics
glViewport(nViewX, nViewY, nViewW, nViewH);
// TODO: This is a bit slow (especially in debug, but 100x faster in release mode???)
// Copy pixel array into texture
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, nScreenWidth, nScreenHeight, GL_RGBA, GL_UNSIGNED_BYTE, pDefaultDrawTarget->GetData());
// Display texture on screen
glBegin(GL_QUADS);
glTexCoord2f(0.0, 1.0); glVertex3f(-1.0f + (fSubPixelOffsetX), -1.0f + (fSubPixelOffsetY), 0.0f);
glTexCoord2f(0.0, 0.0); glVertex3f(-1.0f + (fSubPixelOffsetX), 1.0f + (fSubPixelOffsetY), 0.0f);
glTexCoord2f(1.0, 0.0); glVertex3f(1.0f + (fSubPixelOffsetX), 1.0f + (fSubPixelOffsetY), 0.0f);
glTexCoord2f(1.0, 1.0); glVertex3f(1.0f + (fSubPixelOffsetX), -1.0f + (fSubPixelOffsetY), 0.0f);
glEnd();
// Present Graphics to screen
#if defined(_WIN32)
SwapBuffers(glDeviceContext);
#endif
#if defined(__linux__)
glXSwapBuffers(olc_Display, olc_Window);
#endif
// Update Title Bar
fFrameTimer += fElapsedTime;
nFrameCount++;
if (fFrameTimer >= 1.0f)
{
fFrameTimer -= 1.0f;
std::string sTitle = "OneLoneCoder.com - Pixel Game Engine - " + sAppName + " - FPS: " + std::to_string(nFrameCount);
#if defined(_WIN32)
#ifdef UNICODE
SetWindowText(olc_hWnd, ConvertS2W(sTitle).c_str());
#else
SetWindowText(olc_hWnd, sTitle.c_str());
#endif
#endif
#if defined (__linux__)
XStoreName(olc_Display, olc_Window, sTitle.c_str());
#endif
nFrameCount = 0;
}
}
// Allow the user to free resources if they have overrided the destroy function
if (OnUserDestroy())
{
// User has permitted destroy, so exit and clean up
}
else
{
// User denied destroy for some reason, so continue running
bAtomActive = true;
}
}
#if defined(_WIN32)
wglDeleteContext(glRenderContext);
PostMessage(olc_hWnd, WM_DESTROY, 0, 0);
#endif
#if defined (__linux__)
glXMakeCurrent(olc_Display, None, NULL);
glXDestroyContext(olc_Display, glDeviceContext);
XDestroyWindow(olc_Display, olc_Window);
XCloseDisplay(olc_Display);
#endif
}
#if defined (_WIN32)
// Thanks @MaGetzUb for this, which allows sprites to be defined
// at construction, by initialising the GDI subsystem
static class GDIPlusStartup
{
public:
GDIPlusStartup()
{
Gdiplus::GdiplusStartupInput startupInput;
ULONG_PTR token;
Gdiplus::GdiplusStartup(&token, &startupInput, NULL);
};
} gdistartup;
#endif
void PixelGameEngine::olc_ConstructFontSheet()
{
std::string data;
data += "?Q`0001oOch0o01o@F40o0<AGD4090LAGD<090@A7ch0?00O7Q`0600>00000000";
data += "O000000nOT0063Qo4d8>?7a14Gno94AA4gno94AaOT0>o3`oO400o7QN00000400";
data += "Of80001oOg<7O7moBGT7O7lABET024@aBEd714AiOdl717a_=TH013Q>00000000";
data += "720D000V?V5oB3Q_HdUoE7a9@DdDE4A9@DmoE4A;Hg]oM4Aj8S4D84@`00000000";
data += "OaPT1000Oa`^13P1@AI[?g`1@A=[OdAoHgljA4Ao?WlBA7l1710007l100000000";
data += "ObM6000oOfMV?3QoBDD`O7a0BDDH@5A0BDD<@5A0BGeVO5ao@CQR?5Po00000000";
data += "Oc``000?Ogij70PO2D]??0Ph2DUM@7i`2DTg@7lh2GUj?0TO0C1870T?00000000";
data += "70<4001o?P<7?1QoHg43O;`h@GT0@:@LB@d0>:@hN@L0@?aoN@<0O7ao0000?000";
data += "OcH0001SOglLA7mg24TnK7ln24US>0PL24U140PnOgl0>7QgOcH0K71S0000A000";
data += "00H00000@Dm1S007@DUSg00?OdTnH7YhOfTL<7Yh@Cl0700?@Ah0300700000000";
data += "<008001QL00ZA41a@6HnI<1i@FHLM81M@@0LG81?O`0nC?Y7?`0ZA7Y300080000";
data += "O`082000Oh0827mo6>Hn?Wmo?6HnMb11MP08@C11H`08@FP0@@0004@000000000";
data += "00P00001Oab00003OcKP0006@6=PMgl<@440MglH@000000`@000001P00000000";
data += "Ob@8@@00Ob@8@Ga13R@8Mga172@8?PAo3R@827QoOb@820@0O`0007`0000007P0";
data += "O`000P08Od400g`<3V=P0G`673IP0`@3>1`00P@6O`P00g`<O`000GP800000000";
data += "?P9PL020O`<`N3R0@E4HC7b0@ET<ATB0@@l6C4B0O`H3N7b0?P01L3R000000020";
fontSprite = new olc::Sprite(128, 48);
int px = 0, py = 0;
for (int b = 0; b < 1024; b += 4)
{
uint32_t sym1 = (uint32_t)data[b + 0] - 48;
uint32_t sym2 = (uint32_t)data[b + 1] - 48;
uint32_t sym3 = (uint32_t)data[b + 2] - 48;
uint32_t sym4 = (uint32_t)data[b + 3] - 48;
uint32_t r = sym1 << 18 | sym2 << 12 | sym3 << 6 | sym4;
for (int i = 0; i < 24; i++)
{
int k = r & (1 << i) ? 255 : 0;
fontSprite->SetPixel(px, py, olc::Pixel(k, k, k, k));
if (++py == 48) { px++; py = 0; }
}
}
}
#if defined(_WIN32)
HWND PixelGameEngine::olc_WindowCreate()
{
WNDCLASS wc;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.hInstance = GetModuleHandle(nullptr);
wc.lpfnWndProc = olc_WindowEvent;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.lpszMenuName = nullptr;
wc.hbrBackground = nullptr;
#ifdef UNICODE
wc.lpszClassName = L"OLC_PIXEL_GAME_ENGINE";
#else
wc.lpszClassName = "OLC_PIXEL_GAME_ENGINE";
#endif
RegisterClass(&wc);
nWindowWidth = (LONG)nScreenWidth * (LONG)nPixelWidth;
nWindowHeight = (LONG)nScreenHeight * (LONG)nPixelHeight;
// Define window furniture
DWORD dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
DWORD dwStyle = WS_CAPTION | WS_SYSMENU | WS_VISIBLE | WS_THICKFRAME;
int nCosmeticOffset = 30;
nViewW = nWindowWidth;
nViewH = nWindowHeight;
// Handle Fullscreen
if (bFullScreen)
{
dwExStyle = 0;
dwStyle = WS_VISIBLE | WS_POPUP;
nCosmeticOffset = 0;
HMONITOR hmon = MonitorFromWindow(olc_hWnd, MONITOR_DEFAULTTONEAREST);
MONITORINFO mi = { sizeof(mi) };
if (!GetMonitorInfo(hmon, &mi)) return NULL;
nWindowWidth = mi.rcMonitor.right;
nWindowHeight = mi.rcMonitor.bottom;
}
olc_UpdateViewport();
// Keep client size as requested
RECT rWndRect = { 0, 0, nWindowWidth, nWindowHeight };
AdjustWindowRectEx(&rWndRect, dwStyle, FALSE, dwExStyle);
int width = rWndRect.right - rWndRect.left;
int height = rWndRect.bottom - rWndRect.top;
#ifdef UNICODE
olc_hWnd = CreateWindowEx(dwExStyle, L"OLC_PIXEL_GAME_ENGINE", L"", dwStyle,
nCosmeticOffset, nCosmeticOffset, width, height, NULL, NULL, GetModuleHandle(nullptr), this);
#else
olc_hWnd = CreateWindowEx(dwExStyle, "OLC_PIXEL_GAME_ENGINE", "", dwStyle,
nCosmeticOffset, nCosmeticOffset, width, height, NULL, NULL, GetModuleHandle(nullptr), this);
#endif
// Create Keyboard Mapping
mapKeys[0x00] = Key::NONE;
mapKeys[0x41] = Key::A; mapKeys[0x42] = Key::B; mapKeys[0x43] = Key::C; mapKeys[0x44] = Key::D; mapKeys[0x45] = Key::E;
mapKeys[0x46] = Key::F; mapKeys[0x47] = Key::G; mapKeys[0x48] = Key::H; mapKeys[0x49] = Key::I; mapKeys[0x4A] = Key::J;
mapKeys[0x4B] = Key::K; mapKeys[0x4C] = Key::L; mapKeys[0x4D] = Key::M; mapKeys[0x4E] = Key::N; mapKeys[0x4F] = Key::O;
mapKeys[0x50] = Key::P; mapKeys[0x51] = Key::Q; mapKeys[0x52] = Key::R; mapKeys[0x53] = Key::S; mapKeys[0x54] = Key::T;
mapKeys[0x55] = Key::U; mapKeys[0x56] = Key::V; mapKeys[0x57] = Key::W; mapKeys[0x58] = Key::X; mapKeys[0x59] = Key::Y;
mapKeys[0x5A] = Key::Z;
mapKeys[VK_F1] = Key::F1; mapKeys[VK_F2] = Key::F2; mapKeys[VK_F3] = Key::F3; mapKeys[VK_F4] = Key::F4;
mapKeys[VK_F5] = Key::F5; mapKeys[VK_F6] = Key::F6; mapKeys[VK_F7] = Key::F7; mapKeys[VK_F8] = Key::F8;
mapKeys[VK_F9] = Key::F9; mapKeys[VK_F10] = Key::F10; mapKeys[VK_F11] = Key::F11; mapKeys[VK_F12] = Key::F12;
mapKeys[VK_DOWN] = Key::DOWN; mapKeys[VK_LEFT] = Key::LEFT; mapKeys[VK_RIGHT] = Key::RIGHT; mapKeys[VK_UP] = Key::UP;
mapKeys[VK_RETURN] = Key::ENTER; //mapKeys[VK_RETURN] = Key::RETURN;
mapKeys[VK_BACK] = Key::BACK; mapKeys[VK_ESCAPE] = Key::ESCAPE; mapKeys[VK_RETURN] = Key::ENTER; mapKeys[VK_PAUSE] = Key::PAUSE;
mapKeys[VK_SCROLL] = Key::SCROLL; mapKeys[VK_TAB] = Key::TAB; mapKeys[VK_DELETE] = Key::DEL; mapKeys[VK_HOME] = Key::HOME;
mapKeys[VK_END] = Key::END; mapKeys[VK_PRIOR] = Key::PGUP; mapKeys[VK_NEXT] = Key::PGDN; mapKeys[VK_INSERT] = Key::INS;
mapKeys[VK_SHIFT] = Key::SHIFT; mapKeys[VK_CONTROL] = Key::CTRL;
mapKeys[VK_SPACE] = Key::SPACE;
mapKeys[0x30] = Key::K0; mapKeys[0x31] = Key::K1; mapKeys[0x32] = Key::K2; mapKeys[0x33] = Key::K3; mapKeys[0x34] = Key::K4;
mapKeys[0x35] = Key::K5; mapKeys[0x36] = Key::K6; mapKeys[0x37] = Key::K7; mapKeys[0x38] = Key::K8; mapKeys[0x39] = Key::K9;
mapKeys[VK_NUMPAD0] = Key::NP0; mapKeys[VK_NUMPAD1] = Key::NP1; mapKeys[VK_NUMPAD2] = Key::NP2; mapKeys[VK_NUMPAD3] = Key::NP3; mapKeys[VK_NUMPAD4] = Key::NP4;
mapKeys[VK_NUMPAD5] = Key::NP5; mapKeys[VK_NUMPAD6] = Key::NP6; mapKeys[VK_NUMPAD7] = Key::NP7; mapKeys[VK_NUMPAD8] = Key::NP8; mapKeys[VK_NUMPAD9] = Key::NP9;
mapKeys[VK_MULTIPLY] = Key::NP_MUL; mapKeys[VK_ADD] = Key::NP_ADD; mapKeys[VK_DIVIDE] = Key::NP_DIV; mapKeys[VK_SUBTRACT] = Key::NP_SUB; mapKeys[VK_DECIMAL] = Key::NP_DECIMAL;
return olc_hWnd;
}
bool PixelGameEngine::olc_OpenGLCreate()
{
// Create Device Context
glDeviceContext = GetDC(olc_hWnd);
PIXELFORMATDESCRIPTOR pfd =
{
sizeof(PIXELFORMATDESCRIPTOR), 1,
PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
PFD_MAIN_PLANE, 0, 0, 0, 0
};
int pf = 0;
if (!(pf = ChoosePixelFormat(glDeviceContext, &pfd))) return false;
SetPixelFormat(glDeviceContext, pf, &pfd);
if (!(glRenderContext = wglCreateContext(glDeviceContext))) return false;
wglMakeCurrent(glDeviceContext, glRenderContext);
glViewport(nViewX, nViewY, nViewW, nViewH);
// Remove Frame cap
wglSwapInterval = (wglSwapInterval_t*)wglGetProcAddress("wglSwapIntervalEXT");
if (wglSwapInterval && !bEnableVSYNC) wglSwapInterval(0);
return true;
}
// Windows Event Handler
LRESULT CALLBACK PixelGameEngine::olc_WindowEvent(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
static PixelGameEngine* sge;
switch (uMsg)
{
case WM_CREATE: sge = (PixelGameEngine*)((LPCREATESTRUCT)lParam)->lpCreateParams; return 0;
case WM_MOUSEMOVE:
{
uint16_t x = lParam & 0xFFFF; // Thanks @ForAbby (Discord)
uint16_t y = (lParam >> 16) & 0xFFFF;
int16_t ix = *(int16_t*)&x;
int16_t iy = *(int16_t*)&y;
sge->olc_UpdateMouse(ix, iy);
return 0;
}
case WM_SIZE:
{
sge->olc_UpdateWindowSize(lParam & 0xFFFF, (lParam >> 16) & 0xFFFF);
return 0;
}
case WM_MOUSEWHEEL:
{
sge->olc_UpdateMouseWheel(GET_WHEEL_DELTA_WPARAM(wParam));
return 0;
}
case WM_MOUSELEAVE: sge->bHasMouseFocus = false; return 0;
case WM_SETFOCUS: sge->bHasInputFocus = true; return 0;
case WM_KILLFOCUS: sge->bHasInputFocus = false; return 0;
case WM_KEYDOWN: sge->pKeyNewState[mapKeys[wParam]] = true; return olc::PGEX::pge->OnUserKeyDown(wParam);
case WM_KEYUP: sge->pKeyNewState[mapKeys[wParam]] = false; return olc::PGEX::pge->OnUserKeyUp(wParam);
case WM_LBUTTONDOWN:sge->pMouseNewState[0] = true; return 0;
case WM_LBUTTONUP: sge->pMouseNewState[0] = false; return 0;
case WM_RBUTTONDOWN:sge->pMouseNewState[1] = true; return 0;
case WM_RBUTTONUP: sge->pMouseNewState[1] = false; return 0;
case WM_MBUTTONDOWN:sge->pMouseNewState[2] = true; return 0;
case WM_MBUTTONUP: sge->pMouseNewState[2] = false; return 0;
case WM_CLOSE: bAtomActive = false; return 0;
case WM_DESTROY: PostQuitMessage(0); return 0;
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
#endif
#if defined(__linux__)
// Do the Linux stuff!
Display* PixelGameEngine::olc_WindowCreate()
{
XInitThreads();
// Grab the deafult display and window
olc_Display = XOpenDisplay(NULL);
olc_WindowRoot = DefaultRootWindow(olc_Display);
// Based on the display capabilities, configure the appearance of the window
GLint olc_GLAttribs[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };
olc_VisualInfo = glXChooseVisual(olc_Display, 0, olc_GLAttribs);
olc_ColourMap = XCreateColormap(olc_Display, olc_WindowRoot, olc_VisualInfo->visual, AllocNone);
olc_SetWindowAttribs.colormap = olc_ColourMap;
// Register which events we are interested in receiving
olc_SetWindowAttribs.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | FocusChangeMask | StructureNotifyMask;
// Create the window
olc_Window = XCreateWindow(olc_Display, olc_WindowRoot, 30, 30, nScreenWidth * nPixelWidth, nScreenHeight * nPixelHeight, 0, olc_VisualInfo->depth, InputOutput, olc_VisualInfo->visual, CWColormap | CWEventMask, &olc_SetWindowAttribs);
Atom wmDelete = XInternAtom(olc_Display, "WM_DELETE_WINDOW", true);
XSetWMProtocols(olc_Display, olc_Window, &wmDelete, 1);
XMapWindow(olc_Display, olc_Window);
XStoreName(olc_Display, olc_Window, "OneLoneCoder.com - Pixel Game Engine");
if (bFullScreen) // Thanks DragonEye, again :D
{
Atom wm_state;
Atom fullscreen;
wm_state = XInternAtom(olc_Display, "_NET_WM_STATE", False);
fullscreen = XInternAtom(olc_Display, "_NET_WM_STATE_FULLSCREEN", False);
XEvent xev{ 0 };
xev.type = ClientMessage;
xev.xclient.window = olc_Window;
xev.xclient.message_type = wm_state;
xev.xclient.format = 32;
xev.xclient.data.l[0] = (bFullScreen ? 1 : 0); // the action (0: off, 1: on, 2: toggle)
xev.xclient.data.l[1] = fullscreen; // first property to alter
xev.xclient.data.l[2] = 0; // second property to alter
xev.xclient.data.l[3] = 0; // source indication
XMapWindow(olc_Display, olc_Window);
XSendEvent(olc_Display, DefaultRootWindow(olc_Display), False,
SubstructureRedirectMask | SubstructureNotifyMask, &xev);
XFlush(olc_Display);
XWindowAttributes gwa;
XGetWindowAttributes(olc_Display, olc_Window, &gwa);
nWindowWidth = gwa.width;
nWindowHeight = gwa.height;
olc_UpdateViewport();
}
// Create Keyboard Mapping
mapKeys[0x00] = Key::NONE;
mapKeys[0x61] = Key::A; mapKeys[0x62] = Key::B; mapKeys[0x63] = Key::C; mapKeys[0x64] = Key::D; mapKeys[0x65] = Key::E;
mapKeys[0x66] = Key::F; mapKeys[0x67] = Key::G; mapKeys[0x68] = Key::H; mapKeys[0x69] = Key::I; mapKeys[0x6A] = Key::J;
mapKeys[0x6B] = Key::K; mapKeys[0x6C] = Key::L; mapKeys[0x6D] = Key::M; mapKeys[0x6E] = Key::N; mapKeys[0x6F] = Key::O;
mapKeys[0x70] = Key::P; mapKeys[0x71] = Key::Q; mapKeys[0x72] = Key::R; mapKeys[0x73] = Key::S; mapKeys[0x74] = Key::T;
mapKeys[0x75] = Key::U; mapKeys[0x76] = Key::V; mapKeys[0x77] = Key::W; mapKeys[0x78] = Key::X; mapKeys[0x79] = Key::Y;
mapKeys[0x7A] = Key::Z;
mapKeys[XK_F1] = Key::F1; mapKeys[XK_F2] = Key::F2; mapKeys[XK_F3] = Key::F3; mapKeys[XK_F4] = Key::F4;
mapKeys[XK_F5] = Key::F5; mapKeys[XK_F6] = Key::F6; mapKeys[XK_F7] = Key::F7; mapKeys[XK_F8] = Key::F8;
mapKeys[XK_F9] = Key::F9; mapKeys[XK_F10] = Key::F10; mapKeys[XK_F11] = Key::F11; mapKeys[XK_F12] = Key::F12;
mapKeys[XK_Down] = Key::DOWN; mapKeys[XK_Left] = Key::LEFT; mapKeys[XK_Right] = Key::RIGHT; mapKeys[XK_Up] = Key::UP;
mapKeys[XK_KP_Enter] = Key::ENTER; mapKeys[XK_Return] = Key::ENTER;
mapKeys[XK_BackSpace] = Key::BACK; mapKeys[XK_Escape] = Key::ESCAPE; mapKeys[XK_Linefeed] = Key::ENTER; mapKeys[XK_Pause] = Key::PAUSE;
mapKeys[XK_Scroll_Lock] = Key::SCROLL; mapKeys[XK_Tab] = Key::TAB; mapKeys[XK_Delete] = Key::DEL; mapKeys[XK_Home] = Key::HOME;
mapKeys[XK_End] = Key::END; mapKeys[XK_Page_Up] = Key::PGUP; mapKeys[XK_Page_Down] = Key::PGDN; mapKeys[XK_Insert] = Key::INS;
mapKeys[XK_Shift_L] = Key::SHIFT; mapKeys[XK_Shift_R] = Key::SHIFT; mapKeys[XK_Control_L] = Key::CTRL; mapKeys[XK_Control_R] = Key::CTRL;
mapKeys[XK_space] = Key::SPACE;
mapKeys[XK_0] = Key::K0; mapKeys[XK_1] = Key::K1; mapKeys[XK_2] = Key::K2; mapKeys[XK_3] = Key::K3; mapKeys[XK_4] = Key::K4;
mapKeys[XK_5] = Key::K5; mapKeys[XK_6] = Key::K6; mapKeys[XK_7] = Key::K7; mapKeys[XK_8] = Key::K8; mapKeys[XK_9] = Key::K9;
mapKeys[XK_KP_0] = Key::NP0; mapKeys[XK_KP_1] = Key::NP1; mapKeys[XK_KP_2] = Key::NP2; mapKeys[XK_KP_3] = Key::NP3; mapKeys[XK_KP_4] = Key::NP4;
mapKeys[XK_KP_5] = Key::NP5; mapKeys[XK_KP_6] = Key::NP6; mapKeys[XK_KP_7] = Key::NP7; mapKeys[XK_KP_8] = Key::NP8; mapKeys[XK_KP_9] = Key::NP9;
mapKeys[XK_KP_Multiply] = Key::NP_MUL; mapKeys[XK_KP_Add] = Key::NP_ADD; mapKeys[XK_KP_Divide] = Key::NP_DIV; mapKeys[XK_KP_Subtract] = Key::NP_SUB; mapKeys[XK_KP_Decimal] = Key::NP_DECIMAL;
return olc_Display;
}
bool PixelGameEngine::olc_OpenGLCreate()
{
glDeviceContext = glXCreateContext(olc_Display, olc_VisualInfo, nullptr, GL_TRUE);
glXMakeCurrent(olc_Display, olc_Window, glDeviceContext);
XWindowAttributes gwa;
XGetWindowAttributes(olc_Display, olc_Window, &gwa);
glViewport(0, 0, gwa.width, gwa.height);
glSwapIntervalEXT = nullptr;
glSwapIntervalEXT = (glSwapInterval_t*)glXGetProcAddress((unsigned char*)"glXSwapIntervalEXT");
if (glSwapIntervalEXT == nullptr && !bEnableVSYNC)
{
printf("NOTE: Could not disable VSYNC, glXSwapIntervalEXT() was not found!\n");
printf(" Don't worry though, things will still work, it's just the\n");
printf(" frame rate will be capped to your monitors refresh rate - javidx9\n");
}
if (glSwapIntervalEXT != nullptr && !bEnableVSYNC)
glSwapIntervalEXT(olc_Display, olc_Window, 0);
return true;
}
#endif
// Need a couple of statics as these are singleton instances
// read from multiple locations
std::atomic<bool> PixelGameEngine::bAtomActive{ false };
std::map<size_t, uint8_t> PixelGameEngine::mapKeys;
olc::PixelGameEngine* olc::PGEX::pge = nullptr;
#ifdef OLC_DBG_OVERDRAW
int olc::Sprite::nOverdrawCount = 0;
#endif
//=============================================================
}
#endif | [
"noreply@github.com"
] | tamsinlm.noreply@github.com |
9fddccd54bb66ca577863dab5b8d57dc19cc237b | fad536c75f9871b42a91ad5f7d24cabeaf8351e9 | /heshTab/main.cpp | e155e4c3944b007dd4322f5837b2fc51fa41cf4f | [] | no_license | eeeris/Dictionary_test_task_drweb | 1b85bc0905d77cd40e78b23a1bfe8bc9f7c035d1 | 50e3aa2afa49449805dd7bef9164f45d47cd666e | refs/heads/master | 2022-11-30T18:02:57.209634 | 2020-08-13T16:49:24 | 2020-08-13T16:49:24 | 287,062,831 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 104 | cpp |
#include <iostream>
#include "HashTable.h"
using namespace std;
int main()
{
return 0;
}
| [
"eeris@mail.ru"
] | eeris@mail.ru |
ce40b601014a88028d83bd14a88a85c0385d8153 | d0a5a6e3f5f57a537bce6c4b9cf60e92923ca756 | /helper code/fastvector.cpp | 55391a8e7e02c844b638d47dc7c5117a6cea9d5e | [] | no_license | bbackspace/codechef | 0c8435b839296e727e1030c90b0420509374823f | 8cea9d903eb79b534a507facbbedb70b489526e2 | refs/heads/master | 2016-09-06T00:32:52.923699 | 2015-06-19T12:50:13 | 2015-06-19T12:50:13 | 28,696,031 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 896 | cpp | #include<cstdio>
#include<cstdlib>
template <class T>
class FastVector
{
private:
T *vec;
size_t *from;
size_t *to;
size_t top;
T init_val;
size_t len;
public:
T& at(size_t i)
{
if (from[i] < top && to[from[i]] == i)
return vec[i];
else
{
from[i] = top;
to[top] = i;
top++;
vec[i] = init_val;
return vec[i];
}
}
FastVector(size_t len_, T init_val_)
{
vec = new T[len_];
from = new size_t[len_];
to = new size_t[len_];
setAll(init_val_);
len = len_;
}
void setAll(T init_val_)
{
top = 0;
init_val = init_val_;
}
~FastVector()
{
delete[] vec;
delete[] from;
delete[] to;
}
};
int main()
{
FastVector<double> v(100000000,0);
v.setAll(0.0);
v.at(0) = 0.0;
v.at(1) = 1.0;
for(int i = 2; i < 100000000; ++i)
{
v.at(i) = v.at(i - 2) + v.at(i - 1);
if(i % 1000000 == 0)
printf("%d: %0.0lf\n", i, v.at(i));
}
return 0;
} | [
"joelm.pinto@gmail.com"
] | joelm.pinto@gmail.com |
5d46d03ae1c5d8f247a22023d54b7200ca0ba03a | d5d6047d86e39a99cd09a5bbb2ad0820f5f2d39f | /src/MaterialManager.h | 3099b2c78b9be287eb36a145a3a5dbc3ef42e7b9 | [
"MIT",
"LicenseRef-scancode-public-domain"
] | permissive | gchunev/Dice4D | 5bb184c3767294bb1e80111651d6601fab076335 | f96db406204fdca0155d26db856b66a2afd4e664 | refs/heads/master | 2020-05-23T22:33:42.752018 | 2019-05-24T14:50:28 | 2019-05-24T14:50:28 | 186,976,624 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 857 | h |
#ifndef MATERIAL_MANAGER_H
#define MATERIAL_MANAGER_H
#include "SDL_opengles2.h"
#include <vector>
#include <string>
#include <map>
class MaterialManager
{
public:
static MaterialManager* GetInstance();
bool LoadShaders(const std::string& path);
int GetShaderByName(std::string& shaderName);
int GetShaderByMaterialName(const std::string& materialName);
private:
MaterialManager();
~MaterialManager();
MaterialManager(MaterialManager const&) {};
MaterialManager& operator=(MaterialManager const&) {};
void InitShaderDefs();
void DeleteShaders();
void ReloadShaders();
int CreateShader(std::string& shaderPath);
GLuint LoadShader(GLenum type, const char *shaderSrc);
std::string m_shaderPath;
std::map<std::string, std::string> m_materialMap;
std::map<std::string, int> m_shaderMap;
static MaterialManager* m_pInstance;
};
#endif | [
"georgi.chunev@gameloft.com"
] | georgi.chunev@gameloft.com |
fbe7793051ae6840f181903ca0b7fac51ae5c8b0 | 74388fdac3615e98665c61031afe602829bb95f9 | /tags/MainProject/widget/glwidget.h | fcae8d34fac849147a433314fd550ca045cae5f0 | [] | no_license | mvm9289/vig-qp2010 | 4bc78bce61970e1f67a53ca1a98ba7e10871615d | 2005d0870f53a0a8c78bafad711a3b7f7e11ba4b | refs/heads/master | 2020-03-27T22:55:51.934313 | 2010-09-23T21:15:11 | 2010-09-23T21:15:11 | 32,334,738 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 4,575 | h | #ifndef _GLWIDGET_H_
#define _GLWIDGET_H_
#include <QtOpenGL/qgl.h>
#include <QKeyEvent>
#include <iostream>
#include <qstring.h>
#include <qfiledialog.h>
#include <qtimer.h>
#include <QtDesigner/QDesignerExportWidget>
#include "material_lib.h"
#include "point.h"
#include "scene.h"
#include "llum.h"
#include "finestraLlums.h"
#include <list>
#define ROTATION_FACTOR 0.2
#define ZOOM_FACTOR 0.1
#define PAN_FACTOR 0.03
#define DEFAULT_FOVY 60.0
#define FPV_FOVY 90.0
class QDESIGNER_WIDGET_EXPORT GLWidget : public QGLWidget
{
Q_OBJECT
public:
GLWidget(QWidget * parent);
signals:
void carOpened(bool);
void dialValueChanged(int);
void activateAnimation(QString);
void activateFirstPersonView(bool);
public slots:
// help - Ajuda per la terminal des de la que hem engegat el programa.
void help(void);
// Afegiu aquí la declaració dels slots que necessiteu
// Reestablir la camera per defecte
void setDefaultCamera();
// Obrir un dialeg per seleccionar un model pel vehicle i carregar-lo
void openCar();
// Establir una novia orientación pel vehicle
void orientCar(int alpha);
void timerDone();
void setCarSpeed(int speed);
void configureLight(llum* light);
void showLightsWindow();
void activeSmooth(bool active);
void activeLocalViewer(bool active);
void activeCullFace(bool active);
void activeFirstPersonView(bool active);
void setFPVzFar(int value);
void activeCarLampposts(bool active);
protected:
// initializeGL() - Aqui incluim les inicialitzacions del contexte grafic.
virtual void initializeGL();
// paintGL - Mètode cridat cada cop que cal refrescar la finestra.
// Tot el que es dibuixa es dibuixa aqui.
virtual void paintGL( void );
// resizeGL() - Es cridat quan canvi la mida del widget
virtual void resizeGL (int width, int height);
// keyPressEvent() - Cridat quan es prem una tecla
virtual void keyPressEvent(QKeyEvent *e);
// mousePressEvent() i mouseReleaseEvent()
virtual void mousePressEvent( QMouseEvent *e);
virtual void mouseReleaseEvent( QMouseEvent *);
// mouseMoveEvent() - Cridat quan s'arrosega el ratoli amb algun botó premut.
virtual void mouseMoveEvent(QMouseEvent *e);
// Calcular el parametres de la camera per defecte
void computeDefaultCamera();
// Configurar la matriu modelview segons els parametres de la camera
void setModelview();
// Configurar la matriu de projecció segons els parametres de la camera
void setProjection();
// Recalcular els plans de retallat de l'escena
void computeCuttingPlanes();
void saveCurrentCamera();
void restoreOldCamera();
// Configuracio dels llums
void initializeLights();
void configure(llum* light);
void updateLightsPosition();
void onOffLamppost(int xClick, int yClick); // Realitza el proces de seleccio i tractament del fanal seleccionat per l'usuari
int getSelectedLamppost(int xClick, int yClick); // Retorna el fanal seleccionat per l'usuari mes proper al obs
void onOffCarLampposts(); // Realitza el proces de seleccio i tractament dels fanals visibles pel vehicle
list<int> getVisibleLampposts(); // Retorna com a maxim 4 fanals, els mes propers i visibles pel vehicle
void updateModelView();
private:
// interaccio
typedef enum {NONE, ROTATE, ZOOM, PAN} InteractiveAction;
InteractiveAction DoingInteractive;
int xClick, yClick;
Scene scene; // Escena a representar en el widget
// Afegiu els atributs que necessiteu
QTimer* timer;
llum* L[8];
finestraLlums lightsWindow;
double fovy;
double aspect;
double initialZNear;
double initialZNearLast;
double zNear;
double zNearLast;
double zNearAux;
double zNearAuxLast;
double initialZFar;
double initialZFarLast;
double zFar;
double zFarLast;
double zFarAux;
double zFarAuxLast;
double maxFPVzFar;
double zFarFPV;
Point VRP;
Point VRPLast;
Point OBS;
Point OBSLast;
Vector UP;
Vector UPLast;
double distOBS;
double distOBSLast;
bool carLoaded;
bool firstPersonView;
int NLampposts;
list<int> onLampposts; // Llista amb els fanals encesos per l'usuario en el moment actual
list<int> onCarLampposts; // Llista amb els fanals encesos davant del vehicle (no inclou els encesos manualment)
bool carLampposts; // Indica si cal o no activar els fanals automatics davant del vehicle
};
#endif
| [
"mvm9289@58588aa8-722a-b9c2-831f-873cbd2be5b1"
] | mvm9289@58588aa8-722a-b9c2-831f-873cbd2be5b1 |
cb69e41ca057ec13219d2c9cad2dc6e1c21043b3 | 20f6693bed8e559b32b5b649f7393908964932de | /SDK/BP_Menu_Slasher18_parameters.h | 27af0f6c7ae2a864c1bb96b385d89e1d852c8cf2 | [] | no_license | xnf4o/DBD_SDK_502 | 9e0e210490e2f7b9bc9b021f48972e252d66f0c7 | c7da68275286e53b9a24d6b8afbb6e932fc93407 | refs/heads/main | 2023-05-31T18:55:45.805581 | 2021-07-01T14:23:54 | 2021-07-01T14:23:54 | 382,058,835 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,631 | h | #pragma once
// Name: dbd, Version: 502
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.SM_SetOniEmissiveParameter
struct UBP_Menu_Slasher18_C_SM_SetOniEmissiveParameter_Params
{
struct FLinearColor Emissive; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.SK_SetOniEmissiveParameter
struct UBP_Menu_Slasher18_C_SK_SetOniEmissiveParameter_Params
{
struct FLinearColor Emissive; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.ShowDemonModeCusto
struct UBP_Menu_Slasher18_C_ShowDemonModeCusto_Params
{
bool isInDemonMode; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
bool IsInNormalMode; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.SaveOniEmissiveParameter
struct UBP_Menu_Slasher18_C_SaveOniEmissiveParameter_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.GetDemonModeCusto
struct UBP_Menu_Slasher18_C_GetDemonModeCusto_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.TML_KatanaDissolve__FinishedFunc
struct UBP_Menu_Slasher18_C_TML_KatanaDissolve__FinishedFunc_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.TML_KatanaDissolve__UpdateFunc
struct UBP_Menu_Slasher18_C_TML_KatanaDissolve__UpdateFunc_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.TML_DemonModeCusto__FinishedFunc
struct UBP_Menu_Slasher18_C_TML_DemonModeCusto__FinishedFunc_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.TML_DemonModeCusto__UpdateFunc
struct UBP_Menu_Slasher18_C_TML_DemonModeCusto__UpdateFunc_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.TML_DemonModeCusto__Switch Normal__EventFunc
struct UBP_Menu_Slasher18_C_TML_DemonModeCusto__Switch_Normal__EventFunc_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.TML_DemonModeCusto__Switch Demon__EventFunc
struct UBP_Menu_Slasher18_C_TML_DemonModeCusto__Switch_Demon__EventFunc_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.ActivateEndGameVignette
struct UBP_Menu_Slasher18_C_ActivateEndGameVignette_Params
{
bool isActive; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.ActivatePlayerExposedVFX
struct UBP_Menu_Slasher18_C_ActivatePlayerExposedVFX_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.ActivateLocalPlayerExposedVFX
struct UBP_Menu_Slasher18_C_ActivateLocalPlayerExposedVFX_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.SetPlayerExposedVFX
struct UBP_Menu_Slasher18_C_SetPlayerExposedVFX_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.SetHighlightedVFX
struct UBP_Menu_Slasher18_C_SetHighlightedVFX_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.ActivatePlayerLightningVFX
struct UBP_Menu_Slasher18_C_ActivatePlayerLightningVFX_Params
{
class UMaterialInstanceDynamic* LightningFX; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
bool Intense; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.ActivatePlayerGlitchVFX
struct UBP_Menu_Slasher18_C_ActivatePlayerGlitchVFX_Params
{
class UMaterialInstanceDynamic* GlitchFX; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
bool Face; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
bool Madness; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
bool Killer; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.Start Travelling PP
struct UBP_Menu_Slasher18_C_Start_Travelling_PP_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.Start Travelling Dissolve
struct UBP_Menu_Slasher18_C_Start_Travelling_Dissolve_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.Stop Travelling Dissolve
struct UBP_Menu_Slasher18_C_Stop_Travelling_Dissolve_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.Start Pounce VFX
struct UBP_Menu_Slasher18_C_Start_Pounce_VFX_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.Stop Pounce VFX
struct UBP_Menu_Slasher18_C_Stop_Pounce_VFX_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.Start Saliva VFX
struct UBP_Menu_Slasher18_C_Start_Saliva_VFX_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.Stop Saliva VFX
struct UBP_Menu_Slasher18_C_Stop_Saliva_VFX_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.Stop Travelling PP
struct UBP_Menu_Slasher18_C_Stop_Travelling_PP_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.ActivatePounceStateVFX
struct UBP_Menu_Slasher18_C_ActivatePounceStateVFX_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.Destroy Blood Orb
struct UBP_Menu_Slasher18_C_Destroy_Blood_Orb_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.Switch Oni Weapons To Normal
struct UBP_Menu_Slasher18_C_Switch_Oni_Weapons_To_Normal_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.DisableDemonMode
struct UBP_Menu_Slasher18_C_DisableDemonMode_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.ReturnToDemonMode
struct UBP_Menu_Slasher18_C_ReturnToDemonMode_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.Hide Oni Katana_TPV
struct UBP_Menu_Slasher18_C_Hide_Oni_Katana_TPV_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.ShowGunBullet
struct UBP_Menu_Slasher18_C_ShowGunBullet_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.HideGunBullet
struct UBP_Menu_Slasher18_C_HideGunBullet_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.SpawnFakeBullet
struct UBP_Menu_Slasher18_C_SpawnFakeBullet_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.ActivateSacrificeCamBlood
struct UBP_Menu_Slasher18_C_ActivateSacrificeCamBlood_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.StartDeathBedDissolve
struct UBP_Menu_Slasher18_C_StartDeathBedDissolve_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.DeactivateKnockoutVFX
struct UBP_Menu_Slasher18_C_DeactivateKnockoutVFX_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.ActivateKnockoutVFX
struct UBP_Menu_Slasher18_C_ActivateKnockoutVFX_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.SpawnFullScreenBlood
struct UBP_Menu_Slasher18_C_SpawnFullScreenBlood_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.StartDeathBedRelocateVignette
struct UBP_Menu_Slasher18_C_StartDeathBedRelocateVignette_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.ActivateAttemptEscapeVFX
struct UBP_Menu_Slasher18_C_ActivateAttemptEscapeVFX_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.ShowSyringe
struct UBP_Menu_Slasher18_C_ShowSyringe_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.HideSyringe
struct UBP_Menu_Slasher18_C_HideSyringe_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.AnimateLiquidSyringe
struct UBP_Menu_Slasher18_C_AnimateLiquidSyringe_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.ActivateVignetteOnWallCollision
struct UBP_Menu_Slasher18_C_ActivateVignetteOnWallCollision_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.HideSyringeOnStun
struct UBP_Menu_Slasher18_C_HideSyringeOnStun_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K22_SpawnWipeVFX
struct UBP_Menu_Slasher18_C_K22_SpawnWipeVFX_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K22_HighlightDormantMain
struct UBP_Menu_Slasher18_C_K22_HighlightDormantMain_Params
{
bool IsDormantMain_; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K22_HighlightDormant
struct UBP_Menu_Slasher18_C_K22_HighlightDormant_Params
{
bool IsDormant_; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K22_HighlightMissJump
struct UBP_Menu_Slasher18_C_K22_HighlightMissJump_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K22_DormantAttachedSlasher
struct UBP_Menu_Slasher18_C_K22_DormantAttachedSlasher_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K22_JumpTrail_Activate
struct UBP_Menu_Slasher18_C_K22_JumpTrail_Activate_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K22_JumpTrail_Deactivate
struct UBP_Menu_Slasher18_C_K22_JumpTrail_Deactivate_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K22_ReleaseBrother
struct UBP_Menu_Slasher18_C_K22_ReleaseBrother_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K22_MembraneRecovery
struct UBP_Menu_Slasher18_C_K22_MembraneRecovery_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K22_MembraneDelete
struct UBP_Menu_Slasher18_C_K22_MembraneDelete_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K22_BabyBloodDissolve
struct UBP_Menu_Slasher18_C_K22_BabyBloodDissolve_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K22_BabyRespawn
struct UBP_Menu_Slasher18_C_K22_BabyRespawn_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K22_Jump_Active
struct UBP_Menu_Slasher18_C_K22_Jump_Active_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K22_Jump_Inactive
struct UBP_Menu_Slasher18_C_K22_Jump_Inactive_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.On Execution
struct UBP_Menu_Slasher18_C_On_Execution_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K05_SetTrap
struct UBP_Menu_Slasher18_C_K05_SetTrap_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K05_TrapImpact
struct UBP_Menu_Slasher18_C_K05_TrapImpact_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K05_TrapImpactOff
struct UBP_Menu_Slasher18_C_K05_TrapImpactOff_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K05_BloodDrops
struct UBP_Menu_Slasher18_C_K05_BloodDrops_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K07_TreatmentStart
struct UBP_Menu_Slasher18_C_K07_TreatmentStart_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K04_InvisibleOn
struct UBP_Menu_Slasher18_C_K04_InvisibleOn_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K04_InvisibleOff
struct UBP_Menu_Slasher18_C_K04_InvisibleOff_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K04_TelekinesisOn
struct UBP_Menu_Slasher18_C_K04_TelekinesisOn_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K04_TelekinesisOff
struct UBP_Menu_Slasher18_C_K04_TelekinesisOff_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K22_WrongLanding
struct UBP_Menu_Slasher18_C_K22_WrongLanding_Params
{
bool Wrong_Landing; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K22_AttachedToSurvivor_VFX
struct UBP_Menu_Slasher18_C_K22_AttachedToSurvivor_VFX_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K22_DetachedFromSurvivor_VFX
struct UBP_Menu_Slasher18_C_K22_DetachedFromSurvivor_VFX_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K22_WrongLandingVignette
struct UBP_Menu_Slasher18_C_K22_WrongLandingVignette_Params
{
bool WrongLanding; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K12_GetToxinVignette
struct UBP_Menu_Slasher18_C_K12_GetToxinVignette_Params
{
TheClown_EBombType Bomb_Type; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K12_GetAntidoteVignette
struct UBP_Menu_Slasher18_C_K12_GetAntidoteVignette_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K12_Killer_AntidoteEnd
struct UBP_Menu_Slasher18_C_K12_Killer_AntidoteEnd_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K12_Killer_AntidoteBegin
struct UBP_Menu_Slasher18_C_K12_Killer_AntidoteBegin_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K12_Killer_BombSmokeColor
struct UBP_Menu_Slasher18_C_K12_Killer_BombSmokeColor_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K12_Killer_RemoveVignette
struct UBP_Menu_Slasher18_C_K12_Killer_RemoveVignette_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K12_Killer_PlaceVignette
struct UBP_Menu_Slasher18_C_K12_Killer_PlaceVignette_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K22_QuickDissolveBrother
struct UBP_Menu_Slasher18_C_K22_QuickDissolveBrother_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.Killer_LungeAttack_Start
struct UBP_Menu_Slasher18_C_Killer_LungeAttack_Start_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.Killer_LungeAttack_End
struct UBP_Menu_Slasher18_C_Killer_LungeAttack_End_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.Camper_AntidoteBoostVignette_Start
struct UBP_Menu_Slasher18_C_Camper_AntidoteBoostVignette_Start_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.Camper_AntidoteBoostVignette_End
struct UBP_Menu_Slasher18_C_Camper_AntidoteBoostVignette_End_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K22_BrotherDissolveLocker
struct UBP_Menu_Slasher18_C_K22_BrotherDissolveLocker_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K22_HighlightMissJump_Stop
struct UBP_Menu_Slasher18_C_K22_HighlightMissJump_Stop_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K23_CamperHitByKnife
struct UBP_Menu_Slasher18_C_K23_CamperHitByKnife_Params
{
bool isLocallyObserved; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
float LacerationPercent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
bool IsDangerous; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K22_IsAttachedLocker
struct UBP_Menu_Slasher18_C_K22_IsAttachedLocker_Params
{
bool IsAttachedLocker; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K23_ShowKnifeLT
struct UBP_Menu_Slasher18_C_K23_ShowKnifeLT_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K23_ShowKnifeRT
struct UBP_Menu_Slasher18_C_K23_ShowKnifeRT_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K23_ShowBat
struct UBP_Menu_Slasher18_C_K23_ShowBat_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K23_HideBat
struct UBP_Menu_Slasher18_C_K23_HideBat_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K23_HideKnifeRT
struct UBP_Menu_Slasher18_C_K23_HideKnifeRT_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.K23_HideKnifeLT
struct UBP_Menu_Slasher18_C_K23_HideKnifeLT_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.AddBloodDrippingGKMoriMale
struct UBP_Menu_Slasher18_C_AddBloodDrippingGKMoriMale_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.ReceiveBeginPlay
struct UBP_Menu_Slasher18_C_ReceiveBeginPlay_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.Switch Kanobo To Demon Mode
struct UBP_Menu_Slasher18_C_Switch_Kanobo_To_Demon_Mode_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.Switch Kanobo to Normal Mode
struct UBP_Menu_Slasher18_C_Switch_Kanobo_to_Normal_Mode_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.Show Oni Katana
struct UBP_Menu_Slasher18_C_Show_Oni_Katana_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.Hide Oni Katana
struct UBP_Menu_Slasher18_C_Hide_Oni_Katana_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.On Customisation Updated
struct UBP_Menu_Slasher18_C_On_Customisation_Updated_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.ShowDemonCosmetic
struct UBP_Menu_Slasher18_C_ShowDemonCosmetic_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.HideDemonCosmetic
struct UBP_Menu_Slasher18_C_HideDemonCosmetic_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.ReturnOniToNormal
struct UBP_Menu_Slasher18_C_ReturnOniToNormal_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.StopTransformation
struct UBP_Menu_Slasher18_C_StopTransformation_Params
{
};
// Function BP_Menu_Slasher18.BP_Menu_Slasher18_C.ExecuteUbergraph_BP_Menu_Slasher18
struct UBP_Menu_Slasher18_C_ExecuteUbergraph_BP_Menu_Slasher18_Params
{
int EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"xnf4o@inbox.ru"
] | xnf4o@inbox.ru |
a9ecb796210c74dcf6a6fdd93f1621cc450a1ea0 | a2df82973ae062cfd10af1a15e804ba64f4e027f | /src/turbohttp/turbohttp.hpp | 42b554107e1f0b1cbac4db71876a8d2fc9035067 | [
"Apache-2.0"
] | permissive | jbaldwin/libturbohttp | fd4c1407463645e2aa26cf094c44b28634a02182 | 69c43b2c84a4b318973529ce448c01c741e5a39c | refs/heads/master | 2023-04-10T18:04:08.317030 | 2021-04-25T23:23:20 | 2021-04-25T23:23:20 | 159,764,204 | 0 | 0 | NOASSERTION | 2021-04-25T23:23:21 | 2018-11-30T03:36:46 | C++ | UTF-8 | C++ | false | false | 111 | hpp | #pragma once
#include "turbohttp/method.hpp"
#include "turbohttp/version.hpp"
#include "turbohttp/parser.hpp"
| [
"noreply@github.com"
] | jbaldwin.noreply@github.com |
b740013d805953bed822189233fffc6f1188be91 | c9b5bea7a472d6f9e11192775135fa3680297e5f | /Lista1_Dominik_Grafik/zadanie11.cpp | f829721e27dcf49118e0acde590fd56e6f66400c | [] | no_license | dgrafik/algorytmy-i-struktury-danych | cdd684fc32a03fd7e73f7364c3511ad954cbcb98 | bea58270ab68b71870dd07cab438847d5af98601 | refs/heads/master | 2020-04-09T17:45:02.112075 | 2018-03-28T12:08:22 | 2018-03-28T12:08:22 | 124,238,047 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 475 | cpp | #include <iostream>
#define n 100
bool numbersTable[n + 1];
int main()
{
for(int i = 0; i<n+1; i++){
numbersTable[i] = true;
}
for (int i = 2; i*i <= n; ++i )
{
if (numbersTable[i] == false)
continue;
for (int j = 2*i ; j <= n; j += i)
numbersTable[j] = false;
}
for (int i = 2; i <= n; i++)
if (numbersTable[i] == true)
std::cout << i << std::endl;
return 0;
}
| [
"dominik.grafik@gmail.com"
] | dominik.grafik@gmail.com |
8f1959c012375533d5952468279dc384421887c3 | 024c74f395b4a749b26cf2719b1e4efecd5331fc | /Codeforces/136B.cpp | 13da4631052ad66f8c5f5a9f26fdfe5ffb5a70a4 | [] | no_license | thisisrajat/competitive-programming | 28ed70f77e2c3892ee1d005341ef7d37930caad9 | 422cc7fac78a9908ca7a95a7c6eae724ed4a0631 | refs/heads/master | 2021-01-01T18:12:10.693796 | 2017-01-01T17:42:53 | 2017-01-01T17:42:53 | 17,668,936 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,214 | cpp | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <sstream>
#include <utility>
#include <functional>
#include <numeric>
#include <stack>
#include <queue>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cassert>
#include <bitset>
#include <list>
#include <memory.h>
using namespace std;
string ternary(int n) {
string t = "";
while(n) {
char ch = (n % 3 + '0');
t = ch + t;
n /= 3;
}
return t;
}
long long calc(const string &u, const string &v) {
vector< int > s;
for(int i = 0; i < (int) u.size(); i++) {
int x = u[i] - '0';
int y = v[i] - '0';
int tmp = (y - x + 3) % 3;
s.push_back(tmp);
}
int num = 0;
long long power = 3;
if(s.empty()) {
printf("0\n");
exit(0);
}
num = s[s.size() - 1];
for(int i = s.size() - 2; i >= 0; i--) {
num += power * (s[i]);
power *= 3;
}
return num;
}
int main() {
int a, b;
cin >> a >> b;
string u = ternary(a);
string v = ternary(b);
while(u.size() < v.size()) {
u = '0' + u;
}
while(v.size() < u.size()) {
v = '0' + v;
}
cout << calc(u, v) << '\n';
} | [
"rajat.rj10@gmail.com"
] | rajat.rj10@gmail.com |
1f113459d4a88bcc210c39586c4fb7723ed71794 | 8177a59eb31f17bad3bd88f2371e70c175971a14 | /rt/materials/dummy.cpp | 6d82b508c135a3197689bf24d53658e0966d2373 | [] | no_license | joniali/Cg-Saar-RayTracer | 6be9452b37fdb50f2769e4d5b2bfb23661a0909c | 03b554188dd8bcda593a68431ff04b6843953878 | refs/heads/master | 2020-05-18T12:13:42.865606 | 2014-12-13T15:48:09 | 2014-12-13T15:48:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 632 | cpp | #include <rt\materials\dummy.h>
namespace rt
{
DummyMaterial::DummyMaterial()
{}
RGBColor DummyMaterial::getReflectance(const Point& texPoint, const Vector& normal, const Vector& outDir, const Vector& inDir) const
{
return RGBColor::rep(1.0f);
}
RGBColor DummyMaterial::getEmission(const Point& texPoint, const Vector& normal, const Vector& outDir) const
{
return RGBColor::rep(0.0f);
}
Material::SampleReflectance DummyMaterial::getSampleReflectance(const Point& texPoint, const Vector& normal, const Vector& outDir) const
{
SampleReflectance *ret= new SampleReflectance();
return *ret;
}
} | [
"joniali786@gmail.com"
] | joniali786@gmail.com |
db3b67498cb2bda306047db8859497c84ce5a1d6 | b18adf09556fa66a9db188684c69ea48849bb01b | /Elsov/SkyFrame/PointToPoint/PointToPointDoc.h | d2546e8332e574bedbb00ad77e02ea097be7f8d1 | [] | no_license | zzfd97/projects | d78e3fa6418db1a5a2580edcaef1f2e197d5bf8c | f8e7ceae143317d9e8461f3de8cfccdd7627c3ee | refs/heads/master | 2022-01-12T19:56:48.014510 | 2019-04-05T05:30:31 | 2019-04-05T05:30:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,541 | h | // PointToPointDoc.h : interface of the CPointToPointDoc class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_POINTTOPOINTDOC_H__0DA57542_93B7_474F_87A1_D13B863BFF31__INCLUDED_)
#define AFX_POINTTOPOINTDOC_H__0DA57542_93B7_474F_87A1_D13B863BFF31__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CPointToPointDoc : public CDocument
{
protected: // create from serialization only
CPointToPointDoc();
DECLARE_DYNCREATE(CPointToPointDoc)
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CPointToPointDoc)
public:
virtual BOOL OnNewDocument();
virtual void Serialize(CArchive& ar);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CPointToPointDoc();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
//{{AFX_MSG(CPointToPointDoc)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_POINTTOPOINTDOC_H__0DA57542_93B7_474F_87A1_D13B863BFF31__INCLUDED_)
| [
"hp@kozhevnikov.org"
] | hp@kozhevnikov.org |
1dbe3cfad6ead5367ca825752fb9245d98344f6c | 42141a2b991a8d7242817143860fc59080b1e5c6 | /src/network/receiver.h | 9d1c6569e1a059036d63f6b926b9d52fcd923399 | [] | no_license | earlgreyz/SIK-siktacka | 378fd4f2614b8a684ab4595b0c7d127d94ea2ac4 | bb6cea66d3d1ec6b292c0dc02f1030b7a9e8a02d | refs/heads/master | 2018-12-19T19:42:16.650014 | 2017-06-20T17:28:50 | 2017-06-20T17:28:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 726 | h | #ifndef SIK_RECEIVER_H
#define SIK_RECEIVER_H
#include <string>
#include <netinet/in.h>
#include "types.h"
namespace network {
/**
* Class for receiving messages from socket.
*/
class Receiver {
private:
/// Socket to receive data from
int sock;
public:
/**
* Creates new receiver.
* @param sock socket to send data to.
*/
Receiver(int sock) noexcept;
/**
* Receives message from socket.
* @param address sender address.
* @return received message
* @throws runtime_error if recvfrom finishes with error
*/
buffer_t receive_message(sockaddr_storage *address);
};
}
#endif | [
"mikiwalczak@gmail.com"
] | mikiwalczak@gmail.com |
242a43f323285e1a26a3ed54428bbb4e81350ffd | e52637b524363de6c44ab83913f3e1bfec1a70e4 | /BGM_FileManager.cpp | 9b30a06e77257ca905e8ac53720cdfaf91b031c8 | [] | no_license | drdrpyan/MyDBexample | e8943a67b923dfa92273b5d55f3323c5323e0650 | 6c61b97545621275cbdde24efd0fa36f0ccca7c2 | refs/heads/master | 2016-09-01T18:40:08.752668 | 2015-09-16T16:46:59 | 2015-09-16T16:46:59 | 21,458,280 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,102 | cpp | #include "BGM_FileManager.h"
namespace BGM
{
FileManager::FileManager(const char* fileName)
{
if(!(file=fopen(fileName, "rb+")))
{
file = fopen(fileName, "wb+");
numberOfBlock = 0;
currentBlock = 0;
nextBlock = 1;
lastBlock = 0;
}
else
{
fread_s(buffer, BLOCKSIZE, BLOCKSIZE, 1, file);
numberOfBlock = *((unsigned*)(buffer + NUMBEROFBLOCK_OFFSET));
currentBlock = *((unsigned*)(buffer + CURRENTBLOCK_OFFSET));
nextBlock = *((unsigned*)(buffer+NEXTBLOCK_OFFSET));
lastBlock = *((unsigned*)(buffer+LASTBLOCK_OFFSET));
loadBlock(currentBlock);
}
}
FileManager::~FileManager(void)
{
storeBlock(currentBlock);
fseek(file, 0, SEEK_SET);
fwrite(&numberOfBlock, 4, 1, file);
fwrite(¤tBlock, 4, 1, file);
fwrite(&nextBlock, 4, 1, file);
fwrite(&lastBlock, 4, 1, file);
fclose(file);
}
blockId_t FileManager::newBlock(void)
{
int result = nextBlock;
numberOfBlock++;
if(numberOfBlock > lastBlock)
{
lastBlock++;
nextBlock = lastBlock+1;
}
else
{
fseek(file, nextBlock*BLOCKSIZE, SEEK_SET);
fread_s(buffer, BLOCKSIZE, BLOCKSIZE, 1, file);
nextBlock = *((blockId_t*)buffer);
}
return result;
}
void FileManager::loadBlock(blockId_t id)
{
fseek(file, id*BLOCKSIZE, SEEK_SET);
fread_s(buffer, BLOCKSIZE, BLOCKSIZE, 1, file);
currentBlock = id;
}
void FileManager::loadBlock(blockId_t id, void *externalBuffer)
{
fseek(file, id*BLOCKSIZE, SEEK_SET);
fread_s(externalBuffer, BLOCKSIZE, BLOCKSIZE, 1, file);
}
void FileManager::storeBlock(void)
{
fseek(file, currentBlock*BLOCKSIZE, SEEK_SET);
fwrite(buffer, BLOCKSIZE, 1, file);
}
void FileManager::storeBlock(blockId_t id)
{
fseek(file, id*BLOCKSIZE, SEEK_SET);
fwrite(buffer, BLOCKSIZE, 1, file);
}
void FileManager::storeBlock(blockId_t id, void *externalBuffer)
{
fseek(file, id*BLOCKSIZE, SEEK_SET);
fwrite(externalBuffer, BLOCKSIZE, 1, file);
}
void FileManager::deleteBlock(blockId_t id)
{
fseek(file, id*BLOCKSIZE, SEEK_SET);
fwrite(&nextBlock, 4, 1, file);
nextBlock = id;
numberOfBlock--;
}
} | [
"drdrpyan@gmail.com"
] | drdrpyan@gmail.com |
7adfc7fbe35e1de9af09ea222f43271afca7d308 | 5fca9ab6310f854b655d318b50efa7fc83ad22f8 | /thirdparty/rsocket-cpp/rsocket/framing/FrameHeader.h | 8ce55ee3175a380158fcf64bd1a58887015be862 | [
"Apache-2.0"
] | permissive | algo-data-platform/PredictorService | 4a73dbdac2bd1d72c18f53073fe80afbb4160bba | a7da427617885546c5b5e07aa7740b3dee690337 | refs/heads/main | 2023-03-11T17:08:35.351356 | 2021-02-24T08:46:08 | 2021-02-24T08:46:08 | 321,256,115 | 3 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,373 | h | // Copyright (c) Facebook, Inc. and its affiliates.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <iosfwd>
#include "rsocket/framing/FrameFlags.h"
#include "rsocket/framing/FrameType.h"
#include "rsocket/internal/Common.h"
namespace rsocket {
class FrameHeader {
public:
FrameHeader() {}
FrameHeader(FrameType ty, FrameFlags fflags, StreamId stream)
: type{ty}, flags{fflags}, streamId{stream} {}
bool flagsComplete() const {
return !!(flags & FrameFlags::COMPLETE);
}
bool flagsNext() const {
return !!(flags & FrameFlags::NEXT);
}
bool flagsFollows() const {
return !!(flags & FrameFlags::FOLLOWS);
}
FrameType type{FrameType::RESERVED};
FrameFlags flags{FrameFlags::EMPTY};
StreamId streamId{0};
};
std::ostream& operator<<(std::ostream&, const FrameHeader&);
} // namespace rsocket
| [
"maolei@staff.weibo.com"
] | maolei@staff.weibo.com |
4b355f76242ad6e7a0b6be4b70c9d373891109d9 | 5640dbc72263da3bbad87ab86d836af40360c7b2 | /quadrant.cpp | d36cde511895aad3b81c661f541644f0cafa6143 | [] | no_license | nayana266/Kattis-Solutions- | 5f265e30f4f0b98c227f308bf6aa850ac2be6d79 | b2271b5e769ebddce9e776c6807cc35a9b1c656e | refs/heads/main | 2023-02-17T04:23:53.722985 | 2021-01-14T18:37:44 | 2021-01-14T18:37:44 | 329,699,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 301 | cpp | #include <iostream>
using namespace std;
int main(){
int x, y;
cin >> x >> y;
if(x > 0 && y > 0){
cout << 1 << endl;
} else if(x < 0 && y > 0){
cout<< 2 << endl;
} else if(x < 0 && y < 0){
cout << 3 << endl;
} else{
cout << 4 << endl;
}
}
| [
"noreply@github.com"
] | nayana266.noreply@github.com |
8d1c59b5726d85287c1bea63afa4bf31fdc85e61 | ccb96be721d66d34892bf3405bb859ff09006889 | /options.h | 0a59c9cea39a05a3d63c508904250302a175124c | [] | no_license | cristian1997/tanks | 4a0a2a313a8da53b0ba7fd59f96f7c4374be08b7 | 68c39e4de69c8b5ed2f52748f3983c412b15c074 | refs/heads/master | 2020-06-10T02:48:13.057153 | 2017-01-13T21:21:39 | 2017-01-13T21:21:39 | 76,125,320 | 0 | 1 | null | 2017-01-12T13:03:00 | 2016-12-10T16:50:22 | C++ | UTF-8 | C++ | false | false | 223 | h | #include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include "texture.h"
#include "gamedata.h"
class Options
{
private:
Texture option;
public:
bool loadFilesForOptions();
void run();
void render();
}; | [
"noreply@github.com"
] | cristian1997.noreply@github.com |
c4fa288eb4e27abf776d8422ce10a41aee4ed256 | 7e3da1697f3aad20c7d63095d572c43a58797393 | /09_10_20.CPP | 8147d946bac47ae35a1c0f6183e05c061f19a143 | [] | no_license | krishankant10/C-language | 5d50eb4df5bfbe3017cbb1dad1f1d6f7280a0ce2 | e03e590d7c75e86ceade7a06f52c064db70abe54 | refs/heads/master | 2020-04-28T03:23:47.174914 | 2019-11-24T14:44:10 | 2019-11-24T14:44:10 | 174,935,501 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,643 | cpp | #include <iostream.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
#define succ(node) node->next
struct list
{
int data;
list *next;
};
list *insertnode(int data,list *first)
{
list *newnode;
newnode = new list;
if(newnode==NULL)
{
cout<<"Error: Out-of-memory"<<endl;
exit(1);
}
newnode->data=data;
succ(newnode)=first;
return newnode;
}
list *deletenode(int data,list *first)
{
list *current,*pred;
if(!first)
{
cout<<"Empty list"<<endl;
return first;
}
for(pred=current=first;current;pred=current,current=succ(current))
if(current->data==data)
{
if(current==first)
first=succ(current);
else
succ(pred)=succ(current);
delete current;
return first;
}
return first;
}
void displaylist(list *first)
{
list *LIST;
for(LIST=first;LIST;LIST=succ(LIST))
cout<<"->"<<LIST->data;
cout<<endl;
}
void main()
{
clrscr();
list *LIST=NULL;
int choice,data;
cout<<"Linked-list Manipulation program..\n";
while(1)
{
cout<<"List operation,1-insert,2-Dispaly,3-delete,4-Quit:";
cin>>choice;
switch(choice)
{
case 1:
cout<<"ENter data for node to be created :";
cin>>data;
LIST=insertnode(data,LIST);
break;
case 2:
cout<<"List Contents:";
displaylist(LIST);
break;
case 3:
cout<<"Enter Data for node to be deleted:";
cin>>data;
LIST=deletenode(data,LIST);
break;
case 4:
cout<<"End of Linked List Computation !! .\n";
return;
getch();
default:
cout<<"Bad option Selected\n";
break;
}
}
getch();
}
| [
"noreply@github.com"
] | krishankant10.noreply@github.com |
d03523f92ba8b6a80f258b7e7d755a64d4151af7 | befaf0dfc5880d18f42e1fa7e39e27f8d2f8dde9 | /SDK/SCUM_Horse_Torso_classes.hpp | 0b64d28097395510148f1fa54cafcfbe8a45b81f | [] | no_license | cpkt9762/SCUM-SDK | 0b59c99748a9e131eb37e5e3d3b95ebc893d7024 | c0dbd67e10a288086120cde4f44d60eb12e12273 | refs/heads/master | 2020-03-28T00:04:48.016948 | 2018-09-04T13:32:38 | 2018-09-04T13:32:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 654 | hpp | #pragma once
// SCUM (0.1.17.8320) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SCUM_Horse_Torso_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass Horse_Torso.Horse_Torso_C
// 0x0000 (0x07A0 - 0x07A0)
class AHorse_Torso_C : public AEquipmentItem
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("BlueprintGeneratedClass Horse_Torso.Horse_Torso_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"igromanru@yahoo.de"
] | igromanru@yahoo.de |
544b40b3b63807b1de8f89c11fbe3b46b54af9fc | 58463dc047759d86ed96fb85311e3e167d521a9c | /include/clc/math/gentype.inc | 9f79f6eb037ff466b4038b82bcb58bdbeefb2cc1 | [] | no_license | xianggong/m2c-devtools | 2195e21935b510493282c94d8be37bb8b7fd2c45 | 397cb765f21a4877c17f32f19aed912a3d2f5739 | refs/heads/master | 2021-01-19T07:56:29.388922 | 2015-07-16T14:41:49 | 2015-07-16T14:41:49 | 35,905,794 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,203 | inc | #define __CLC_SCALAR_GENTYPE float
#define __CLC_FPSIZE 32
#define __CLC_GENTYPE float
#define __CLC_SCALAR
#include __CLC_BODY
#undef __CLC_GENTYPE
#undef __CLC_SCALAR
#define __CLC_GENTYPE float2
#include __CLC_BODY
#undef __CLC_GENTYPE
#define __CLC_GENTYPE float3
#include __CLC_BODY
#undef __CLC_GENTYPE
#define __CLC_GENTYPE float4
#include __CLC_BODY
#undef __CLC_GENTYPE
#define __CLC_GENTYPE float8
#include __CLC_BODY
#undef __CLC_GENTYPE
#define __CLC_GENTYPE float16
#include __CLC_BODY
#undef __CLC_GENTYPE
#undef __CLC_FPSIZE
#undef __CLC_SCALAR_GENTYPE
#ifdef cl_khr_fp64
#define __CLC_SCALAR_GENTYPE double
#define __CLC_FPSIZE 64
#define __CLC_SCALAR
#define __CLC_GENTYPE double
#include __CLC_BODY
#undef __CLC_GENTYPE
#undef __CLC_SCALAR
#define __CLC_GENTYPE double2
#include __CLC_BODY
#undef __CLC_GENTYPE
#define __CLC_GENTYPE double3
#include __CLC_BODY
#undef __CLC_GENTYPE
#define __CLC_GENTYPE double4
#include __CLC_BODY
#undef __CLC_GENTYPE
#define __CLC_GENTYPE double8
#include __CLC_BODY
#undef __CLC_GENTYPE
#define __CLC_GENTYPE double16
#include __CLC_BODY
#undef __CLC_GENTYPE
#undef __CLC_FPSIZE
#undef __CLC_SCALAR_GENTYPE
#endif
#undef __CLC_BODY
| [
"xgong@ece.neu.edu"
] | xgong@ece.neu.edu |
efd660e9c8933de6a4836896a5b87ea9c279afd8 | 58af6924180b6a739577634d2db3e9a867a84a8b | /cpp.boost/iostream/http_source/main.cpp | 4a60c0aebcd6542bf7229b7580baacffe92feba1 | [] | no_license | MagnusTiberius/code | 38751016ca14810c0d939ae84a0e2680374e634a | 0b24bd4f9d6d57bb81603b27f1320accdf0289ab | refs/heads/master | 2021-01-16T01:02:12.484598 | 2016-04-19T04:24:46 | 2016-04-19T04:24:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 219 | cpp | #include "http_source.h"
#include <iostream>
int main (int argc, char * const argv[])
{
HTTPSource source;
if (source.handshake("www.boost.org", 60))
{
std::cout << "ok\n";
}
return 0;
}
| [
"yielding@gmail.com"
] | yielding@gmail.com |
4a74bc9bb0c02a86c31f6a070dfe61e031b30a87 | 8170b6db2d9446c5f97e6ff07131d92eb9da55eb | /Assignment 2/mat_inv.cc | 85023d8576cb462c57f58882a1b9278b8bb04f3f | [] | no_license | harshitrai17152/Computer-Architecture | ec6d766e37b14195a1fcdadce95e11178d555cfc | 6327f2428c788799970bd401b40b2e109d2224ec | refs/heads/main | 2023-01-20T00:09:31.365932 | 2020-11-24T12:40:56 | 2020-11-24T12:40:56 | 301,419,623 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,756 | cc | #include "learning_gem5/mat_inv.hh"
#include "debug/MATRIX.hh"
#include "debug/RESULT.hh"
#include <iostream>
#include "base/trace.hh"
MatInv::MatInv(MatInvParams *params) :
SimObject(params), event([this]{processEvent();},name())
{
std::cout << "Finding Inverse of the given matrix" << std::endl;
}
void
MatInv::processEvent()
{
float inv[N][N];
bool ans=inverse(A,inv);
std::cout<<"\n";
if(DTRACE(MATRIX))
{
DPRINTF(MATRIX,"MATRIX DEBUG flag enabled");
std::cout<<"\n";
std::cout<<"Size Of Matrix is: "<<N;
std::cout<<"\n";
std::cout<<"Input Matrix is as follows:\n";
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
std::cout<<A[i][j]<<" ";
std::cout<<"\n";
}
}
std::cout<<"\n";
if(DTRACE(RESULT))
{
if(ans)
{
DPRINTF(RESULT,"RESULT DEBUG flag enabled");
std::cout<<"\n";
std::cout<<"Inverse of Matrix is as follows:\n";
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
std::cout<<inv[i][j]<<" ";
std::cout<<"\n";
}
}
else
std::cout<<"Inverse does not exist\n";
}
std::cout<<"\n";
}
void
MatInv::adjoint(int A[N][N],int adj[N][N])
{
if(N==1)
{
adj[0][0]=1;
return;
}
int temp[N][N];
int sign=1;
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
getCofactor(A,temp,i,j,N);
sign=((i+j)%2==0)?1:-1;
adj[j][i]=(sign)*(determinant(temp,N-1));
}
}
}
int
MatInv::determinant(int A[N][N],int n)
{
int D=0;
if(n==1)
return(A[0][0]);
int temp[N][N];
int sign=1;
for(int f=0;f<n;f++)
{
getCofactor(A,temp,0,f,n);
D+=sign*A[0][f]*determinant(temp,n-1);
sign=-sign;
}
return(D);
}
void
MatInv::getCofactor(int A[N][N],int temp[N][N],int p,int q,int n)
{
int i=0,j=0;
for(int row=0;row<n;row++)
{
for (int col=0;col<n;col++)
{
if(row!=p && col!=q)
{
temp[i][j++]=A[row][col];
if(j==n-1)
{
j=0;
i++;
}
}
}
}
}
bool
MatInv::inverse(int A[N][N],float inverse[N][N])
{
int adj[N][N];
int det=determinant(A,N);
if(det==0)
return(false);
adjoint(A,adj);
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
inverse[i][j]=adj[i][j]/float(det);
}
return(true);
}
void
MatInv::startup()
{
schedule(event,100);
}
MatInv*
MatInvParams::create()
{
return new MatInv(this);
}
| [
"noreply@github.com"
] | harshitrai17152.noreply@github.com |
cb5e29de7ea560b2241fb91cba1fdbdd03898996 | 98929eb901ec6e774690b455aaa7311ac70f1382 | /BnsProjects/GameDetection.h | 7b6046d009adf3075ab2c8334b14359b2a7a6c56 | [] | no_license | wyexe/BnsProjects_Korea | 68cc5843b05376d56d052ce7f210dbfdc0c866cb | 1c06e2f60a3c65f0635e1b20ae3b5b07b7b39fb6 | refs/heads/master | 2022-06-01T03:11:47.928354 | 2020-05-04T10:23:44 | 2020-05-04T10:23:44 | 261,142,312 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,253 | h | #ifndef __GITBNSPROJECTS_BNSPROJECTS_GAME_GAMELOWDESIGN_GAMEDETECTION_H__
#define __GITBNSPROJECTS_BNSPROJECTS_GAME_GAMELOWDESIGN_GAMEDETECTION_H__
#include <winternl.h>
#include <MyTools/ClassInstance.h>
class CGameDetection : public MyTools::CClassInstance<CGameDetection>
{
private:
typedef enum _MEMORY_INFORMATION_CLASS {
MemoryBasicInformation
} MEMORY_INFORMATION_CLASS;
using ZwQueryVirtualMemoryPtr = NTSTATUS(WINAPI *)(
_In_ HANDLE ProcessHandle,
_In_opt_ PVOID BaseAddress,
_In_ MEMORY_INFORMATION_CLASS MemoryInformationClass,
_Out_ PVOID MemoryInformation,
_In_ SIZE_T MemoryInformationLength,
_Out_opt_ PSIZE_T ReturnLength
);
using VirtualQueryPtr = SIZE_T(WINAPI *)(
_In_opt_ LPCVOID lpAddress,
_Out_writes_bytes_to_(dwLength, return) PMEMORY_BASIC_INFORMATION lpBuffer,
_In_ SIZE_T dwLength
);
using NtQuerySystemInformationPtr = NTSTATUS(WINAPI *)(
_In_ SYSTEM_INFORMATION_CLASS SystemInformationClass,
_Inout_ PVOID SystemInformation,
_In_ ULONG SystemInformationLength,
_Out_opt_ PULONG ReturnLength);
public:
CGameDetection () = default;
~CGameDetection ();
BOOL Run();
VOID Stop();
private:
static NTSTATUS WINAPI NewZwQueryVirtualMemory(_In_ HANDLE ProcessHandle, _In_opt_ PVOID BaseAddress, _In_ MEMORY_INFORMATION_CLASS MemoryInformationClass, _Out_ PVOID MemoryInformation, _In_ SIZE_T MemoryInformationLength, _Out_opt_ PSIZE_T ReturnLength);
static SIZE_T WINAPI NewVirtualQuery(_In_opt_ LPCVOID lpAddress, _Out_writes_bytes_to_(dwLength, return) PMEMORY_BASIC_INFORMATION lpBuffer, _In_ SIZE_T dwLength);
static NTSTATUS WINAPI NewNtQuerySystemInformation(_In_ SYSTEM_INFORMATION_CLASS SystemInformationClass, _Inout_ PVOID SystemInformation, _In_ ULONG SystemInformationLength, _Out_opt_ PULONG ReturnLength);
private:
ZwQueryVirtualMemoryPtr _RealZwQueryVirtualMemoryPtr = nullptr;
VirtualQueryPtr _RealVirtualQueryPtr = nullptr;
NtQuerySystemInformationPtr _RealNtQuerySystemInformationPtr = nullptr;
};
#endif // !__GITBNSPROJECTS_BNSPROJECTS_GAME_GAMELOWDESIGN_GAMEDETECTION_H__
| [
"wy.exe@hotmail.com"
] | wy.exe@hotmail.com |
0ba93ae79139b09ceb8e2bf2ba327c05488c9635 | dcf7a0c407af384979a8031d71433697672894c4 | /내리막 길.cpp | 067cc837b395da3dfd5f5b091c65de6ea64313b3 | [] | no_license | presentnine/Algorithm-Code | 77d2b68d88ae88ce022c6001435d7ad195ef56d2 | 90cbbc68b2a7994b12c866a439fbba7f1a0db8ad | refs/heads/master | 2023-07-08T12:10:56.531912 | 2021-08-06T14:27:10 | 2021-08-06T14:27:10 | 345,614,665 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,295 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<vector<int>> cache;
int searchRoute(int M, int N, vector<vector<int>> &map, int r, int c, int prev) {
int result = 0;
if (r<0 || r>=M || c<0 || c>=N) //인덱스 범위 밖
return 0;
if (map[r][c] >= prev) //이전 높이 보다 높거나 같은 경우
return 0;
if (r == M - 1 && c == N - 1) //끝에 도달한 경우
return 1;
if (cache[r][c] != -1) //한 번도 가본 길이 아닌 경우 캐시 반환
return cache[r][c];
//상하좌우 길 탐색
result += searchRoute(M, N, map, r, c + 1, map[r][c]);
result += searchRoute(M, N, map, r + 1, c, map[r][c]);
result += searchRoute(M, N, map, r, c - 1, map[r][c]);
result += searchRoute(M, N, map, r - 1, c, map[r][c]);
return cache[r][c] = result;//저장한 캐시 반환
}
int main() {
int M, N, answer = 0;
vector<vector<int>> map;
cin >> M >> N;
for (int i = 0; i < M; i++) {//지도, 캐시 벡터 생성
vector<int> temp(N, 0);
vector<int> temp2(N, -1);//-1을 통해 길이 없는 경우인지 안 가본 경우인지 구분
cache.push_back(temp2);
for (int j = 0; j < N; j++)
cin >> temp[j];
map.push_back(temp);
}
answer = searchRoute(M, N, map, 0, 0, 10001);
cout << answer;
return 0;
} | [
"presentnine@naver.com"
] | presentnine@naver.com |
eba050d70160308c62e2790dc34961288f8cabf2 | 16a12666f15a134ff2ca39776496d719fe934aff | /tf03_common/cart_test_sheet.h | a81effbf475c7da44b3b0c3ca25096cdedf50388 | [] | no_license | iamkevinzhao/tf03_sdk | b7ae4ea6443aff1e16e5811240027db7061b2d55 | 6a8df4246ae9b01f6440c14b358dd564cac663d0 | refs/heads/master | 2020-03-27T15:01:55.675112 | 2018-12-20T01:19:32 | 2018-12-20T01:19:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 290 | h | #ifndef CART_TEST_SHEET_H
#define CART_TEST_SHEET_H
#include "cart_test_sheet_widget.h"
struct CartStep;
class API CartTestSheet : public CartTestSheetWidget
{
public:
CartTestSheet(QWidget *parent = 0);
void Update(const std::list<CartStep>& steps);
};
#endif // CART_TEST_SHEET_H
| [
"codincodee@outlook.com"
] | codincodee@outlook.com |
f99c9ac6c4c037f98ec0d6693b5f3e9128b451f2 | 4a71a5cbda33b3fd53162fd2a2c61047dac11cad | /src/clipboard/PatternClipboard.hpp | 4444627b22137a098ac0523c6a1446dcff029427 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | stoneface86/trackerboy | 81f177d6f9bcb2310b047d44a72341c830e7b4b5 | 9b5b1bf4227e1ab5ac7983967068be8b1af57d56 | refs/heads/develop | 2023-02-25T09:59:39.495946 | 2023-01-26T05:29:31 | 2023-01-26T05:29:31 | 190,796,979 | 93 | 4 | MIT | 2022-03-09T16:58:27 | 2019-06-07T19:18:53 | C++ | UTF-8 | C++ | false | false | 619 | hpp |
#pragma once
#include "clipboard/PatternClip.hpp"
#include <QObject>
#include <optional>
//
// Utility class for managing the system clipboard.
//
class PatternClipboard : public QObject {
Q_OBJECT
public:
explicit PatternClipboard(QObject *parent = nullptr);
bool hasClip() const;
PatternClip const& clip() const;
//
// Puts the given pattern clip on the system clipboard. This class takes
// ownership of the clip.
//
void setClip(PatternClip &clip);
private:
void parseClipboard();
private:
std::optional<PatternClip> mClip;
bool mSettingClipboard;
};
| [
"44489054+stoneface86@users.noreply.github.com"
] | 44489054+stoneface86@users.noreply.github.com |
2f4d66a7bd80bbefdfe255e47a23cb1d06f176c0 | 4c9716c0e708a4c8ddb5b63925f21f284701a42c | /code/btas/ctf-master/src/summation/spr_seq_sum.cxx | b10f86d4f4e62a56c52145d38be71a9cf6e0869b | [
"BSD-3-Clause"
] | permissive | shiyangdaisy23/tensor-contraction | 8564e97c820be07614d9f821210c8ea99533b4c6 | cc79c5683da718dfc8735aea7f56fba36fb628b9 | refs/heads/master | 2021-01-16T18:24:02.409163 | 2017-08-11T20:45:48 | 2017-08-11T20:45:48 | 100,068,903 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,421 | cxx | #include "spr_seq_sum.h"
#include "../shared/iter_tsr.h"
#include "../shared/util.h"
namespace CTF_int{
template<int idim>
void spA_dnB_seq_sum_loop(char const * alpha,
ConstPairIterator & A,
int64_t & size_A,
algstrct const * sr_A,
char const * beta,
char *& B,
algstrct const * sr_B,
int order_B,
int64_t idx_B,
int const * edge_len_B,
int64_t const * lda_B,
int const * sym_B,
univar_function const * func){
int imax = edge_len_B[idim];
if (sym_B[idim] != NS) imax = (idx_B/lda_B[idim+1])%edge_len_B[idim+1];
for (int i=0; i<imax; i++){
//int nidx_B[order_B];
//memcpy(nidx_B, idx_B, order_B*sizeof(int));
spA_dnB_seq_sum_loop<idim-1>(alpha,A,size_A,sr_A,beta,B,sr_B,order_B,
idx_B+i*lda_B[idim],
edge_len_B, lda_B, sym_B, func);
}
}
template<>
void spA_dnB_seq_sum_loop<0>(char const * alpha,
ConstPairIterator & A,
int64_t & size_A,
algstrct const * sr_A,
char const * beta,
char *& B,
algstrct const * sr_B,
int order_B,
int64_t idx_B,
int const * edge_len_B,
int64_t const * lda_B,
int const * sym_B,
univar_function const * func){
int imax = edge_len_B[0];
if (sym_B[0] != NS) imax = (idx_B/lda_B[0+1])%edge_len_B[0+1];
for (int i=0; i<imax; i++){
while (size_A > 0 && idx_B == A.k()){
if (func == NULL){
if (sr_A->isequal(alpha, sr_A->mulid()) || alpha == NULL){
sr_B->add(A.d(), B, B);
} else {
char tmp[sr_A->el_size];
sr_A->mul(A.d(), alpha, tmp);
sr_B->add(tmp, B, B);
}
} else {
if (sr_A->isequal(alpha, sr_A->mulid()) || alpha == NULL){
func->acc_f(A.d(), B, sr_B);
} else {
char tmp[sr_A->el_size];
sr_A->mul(A.d(), alpha, tmp);
func->acc_f(tmp, B, sr_B);
}
}
A = A[1];
size_A--;
}
B += sr_B->el_size;
idx_B++;
}
}
template
void spA_dnB_seq_sum_loop< MAX_ORD >
(char const * alpha,
ConstPairIterator & A,
int64_t & size_A,
algstrct const * sr_A,
char const * beta,
char *& B,
algstrct const * sr_B,
int order_B,
int64_t idx_B,
int const * edge_len_B,
int64_t const * lda_B,
int const * sym_B,
univar_function const * func);
void spA_dnB_seq_sum(char const * alpha,
char const * A,
int64_t size_A,
algstrct const * sr_A,
char const * beta,
char * B,
algstrct const * sr_B,
int order_B,
int const * edge_len_B,
int const * sym_B,
univar_function const * func){
TAU_FSTART(spA_dnB_seq_sum);
if (order_B == 0){
if (!sr_B->isequal(beta, sr_B->mulid())){
sr_B->mul(beta, B, B);
}
ConstPairIterator pi(sr_A, A);
for (int64_t i=0; i<size_A; i++){
char tmp_buf[sr_A->el_size];
char const * tmp_ptr;
if (alpha != NULL){
sr_A->mul(alpha, pi[i].d(), tmp_buf);
tmp_ptr = tmp_buf;
} else tmp_ptr = pi[i].d();
if (func != NULL){
func->acc_f(tmp_ptr, B, sr_B);
} else {
sr_B->add(tmp_ptr, B, B);
}
}
} else {
int64_t sz_B = sy_packed_size(order_B, edge_len_B, sym_B);
if (!sr_B->isequal(beta, sr_B->mulid())){
if (sr_B->isequal(beta, sr_B->addid()) || sr_B->isequal(beta, NULL))
sr_B->set(B, sr_B->addid(), sz_B);
else
sr_B->scal(sz_B, beta, B, 1);
}
int64_t lda_B[order_B];
for (int i=0; i<order_B; i++){
if (i==0) lda_B[i] = 1;
else lda_B[i] = lda_B[i-1]*edge_len_B[i-1];
}
ASSERT(order_B<=MAX_ORD);
ConstPairIterator pA(sr_A, A);
int64_t idx = 0;
SWITCH_ORD_CALL(spA_dnB_seq_sum_loop, order_B-1, alpha, pA, size_A, sr_A, beta, B, sr_B, order_B, idx, edge_len_B, lda_B, sym_B, func);
}
TAU_FSTOP(spA_dnB_seq_sum);
}
void dnA_spB_seq_sum(char const * alpha,
char const * A,
algstrct const * sr_A,
int order_A,
int const * edge_len_A,
int const * sym_A,
char const * beta,
char const * B,
int64_t size_B,
char *& new_B,
int64_t & new_size_B,
algstrct const * sr_B,
univar_function const * func){
printf("not implted\n");
assert(0);
}
/**
* \brief As pairs in a sparse A set to the
* sparse set of elements defining the tensor,
* resulting in a set of size between nB and nB+nA
* \param[in] sr algstrct defining data type of array
* \param[in] nB number of elements in sparse tensor
* \param[in] prs_B pairs of the sparse tensor
* \param[in] beta scaling factor for data of the sparse tensor
* \param[in] nA number of elements in the A set
* \param[in] prs_A pairs of the A set
* \param[in] alpha scaling factor for data of the A set
* \param[out] nnew number of elements in resulting set
* \param[out] pprs_new char array containing the pairs of the resulting set
* \param[in] func NULL or pointer to a function to apply elementwise
* \param[in] map_pfx how many times each element of A should be replicated
*/
void spspsum(algstrct const * sr_A,
int64_t nA,
ConstPairIterator prs_A,
char const * beta,
algstrct const * sr_B,
int64_t nB,
ConstPairIterator prs_B,
char const * alpha,
int64_t & nnew,
char *& pprs_new,
univar_function const * func,
int64_t map_pfx){
// determine how many unique keys there are in prs_tsr and prs_Write
nnew = nB;
for (int64_t t=0,ww=0; ww<nA*map_pfx; ww++){
while (ww<nA*map_pfx){
int64_t w = ww/map_pfx;
int64_t mw = ww%map_pfx;
if (t<nB && prs_B[t].k() < prs_A[w].k()*map_pfx+mw)
t++;
else if (t<nB && prs_B[t].k() == prs_A[w].k()*map_pfx+mw){
t++;
ww++;
} else {
//ASSERT(map_pfx == 1);
if (map_pfx != 1 || ww==0 || prs_A[ww-1].k() != prs_A[ww].k())
nnew++;
ww++; w=ww;
}
}
}
// printf("nB = %ld nA = %ld nnew = %ld\n",nB,nA,nnew);
alloc_ptr(sr_B->pair_size()*nnew, (void**)&pprs_new);
PairIterator prs_new(sr_B, pprs_new);
// each for loop computes one new value of prs_new
// (multiple writes may contribute to it),
// t, w, and n are incremented within
// only incrementing r allows multiple writes of the same val
for (int64_t t=0,ww=0,n=0; n<nnew; n++){
int64_t w = ww/map_pfx;
int64_t mw = ww%map_pfx;
if (t<nB && (w==nA || prs_B[t].k() < prs_A[w].k()*map_pfx+mw)){
memcpy(prs_new[n].ptr, prs_B[t].ptr, sr_B->pair_size());
if (beta != NULL)
sr_B->mul(prs_B[t].d(), beta, prs_new[n].d());
t++;
} else {
if (t>=nB || prs_B[t].k() > prs_A[w].k()*map_pfx+mw){
if (func == NULL){
if (map_pfx == 1){
memcpy(prs_new[n].ptr, prs_A[w].ptr, sr_A->pair_size());
} else {
((int64_t*)prs_new[n].ptr)[0] = prs_A[w].k()*map_pfx+mw;
prs_new[n].write_val(prs_A[w].d());
}
if (alpha != NULL)
sr_A->mul(prs_new[n].d(), alpha, prs_new[n].d());
} else {
//((int64_t*)prs_new[n].ptr)[0] = prs_A[w].k();
((int64_t*)prs_new.ptr)[0] = prs_A[w].k()*map_pfx+mw;
if (alpha != NULL){
char a[sr_A->el_size];
sr_A->mul(prs_A[w].d(), alpha, a);
func->apply_f(a, prs_new[n].d());
}
}
ww++;
} else {
char a[sr_A->el_size];
char b[sr_B->el_size];
if (alpha != NULL){
sr_A->mul(prs_A[w].d(), alpha, a);
} else {
prs_A[w].read_val(a);
}
if (beta != NULL){
sr_B->mul(prs_B[t].d(), beta, b);
} else {
prs_B[t].read_val(b);
}
if (func == NULL)
sr_B->add(a, b, b);
else
func->acc_f(a, b, sr_B);
prs_new[n].write_val(b);
((int64_t*)(prs_new[n].ptr))[0] = prs_B[t].k();
t++;
ww++;
}
// accumulate any repeated key writes
while (map_pfx == 1 && ww > 0 && ww<nA && prs_A[ww].k() == prs_A[ww-1].k()){
if (alpha != NULL){
char a[sr_A->el_size];
sr_A->mul(prs_A[ww].d(), alpha, a);
if (func == NULL)
sr_B->add(prs_new[n].d(), a, prs_new[n].d());
else
func->acc_f(a, prs_new[n].d(), sr_B);
} else {
if (func == NULL)
sr_B->add(prs_new[n].d(), prs_A[ww].d(), prs_new[n].d());
else
func->acc_f(prs_A[ww].d(), prs_new[n].d(), sr_B);
}
ww++; w=ww;
}
}
/*printf("%ldth value is ", n);
sr_B->print(prs_new[n].d());
printf(" with key %ld\n",prs_new[n].k());*/
}
}
void spA_spB_seq_sum(char const * alpha,
char const * A,
int64_t size_A,
algstrct const * sr_A,
char const * beta,
char * B,
int64_t size_B,
char *& new_B,
int64_t & new_size_B,
algstrct const * sr_B,
univar_function const * func,
int64_t map_pfx){
/* if (!sr_B->isequal(beta, sr_B->mulid())){
printf("scaling B by 0\n");
sr_B->scal(size_B, beta, B, 1);
}*/
spspsum(sr_A, size_A, ConstPairIterator(sr_A, A), beta,
sr_B, size_B, ConstPairIterator(sr_B, B),alpha,
new_size_B, new_B, func, map_pfx);
}
}
| [
"shiyangdaisy@126.com"
] | shiyangdaisy@126.com |
4d2636f749aee4282677f25483766222dd95f8f5 | b95b7a231f250f17688484de5592bccc3c439d3e | /Array/q90.cpp | fbbf3e43087ef0cb18e69988e3ea1f4b4e226bd9 | [] | no_license | GuanyiLi-Craig/interview | 725e91a107bf11daf2120b5bd2e4d86f7b6804ea | 87269f436c92fc2ed34a2b51168836f5272b74f6 | refs/heads/master | 2021-08-30T03:59:26.590964 | 2017-12-15T23:49:08 | 2017-12-15T23:49:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,240 | cpp | /****************************************************************************************************
90. Subsets II
-----------------------------------------------------------------------------------------------------
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
****************************************************************************************************/
#include "problems\problems\Header.h"
namespace std
{
class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
int len=nums.size();
vector<vector<int> > rst(1,vector<int>());
if (len==0) return rst;
if (len==1) {rst.push_back(nums); return rst;}
sort(nums.begin(),nums.end());
map<int,int> count;
for(int i=0;i<len;i++)
{
count[nums[i]]++; //real count *
}
map<int,int>::iterator it; it = count.begin();
for(it=count.begin();it!=count.end();it++)
{
int n=rst.size();
for(int i=0;i<n;i++)
{
rst.push_back(rst[i]);
for(int j=0;j<it->second;j++)
{
rst.back().push_back(it->first);
if(j+1<it->second) // **
rst.push_back(rst.back());
}
}
}
return rst;
}
};
class OthersSolution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
int len=nums.size();
vector<vector<int> > rst(1,vector<int>());
if (len==0) return rst;
if (len==1) {rst.push_back(nums); return rst;}
sort(nums.begin(),nums.end());
int currsize=0;
for(int i=0;i<len;i++)
{
int ind = i>0 && nums[i-1]==nums[i] ? currsize:0;
currsize=rst.size();
for(int j=ind;j<currsize;j++)
{
rst.push_back(rst[j]);
rst.back().push_back(nums[i]);
}
}
return rst;
}
};
}
/****************************************************************************************************
Note
* it is real count because it was ++, so first time result 1
** because it was added before.
And there is better solution, just set the start point
vector<vector<int> > subsetsWithDup(vector<int> &S) {
sort(S.begin(), S.end());
vector<vector<int>> ret = {{}};
int size = 0, startIndex = 0;
for (int i = 0; i < S.size(); i++) {
startIndex = i >= 1 && S[i] == S[i - 1] ? size : 0;
size = ret.size();
for (int j = startIndex; j < size; j++) {
vector<int> temp = ret[j];
temp.push_back(S[i]);
ret.push_back(temp);
}
}
return ret;
}
****************************************************************************************************/ | [
"bitforce.studio@gmail.com"
] | bitforce.studio@gmail.com |
652209ef967b13d3a1c4ecd08a6af19f1818b688 | 1a17167c38dc9a12c1f72dd0f3ae7288f5cd7da0 | /Source/ThirdParty/angle/third_party/deqp/src/external/vulkancts/framework/vulkan/vkStructTypes.inl | cd09f0d2bee08376b5e3b5be12c27780b25ac943 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"Zlib",
"LicenseRef-scancode-khronos",
"BSL-1.0",
"BSD-2-Clause"
] | permissive | elix22/Urho3D | c57c7ecb58975f51fabb95bcc4330bc5b0812de7 | 99902ae2a867be0d6dbe4c575f9c8c318805ec64 | refs/heads/master | 2023-06-01T01:19:57.155566 | 2021-12-07T16:47:20 | 2021-12-07T17:46:58 | 165,504,739 | 21 | 4 | MIT | 2021-11-05T01:02:08 | 2019-01-13T12:51:17 | C++ | UTF-8 | C++ | false | false | 79,571 | inl | /* WARNING: This is auto-generated file. Do not modify, since changes will
* be lost! Modify the generating script instead.
*/
struct VkApplicationInfo
{
VkStructureType sType;
const void* pNext;
const char* pApplicationName;
deUint32 applicationVersion;
const char* pEngineName;
deUint32 engineVersion;
deUint32 apiVersion;
};
struct VkInstanceCreateInfo
{
VkStructureType sType;
const void* pNext;
VkInstanceCreateFlags flags;
const VkApplicationInfo* pApplicationInfo;
deUint32 enabledLayerCount;
const char* const* ppEnabledLayerNames;
deUint32 enabledExtensionCount;
const char* const* ppEnabledExtensionNames;
};
struct VkAllocationCallbacks
{
void* pUserData;
PFN_vkAllocationFunction pfnAllocation;
PFN_vkReallocationFunction pfnReallocation;
PFN_vkFreeFunction pfnFree;
PFN_vkInternalAllocationNotification pfnInternalAllocation;
PFN_vkInternalFreeNotification pfnInternalFree;
};
struct VkPhysicalDeviceFeatures
{
VkBool32 robustBufferAccess;
VkBool32 fullDrawIndexUint32;
VkBool32 imageCubeArray;
VkBool32 independentBlend;
VkBool32 geometryShader;
VkBool32 tessellationShader;
VkBool32 sampleRateShading;
VkBool32 dualSrcBlend;
VkBool32 logicOp;
VkBool32 multiDrawIndirect;
VkBool32 drawIndirectFirstInstance;
VkBool32 depthClamp;
VkBool32 depthBiasClamp;
VkBool32 fillModeNonSolid;
VkBool32 depthBounds;
VkBool32 wideLines;
VkBool32 largePoints;
VkBool32 alphaToOne;
VkBool32 multiViewport;
VkBool32 samplerAnisotropy;
VkBool32 textureCompressionETC2;
VkBool32 textureCompressionASTC_LDR;
VkBool32 textureCompressionBC;
VkBool32 occlusionQueryPrecise;
VkBool32 pipelineStatisticsQuery;
VkBool32 vertexPipelineStoresAndAtomics;
VkBool32 fragmentStoresAndAtomics;
VkBool32 shaderTessellationAndGeometryPointSize;
VkBool32 shaderImageGatherExtended;
VkBool32 shaderStorageImageExtendedFormats;
VkBool32 shaderStorageImageMultisample;
VkBool32 shaderStorageImageReadWithoutFormat;
VkBool32 shaderStorageImageWriteWithoutFormat;
VkBool32 shaderUniformBufferArrayDynamicIndexing;
VkBool32 shaderSampledImageArrayDynamicIndexing;
VkBool32 shaderStorageBufferArrayDynamicIndexing;
VkBool32 shaderStorageImageArrayDynamicIndexing;
VkBool32 shaderClipDistance;
VkBool32 shaderCullDistance;
VkBool32 shaderFloat64;
VkBool32 shaderInt64;
VkBool32 shaderInt16;
VkBool32 shaderResourceResidency;
VkBool32 shaderResourceMinLod;
VkBool32 sparseBinding;
VkBool32 sparseResidencyBuffer;
VkBool32 sparseResidencyImage2D;
VkBool32 sparseResidencyImage3D;
VkBool32 sparseResidency2Samples;
VkBool32 sparseResidency4Samples;
VkBool32 sparseResidency8Samples;
VkBool32 sparseResidency16Samples;
VkBool32 sparseResidencyAliased;
VkBool32 variableMultisampleRate;
VkBool32 inheritedQueries;
};
struct VkFormatProperties
{
VkFormatFeatureFlags linearTilingFeatures;
VkFormatFeatureFlags optimalTilingFeatures;
VkFormatFeatureFlags bufferFeatures;
};
struct VkExtent3D
{
deUint32 width;
deUint32 height;
deUint32 depth;
};
struct VkImageFormatProperties
{
VkExtent3D maxExtent;
deUint32 maxMipLevels;
deUint32 maxArrayLayers;
VkSampleCountFlags sampleCounts;
VkDeviceSize maxResourceSize;
};
struct VkPhysicalDeviceLimits
{
deUint32 maxImageDimension1D;
deUint32 maxImageDimension2D;
deUint32 maxImageDimension3D;
deUint32 maxImageDimensionCube;
deUint32 maxImageArrayLayers;
deUint32 maxTexelBufferElements;
deUint32 maxUniformBufferRange;
deUint32 maxStorageBufferRange;
deUint32 maxPushConstantsSize;
deUint32 maxMemoryAllocationCount;
deUint32 maxSamplerAllocationCount;
VkDeviceSize bufferImageGranularity;
VkDeviceSize sparseAddressSpaceSize;
deUint32 maxBoundDescriptorSets;
deUint32 maxPerStageDescriptorSamplers;
deUint32 maxPerStageDescriptorUniformBuffers;
deUint32 maxPerStageDescriptorStorageBuffers;
deUint32 maxPerStageDescriptorSampledImages;
deUint32 maxPerStageDescriptorStorageImages;
deUint32 maxPerStageDescriptorInputAttachments;
deUint32 maxPerStageResources;
deUint32 maxDescriptorSetSamplers;
deUint32 maxDescriptorSetUniformBuffers;
deUint32 maxDescriptorSetUniformBuffersDynamic;
deUint32 maxDescriptorSetStorageBuffers;
deUint32 maxDescriptorSetStorageBuffersDynamic;
deUint32 maxDescriptorSetSampledImages;
deUint32 maxDescriptorSetStorageImages;
deUint32 maxDescriptorSetInputAttachments;
deUint32 maxVertexInputAttributes;
deUint32 maxVertexInputBindings;
deUint32 maxVertexInputAttributeOffset;
deUint32 maxVertexInputBindingStride;
deUint32 maxVertexOutputComponents;
deUint32 maxTessellationGenerationLevel;
deUint32 maxTessellationPatchSize;
deUint32 maxTessellationControlPerVertexInputComponents;
deUint32 maxTessellationControlPerVertexOutputComponents;
deUint32 maxTessellationControlPerPatchOutputComponents;
deUint32 maxTessellationControlTotalOutputComponents;
deUint32 maxTessellationEvaluationInputComponents;
deUint32 maxTessellationEvaluationOutputComponents;
deUint32 maxGeometryShaderInvocations;
deUint32 maxGeometryInputComponents;
deUint32 maxGeometryOutputComponents;
deUint32 maxGeometryOutputVertices;
deUint32 maxGeometryTotalOutputComponents;
deUint32 maxFragmentInputComponents;
deUint32 maxFragmentOutputAttachments;
deUint32 maxFragmentDualSrcAttachments;
deUint32 maxFragmentCombinedOutputResources;
deUint32 maxComputeSharedMemorySize;
deUint32 maxComputeWorkGroupCount[3];
deUint32 maxComputeWorkGroupInvocations;
deUint32 maxComputeWorkGroupSize[3];
deUint32 subPixelPrecisionBits;
deUint32 subTexelPrecisionBits;
deUint32 mipmapPrecisionBits;
deUint32 maxDrawIndexedIndexValue;
deUint32 maxDrawIndirectCount;
float maxSamplerLodBias;
float maxSamplerAnisotropy;
deUint32 maxViewports;
deUint32 maxViewportDimensions[2];
float viewportBoundsRange[2];
deUint32 viewportSubPixelBits;
deUintptr minMemoryMapAlignment;
VkDeviceSize minTexelBufferOffsetAlignment;
VkDeviceSize minUniformBufferOffsetAlignment;
VkDeviceSize minStorageBufferOffsetAlignment;
deInt32 minTexelOffset;
deUint32 maxTexelOffset;
deInt32 minTexelGatherOffset;
deUint32 maxTexelGatherOffset;
float minInterpolationOffset;
float maxInterpolationOffset;
deUint32 subPixelInterpolationOffsetBits;
deUint32 maxFramebufferWidth;
deUint32 maxFramebufferHeight;
deUint32 maxFramebufferLayers;
VkSampleCountFlags framebufferColorSampleCounts;
VkSampleCountFlags framebufferDepthSampleCounts;
VkSampleCountFlags framebufferStencilSampleCounts;
VkSampleCountFlags framebufferNoAttachmentsSampleCounts;
deUint32 maxColorAttachments;
VkSampleCountFlags sampledImageColorSampleCounts;
VkSampleCountFlags sampledImageIntegerSampleCounts;
VkSampleCountFlags sampledImageDepthSampleCounts;
VkSampleCountFlags sampledImageStencilSampleCounts;
VkSampleCountFlags storageImageSampleCounts;
deUint32 maxSampleMaskWords;
VkBool32 timestampComputeAndGraphics;
float timestampPeriod;
deUint32 maxClipDistances;
deUint32 maxCullDistances;
deUint32 maxCombinedClipAndCullDistances;
deUint32 discreteQueuePriorities;
float pointSizeRange[2];
float lineWidthRange[2];
float pointSizeGranularity;
float lineWidthGranularity;
VkBool32 strictLines;
VkBool32 standardSampleLocations;
VkDeviceSize optimalBufferCopyOffsetAlignment;
VkDeviceSize optimalBufferCopyRowPitchAlignment;
VkDeviceSize nonCoherentAtomSize;
};
struct VkPhysicalDeviceSparseProperties
{
VkBool32 residencyStandard2DBlockShape;
VkBool32 residencyStandard2DMultisampleBlockShape;
VkBool32 residencyStandard3DBlockShape;
VkBool32 residencyAlignedMipSize;
VkBool32 residencyNonResidentStrict;
};
struct VkPhysicalDeviceProperties
{
deUint32 apiVersion;
deUint32 driverVersion;
deUint32 vendorID;
deUint32 deviceID;
VkPhysicalDeviceType deviceType;
char deviceName[VK_MAX_PHYSICAL_DEVICE_NAME_SIZE];
deUint8 pipelineCacheUUID[VK_UUID_SIZE];
VkPhysicalDeviceLimits limits;
VkPhysicalDeviceSparseProperties sparseProperties;
};
struct VkQueueFamilyProperties
{
VkQueueFlags queueFlags;
deUint32 queueCount;
deUint32 timestampValidBits;
VkExtent3D minImageTransferGranularity;
};
struct VkMemoryType
{
VkMemoryPropertyFlags propertyFlags;
deUint32 heapIndex;
};
struct VkMemoryHeap
{
VkDeviceSize size;
VkMemoryHeapFlags flags;
};
struct VkPhysicalDeviceMemoryProperties
{
deUint32 memoryTypeCount;
VkMemoryType memoryTypes[VK_MAX_MEMORY_TYPES];
deUint32 memoryHeapCount;
VkMemoryHeap memoryHeaps[VK_MAX_MEMORY_HEAPS];
};
struct VkDeviceQueueCreateInfo
{
VkStructureType sType;
const void* pNext;
VkDeviceQueueCreateFlags flags;
deUint32 queueFamilyIndex;
deUint32 queueCount;
const float* pQueuePriorities;
};
struct VkDeviceCreateInfo
{
VkStructureType sType;
const void* pNext;
VkDeviceCreateFlags flags;
deUint32 queueCreateInfoCount;
const VkDeviceQueueCreateInfo* pQueueCreateInfos;
deUint32 enabledLayerCount;
const char* const* ppEnabledLayerNames;
deUint32 enabledExtensionCount;
const char* const* ppEnabledExtensionNames;
const VkPhysicalDeviceFeatures* pEnabledFeatures;
};
struct VkExtensionProperties
{
char extensionName[VK_MAX_EXTENSION_NAME_SIZE];
deUint32 specVersion;
};
struct VkLayerProperties
{
char layerName[VK_MAX_EXTENSION_NAME_SIZE];
deUint32 specVersion;
deUint32 implementationVersion;
char description[VK_MAX_DESCRIPTION_SIZE];
};
struct VkSubmitInfo
{
VkStructureType sType;
const void* pNext;
deUint32 waitSemaphoreCount;
const VkSemaphore* pWaitSemaphores;
const VkPipelineStageFlags* pWaitDstStageMask;
deUint32 commandBufferCount;
const VkCommandBuffer* pCommandBuffers;
deUint32 signalSemaphoreCount;
const VkSemaphore* pSignalSemaphores;
};
struct VkMemoryAllocateInfo
{
VkStructureType sType;
const void* pNext;
VkDeviceSize allocationSize;
deUint32 memoryTypeIndex;
};
struct VkMappedMemoryRange
{
VkStructureType sType;
const void* pNext;
VkDeviceMemory memory;
VkDeviceSize offset;
VkDeviceSize size;
};
struct VkMemoryRequirements
{
VkDeviceSize size;
VkDeviceSize alignment;
deUint32 memoryTypeBits;
};
struct VkSparseImageFormatProperties
{
VkImageAspectFlags aspectMask;
VkExtent3D imageGranularity;
VkSparseImageFormatFlags flags;
};
struct VkSparseImageMemoryRequirements
{
VkSparseImageFormatProperties formatProperties;
deUint32 imageMipTailFirstLod;
VkDeviceSize imageMipTailSize;
VkDeviceSize imageMipTailOffset;
VkDeviceSize imageMipTailStride;
};
struct VkSparseMemoryBind
{
VkDeviceSize resourceOffset;
VkDeviceSize size;
VkDeviceMemory memory;
VkDeviceSize memoryOffset;
VkSparseMemoryBindFlags flags;
};
struct VkSparseBufferMemoryBindInfo
{
VkBuffer buffer;
deUint32 bindCount;
const VkSparseMemoryBind* pBinds;
};
struct VkSparseImageOpaqueMemoryBindInfo
{
VkImage image;
deUint32 bindCount;
const VkSparseMemoryBind* pBinds;
};
struct VkImageSubresource
{
VkImageAspectFlags aspectMask;
deUint32 mipLevel;
deUint32 arrayLayer;
};
struct VkOffset3D
{
deInt32 x;
deInt32 y;
deInt32 z;
};
struct VkSparseImageMemoryBind
{
VkImageSubresource subresource;
VkOffset3D offset;
VkExtent3D extent;
VkDeviceMemory memory;
VkDeviceSize memoryOffset;
VkSparseMemoryBindFlags flags;
};
struct VkSparseImageMemoryBindInfo
{
VkImage image;
deUint32 bindCount;
const VkSparseImageMemoryBind* pBinds;
};
struct VkBindSparseInfo
{
VkStructureType sType;
const void* pNext;
deUint32 waitSemaphoreCount;
const VkSemaphore* pWaitSemaphores;
deUint32 bufferBindCount;
const VkSparseBufferMemoryBindInfo* pBufferBinds;
deUint32 imageOpaqueBindCount;
const VkSparseImageOpaqueMemoryBindInfo* pImageOpaqueBinds;
deUint32 imageBindCount;
const VkSparseImageMemoryBindInfo* pImageBinds;
deUint32 signalSemaphoreCount;
const VkSemaphore* pSignalSemaphores;
};
struct VkFenceCreateInfo
{
VkStructureType sType;
const void* pNext;
VkFenceCreateFlags flags;
};
struct VkSemaphoreCreateInfo
{
VkStructureType sType;
const void* pNext;
VkSemaphoreCreateFlags flags;
};
struct VkEventCreateInfo
{
VkStructureType sType;
const void* pNext;
VkEventCreateFlags flags;
};
struct VkQueryPoolCreateInfo
{
VkStructureType sType;
const void* pNext;
VkQueryPoolCreateFlags flags;
VkQueryType queryType;
deUint32 queryCount;
VkQueryPipelineStatisticFlags pipelineStatistics;
};
struct VkBufferCreateInfo
{
VkStructureType sType;
const void* pNext;
VkBufferCreateFlags flags;
VkDeviceSize size;
VkBufferUsageFlags usage;
VkSharingMode sharingMode;
deUint32 queueFamilyIndexCount;
const deUint32* pQueueFamilyIndices;
};
struct VkBufferViewCreateInfo
{
VkStructureType sType;
const void* pNext;
VkBufferViewCreateFlags flags;
VkBuffer buffer;
VkFormat format;
VkDeviceSize offset;
VkDeviceSize range;
};
struct VkImageCreateInfo
{
VkStructureType sType;
const void* pNext;
VkImageCreateFlags flags;
VkImageType imageType;
VkFormat format;
VkExtent3D extent;
deUint32 mipLevels;
deUint32 arrayLayers;
VkSampleCountFlagBits samples;
VkImageTiling tiling;
VkImageUsageFlags usage;
VkSharingMode sharingMode;
deUint32 queueFamilyIndexCount;
const deUint32* pQueueFamilyIndices;
VkImageLayout initialLayout;
};
struct VkSubresourceLayout
{
VkDeviceSize offset;
VkDeviceSize size;
VkDeviceSize rowPitch;
VkDeviceSize arrayPitch;
VkDeviceSize depthPitch;
};
struct VkComponentMapping
{
VkComponentSwizzle r;
VkComponentSwizzle g;
VkComponentSwizzle b;
VkComponentSwizzle a;
};
struct VkImageSubresourceRange
{
VkImageAspectFlags aspectMask;
deUint32 baseMipLevel;
deUint32 levelCount;
deUint32 baseArrayLayer;
deUint32 layerCount;
};
struct VkImageViewCreateInfo
{
VkStructureType sType;
const void* pNext;
VkImageViewCreateFlags flags;
VkImage image;
VkImageViewType viewType;
VkFormat format;
VkComponentMapping components;
VkImageSubresourceRange subresourceRange;
};
struct VkShaderModuleCreateInfo
{
VkStructureType sType;
const void* pNext;
VkShaderModuleCreateFlags flags;
deUintptr codeSize;
const deUint32* pCode;
};
struct VkPipelineCacheCreateInfo
{
VkStructureType sType;
const void* pNext;
VkPipelineCacheCreateFlags flags;
deUintptr initialDataSize;
const void* pInitialData;
};
struct VkSpecializationMapEntry
{
deUint32 constantID;
deUint32 offset;
deUintptr size;
};
struct VkSpecializationInfo
{
deUint32 mapEntryCount;
const VkSpecializationMapEntry* pMapEntries;
deUintptr dataSize;
const void* pData;
};
struct VkPipelineShaderStageCreateInfo
{
VkStructureType sType;
const void* pNext;
VkPipelineShaderStageCreateFlags flags;
VkShaderStageFlagBits stage;
VkShaderModule module;
const char* pName;
const VkSpecializationInfo* pSpecializationInfo;
};
struct VkVertexInputBindingDescription
{
deUint32 binding;
deUint32 stride;
VkVertexInputRate inputRate;
};
struct VkVertexInputAttributeDescription
{
deUint32 location;
deUint32 binding;
VkFormat format;
deUint32 offset;
};
struct VkPipelineVertexInputStateCreateInfo
{
VkStructureType sType;
const void* pNext;
VkPipelineVertexInputStateCreateFlags flags;
deUint32 vertexBindingDescriptionCount;
const VkVertexInputBindingDescription* pVertexBindingDescriptions;
deUint32 vertexAttributeDescriptionCount;
const VkVertexInputAttributeDescription* pVertexAttributeDescriptions;
};
struct VkPipelineInputAssemblyStateCreateInfo
{
VkStructureType sType;
const void* pNext;
VkPipelineInputAssemblyStateCreateFlags flags;
VkPrimitiveTopology topology;
VkBool32 primitiveRestartEnable;
};
struct VkPipelineTessellationStateCreateInfo
{
VkStructureType sType;
const void* pNext;
VkPipelineTessellationStateCreateFlags flags;
deUint32 patchControlPoints;
};
struct VkViewport
{
float x;
float y;
float width;
float height;
float minDepth;
float maxDepth;
};
struct VkOffset2D
{
deInt32 x;
deInt32 y;
};
struct VkExtent2D
{
deUint32 width;
deUint32 height;
};
struct VkRect2D
{
VkOffset2D offset;
VkExtent2D extent;
};
struct VkPipelineViewportStateCreateInfo
{
VkStructureType sType;
const void* pNext;
VkPipelineViewportStateCreateFlags flags;
deUint32 viewportCount;
const VkViewport* pViewports;
deUint32 scissorCount;
const VkRect2D* pScissors;
};
struct VkPipelineRasterizationStateCreateInfo
{
VkStructureType sType;
const void* pNext;
VkPipelineRasterizationStateCreateFlags flags;
VkBool32 depthClampEnable;
VkBool32 rasterizerDiscardEnable;
VkPolygonMode polygonMode;
VkCullModeFlags cullMode;
VkFrontFace frontFace;
VkBool32 depthBiasEnable;
float depthBiasConstantFactor;
float depthBiasClamp;
float depthBiasSlopeFactor;
float lineWidth;
};
struct VkPipelineMultisampleStateCreateInfo
{
VkStructureType sType;
const void* pNext;
VkPipelineMultisampleStateCreateFlags flags;
VkSampleCountFlagBits rasterizationSamples;
VkBool32 sampleShadingEnable;
float minSampleShading;
const VkSampleMask* pSampleMask;
VkBool32 alphaToCoverageEnable;
VkBool32 alphaToOneEnable;
};
struct VkStencilOpState
{
VkStencilOp failOp;
VkStencilOp passOp;
VkStencilOp depthFailOp;
VkCompareOp compareOp;
deUint32 compareMask;
deUint32 writeMask;
deUint32 reference;
};
struct VkPipelineDepthStencilStateCreateInfo
{
VkStructureType sType;
const void* pNext;
VkPipelineDepthStencilStateCreateFlags flags;
VkBool32 depthTestEnable;
VkBool32 depthWriteEnable;
VkCompareOp depthCompareOp;
VkBool32 depthBoundsTestEnable;
VkBool32 stencilTestEnable;
VkStencilOpState front;
VkStencilOpState back;
float minDepthBounds;
float maxDepthBounds;
};
struct VkPipelineColorBlendAttachmentState
{
VkBool32 blendEnable;
VkBlendFactor srcColorBlendFactor;
VkBlendFactor dstColorBlendFactor;
VkBlendOp colorBlendOp;
VkBlendFactor srcAlphaBlendFactor;
VkBlendFactor dstAlphaBlendFactor;
VkBlendOp alphaBlendOp;
VkColorComponentFlags colorWriteMask;
};
struct VkPipelineColorBlendStateCreateInfo
{
VkStructureType sType;
const void* pNext;
VkPipelineColorBlendStateCreateFlags flags;
VkBool32 logicOpEnable;
VkLogicOp logicOp;
deUint32 attachmentCount;
const VkPipelineColorBlendAttachmentState* pAttachments;
float blendConstants[4];
};
struct VkPipelineDynamicStateCreateInfo
{
VkStructureType sType;
const void* pNext;
VkPipelineDynamicStateCreateFlags flags;
deUint32 dynamicStateCount;
const VkDynamicState* pDynamicStates;
};
struct VkGraphicsPipelineCreateInfo
{
VkStructureType sType;
const void* pNext;
VkPipelineCreateFlags flags;
deUint32 stageCount;
const VkPipelineShaderStageCreateInfo* pStages;
const VkPipelineVertexInputStateCreateInfo* pVertexInputState;
const VkPipelineInputAssemblyStateCreateInfo* pInputAssemblyState;
const VkPipelineTessellationStateCreateInfo* pTessellationState;
const VkPipelineViewportStateCreateInfo* pViewportState;
const VkPipelineRasterizationStateCreateInfo* pRasterizationState;
const VkPipelineMultisampleStateCreateInfo* pMultisampleState;
const VkPipelineDepthStencilStateCreateInfo* pDepthStencilState;
const VkPipelineColorBlendStateCreateInfo* pColorBlendState;
const VkPipelineDynamicStateCreateInfo* pDynamicState;
VkPipelineLayout layout;
VkRenderPass renderPass;
deUint32 subpass;
VkPipeline basePipelineHandle;
deInt32 basePipelineIndex;
};
struct VkComputePipelineCreateInfo
{
VkStructureType sType;
const void* pNext;
VkPipelineCreateFlags flags;
VkPipelineShaderStageCreateInfo stage;
VkPipelineLayout layout;
VkPipeline basePipelineHandle;
deInt32 basePipelineIndex;
};
struct VkPushConstantRange
{
VkShaderStageFlags stageFlags;
deUint32 offset;
deUint32 size;
};
struct VkPipelineLayoutCreateInfo
{
VkStructureType sType;
const void* pNext;
VkPipelineLayoutCreateFlags flags;
deUint32 setLayoutCount;
const VkDescriptorSetLayout* pSetLayouts;
deUint32 pushConstantRangeCount;
const VkPushConstantRange* pPushConstantRanges;
};
struct VkSamplerCreateInfo
{
VkStructureType sType;
const void* pNext;
VkSamplerCreateFlags flags;
VkFilter magFilter;
VkFilter minFilter;
VkSamplerMipmapMode mipmapMode;
VkSamplerAddressMode addressModeU;
VkSamplerAddressMode addressModeV;
VkSamplerAddressMode addressModeW;
float mipLodBias;
VkBool32 anisotropyEnable;
float maxAnisotropy;
VkBool32 compareEnable;
VkCompareOp compareOp;
float minLod;
float maxLod;
VkBorderColor borderColor;
VkBool32 unnormalizedCoordinates;
};
struct VkDescriptorSetLayoutBinding
{
deUint32 binding;
VkDescriptorType descriptorType;
deUint32 descriptorCount;
VkShaderStageFlags stageFlags;
const VkSampler* pImmutableSamplers;
};
struct VkDescriptorSetLayoutCreateInfo
{
VkStructureType sType;
const void* pNext;
VkDescriptorSetLayoutCreateFlags flags;
deUint32 bindingCount;
const VkDescriptorSetLayoutBinding* pBindings;
};
struct VkDescriptorPoolSize
{
VkDescriptorType type;
deUint32 descriptorCount;
};
struct VkDescriptorPoolCreateInfo
{
VkStructureType sType;
const void* pNext;
VkDescriptorPoolCreateFlags flags;
deUint32 maxSets;
deUint32 poolSizeCount;
const VkDescriptorPoolSize* pPoolSizes;
};
struct VkDescriptorSetAllocateInfo
{
VkStructureType sType;
const void* pNext;
VkDescriptorPool descriptorPool;
deUint32 descriptorSetCount;
const VkDescriptorSetLayout* pSetLayouts;
};
struct VkDescriptorImageInfo
{
VkSampler sampler;
VkImageView imageView;
VkImageLayout imageLayout;
};
struct VkDescriptorBufferInfo
{
VkBuffer buffer;
VkDeviceSize offset;
VkDeviceSize range;
};
struct VkWriteDescriptorSet
{
VkStructureType sType;
const void* pNext;
VkDescriptorSet dstSet;
deUint32 dstBinding;
deUint32 dstArrayElement;
deUint32 descriptorCount;
VkDescriptorType descriptorType;
const VkDescriptorImageInfo* pImageInfo;
const VkDescriptorBufferInfo* pBufferInfo;
const VkBufferView* pTexelBufferView;
};
struct VkCopyDescriptorSet
{
VkStructureType sType;
const void* pNext;
VkDescriptorSet srcSet;
deUint32 srcBinding;
deUint32 srcArrayElement;
VkDescriptorSet dstSet;
deUint32 dstBinding;
deUint32 dstArrayElement;
deUint32 descriptorCount;
};
struct VkFramebufferCreateInfo
{
VkStructureType sType;
const void* pNext;
VkFramebufferCreateFlags flags;
VkRenderPass renderPass;
deUint32 attachmentCount;
const VkImageView* pAttachments;
deUint32 width;
deUint32 height;
deUint32 layers;
};
struct VkAttachmentDescription
{
VkAttachmentDescriptionFlags flags;
VkFormat format;
VkSampleCountFlagBits samples;
VkAttachmentLoadOp loadOp;
VkAttachmentStoreOp storeOp;
VkAttachmentLoadOp stencilLoadOp;
VkAttachmentStoreOp stencilStoreOp;
VkImageLayout initialLayout;
VkImageLayout finalLayout;
};
struct VkAttachmentReference
{
deUint32 attachment;
VkImageLayout layout;
};
struct VkSubpassDescription
{
VkSubpassDescriptionFlags flags;
VkPipelineBindPoint pipelineBindPoint;
deUint32 inputAttachmentCount;
const VkAttachmentReference* pInputAttachments;
deUint32 colorAttachmentCount;
const VkAttachmentReference* pColorAttachments;
const VkAttachmentReference* pResolveAttachments;
const VkAttachmentReference* pDepthStencilAttachment;
deUint32 preserveAttachmentCount;
const deUint32* pPreserveAttachments;
};
struct VkSubpassDependency
{
deUint32 srcSubpass;
deUint32 dstSubpass;
VkPipelineStageFlags srcStageMask;
VkPipelineStageFlags dstStageMask;
VkAccessFlags srcAccessMask;
VkAccessFlags dstAccessMask;
VkDependencyFlags dependencyFlags;
};
struct VkRenderPassCreateInfo
{
VkStructureType sType;
const void* pNext;
VkRenderPassCreateFlags flags;
deUint32 attachmentCount;
const VkAttachmentDescription* pAttachments;
deUint32 subpassCount;
const VkSubpassDescription* pSubpasses;
deUint32 dependencyCount;
const VkSubpassDependency* pDependencies;
};
struct VkCommandPoolCreateInfo
{
VkStructureType sType;
const void* pNext;
VkCommandPoolCreateFlags flags;
deUint32 queueFamilyIndex;
};
struct VkCommandBufferAllocateInfo
{
VkStructureType sType;
const void* pNext;
VkCommandPool commandPool;
VkCommandBufferLevel level;
deUint32 commandBufferCount;
};
struct VkCommandBufferInheritanceInfo
{
VkStructureType sType;
const void* pNext;
VkRenderPass renderPass;
deUint32 subpass;
VkFramebuffer framebuffer;
VkBool32 occlusionQueryEnable;
VkQueryControlFlags queryFlags;
VkQueryPipelineStatisticFlags pipelineStatistics;
};
struct VkCommandBufferBeginInfo
{
VkStructureType sType;
const void* pNext;
VkCommandBufferUsageFlags flags;
const VkCommandBufferInheritanceInfo* pInheritanceInfo;
};
struct VkBufferCopy
{
VkDeviceSize srcOffset;
VkDeviceSize dstOffset;
VkDeviceSize size;
};
struct VkImageSubresourceLayers
{
VkImageAspectFlags aspectMask;
deUint32 mipLevel;
deUint32 baseArrayLayer;
deUint32 layerCount;
};
struct VkImageCopy
{
VkImageSubresourceLayers srcSubresource;
VkOffset3D srcOffset;
VkImageSubresourceLayers dstSubresource;
VkOffset3D dstOffset;
VkExtent3D extent;
};
struct VkImageBlit
{
VkImageSubresourceLayers srcSubresource;
VkOffset3D srcOffsets[2];
VkImageSubresourceLayers dstSubresource;
VkOffset3D dstOffsets[2];
};
struct VkBufferImageCopy
{
VkDeviceSize bufferOffset;
deUint32 bufferRowLength;
deUint32 bufferImageHeight;
VkImageSubresourceLayers imageSubresource;
VkOffset3D imageOffset;
VkExtent3D imageExtent;
};
union VkClearColorValue
{
float float32[4];
deInt32 int32[4];
deUint32 uint32[4];
};
struct VkClearDepthStencilValue
{
float depth;
deUint32 stencil;
};
union VkClearValue
{
VkClearColorValue color;
VkClearDepthStencilValue depthStencil;
};
struct VkClearAttachment
{
VkImageAspectFlags aspectMask;
deUint32 colorAttachment;
VkClearValue clearValue;
};
struct VkClearRect
{
VkRect2D rect;
deUint32 baseArrayLayer;
deUint32 layerCount;
};
struct VkImageResolve
{
VkImageSubresourceLayers srcSubresource;
VkOffset3D srcOffset;
VkImageSubresourceLayers dstSubresource;
VkOffset3D dstOffset;
VkExtent3D extent;
};
struct VkMemoryBarrier
{
VkStructureType sType;
const void* pNext;
VkAccessFlags srcAccessMask;
VkAccessFlags dstAccessMask;
};
struct VkBufferMemoryBarrier
{
VkStructureType sType;
const void* pNext;
VkAccessFlags srcAccessMask;
VkAccessFlags dstAccessMask;
deUint32 srcQueueFamilyIndex;
deUint32 dstQueueFamilyIndex;
VkBuffer buffer;
VkDeviceSize offset;
VkDeviceSize size;
};
struct VkImageMemoryBarrier
{
VkStructureType sType;
const void* pNext;
VkAccessFlags srcAccessMask;
VkAccessFlags dstAccessMask;
VkImageLayout oldLayout;
VkImageLayout newLayout;
deUint32 srcQueueFamilyIndex;
deUint32 dstQueueFamilyIndex;
VkImage image;
VkImageSubresourceRange subresourceRange;
};
struct VkRenderPassBeginInfo
{
VkStructureType sType;
const void* pNext;
VkRenderPass renderPass;
VkFramebuffer framebuffer;
VkRect2D renderArea;
deUint32 clearValueCount;
const VkClearValue* pClearValues;
};
struct VkDispatchIndirectCommand
{
deUint32 x;
deUint32 y;
deUint32 z;
};
struct VkDrawIndexedIndirectCommand
{
deUint32 indexCount;
deUint32 instanceCount;
deUint32 firstIndex;
deInt32 vertexOffset;
deUint32 firstInstance;
};
struct VkDrawIndirectCommand
{
deUint32 vertexCount;
deUint32 instanceCount;
deUint32 firstVertex;
deUint32 firstInstance;
};
struct VkPhysicalDeviceSubgroupProperties
{
VkStructureType sType;
void* pNext;
deUint32 subgroupSize;
VkShaderStageFlags supportedStages;
VkSubgroupFeatureFlags supportedOperations;
VkBool32 quadOperationsInAllStages;
};
struct VkBindBufferMemoryInfo
{
VkStructureType sType;
const void* pNext;
VkBuffer buffer;
VkDeviceMemory memory;
VkDeviceSize memoryOffset;
};
struct VkBindImageMemoryInfo
{
VkStructureType sType;
const void* pNext;
VkImage image;
VkDeviceMemory memory;
VkDeviceSize memoryOffset;
};
struct VkPhysicalDevice8BitStorageFeaturesKHR
{
VkStructureType sType;
void* pNext;
VkBool32 storageBuffer8BitAccess;
VkBool32 uniformAndStorageBuffer8BitAccess;
VkBool32 storagePushConstant8;
};
struct VkPhysicalDevice16BitStorageFeatures
{
VkStructureType sType;
void* pNext;
VkBool32 storageBuffer16BitAccess;
VkBool32 uniformAndStorageBuffer16BitAccess;
VkBool32 storagePushConstant16;
VkBool32 storageInputOutput16;
};
struct VkMemoryDedicatedRequirements
{
VkStructureType sType;
void* pNext;
VkBool32 prefersDedicatedAllocation;
VkBool32 requiresDedicatedAllocation;
};
struct VkMemoryDedicatedAllocateInfo
{
VkStructureType sType;
const void* pNext;
VkImage image;
VkBuffer buffer;
};
struct VkMemoryAllocateFlagsInfo
{
VkStructureType sType;
const void* pNext;
VkMemoryAllocateFlags flags;
deUint32 deviceMask;
};
struct VkDeviceGroupRenderPassBeginInfo
{
VkStructureType sType;
const void* pNext;
deUint32 deviceMask;
deUint32 deviceRenderAreaCount;
const VkRect2D* pDeviceRenderAreas;
};
struct VkDeviceGroupCommandBufferBeginInfo
{
VkStructureType sType;
const void* pNext;
deUint32 deviceMask;
};
struct VkDeviceGroupSubmitInfo
{
VkStructureType sType;
const void* pNext;
deUint32 waitSemaphoreCount;
const deUint32* pWaitSemaphoreDeviceIndices;
deUint32 commandBufferCount;
const deUint32* pCommandBufferDeviceMasks;
deUint32 signalSemaphoreCount;
const deUint32* pSignalSemaphoreDeviceIndices;
};
struct VkDeviceGroupBindSparseInfo
{
VkStructureType sType;
const void* pNext;
deUint32 resourceDeviceIndex;
deUint32 memoryDeviceIndex;
};
struct VkBindBufferMemoryDeviceGroupInfo
{
VkStructureType sType;
const void* pNext;
deUint32 deviceIndexCount;
const deUint32* pDeviceIndices;
};
struct VkBindImageMemoryDeviceGroupInfo
{
VkStructureType sType;
const void* pNext;
deUint32 deviceIndexCount;
const deUint32* pDeviceIndices;
deUint32 SFRRectCount;
const VkRect2D* pSFRRects;
};
struct VkPhysicalDeviceGroupProperties
{
VkStructureType sType;
void* pNext;
deUint32 physicalDeviceCount;
VkPhysicalDevice physicalDevices[VK_MAX_DEVICE_GROUP_SIZE];
VkBool32 subsetAllocation;
};
struct VkDeviceGroupDeviceCreateInfo
{
VkStructureType sType;
const void* pNext;
deUint32 physicalDeviceCount;
const VkPhysicalDevice* pPhysicalDevices;
};
struct VkBufferMemoryRequirementsInfo2
{
VkStructureType sType;
const void* pNext;
VkBuffer buffer;
};
struct VkImageMemoryRequirementsInfo2
{
VkStructureType sType;
const void* pNext;
VkImage image;
};
struct VkImageSparseMemoryRequirementsInfo2
{
VkStructureType sType;
const void* pNext;
VkImage image;
};
struct VkMemoryRequirements2
{
VkStructureType sType;
void* pNext;
VkMemoryRequirements memoryRequirements;
};
struct VkSparseImageMemoryRequirements2
{
VkStructureType sType;
void* pNext;
VkSparseImageMemoryRequirements memoryRequirements;
};
struct VkPhysicalDeviceFeatures2
{
VkStructureType sType;
void* pNext;
VkPhysicalDeviceFeatures features;
};
struct VkPhysicalDeviceProperties2
{
VkStructureType sType;
void* pNext;
VkPhysicalDeviceProperties properties;
};
struct VkFormatProperties2
{
VkStructureType sType;
void* pNext;
VkFormatProperties formatProperties;
};
struct VkImageFormatProperties2
{
VkStructureType sType;
void* pNext;
VkImageFormatProperties imageFormatProperties;
};
struct VkPhysicalDeviceImageFormatInfo2
{
VkStructureType sType;
const void* pNext;
VkFormat format;
VkImageType type;
VkImageTiling tiling;
VkImageUsageFlags usage;
VkImageCreateFlags flags;
};
struct VkQueueFamilyProperties2
{
VkStructureType sType;
void* pNext;
VkQueueFamilyProperties queueFamilyProperties;
};
struct VkPhysicalDeviceMemoryProperties2
{
VkStructureType sType;
void* pNext;
VkPhysicalDeviceMemoryProperties memoryProperties;
};
struct VkSparseImageFormatProperties2
{
VkStructureType sType;
void* pNext;
VkSparseImageFormatProperties properties;
};
struct VkPhysicalDeviceSparseImageFormatInfo2
{
VkStructureType sType;
const void* pNext;
VkFormat format;
VkImageType type;
VkSampleCountFlagBits samples;
VkImageUsageFlags usage;
VkImageTiling tiling;
};
struct VkPhysicalDevicePointClippingProperties
{
VkStructureType sType;
void* pNext;
VkPointClippingBehavior pointClippingBehavior;
};
struct VkInputAttachmentAspectReference
{
deUint32 subpass;
deUint32 inputAttachmentIndex;
VkImageAspectFlags aspectMask;
};
struct VkRenderPassInputAttachmentAspectCreateInfo
{
VkStructureType sType;
const void* pNext;
deUint32 aspectReferenceCount;
const VkInputAttachmentAspectReference* pAspectReferences;
};
struct VkImageViewUsageCreateInfo
{
VkStructureType sType;
const void* pNext;
VkImageUsageFlags usage;
};
struct VkPipelineTessellationDomainOriginStateCreateInfo
{
VkStructureType sType;
const void* pNext;
VkTessellationDomainOrigin domainOrigin;
};
struct VkRenderPassMultiviewCreateInfo
{
VkStructureType sType;
const void* pNext;
deUint32 subpassCount;
const deUint32* pViewMasks;
deUint32 dependencyCount;
const deInt32* pViewOffsets;
deUint32 correlationMaskCount;
const deUint32* pCorrelationMasks;
};
struct VkPhysicalDeviceMultiviewFeatures
{
VkStructureType sType;
void* pNext;
VkBool32 multiview;
VkBool32 multiviewGeometryShader;
VkBool32 multiviewTessellationShader;
};
struct VkPhysicalDeviceMultiviewProperties
{
VkStructureType sType;
void* pNext;
deUint32 maxMultiviewViewCount;
deUint32 maxMultiviewInstanceIndex;
};
struct VkPhysicalDeviceVariablePointersFeatures
{
VkStructureType sType;
void* pNext;
VkBool32 variablePointersStorageBuffer;
VkBool32 variablePointers;
};
struct VkPhysicalDeviceProtectedMemoryFeatures
{
VkStructureType sType;
void* pNext;
VkBool32 protectedMemory;
};
struct VkPhysicalDeviceProtectedMemoryProperties
{
VkStructureType sType;
void* pNext;
VkBool32 protectedNoFault;
};
struct VkDeviceQueueInfo2
{
VkStructureType sType;
const void* pNext;
VkDeviceQueueCreateFlags flags;
deUint32 queueFamilyIndex;
deUint32 queueIndex;
};
struct VkProtectedSubmitInfo
{
VkStructureType sType;
const void* pNext;
VkBool32 protectedSubmit;
};
struct VkSamplerYcbcrConversionCreateInfo
{
VkStructureType sType;
const void* pNext;
VkFormat format;
VkSamplerYcbcrModelConversion ycbcrModel;
VkSamplerYcbcrRange ycbcrRange;
VkComponentMapping components;
VkChromaLocation xChromaOffset;
VkChromaLocation yChromaOffset;
VkFilter chromaFilter;
VkBool32 forceExplicitReconstruction;
};
struct VkSamplerYcbcrConversionInfo
{
VkStructureType sType;
const void* pNext;
VkSamplerYcbcrConversion conversion;
};
struct VkBindImagePlaneMemoryInfo
{
VkStructureType sType;
const void* pNext;
VkImageAspectFlagBits planeAspect;
};
struct VkImagePlaneMemoryRequirementsInfo
{
VkStructureType sType;
const void* pNext;
VkImageAspectFlagBits planeAspect;
};
struct VkPhysicalDeviceSamplerYcbcrConversionFeatures
{
VkStructureType sType;
void* pNext;
VkBool32 samplerYcbcrConversion;
};
struct VkSamplerYcbcrConversionImageFormatProperties
{
VkStructureType sType;
void* pNext;
deUint32 combinedImageSamplerDescriptorCount;
};
struct VkDescriptorUpdateTemplateEntry
{
deUint32 dstBinding;
deUint32 dstArrayElement;
deUint32 descriptorCount;
VkDescriptorType descriptorType;
deUintptr offset;
deUintptr stride;
};
struct VkDescriptorUpdateTemplateCreateInfo
{
VkStructureType sType;
void* pNext;
VkDescriptorUpdateTemplateCreateFlags flags;
deUint32 descriptorUpdateEntryCount;
const VkDescriptorUpdateTemplateEntry* pDescriptorUpdateEntries;
VkDescriptorUpdateTemplateType templateType;
VkDescriptorSetLayout descriptorSetLayout;
VkPipelineBindPoint pipelineBindPoint;
VkPipelineLayout pipelineLayout;
deUint32 set;
};
struct VkExternalMemoryProperties
{
VkExternalMemoryFeatureFlags externalMemoryFeatures;
VkExternalMemoryHandleTypeFlags exportFromImportedHandleTypes;
VkExternalMemoryHandleTypeFlags compatibleHandleTypes;
};
struct VkPhysicalDeviceExternalImageFormatInfo
{
VkStructureType sType;
const void* pNext;
VkExternalMemoryHandleTypeFlagBits handleType;
};
struct VkExternalImageFormatProperties
{
VkStructureType sType;
void* pNext;
VkExternalMemoryProperties externalMemoryProperties;
};
struct VkPhysicalDeviceExternalBufferInfo
{
VkStructureType sType;
const void* pNext;
VkBufferCreateFlags flags;
VkBufferUsageFlags usage;
VkExternalMemoryHandleTypeFlagBits handleType;
};
struct VkExternalBufferProperties
{
VkStructureType sType;
void* pNext;
VkExternalMemoryProperties externalMemoryProperties;
};
struct VkPhysicalDeviceIDProperties
{
VkStructureType sType;
void* pNext;
deUint8 deviceUUID[VK_UUID_SIZE];
deUint8 driverUUID[VK_UUID_SIZE];
deUint8 deviceLUID[VK_LUID_SIZE];
deUint32 deviceNodeMask;
VkBool32 deviceLUIDValid;
};
struct VkExternalMemoryImageCreateInfo
{
VkStructureType sType;
const void* pNext;
VkExternalMemoryHandleTypeFlags handleTypes;
};
struct VkExternalMemoryBufferCreateInfo
{
VkStructureType sType;
const void* pNext;
VkExternalMemoryHandleTypeFlags handleTypes;
};
struct VkExportMemoryAllocateInfo
{
VkStructureType sType;
const void* pNext;
VkExternalMemoryHandleTypeFlags handleTypes;
};
struct VkPhysicalDeviceExternalFenceInfo
{
VkStructureType sType;
const void* pNext;
VkExternalFenceHandleTypeFlagBits handleType;
};
struct VkExternalFenceProperties
{
VkStructureType sType;
void* pNext;
VkExternalFenceHandleTypeFlags exportFromImportedHandleTypes;
VkExternalFenceHandleTypeFlags compatibleHandleTypes;
VkExternalFenceFeatureFlags externalFenceFeatures;
};
struct VkExportFenceCreateInfo
{
VkStructureType sType;
const void* pNext;
VkExternalFenceHandleTypeFlags handleTypes;
};
struct VkExportSemaphoreCreateInfo
{
VkStructureType sType;
const void* pNext;
VkExternalSemaphoreHandleTypeFlags handleTypes;
};
struct VkPhysicalDeviceExternalSemaphoreInfo
{
VkStructureType sType;
const void* pNext;
VkExternalSemaphoreHandleTypeFlagBits handleType;
};
struct VkExternalSemaphoreProperties
{
VkStructureType sType;
void* pNext;
VkExternalSemaphoreHandleTypeFlags exportFromImportedHandleTypes;
VkExternalSemaphoreHandleTypeFlags compatibleHandleTypes;
VkExternalSemaphoreFeatureFlags externalSemaphoreFeatures;
};
struct VkPhysicalDeviceMaintenance3Properties
{
VkStructureType sType;
void* pNext;
deUint32 maxPerSetDescriptors;
VkDeviceSize maxMemoryAllocationSize;
};
struct VkDescriptorSetLayoutSupport
{
VkStructureType sType;
void* pNext;
VkBool32 supported;
};
struct VkPhysicalDeviceShaderDrawParametersFeatures
{
VkStructureType sType;
void* pNext;
VkBool32 shaderDrawParameters;
};
struct VkSurfaceCapabilitiesKHR
{
deUint32 minImageCount;
deUint32 maxImageCount;
VkExtent2D currentExtent;
VkExtent2D minImageExtent;
VkExtent2D maxImageExtent;
deUint32 maxImageArrayLayers;
VkSurfaceTransformFlagsKHR supportedTransforms;
VkSurfaceTransformFlagBitsKHR currentTransform;
VkCompositeAlphaFlagsKHR supportedCompositeAlpha;
VkImageUsageFlags supportedUsageFlags;
};
struct VkSurfaceFormatKHR
{
VkFormat format;
VkColorSpaceKHR colorSpace;
};
struct VkSwapchainCreateInfoKHR
{
VkStructureType sType;
const void* pNext;
VkSwapchainCreateFlagsKHR flags;
VkSurfaceKHR surface;
deUint32 minImageCount;
VkFormat imageFormat;
VkColorSpaceKHR imageColorSpace;
VkExtent2D imageExtent;
deUint32 imageArrayLayers;
VkImageUsageFlags imageUsage;
VkSharingMode imageSharingMode;
deUint32 queueFamilyIndexCount;
const deUint32* pQueueFamilyIndices;
VkSurfaceTransformFlagBitsKHR preTransform;
VkCompositeAlphaFlagBitsKHR compositeAlpha;
VkPresentModeKHR presentMode;
VkBool32 clipped;
VkSwapchainKHR oldSwapchain;
};
struct VkPresentInfoKHR
{
VkStructureType sType;
const void* pNext;
deUint32 waitSemaphoreCount;
const VkSemaphore* pWaitSemaphores;
deUint32 swapchainCount;
const VkSwapchainKHR* pSwapchains;
const deUint32* pImageIndices;
VkResult* pResults;
};
struct VkImageSwapchainCreateInfoKHR
{
VkStructureType sType;
const void* pNext;
VkSwapchainKHR swapchain;
};
struct VkBindImageMemorySwapchainInfoKHR
{
VkStructureType sType;
const void* pNext;
VkSwapchainKHR swapchain;
deUint32 imageIndex;
};
struct VkAcquireNextImageInfoKHR
{
VkStructureType sType;
const void* pNext;
VkSwapchainKHR swapchain;
deUint64 timeout;
VkSemaphore semaphore;
VkFence fence;
deUint32 deviceMask;
};
struct VkDeviceGroupPresentCapabilitiesKHR
{
VkStructureType sType;
const void* pNext;
deUint32 presentMask[VK_MAX_DEVICE_GROUP_SIZE];
VkDeviceGroupPresentModeFlagsKHR modes;
};
struct VkDeviceGroupPresentInfoKHR
{
VkStructureType sType;
const void* pNext;
deUint32 swapchainCount;
const deUint32* pDeviceMasks;
VkDeviceGroupPresentModeFlagBitsKHR mode;
};
struct VkDeviceGroupSwapchainCreateInfoKHR
{
VkStructureType sType;
const void* pNext;
VkDeviceGroupPresentModeFlagsKHR modes;
};
struct VkDisplayPropertiesKHR
{
VkDisplayKHR display;
const char* displayName;
VkExtent2D physicalDimensions;
VkExtent2D physicalResolution;
VkSurfaceTransformFlagsKHR supportedTransforms;
VkBool32 planeReorderPossible;
VkBool32 persistentContent;
};
struct VkDisplayModeParametersKHR
{
VkExtent2D visibleRegion;
deUint32 refreshRate;
};
struct VkDisplayModePropertiesKHR
{
VkDisplayModeKHR displayMode;
VkDisplayModeParametersKHR parameters;
};
struct VkDisplayModeCreateInfoKHR
{
VkStructureType sType;
const void* pNext;
VkDisplayModeCreateFlagsKHR flags;
VkDisplayModeParametersKHR parameters;
};
struct VkDisplayPlaneCapabilitiesKHR
{
VkDisplayPlaneAlphaFlagsKHR supportedAlpha;
VkOffset2D minSrcPosition;
VkOffset2D maxSrcPosition;
VkExtent2D minSrcExtent;
VkExtent2D maxSrcExtent;
VkOffset2D minDstPosition;
VkOffset2D maxDstPosition;
VkExtent2D minDstExtent;
VkExtent2D maxDstExtent;
};
struct VkDisplayPlanePropertiesKHR
{
VkDisplayKHR currentDisplay;
deUint32 currentStackIndex;
};
struct VkDisplaySurfaceCreateInfoKHR
{
VkStructureType sType;
const void* pNext;
VkDisplaySurfaceCreateFlagsKHR flags;
VkDisplayModeKHR displayMode;
deUint32 planeIndex;
deUint32 planeStackIndex;
VkSurfaceTransformFlagBitsKHR transform;
float globalAlpha;
VkDisplayPlaneAlphaFlagBitsKHR alphaMode;
VkExtent2D imageExtent;
};
struct VkDisplayPresentInfoKHR
{
VkStructureType sType;
const void* pNext;
VkRect2D srcRect;
VkRect2D dstRect;
VkBool32 persistent;
};
struct VkXlibSurfaceCreateInfoKHR
{
VkStructureType sType;
const void* pNext;
VkXlibSurfaceCreateFlagsKHR flags;
pt::XlibDisplayPtr dpy;
pt::XlibWindow window;
};
struct VkXcbSurfaceCreateInfoKHR
{
VkStructureType sType;
const void* pNext;
VkXcbSurfaceCreateFlagsKHR flags;
pt::XcbConnectionPtr connection;
pt::XcbWindow window;
};
struct VkWaylandSurfaceCreateInfoKHR
{
VkStructureType sType;
const void* pNext;
VkWaylandSurfaceCreateFlagsKHR flags;
pt::WaylandDisplayPtr display;
pt::WaylandSurfacePtr surface;
};
struct VkMirSurfaceCreateInfoKHR
{
VkStructureType sType;
const void* pNext;
VkMirSurfaceCreateFlagsKHR flags;
pt::MirConnectionPtr connection;
pt::MirSurfacePtr mirSurface;
};
struct VkAndroidSurfaceCreateInfoKHR
{
VkStructureType sType;
const void* pNext;
VkAndroidSurfaceCreateFlagsKHR flags;
pt::AndroidNativeWindowPtr window;
};
struct VkWin32SurfaceCreateInfoKHR
{
VkStructureType sType;
const void* pNext;
VkWin32SurfaceCreateFlagsKHR flags;
pt::Win32InstanceHandle hinstance;
pt::Win32WindowHandle hwnd;
};
struct VkImportMemoryWin32HandleInfoKHR
{
VkStructureType sType;
const void* pNext;
VkExternalMemoryHandleTypeFlagBits handleType;
pt::Win32Handle handle;
char* name;
};
struct VkExportMemoryWin32HandleInfoKHR
{
VkStructureType sType;
const void* pNext;
pt::Win32SecurityAttributesPtr pAttributes;
deUint32 dwAccess;
char* name;
};
struct VkMemoryWin32HandlePropertiesKHR
{
VkStructureType sType;
void* pNext;
deUint32 memoryTypeBits;
};
struct VkMemoryGetWin32HandleInfoKHR
{
VkStructureType sType;
const void* pNext;
VkDeviceMemory memory;
VkExternalMemoryHandleTypeFlagBits handleType;
};
struct VkImportMemoryFdInfoKHR
{
VkStructureType sType;
const void* pNext;
VkExternalMemoryHandleTypeFlagBits handleType;
int fd;
};
struct VkMemoryFdPropertiesKHR
{
VkStructureType sType;
void* pNext;
deUint32 memoryTypeBits;
};
struct VkMemoryGetFdInfoKHR
{
VkStructureType sType;
const void* pNext;
VkDeviceMemory memory;
VkExternalMemoryHandleTypeFlagBits handleType;
};
struct VkWin32KeyedMutexAcquireReleaseInfoKHR
{
VkStructureType sType;
const void* pNext;
deUint32 acquireCount;
const VkDeviceMemory* pAcquireSyncs;
const deUint64* pAcquireKeys;
const deUint32* pAcquireTimeouts;
deUint32 releaseCount;
const VkDeviceMemory* pReleaseSyncs;
const deUint64* pReleaseKeys;
};
struct VkImportSemaphoreWin32HandleInfoKHR
{
VkStructureType sType;
const void* pNext;
VkSemaphore semaphore;
VkSemaphoreImportFlags flags;
VkExternalSemaphoreHandleTypeFlagBits handleType;
pt::Win32Handle handle;
char* name;
};
struct VkExportSemaphoreWin32HandleInfoKHR
{
VkStructureType sType;
const void* pNext;
pt::Win32SecurityAttributesPtr pAttributes;
deUint32 dwAccess;
char* name;
};
struct VkD3D12FenceSubmitInfoKHR
{
VkStructureType sType;
const void* pNext;
deUint32 waitSemaphoreValuesCount;
const deUint64* pWaitSemaphoreValues;
deUint32 signalSemaphoreValuesCount;
const deUint64* pSignalSemaphoreValues;
};
struct VkSemaphoreGetWin32HandleInfoKHR
{
VkStructureType sType;
const void* pNext;
VkSemaphore semaphore;
VkExternalSemaphoreHandleTypeFlagBits handleType;
};
struct VkImportSemaphoreFdInfoKHR
{
VkStructureType sType;
const void* pNext;
VkSemaphore semaphore;
VkSemaphoreImportFlags flags;
VkExternalSemaphoreHandleTypeFlagBits handleType;
int fd;
};
struct VkSemaphoreGetFdInfoKHR
{
VkStructureType sType;
const void* pNext;
VkSemaphore semaphore;
VkExternalSemaphoreHandleTypeFlagBits handleType;
};
struct VkPhysicalDevicePushDescriptorPropertiesKHR
{
VkStructureType sType;
void* pNext;
deUint32 maxPushDescriptors;
};
struct VkPhysicalDeviceFloat16Int8FeaturesKHR
{
VkStructureType sType;
void* pNext;
VkBool32 shaderFloat16;
VkBool32 shaderInt8;
};
struct VkRectLayerKHR
{
VkOffset2D offset;
VkExtent2D extent;
deUint32 layer;
};
struct VkPresentRegionKHR
{
deUint32 rectangleCount;
const VkRectLayerKHR* pRectangles;
};
struct VkPresentRegionsKHR
{
VkStructureType sType;
const void* pNext;
deUint32 swapchainCount;
const VkPresentRegionKHR* pRegions;
};
struct VkAttachmentDescription2KHR
{
VkStructureType sType;
const void* pNext;
VkAttachmentDescriptionFlags flags;
VkFormat format;
VkSampleCountFlagBits samples;
VkAttachmentLoadOp loadOp;
VkAttachmentStoreOp storeOp;
VkAttachmentLoadOp stencilLoadOp;
VkAttachmentStoreOp stencilStoreOp;
VkImageLayout initialLayout;
VkImageLayout finalLayout;
};
struct VkAttachmentReference2KHR
{
VkStructureType sType;
const void* pNext;
deUint32 attachment;
VkImageLayout layout;
VkImageAspectFlags aspectMask;
};
struct VkSubpassDescription2KHR
{
VkStructureType sType;
const void* pNext;
VkSubpassDescriptionFlags flags;
VkPipelineBindPoint pipelineBindPoint;
deUint32 viewMask;
deUint32 inputAttachmentCount;
const VkAttachmentReference2KHR* pInputAttachments;
deUint32 colorAttachmentCount;
const VkAttachmentReference2KHR* pColorAttachments;
const VkAttachmentReference2KHR* pResolveAttachments;
const VkAttachmentReference2KHR* pDepthStencilAttachment;
deUint32 preserveAttachmentCount;
const deUint32* pPreserveAttachments;
};
struct VkSubpassDependency2KHR
{
VkStructureType sType;
const void* pNext;
deUint32 srcSubpass;
deUint32 dstSubpass;
VkPipelineStageFlags srcStageMask;
VkPipelineStageFlags dstStageMask;
VkAccessFlags srcAccessMask;
VkAccessFlags dstAccessMask;
VkDependencyFlags dependencyFlags;
deInt32 viewOffset;
};
struct VkRenderPassCreateInfo2KHR
{
VkStructureType sType;
const void* pNext;
VkRenderPassCreateFlags flags;
deUint32 attachmentCount;
const VkAttachmentDescription2KHR* pAttachments;
deUint32 subpassCount;
const VkSubpassDescription2KHR* pSubpasses;
deUint32 dependencyCount;
const VkSubpassDependency2KHR* pDependencies;
deUint32 correlatedViewMaskCount;
const deUint32* pCorrelatedViewMasks;
};
struct VkSubpassBeginInfoKHR
{
VkStructureType sType;
const void* pNext;
VkSubpassContents contents;
};
struct VkSubpassEndInfoKHR
{
VkStructureType sType;
const void* pNext;
};
struct VkSharedPresentSurfaceCapabilitiesKHR
{
VkStructureType sType;
void* pNext;
VkImageUsageFlags sharedPresentSupportedUsageFlags;
};
struct VkImportFenceWin32HandleInfoKHR
{
VkStructureType sType;
const void* pNext;
VkFence fence;
VkFenceImportFlags flags;
VkExternalFenceHandleTypeFlagBits handleType;
pt::Win32Handle handle;
char* name;
};
struct VkExportFenceWin32HandleInfoKHR
{
VkStructureType sType;
const void* pNext;
pt::Win32SecurityAttributesPtr pAttributes;
deUint32 dwAccess;
char* name;
};
struct VkFenceGetWin32HandleInfoKHR
{
VkStructureType sType;
const void* pNext;
VkFence fence;
VkExternalFenceHandleTypeFlagBits handleType;
};
struct VkImportFenceFdInfoKHR
{
VkStructureType sType;
const void* pNext;
VkFence fence;
VkFenceImportFlags flags;
VkExternalFenceHandleTypeFlagBits handleType;
int fd;
};
struct VkFenceGetFdInfoKHR
{
VkStructureType sType;
const void* pNext;
VkFence fence;
VkExternalFenceHandleTypeFlagBits handleType;
};
struct VkPhysicalDeviceSurfaceInfo2KHR
{
VkStructureType sType;
const void* pNext;
VkSurfaceKHR surface;
};
struct VkSurfaceCapabilities2KHR
{
VkStructureType sType;
void* pNext;
VkSurfaceCapabilitiesKHR surfaceCapabilities;
};
struct VkSurfaceFormat2KHR
{
VkStructureType sType;
void* pNext;
VkSurfaceFormatKHR surfaceFormat;
};
struct VkDisplayProperties2KHR
{
VkStructureType sType;
void* pNext;
VkDisplayPropertiesKHR displayProperties;
};
struct VkDisplayPlaneProperties2KHR
{
VkStructureType sType;
void* pNext;
VkDisplayPlanePropertiesKHR displayPlaneProperties;
};
struct VkDisplayModeProperties2KHR
{
VkStructureType sType;
void* pNext;
VkDisplayModePropertiesKHR displayModeProperties;
};
struct VkDisplayPlaneInfo2KHR
{
VkStructureType sType;
const void* pNext;
VkDisplayModeKHR mode;
deUint32 planeIndex;
};
struct VkDisplayPlaneCapabilities2KHR
{
VkStructureType sType;
void* pNext;
VkDisplayPlaneCapabilitiesKHR capabilities;
};
struct VkImageFormatListCreateInfoKHR
{
VkStructureType sType;
const void* pNext;
deUint32 viewFormatCount;
const VkFormat* pViewFormats;
};
struct VkConformanceVersionKHR
{
deUint8 major;
deUint8 minor;
deUint8 subminor;
deUint8 patch;
};
struct VkPhysicalDeviceDriverPropertiesKHR
{
VkStructureType sType;
void* pNext;
deUint32 driverID;
char driverName[VK_MAX_DRIVER_NAME_SIZE_KHR];
char driverInfo[VK_MAX_DRIVER_INFO_SIZE_KHR];
VkConformanceVersionKHR conformanceVersion;
};
struct VkPhysicalDeviceFloatControlsPropertiesKHR
{
VkStructureType sType;
void* pNext;
VkBool32 separateDenormSettings;
VkBool32 separateRoundingModeSettings;
VkBool32 shaderSignedZeroInfNanPreserveFloat16;
VkBool32 shaderSignedZeroInfNanPreserveFloat32;
VkBool32 shaderSignedZeroInfNanPreserveFloat64;
VkBool32 shaderDenormPreserveFloat16;
VkBool32 shaderDenormPreserveFloat32;
VkBool32 shaderDenormPreserveFloat64;
VkBool32 shaderDenormFlushToZeroFloat16;
VkBool32 shaderDenormFlushToZeroFloat32;
VkBool32 shaderDenormFlushToZeroFloat64;
VkBool32 shaderRoundingModeRTEFloat16;
VkBool32 shaderRoundingModeRTEFloat32;
VkBool32 shaderRoundingModeRTEFloat64;
VkBool32 shaderRoundingModeRTZFloat16;
VkBool32 shaderRoundingModeRTZFloat32;
VkBool32 shaderRoundingModeRTZFloat64;
};
struct VkSubpassDescriptionDepthStencilResolveKHR
{
VkStructureType sType;
const void* pNext;
VkResolveModeFlagBitsKHR depthResolveMode;
VkResolveModeFlagBitsKHR stencilResolveMode;
const VkAttachmentReference2KHR* pDepthStencilResolveAttachment;
};
struct VkPhysicalDeviceDepthStencilResolvePropertiesKHR
{
VkStructureType sType;
void* pNext;
VkResolveModeFlagsKHR supportedDepthResolveModes;
VkResolveModeFlagsKHR supportedStencilResolveModes;
VkBool32 independentResolveNone;
VkBool32 independentResolve;
};
struct VkSurfaceProtectedCapabilitiesKHR
{
VkStructureType sType;
const void* pNext;
VkBool32 supportsProtected;
};
struct VkDebugReportCallbackCreateInfoEXT
{
VkStructureType sType;
const void* pNext;
VkDebugReportFlagsEXT flags;
PFN_vkDebugReportCallbackEXT pfnCallback;
void* pUserData;
};
struct VkPipelineRasterizationStateRasterizationOrderAMD
{
VkStructureType sType;
const void* pNext;
VkRasterizationOrderAMD rasterizationOrder;
};
struct VkDebugMarkerObjectNameInfoEXT
{
VkStructureType sType;
const void* pNext;
VkDebugReportObjectTypeEXT objectType;
deUint64 object;
const char* pObjectName;
};
struct VkDebugMarkerObjectTagInfoEXT
{
VkStructureType sType;
const void* pNext;
VkDebugReportObjectTypeEXT objectType;
deUint64 object;
deUint64 tagName;
deUintptr tagSize;
const void* pTag;
};
struct VkDebugMarkerMarkerInfoEXT
{
VkStructureType sType;
const void* pNext;
const char* pMarkerName;
float color[4];
};
struct VkDedicatedAllocationImageCreateInfoNV
{
VkStructureType sType;
const void* pNext;
VkBool32 dedicatedAllocation;
};
struct VkDedicatedAllocationBufferCreateInfoNV
{
VkStructureType sType;
const void* pNext;
VkBool32 dedicatedAllocation;
};
struct VkDedicatedAllocationMemoryAllocateInfoNV
{
VkStructureType sType;
const void* pNext;
VkImage image;
VkBuffer buffer;
};
struct VkPhysicalDeviceTransformFeedbackFeaturesEXT
{
VkStructureType sType;
void* pNext;
VkBool32 transformFeedback;
VkBool32 geometryStreams;
};
struct VkPhysicalDeviceTransformFeedbackPropertiesEXT
{
VkStructureType sType;
void* pNext;
deUint32 maxTransformFeedbackStreams;
deUint32 maxTransformFeedbackBuffers;
VkDeviceSize maxTransformFeedbackBufferSize;
deUint32 maxTransformFeedbackStreamDataSize;
deUint32 maxTransformFeedbackBufferDataSize;
deUint32 maxTransformFeedbackBufferDataStride;
VkBool32 transformFeedbackQueries;
VkBool32 transformFeedbackStreamsLinesTriangles;
VkBool32 transformFeedbackRasterizationStreamSelect;
VkBool32 transformFeedbackDraw;
};
struct VkPipelineRasterizationStateStreamCreateInfoEXT
{
VkStructureType sType;
const void* pNext;
VkPipelineRasterizationStateStreamCreateFlagsEXT flags;
deUint32 rasterizationStream;
};
struct VkTextureLODGatherFormatPropertiesAMD
{
VkStructureType sType;
void* pNext;
VkBool32 supportsTextureGatherLODBiasAMD;
};
struct VkExternalImageFormatPropertiesNV
{
VkImageFormatProperties imageFormatProperties;
VkExternalMemoryFeatureFlagsNV externalMemoryFeatures;
VkExternalMemoryHandleTypeFlagsNV exportFromImportedHandleTypes;
VkExternalMemoryHandleTypeFlagsNV compatibleHandleTypes;
};
struct VkExternalMemoryImageCreateInfoNV
{
VkStructureType sType;
const void* pNext;
VkExternalMemoryHandleTypeFlagsNV handleTypes;
};
struct VkExportMemoryAllocateInfoNV
{
VkStructureType sType;
const void* pNext;
VkExternalMemoryHandleTypeFlagsNV handleTypes;
};
struct VkImportMemoryWin32HandleInfoNV
{
VkStructureType sType;
const void* pNext;
VkExternalMemoryHandleTypeFlagsNV handleType;
pt::Win32Handle handle;
};
struct VkExportMemoryWin32HandleInfoNV
{
VkStructureType sType;
const void* pNext;
pt::Win32SecurityAttributesPtr pAttributes;
deUint32 dwAccess;
};
struct VkWin32KeyedMutexAcquireReleaseInfoNV
{
VkStructureType sType;
const void* pNext;
deUint32 acquireCount;
const VkDeviceMemory* pAcquireSyncs;
const deUint64* pAcquireKeys;
const deUint32* pAcquireTimeoutMilliseconds;
deUint32 releaseCount;
const VkDeviceMemory* pReleaseSyncs;
const deUint64* pReleaseKeys;
};
struct VkValidationFlagsEXT
{
VkStructureType sType;
const void* pNext;
deUint32 disabledValidationCheckCount;
VkValidationCheckEXT* pDisabledValidationChecks;
};
struct VkViSurfaceCreateInfoNN
{
VkStructureType sType;
const void* pNext;
VkViSurfaceCreateFlagsNN flags;
void* window;
};
struct VkConditionalRenderingBeginInfoEXT
{
VkStructureType sType;
const void* pNext;
VkBuffer buffer;
VkDeviceSize offset;
VkConditionalRenderingFlagsEXT flags;
};
struct VkPhysicalDeviceConditionalRenderingFeaturesEXT
{
VkStructureType sType;
void* pNext;
VkBool32 conditionalRendering;
VkBool32 inheritedConditionalRendering;
};
struct VkCommandBufferInheritanceConditionalRenderingInfoEXT
{
VkStructureType sType;
const void* pNext;
VkBool32 conditionalRenderingEnable;
};
struct VkDeviceGeneratedCommandsFeaturesNVX
{
VkStructureType sType;
const void* pNext;
VkBool32 computeBindingPointSupport;
};
struct VkDeviceGeneratedCommandsLimitsNVX
{
VkStructureType sType;
const void* pNext;
deUint32 maxIndirectCommandsLayoutTokenCount;
deUint32 maxObjectEntryCounts;
deUint32 minSequenceCountBufferOffsetAlignment;
deUint32 minSequenceIndexBufferOffsetAlignment;
deUint32 minCommandsTokenBufferOffsetAlignment;
};
struct VkIndirectCommandsTokenNVX
{
VkIndirectCommandsTokenTypeNVX tokenType;
VkBuffer buffer;
VkDeviceSize offset;
};
struct VkIndirectCommandsLayoutTokenNVX
{
VkIndirectCommandsTokenTypeNVX tokenType;
deUint32 bindingUnit;
deUint32 dynamicCount;
deUint32 divisor;
};
struct VkIndirectCommandsLayoutCreateInfoNVX
{
VkStructureType sType;
const void* pNext;
VkPipelineBindPoint pipelineBindPoint;
VkIndirectCommandsLayoutUsageFlagsNVX flags;
deUint32 tokenCount;
const VkIndirectCommandsLayoutTokenNVX* pTokens;
};
struct VkCmdProcessCommandsInfoNVX
{
VkStructureType sType;
const void* pNext;
VkObjectTableNVX objectTable;
VkIndirectCommandsLayoutNVX indirectCommandsLayout;
deUint32 indirectCommandsTokenCount;
const VkIndirectCommandsTokenNVX* pIndirectCommandsTokens;
deUint32 maxSequencesCount;
VkCommandBuffer targetCommandBuffer;
VkBuffer sequencesCountBuffer;
VkDeviceSize sequencesCountOffset;
VkBuffer sequencesIndexBuffer;
VkDeviceSize sequencesIndexOffset;
};
struct VkCmdReserveSpaceForCommandsInfoNVX
{
VkStructureType sType;
const void* pNext;
VkObjectTableNVX objectTable;
VkIndirectCommandsLayoutNVX indirectCommandsLayout;
deUint32 maxSequencesCount;
};
struct VkObjectTableCreateInfoNVX
{
VkStructureType sType;
const void* pNext;
deUint32 objectCount;
const VkObjectEntryTypeNVX* pObjectEntryTypes;
const deUint32* pObjectEntryCounts;
const VkObjectEntryUsageFlagsNVX* pObjectEntryUsageFlags;
deUint32 maxUniformBuffersPerDescriptor;
deUint32 maxStorageBuffersPerDescriptor;
deUint32 maxStorageImagesPerDescriptor;
deUint32 maxSampledImagesPerDescriptor;
deUint32 maxPipelineLayouts;
};
struct VkObjectTableEntryNVX
{
VkObjectEntryTypeNVX type;
VkObjectEntryUsageFlagsNVX flags;
};
struct VkObjectTablePipelineEntryNVX
{
VkObjectEntryTypeNVX type;
VkObjectEntryUsageFlagsNVX flags;
VkPipeline pipeline;
};
struct VkObjectTableDescriptorSetEntryNVX
{
VkObjectEntryTypeNVX type;
VkObjectEntryUsageFlagsNVX flags;
VkPipelineLayout pipelineLayout;
VkDescriptorSet descriptorSet;
};
struct VkObjectTableVertexBufferEntryNVX
{
VkObjectEntryTypeNVX type;
VkObjectEntryUsageFlagsNVX flags;
VkBuffer buffer;
};
struct VkObjectTableIndexBufferEntryNVX
{
VkObjectEntryTypeNVX type;
VkObjectEntryUsageFlagsNVX flags;
VkBuffer buffer;
VkIndexType indexType;
};
struct VkObjectTablePushConstantEntryNVX
{
VkObjectEntryTypeNVX type;
VkObjectEntryUsageFlagsNVX flags;
VkPipelineLayout pipelineLayout;
VkShaderStageFlags stageFlags;
};
struct VkViewportWScalingNV
{
float xcoeff;
float ycoeff;
};
struct VkPipelineViewportWScalingStateCreateInfoNV
{
VkStructureType sType;
const void* pNext;
VkBool32 viewportWScalingEnable;
deUint32 viewportCount;
const VkViewportWScalingNV* pViewportWScalings;
};
struct VkSurfaceCapabilities2EXT
{
VkStructureType sType;
void* pNext;
deUint32 minImageCount;
deUint32 maxImageCount;
VkExtent2D currentExtent;
VkExtent2D minImageExtent;
VkExtent2D maxImageExtent;
deUint32 maxImageArrayLayers;
VkSurfaceTransformFlagsKHR supportedTransforms;
VkSurfaceTransformFlagBitsKHR currentTransform;
VkCompositeAlphaFlagsKHR supportedCompositeAlpha;
VkImageUsageFlags supportedUsageFlags;
VkSurfaceCounterFlagsEXT supportedSurfaceCounters;
};
struct VkDisplayPowerInfoEXT
{
VkStructureType sType;
const void* pNext;
VkDisplayPowerStateEXT powerState;
};
struct VkDeviceEventInfoEXT
{
VkStructureType sType;
const void* pNext;
VkDeviceEventTypeEXT deviceEvent;
};
struct VkDisplayEventInfoEXT
{
VkStructureType sType;
const void* pNext;
VkDisplayEventTypeEXT displayEvent;
};
struct VkSwapchainCounterCreateInfoEXT
{
VkStructureType sType;
const void* pNext;
VkSurfaceCounterFlagsEXT surfaceCounters;
};
struct VkRefreshCycleDurationGOOGLE
{
deUint64 refreshDuration;
};
struct VkPastPresentationTimingGOOGLE
{
deUint32 presentID;
deUint64 desiredPresentTime;
deUint64 actualPresentTime;
deUint64 earliestPresentTime;
deUint64 presentMargin;
};
struct VkPresentTimeGOOGLE
{
deUint32 presentID;
deUint64 desiredPresentTime;
};
struct VkPresentTimesInfoGOOGLE
{
VkStructureType sType;
const void* pNext;
deUint32 swapchainCount;
const VkPresentTimeGOOGLE* pTimes;
};
struct VkPhysicalDeviceMultiviewPerViewAttributesPropertiesNVX
{
VkStructureType sType;
void* pNext;
VkBool32 perViewPositionAllComponents;
};
struct VkViewportSwizzleNV
{
VkViewportCoordinateSwizzleNV x;
VkViewportCoordinateSwizzleNV y;
VkViewportCoordinateSwizzleNV z;
VkViewportCoordinateSwizzleNV w;
};
struct VkPipelineViewportSwizzleStateCreateInfoNV
{
VkStructureType sType;
const void* pNext;
VkPipelineViewportSwizzleStateCreateFlagsNV flags;
deUint32 viewportCount;
const VkViewportSwizzleNV* pViewportSwizzles;
};
struct VkPhysicalDeviceDiscardRectanglePropertiesEXT
{
VkStructureType sType;
void* pNext;
deUint32 maxDiscardRectangles;
};
struct VkPipelineDiscardRectangleStateCreateInfoEXT
{
VkStructureType sType;
const void* pNext;
VkPipelineDiscardRectangleStateCreateFlagsEXT flags;
VkDiscardRectangleModeEXT discardRectangleMode;
deUint32 discardRectangleCount;
const VkRect2D* pDiscardRectangles;
};
struct VkXYColorEXT
{
float x;
float y;
};
struct VkHdrMetadataEXT
{
VkStructureType sType;
const void* pNext;
VkXYColorEXT displayPrimaryRed;
VkXYColorEXT displayPrimaryGreen;
VkXYColorEXT displayPrimaryBlue;
VkXYColorEXT whitePoint;
float maxLuminance;
float minLuminance;
float maxContentLightLevel;
float maxFrameAverageLightLevel;
};
struct VkIOSSurfaceCreateInfoMVK
{
VkStructureType sType;
const void* pNext;
VkIOSSurfaceCreateFlagsMVK flags;
const void* pView;
};
struct VkMacOSSurfaceCreateInfoMVK
{
VkStructureType sType;
const void* pNext;
VkMacOSSurfaceCreateFlagsMVK flags;
const void* pView;
};
struct VkSamplerReductionModeCreateInfoEXT
{
VkStructureType sType;
const void* pNext;
VkSamplerReductionModeEXT reductionMode;
};
struct VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT
{
VkStructureType sType;
void* pNext;
VkBool32 filterMinmaxSingleComponentFormats;
VkBool32 filterMinmaxImageComponentMapping;
};
struct VkSampleLocationEXT
{
float x;
float y;
};
struct VkSampleLocationsInfoEXT
{
VkStructureType sType;
const void* pNext;
VkSampleCountFlagBits sampleLocationsPerPixel;
VkExtent2D sampleLocationGridSize;
deUint32 sampleLocationsCount;
const VkSampleLocationEXT* pSampleLocations;
};
struct VkAttachmentSampleLocationsEXT
{
deUint32 attachmentIndex;
VkSampleLocationsInfoEXT sampleLocationsInfo;
};
struct VkSubpassSampleLocationsEXT
{
deUint32 subpassIndex;
VkSampleLocationsInfoEXT sampleLocationsInfo;
};
struct VkRenderPassSampleLocationsBeginInfoEXT
{
VkStructureType sType;
const void* pNext;
deUint32 attachmentInitialSampleLocationsCount;
const VkAttachmentSampleLocationsEXT* pAttachmentInitialSampleLocations;
deUint32 postSubpassSampleLocationsCount;
const VkSubpassSampleLocationsEXT* pSubpassSampleLocations;
};
struct VkPipelineSampleLocationsStateCreateInfoEXT
{
VkStructureType sType;
const void* pNext;
VkBool32 sampleLocationsEnable;
VkSampleLocationsInfoEXT sampleLocationsInfo;
};
struct VkPhysicalDeviceSampleLocationsPropertiesEXT
{
VkStructureType sType;
void* pNext;
VkSampleCountFlags sampleLocationSampleCounts;
VkExtent2D maxSampleLocationGridSize;
float sampleLocationCoordinateRange[2];
deUint32 sampleLocationSubPixelBits;
VkBool32 variableSampleLocations;
};
struct VkMultisamplePropertiesEXT
{
VkStructureType sType;
void* pNext;
VkExtent2D maxSampleLocationGridSize;
};
struct VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT
{
VkStructureType sType;
void* pNext;
VkBool32 advancedBlendCoherentOperations;
};
struct VkPhysicalDeviceBlendOperationAdvancedPropertiesEXT
{
VkStructureType sType;
void* pNext;
deUint32 advancedBlendMaxColorAttachments;
VkBool32 advancedBlendIndependentBlend;
VkBool32 advancedBlendNonPremultipliedSrcColor;
VkBool32 advancedBlendNonPremultipliedDstColor;
VkBool32 advancedBlendCorrelatedOverlap;
VkBool32 advancedBlendAllOperations;
};
struct VkPipelineColorBlendAdvancedStateCreateInfoEXT
{
VkStructureType sType;
const void* pNext;
VkBool32 srcPremultiplied;
VkBool32 dstPremultiplied;
VkBlendOverlapEXT blendOverlap;
};
struct VkPipelineCoverageToColorStateCreateInfoNV
{
VkStructureType sType;
const void* pNext;
VkPipelineCoverageToColorStateCreateFlagsNV flags;
VkBool32 coverageToColorEnable;
deUint32 coverageToColorLocation;
};
struct VkPipelineCoverageModulationStateCreateInfoNV
{
VkStructureType sType;
const void* pNext;
VkPipelineCoverageModulationStateCreateFlagsNV flags;
VkCoverageModulationModeNV coverageModulationMode;
VkBool32 coverageModulationTableEnable;
deUint32 coverageModulationTableCount;
const float* pCoverageModulationTable;
};
struct VkValidationCacheCreateInfoEXT
{
VkStructureType sType;
const void* pNext;
VkValidationCacheCreateFlagsEXT flags;
deUintptr initialDataSize;
const void* pInitialData;
};
struct VkShaderModuleValidationCacheCreateInfoEXT
{
VkStructureType sType;
const void* pNext;
VkValidationCacheEXT validationCache;
};
struct VkAndroidHardwareBufferUsageANDROID
{
VkStructureType sType;
void* pNext;
deUint64 androidHardwareBufferUsage;
};
struct VkAndroidHardwareBufferPropertiesANDROID
{
VkStructureType sType;
void* pNext;
VkDeviceSize allocationSize;
deUint32 memoryTypeBits;
};
struct VkAndroidHardwareBufferFormatPropertiesANDROID
{
VkStructureType sType;
void* pNext;
VkFormat format;
deUint64 externalFormat;
VkFormatFeatureFlags formatFeatures;
VkComponentMapping samplerYcbcrConversionComponents;
VkSamplerYcbcrModelConversion suggestedYcbcrModel;
VkSamplerYcbcrRange suggestedYcbcrRange;
VkChromaLocation suggestedXChromaOffset;
VkChromaLocation suggestedYChromaOffset;
};
struct VkImportAndroidHardwareBufferInfoANDROID
{
VkStructureType sType;
const void* pNext;
struct pt::AndroidHardwareBufferPtr buffer;
};
struct VkMemoryGetAndroidHardwareBufferInfoANDROID
{
VkStructureType sType;
void* pNext;
VkDeviceMemory memory;
};
struct VkExternalFormatANDROID
{
VkStructureType sType;
void* pNext;
deUint64 externalFormat;
};
struct VkImportMemoryHostPointerInfoEXT
{
VkStructureType sType;
const void* pNext;
VkExternalMemoryHandleTypeFlagBits handleType;
void* pHostPointer;
};
struct VkMemoryHostPointerPropertiesEXT
{
VkStructureType sType;
void* pNext;
deUint32 memoryTypeBits;
};
struct VkPhysicalDeviceExternalMemoryHostPropertiesEXT
{
VkStructureType sType;
void* pNext;
VkDeviceSize minImportedHostPointerAlignment;
};
struct VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT
{
VkStructureType sType;
void* pNext;
deUint32 maxVertexAttribDivisor;
};
struct VkVertexInputBindingDivisorDescriptionEXT
{
deUint32 binding;
deUint32 divisor;
};
struct VkPipelineVertexInputDivisorStateCreateInfoEXT
{
VkStructureType sType;
const void* pNext;
deUint32 vertexBindingDivisorCount;
const VkVertexInputBindingDivisorDescriptionEXT* pVertexBindingDivisors;
};
struct VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT
{
VkStructureType sType;
void* pNext;
VkBool32 vertexAttributeInstanceRateDivisor;
VkBool32 vertexAttributeInstanceRateZeroDivisor;
};
struct VkDescriptorSetLayoutBindingFlagsCreateInfoEXT
{
VkStructureType sType;
const void* pNext;
deUint32 bindingCount;
const VkDescriptorBindingFlagsEXT* pBindingFlags;
};
struct VkPhysicalDeviceDescriptorIndexingFeaturesEXT
{
VkStructureType sType;
void* pNext;
VkBool32 shaderInputAttachmentArrayDynamicIndexing;
VkBool32 shaderUniformTexelBufferArrayDynamicIndexing;
VkBool32 shaderStorageTexelBufferArrayDynamicIndexing;
VkBool32 shaderUniformBufferArrayNonUniformIndexing;
VkBool32 shaderSampledImageArrayNonUniformIndexing;
VkBool32 shaderStorageBufferArrayNonUniformIndexing;
VkBool32 shaderStorageImageArrayNonUniformIndexing;
VkBool32 shaderInputAttachmentArrayNonUniformIndexing;
VkBool32 shaderUniformTexelBufferArrayNonUniformIndexing;
VkBool32 shaderStorageTexelBufferArrayNonUniformIndexing;
VkBool32 descriptorBindingUniformBufferUpdateAfterBind;
VkBool32 descriptorBindingSampledImageUpdateAfterBind;
VkBool32 descriptorBindingStorageImageUpdateAfterBind;
VkBool32 descriptorBindingStorageBufferUpdateAfterBind;
VkBool32 descriptorBindingUniformTexelBufferUpdateAfterBind;
VkBool32 descriptorBindingStorageTexelBufferUpdateAfterBind;
VkBool32 descriptorBindingUpdateUnusedWhilePending;
VkBool32 descriptorBindingPartiallyBound;
VkBool32 descriptorBindingVariableDescriptorCount;
VkBool32 runtimeDescriptorArray;
};
struct VkPhysicalDeviceDescriptorIndexingPropertiesEXT
{
VkStructureType sType;
void* pNext;
deUint32 maxUpdateAfterBindDescriptorsInAllPools;
VkBool32 shaderUniformBufferArrayNonUniformIndexingNative;
VkBool32 shaderSampledImageArrayNonUniformIndexingNative;
VkBool32 shaderStorageBufferArrayNonUniformIndexingNative;
VkBool32 shaderStorageImageArrayNonUniformIndexingNative;
VkBool32 shaderInputAttachmentArrayNonUniformIndexingNative;
VkBool32 robustBufferAccessUpdateAfterBind;
VkBool32 quadDivergentImplicitLod;
deUint32 maxPerStageDescriptorUpdateAfterBindSamplers;
deUint32 maxPerStageDescriptorUpdateAfterBindUniformBuffers;
deUint32 maxPerStageDescriptorUpdateAfterBindStorageBuffers;
deUint32 maxPerStageDescriptorUpdateAfterBindSampledImages;
deUint32 maxPerStageDescriptorUpdateAfterBindStorageImages;
deUint32 maxPerStageDescriptorUpdateAfterBindInputAttachments;
deUint32 maxPerStageUpdateAfterBindResources;
deUint32 maxDescriptorSetUpdateAfterBindSamplers;
deUint32 maxDescriptorSetUpdateAfterBindUniformBuffers;
deUint32 maxDescriptorSetUpdateAfterBindUniformBuffersDynamic;
deUint32 maxDescriptorSetUpdateAfterBindStorageBuffers;
deUint32 maxDescriptorSetUpdateAfterBindStorageBuffersDynamic;
deUint32 maxDescriptorSetUpdateAfterBindSampledImages;
deUint32 maxDescriptorSetUpdateAfterBindStorageImages;
deUint32 maxDescriptorSetUpdateAfterBindInputAttachments;
};
struct VkDescriptorSetVariableDescriptorCountAllocateInfoEXT
{
VkStructureType sType;
const void* pNext;
deUint32 descriptorSetCount;
const deUint32* pDescriptorCounts;
};
struct VkDescriptorSetVariableDescriptorCountLayoutSupportEXT
{
VkStructureType sType;
void* pNext;
deUint32 maxVariableDescriptorCount;
};
struct VkPhysicalDeviceInlineUniformBlockFeaturesEXT
{
VkStructureType sType;
void* pNext;
VkBool32 inlineUniformBlock;
VkBool32 descriptorBindingInlineUniformBlockUpdateAfterBind;
};
struct VkPhysicalDeviceInlineUniformBlockPropertiesEXT
{
VkStructureType sType;
void* pNext;
deUint32 maxInlineUniformBlockSize;
deUint32 maxPerStageDescriptorInlineUniformBlocks;
deUint32 maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks;
deUint32 maxDescriptorSetInlineUniformBlocks;
deUint32 maxDescriptorSetUpdateAfterBindInlineUniformBlocks;
};
struct VkWriteDescriptorSetInlineUniformBlockEXT
{
VkStructureType sType;
const void* pNext;
deUint32 dataSize;
const void* pData;
};
struct VkDescriptorPoolInlineUniformBlockCreateInfoEXT
{
VkStructureType sType;
const void* pNext;
deUint32 maxInlineUniformBlockBindings;
};
struct VkPhysicalDeviceShaderAtomicInt64FeaturesKHR
{
VkStructureType sType;
void* pNext;
VkBool32 shaderBufferInt64Atomics;
VkBool32 shaderSharedInt64Atomics;
};
struct VkPhysicalDeviceVulkanMemoryModelFeaturesKHR
{
VkStructureType sType;
void* pNext;
VkBool32 vulkanMemoryModel;
VkBool32 vulkanMemoryModelDeviceScope;
VkBool32 vulkanMemoryModelAvailabilityVisibilityChains;
};
struct VkPhysicalDeviceScalarBlockLayoutFeaturesEXT
{
VkStructureType sType;
void* pNext;
VkBool32 scalarBlockLayout;
};
struct VkPhysicalDeviceDepthClipEnableFeaturesEXT
{
VkStructureType sType;
void* pNext;
VkBool32 depthClipEnable;
};
struct VkPipelineRasterizationDepthClipStateCreateInfoEXT
{
VkStructureType sType;
const void* pNext;
VkPipelineRasterizationDepthClipStateCreateFlagsEXT flags;
VkBool32 depthClipEnable;
};
struct VkPhysicalDeviceBufferDeviceAddressFeaturesEXT
{
VkStructureType sType;
void* pNext;
VkBool32 bufferDeviceAddress;
VkBool32 bufferDeviceAddressCaptureReplay;
VkBool32 bufferDeviceAddressMultiDevice;
};
struct VkBufferDeviceAddressInfoEXT
{
VkStructureType sType;
const void* pNext;
VkBuffer buffer;
};
struct VkBufferDeviceAddressCreateInfoEXT
{
VkStructureType sType;
const void* pNext;
VkDeviceSize deviceAddress;
};
struct VkImageStencilUsageCreateInfoEXT
{
VkStructureType sType;
const void* pNext;
VkImageUsageFlags stencilUsage;
};
struct VkCooperativeMatrixPropertiesNV
{
VkStructureType sType;
void* pNext;
deUint32 MSize;
deUint32 NSize;
deUint32 KSize;
VkComponentTypeNV AType;
VkComponentTypeNV BType;
VkComponentTypeNV CType;
VkComponentTypeNV DType;
VkScopeNV scope;
};
struct VkPhysicalDeviceCooperativeMatrixPropertiesNV
{
VkStructureType sType;
void* pNext;
VkShaderStageFlags cooperativeMatrixSupportedStages;
};
struct VkPhysicalDeviceCooperativeMatrixFeaturesNV
{
VkStructureType sType;
void* pNext;
VkBool32 cooperativeMatrix;
VkBool32 cooperativeMatrixRobustBufferAccess;
};
struct VkPhysicalDeviceHostQueryResetFeaturesEXT
{
VkStructureType sType;
void* pNext;
VkBool32 hostQueryReset;
};
struct VkPhysicalDevicePCIBusInfoPropertiesEXT
{
VkStructureType sType;
void* pNext;
deUint32 pciDomain;
deUint32 pciBus;
deUint32 pciDevice;
deUint32 pciFunction;
};
struct VkPhysicalDeviceMemoryBudgetPropertiesEXT
{
VkStructureType sType;
void* pNext;
VkDeviceSize heapBudget[VK_MAX_MEMORY_HEAPS];
VkDeviceSize heapUsage[VK_MAX_MEMORY_HEAPS];
};
struct VkPhysicalDeviceMemoryPriorityFeaturesEXT
{
VkStructureType sType;
void* pNext;
VkBool32 memoryPriority;
};
struct VkMemoryPriorityAllocateInfoEXT
{
VkStructureType sType;
const void* pNext;
float priority;
};
struct VkPhysicalDeviceUniformBufferStandardLayoutFeaturesKHR
{
VkStructureType sType;
void* pNext;
VkBool32 uniformBufferStandardLayout;
};
struct VkPipelineCreationFeedbackEXT
{
VkPipelineCreationFeedbackFlagsEXT flags;
deUint64 duration;
};
struct VkPipelineCreationFeedbackCreateInfoEXT
{
VkStructureType sType;
const void* pNext;
VkPipelineCreationFeedbackEXT* pPipelineCreationFeedback;
deUint32 pipelineStageCreationFeedbackCount;
VkPipelineCreationFeedbackEXT* pPipelineStageCreationFeedbacks;
};
struct VkCalibratedTimestampInfoEXT
{
VkStructureType sType;
const void* pNext;
VkTimeDomainEXT timeDomain;
};
| [
"elix22@gmail.com"
] | elix22@gmail.com |
77e74c71b91ae41b55668349d87a6abc1a60c496 | 74d22b45e00527d6331dab77431e8e15d71e9e2c | /src/Sudoku.h | 4fa45737f60fb3e11c470875b2306d6b7e6d8e2a | [] | no_license | mviseu/Sudoku | 125ca10c2ebe5e7819403343223df07691d97ed0 | 5a156499ae0e3c10d1e92d49ad91aec0f083c125 | refs/heads/master | 2021-01-22T07:58:30.309119 | 2018-08-25T12:38:40 | 2018-08-25T12:38:40 | 92,592,223 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,160 | h | #pragma once
#include "Matrix.h"
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::ostream;
using std::vector;
class Sudoku {
private:
using v_int = vector<int>;
using vv_int = vector<vector<int>>;
public:
Sudoku() = default;
Sudoku(const vv_int &vv) : data(vv) {originalGrid = getOriginalPositions();}
const Sudoku &printSudoku() const;
Sudoku &printSudoku();
Sudoku &playOneMove();
bool isGameOver() const;
private:
Matrix data;
vector<Point> originalGrid;
vector<Point> getOriginalPositions() const;
void printRow(const v_int &row) const;
Sudoku &doPrintSudoku() const;
void readValidElementFromCin();
void readValidPositionFromCin();
Sudoku &readPositionAndElementFromCin();
bool isDuplicateInRow() const;
bool isDuplicateInColumn() const;
bool isDuplicateInSubSquare() const;
bool isDuplicateInRowOrColumnOrSubSquare() const;
bool isValueDuplicateOfCursorElement(int cursorIndex, v_int::const_iterator Beg, v_int::const_iterator iter) const;
bool isDuplicateInCursorVector(int cursorIndex, const vector<int> &v) const;
void warnDuplicateMove() const;
const short nrRows = 9;
};
| [
"mariaviseu@gmail.com"
] | mariaviseu@gmail.com |
0602c23745778e462ad8b1b83c968ffa468e327a | 84a04da079e1cbd120813de748e4aa3d97143601 | /ISurvivor.h | e62dee0efe3f41826554038d88565c01a582b941 | [] | no_license | Sylean92/Compsci_376_ZombieWar | db4f9602bafea12ef7eadc9674e792b879b9e77f | dd8cddc24a87a41cebdb3a14c2f4e57fb5c09d4b | refs/heads/master | 2021-01-13T09:22:44.328668 | 2016-10-17T02:36:47 | 2016-10-17T02:36:47 | 69,929,909 | 0 | 2 | null | 2016-10-15T17:28:52 | 2016-10-04T02:57:19 | C++ | UTF-8 | C++ | false | false | 475 | h | /*
* File: ISurvival.h
* Author: thaoc
*
* Created on May 20, 2015, 8:08 PM
*/
#ifndef ISURVIVOR_H
#define ISURVIVOR_H
#include "ICharacter.h"
#include "IZombie.h"
//#include "Child.h"
//#include "Teacher.h"
//#include "Soldier.h"
#include <string>
using namespace std;
class IZombie;
class ISurvivor:public ICharacter{
public:
virtual void attack(IZombie* zombie) = 0;
virtual string getName(); //function added by Lauren
};
#endif /* ISURVIVAL_H */
| [
"noreply@github.com"
] | Sylean92.noreply@github.com |
0285b31f67288962743a0df0b003f1877aef35f9 | 3e65ad1a906e7f6ab7831fbf01adc83d42b006ea | /string/isAnagram.cc | f03c71c47e63fafe622498e8f674f1820d4b8a6e | [] | no_license | yukimura1330/leetcode | c0fd0b696529f8f37ff9d82da8a3e6475ad6ead1 | 1d70ab4a7038b79df04d487c658cd8f15efc4a42 | refs/heads/master | 2021-01-19T14:25:34.008890 | 2020-02-22T14:00:36 | 2020-02-22T14:00:36 | 88,161,461 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 905 | cc | /*
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。
输入: s = "anagram", t = "nagaram"
输出: true
输入: s = "rat", t = "car"
输出: false
*/
#include <iostream>
#include <string>
using namespace std;
bool isAnagram(string s, string t) {
int index = 0;
int bucket[26];
int len1 = s.length();
int len2 = t.length();
if(len1 != len2) {
return false;
}
memset(bucket, 0, sizeof(bucket));
for(int i = 0; i < len1; i++) {
index = s[i] - 'a';
bucket[index] += 1;
index = t[i] - 'a';
bucket[index] -= 1;
}
for(int i = 0; i < 26; i++) {
if(bucket[i] != 0) {
return false;
}
}
return true;
}
int main() {
string s1 = "rat";
string s2 = "cat";
cout << "isAnagram is " << isAnagram(s1, s2) << endl;
return 0;
} | [
"1012872869@qq.com"
] | 1012872869@qq.com |
a75d062b673b8f5de4a581e89a9ed55cf4d7ad07 | 8134e49b7c40c1a489de2cd4e7b8855f328b0fac | /bvm/Shaders/fuddle/contract.h | d0228956171102e5790e8a5bbd2b04ec3388b79e | [
"Apache-2.0"
] | permissive | BeamMW/beam | 3efa193b22965397da26c1af2aebb2c045194d4d | 956a71ad4fedc5130cbbbced4359d38534f8a7a5 | refs/heads/master | 2023-09-01T12:00:09.204471 | 2023-08-31T09:22:40 | 2023-08-31T09:22:40 | 125,412,400 | 671 | 233 | Apache-2.0 | 2023-08-18T12:47:41 | 2018-03-15T18:49:06 | C++ | UTF-8 | C++ | false | false | 2,808 | h | #pragma once
namespace Fuddle
{
static const ShaderID s_SID = { 0x14,0x7b,0xf6,0x72,0xc2,0x26,0x21,0x39,0x9d,0xd4,0x9f,0x97,0x63,0x01,0xf5,0x63,0xaf,0x95,0x3a,0xca,0x49,0x25,0x1f,0x19,0xa8,0x64,0x4e,0x9d,0x44,0x2f,0x78,0x3f };
#pragma pack (push, 1)
struct Tags
{
static const uint8_t s_Global = 2;
static const uint8_t s_Payout = 3;
static const uint8_t s_Letter = 4;
static const uint8_t s_Goal = 5;
};
struct AmountWithAsset {
Amount m_Amount;
AssetID m_Aid;
};
struct Payout
{
struct Key
{
uint8_t m_Tag = Tags::s_Payout;
PubKey m_pkUser;
AssetID m_Aid;
};
Amount m_Amount;
};
struct Letter
{
typedef uint32_t Char;
struct Key
{
uint8_t m_Tag = Tags::s_Letter;
struct Raw {
PubKey m_pkUser;
Char m_Char;
} m_Raw;
};
uint32_t m_Count;
AmountWithAsset m_Price;
};
struct Goal
{
typedef uint32_t ID;
struct Key
{
uint8_t m_Tag = Tags::s_Goal;
ID m_ID;
};
static const uint32_t s_MaxLen = 256;
AmountWithAsset m_Prize;
// followed by Chars
};
struct GoalMax :public Goal {
Letter::Char m_pCh[s_MaxLen];
};
struct Config
{
PubKey m_pkAdmin;
};
struct State
{
static const uint8_t s_Key = Tags::s_Global;
Config m_Config;
Goal::ID m_Goals;
};
namespace Method
{
struct Init
{
static const uint32_t s_iMethod = 0;
Config m_Config;
};
struct Withdraw
{
static const uint32_t s_iMethod = 3;
PubKey m_pkUser;
AmountWithAsset m_Val;
};
struct SetPrice
{
static const uint32_t s_iMethod = 4;
Letter::Key::Raw m_Key;
AmountWithAsset m_Price;
};
struct Buy
{
static const uint32_t s_iMethod = 5;
Letter::Key::Raw m_Key;
PubKey m_pkNewOwner;
};
struct Mint
{
static const uint32_t s_iMethod = 6;
Letter::Key::Raw m_Key;
uint32_t m_Count;
};
struct SetGoal
{
static const uint32_t s_iMethod = 7;
AmountWithAsset m_Prize;
uint32_t m_Len;
// followed by array of Chars
};
struct SolveGoal
{
static const uint32_t s_iMethod = 8;
PubKey m_pkUser;
Goal::ID m_iGoal;
};
} // namespace Method
#pragma pack (pop)
}
| [
"valdo@beam-mw.com"
] | valdo@beam-mw.com |
f95da86d6b35030daf52e5c432601a43bf381916 | 187c0aa39f9c6dc6f2b965274ee8ec7e02379034 | /Chapter 12/Problem 12.1/Problem_12_1.cc | 64a592fde700e47611fd6eb513a7f406c3c06a28 | [] | no_license | jl-1992/Cracking-The-Coding-Interview-Problems | deee71de58354b0c8893aea74f8e71c36177cd4c | 04df2061e5d3252e0e6b4494bf0979dd4a436039 | refs/heads/master | 2021-01-01T18:10:10.879918 | 2017-10-18T02:56:06 | 2017-10-18T02:56:06 | 98,267,107 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 397 | cc | #include <iostream>
#include <fstream>
using namespace std;
void print_last_k_lines(ifstream &in, int k){
string line;
int num_lines=0;
while(getline(in,line))
++num_lines;
in.clear();
in.seekg(0,ios::beg);
for(int i=0;i<num_lines;++i){
getline(in,line);
if(i>=num_lines-k)
cout << line << endl;
}
}
int main(){
ifstream in("Sample.txt");
print_last_k_lines(in,3);
return 0;
} | [
"joseph.earl.ludy@gmail.com"
] | joseph.earl.ludy@gmail.com |
a2d5e4d2df500768c7d853cb31609ccd87ea8742 | 1d928c3f90d4a0a9a3919a804597aa0a4aab19a3 | /c++/Chaste/2015/12/ChasteCuboid.cpp | 85435e3fed3b2788e99596998efc081785f8e355 | [] | no_license | rosoareslv/SED99 | d8b2ff5811e7f0ffc59be066a5a0349a92cbb845 | a062c118f12b93172e31e8ca115ce3f871b64461 | refs/heads/main | 2023-02-22T21:59:02.703005 | 2021-01-28T19:40:51 | 2021-01-28T19:40:51 | 306,497,459 | 1 | 1 | null | 2020-11-24T20:56:18 | 2020-10-23T01:18:07 | null | UTF-8 | C++ | false | false | 4,099 | cpp | /*
Copyright (c) 2005-2015, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "ChasteCuboid.hpp"
#include "Exception.hpp"
template <unsigned SPACE_DIM>
ChasteCuboid<SPACE_DIM>::ChasteCuboid(ChastePoint<SPACE_DIM>& rLowerPoint, ChastePoint<SPACE_DIM>& rUpperPoint)
: mLowerCorner(rLowerPoint),
mUpperCorner(rUpperPoint)
{
for (unsigned dim=0; dim<SPACE_DIM; dim++)
{
if (mLowerCorner[dim] > mUpperCorner[dim])
{
EXCEPTION("Attempt to create a cuboid with MinCorner greater than MaxCorner in some dimension");
}
}
}
template <unsigned SPACE_DIM>
bool ChasteCuboid<SPACE_DIM>::DoesContain(const ChastePoint<SPACE_DIM>& rPointToCheck) const
{
for (unsigned dim=0; dim<SPACE_DIM; dim++)
{
if (rPointToCheck[dim] < mLowerCorner[dim] - 100*DBL_EPSILON
|| mUpperCorner[dim] + 100* DBL_EPSILON < rPointToCheck[dim])
{
return false;
}
}
return true;
}
template <unsigned SPACE_DIM>
const ChastePoint<SPACE_DIM>& ChasteCuboid<SPACE_DIM>::rGetUpperCorner() const
{
return mUpperCorner;
}
template <unsigned SPACE_DIM>
const ChastePoint<SPACE_DIM>& ChasteCuboid<SPACE_DIM>::rGetLowerCorner() const
{
return mLowerCorner;
}
template <unsigned SPACE_DIM>
double ChasteCuboid<SPACE_DIM>::GetWidth(unsigned rDimension) const
{
assert(rDimension<SPACE_DIM);
return mUpperCorner[rDimension] - mLowerCorner[rDimension];
}
template <unsigned SPACE_DIM>
unsigned ChasteCuboid<SPACE_DIM>::GetLongestAxis() const
{
unsigned axis=0;
double max_dimension = 0.0;
for (unsigned i=0; i<SPACE_DIM; i++)
{
double dimension = mUpperCorner[i] - mLowerCorner[i];
if ( dimension > max_dimension)
{
axis=i;
max_dimension = dimension;
}
}
return axis;
}
/////////////////////////////////////////////////////////////////////
// Explicit instantiation
/////////////////////////////////////////////////////////////////////
template class ChasteCuboid<1>;
template class ChasteCuboid<2>;
template class ChasteCuboid<3>;
// Serialization for Boost >= 1.36
#include "SerializationExportWrapperForCpp.hpp"
EXPORT_TEMPLATE_CLASS_SAME_DIMS(ChasteCuboid)
| [
"rodrigosoaresilva@gmail.com"
] | rodrigosoaresilva@gmail.com |
e2f7433598952cc1e340056e22db4935350ce663 | ba5d1d776888be6ae9688d850f0445d80973ee8f | /game/server/func_movelinear.cpp | 397fefd18558e77f65ad45fe2fc46544c8e71171 | [
"MIT"
] | permissive | BerntA/tfo-code | eb127b86111dce2b6f66e98c9476adc9ddbbd267 | b82efd940246af8fe90cb76fa6a96bba42c277b7 | refs/heads/master | 2023-08-17T06:57:13.107323 | 2023-08-09T18:37:54 | 2023-08-09T18:37:54 | 41,260,457 | 16 | 5 | MIT | 2023-05-29T23:35:33 | 2015-08-23T17:52:50 | C++ | UTF-8 | C++ | false | false | 11,829 | cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Implements a brush model entity that moves along a linear path.
// Water whose level can be changed is implemented using the same entity.
//
//=============================================================================//
#include "cbase.h"
#include "func_movelinear.h"
#include "entitylist.h"
#include "locksounds.h"
#include "ndebugoverlay.h"
#include "engine/IEngineSound.h"
#include "physics_saverestore.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
// -------------------------------
// SPAWN_FLAGS
// -------------------------------
#define SF_MOVELINEAR_NOTSOLID 8
LINK_ENTITY_TO_CLASS( func_movelinear, CFuncMoveLinear );
LINK_ENTITY_TO_CLASS( momentary_door, CFuncMoveLinear ); // For backward compatibility
//
// func_water_analog is implemented as a linear mover so we can raise/lower the water level.
//
LINK_ENTITY_TO_CLASS( func_water_analog, CFuncMoveLinear );
BEGIN_DATADESC( CFuncMoveLinear )
DEFINE_KEYFIELD( m_vecMoveDir, FIELD_VECTOR, "movedir" ),
DEFINE_KEYFIELD( m_soundStart, FIELD_SOUNDNAME, "StartSound" ),
DEFINE_KEYFIELD( m_soundStop, FIELD_SOUNDNAME, "StopSound" ),
DEFINE_FIELD( m_currentSound, FIELD_SOUNDNAME ),
DEFINE_KEYFIELD( m_flBlockDamage, FIELD_FLOAT, "BlockDamage"),
DEFINE_KEYFIELD( m_flStartPosition, FIELD_FLOAT, "StartPosition"),
DEFINE_KEYFIELD( m_flMoveDistance, FIELD_FLOAT, "MoveDistance"),
// DEFINE_PHYSPTR( m_pFluidController ),
// Inputs
DEFINE_INPUTFUNC( FIELD_VOID, "Open", InputOpen ),
DEFINE_INPUTFUNC( FIELD_VOID, "Close", InputClose ),
DEFINE_INPUTFUNC( FIELD_FLOAT, "SetPosition", InputSetPosition ),
DEFINE_INPUTFUNC( FIELD_FLOAT, "SetSpeed", InputSetSpeed ),
// Outputs
DEFINE_OUTPUT( m_OnFullyOpen, "OnFullyOpen" ),
DEFINE_OUTPUT( m_OnFullyClosed, "OnFullyClosed" ),
// Functions
DEFINE_FUNCTION( StopMoveSound ),
END_DATADESC()
//------------------------------------------------------------------------------
// Purpose: Called before spawning, after keyvalues have been parsed.
//------------------------------------------------------------------------------
void CFuncMoveLinear::Spawn( void )
{
// Convert movedir from angles to a vector
QAngle angMoveDir = QAngle( m_vecMoveDir.x, m_vecMoveDir.y, m_vecMoveDir.z );
AngleVectors( angMoveDir, &m_vecMoveDir );
SetMoveType( MOVETYPE_PUSH );
SetModel( STRING( GetModelName() ) );
// Don't allow zero or negative speeds
if (m_flSpeed <= 0)
{
m_flSpeed = 100;
}
// If move distance is set to zero, use with width of the
// brush to determine the size of the move distance
if (m_flMoveDistance <= 0)
{
Vector vecOBB = CollisionProp()->OBBSize();
vecOBB -= Vector( 2, 2, 2 );
m_flMoveDistance = DotProductAbs( m_vecMoveDir, vecOBB ) - m_flLip;
}
m_vecPosition1 = GetAbsOrigin() - (m_vecMoveDir * m_flMoveDistance * m_flStartPosition);
m_vecPosition2 = m_vecPosition1 + (m_vecMoveDir * m_flMoveDistance);
m_vecFinalDest = GetAbsOrigin();
SetTouch( NULL );
Precache();
// It is solid?
SetSolid( SOLID_VPHYSICS );
if ( FClassnameIs( this, "func_water_analog" ) )
{
AddSolidFlags( FSOLID_VOLUME_CONTENTS );
}
if ( !FClassnameIs( this, "func_water_analog" ) && FBitSet (m_spawnflags, SF_MOVELINEAR_NOTSOLID) )
{
AddSolidFlags( FSOLID_NOT_SOLID );
}
CreateVPhysics();
}
bool CFuncMoveLinear::ShouldSavePhysics( void )
{
// don't save physics for func_water_analog, regen
return !FClassnameIs( this, "func_water_analog" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CFuncMoveLinear::CreateVPhysics( void )
{
if ( !FClassnameIs( this, "func_water_analog" ) )
{
//normal door
if ( !IsSolidFlagSet( FSOLID_NOT_SOLID ) )
{
VPhysicsInitShadow( false, false );
}
}
else
{
// special contents
AddSolidFlags( FSOLID_VOLUME_CONTENTS );
//SETBITS( m_spawnflags, SF_DOOR_SILENT ); // water is silent for now
IPhysicsObject *pPhysics = VPhysicsInitShadow( false, false );
fluidparams_t fluid;
Assert( CollisionProp()->GetCollisionAngles() == vec3_angle );
fluid.damping = 0.01f;
fluid.surfacePlane[0] = 0;
fluid.surfacePlane[1] = 0;
fluid.surfacePlane[2] = 1;
fluid.surfacePlane[3] = CollisionProp()->GetCollisionOrigin().z + CollisionProp()->OBBMaxs().z - 1;
fluid.currentVelocity.Init(0,0,0);
fluid.torqueFactor = 0.1f;
fluid.viscosityFactor = 0.01f;
fluid.pGameData = static_cast<void *>(this);
//FIXME: Currently there's no way to specify that you want slime
fluid.contents = CONTENTS_WATER;
m_pFluidController = physenv->CreateFluidController( pPhysics, &fluid );
}
return true;
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CFuncMoveLinear::Precache( void )
{
if (m_soundStart != NULL_STRING)
{
PrecacheScriptSound( (char *) STRING(m_soundStart) );
}
if (m_soundStop != NULL_STRING)
{
PrecacheScriptSound( (char *) STRING(m_soundStop) );
}
m_currentSound = NULL_STRING;
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CFuncMoveLinear::MoveTo(Vector vPosition, float flSpeed)
{
if ( flSpeed != 0 )
{
if ( m_soundStart != NULL_STRING )
{
if (m_currentSound == m_soundStart)
{
StopSound(entindex(), CHAN_BODY, (char*)STRING(m_soundStop));
}
else
{
m_currentSound = m_soundStart;
CPASAttenuationFilter filter( this );
EmitSound_t ep;
ep.m_nChannel = CHAN_BODY;
ep.m_pSoundName = (char*)STRING(m_soundStart);
ep.m_flVolume = 1;
ep.m_SoundLevel = SNDLVL_NORM;
EmitSound( filter, entindex(), ep );
}
}
LinearMove( vPosition, flSpeed );
if ( m_pFluidController )
{
m_pFluidController->WakeAllSleepingObjects();
}
// Clear think (that stops sounds)
SetThink(NULL);
}
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CFuncMoveLinear::StopMoveSound( void )
{
if ( m_soundStart != NULL_STRING && ( m_currentSound == m_soundStart ) )
{
StopSound(entindex(), CHAN_BODY, (char*)STRING(m_soundStart) );
}
if ( m_soundStop != NULL_STRING && ( m_currentSound != m_soundStop ) )
{
m_currentSound = m_soundStop;
CPASAttenuationFilter filter( this );
EmitSound_t ep;
ep.m_nChannel = CHAN_BODY;
ep.m_pSoundName = (char*)STRING(m_soundStop);
ep.m_flVolume = 1;
ep.m_SoundLevel = SNDLVL_NORM;
EmitSound( filter, entindex(), ep );
}
SetThink(NULL);
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CFuncMoveLinear::MoveDone( void )
{
// Stop sounds at the next think, rather than here as another
// SetPosition call might immediately follow the end of this move
SetThink(&CFuncMoveLinear::StopMoveSound);
SetNextThink( gpGlobals->curtime + 0.1f );
BaseClass::MoveDone();
if ( GetAbsOrigin() == m_vecPosition2 )
{
m_OnFullyOpen.FireOutput( this, this );
}
else if ( GetAbsOrigin() == m_vecPosition1 )
{
m_OnFullyClosed.FireOutput( this, this );
}
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CFuncMoveLinear::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
if ( useType != USE_SET ) // Momentary buttons will pass down a float in here
return;
if ( value > 1.0 )
value = 1.0;
Vector move = m_vecPosition1 + (value * (m_vecPosition2 - m_vecPosition1));
Vector delta = move - GetLocalOrigin();
float speed = delta.Length() * 10;
MoveTo(move, speed);
}
//-----------------------------------------------------------------------------
// Purpose: Sets the position as a value from [0..1].
//-----------------------------------------------------------------------------
void CFuncMoveLinear::SetPosition( float flPosition )
{
Vector vTargetPos = m_vecPosition1 + ( flPosition * (m_vecPosition2 - m_vecPosition1));
if ((vTargetPos - GetLocalOrigin()).Length() > 0.001)
{
MoveTo(vTargetPos, m_flSpeed);
}
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CFuncMoveLinear::InputOpen( inputdata_t &inputdata )
{
if (GetLocalOrigin() != m_vecPosition2)
{
MoveTo(m_vecPosition2, m_flSpeed);
}
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CFuncMoveLinear::InputClose( inputdata_t &inputdata )
{
if (GetLocalOrigin() != m_vecPosition1)
{
MoveTo(m_vecPosition1, m_flSpeed);
}
}
//------------------------------------------------------------------------------
// Purpose: Input handler for setting the position from [0..1].
// Input : Float position.
//-----------------------------------------------------------------------------
void CFuncMoveLinear::InputSetPosition( inputdata_t &inputdata )
{
SetPosition( inputdata.value.Float() );
}
//-----------------------------------------------------------------------------
// Purpose: Called every frame when the bruch is blocked while moving
// Input : pOther - The blocking entity.
//-----------------------------------------------------------------------------
void CFuncMoveLinear::Blocked( CBaseEntity *pOther )
{
// Hurt the blocker
if ( m_flBlockDamage )
{
if ( pOther->m_takedamage == DAMAGE_EVENTS_ONLY )
{
if ( FClassnameIs( pOther, "gib" ) )
UTIL_Remove( pOther );
}
else
pOther->TakeDamage( CTakeDamageInfo( this, this, m_flBlockDamage, DMG_CRUSH ) );
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &inputdata -
//-----------------------------------------------------------------------------
void CFuncMoveLinear::InputSetSpeed( inputdata_t &inputdata )
{
// Set the new speed
m_flSpeed = inputdata.value.Float();
// FIXME: This is a little questionable. Do we want to fix the speed, or let it continue on at the old speed?
float flDistToGoalSqr = ( m_vecFinalDest - GetAbsOrigin() ).LengthSqr();
if ( flDistToGoalSqr > Square( FLT_EPSILON ) )
{
// NOTE: We do NOT want to call sound functions here, just vanilla position changes
LinearMove( m_vecFinalDest, m_flSpeed );
}
}
//-----------------------------------------------------------------------------
// Purpose: Draw any debug text overlays
// Output : Current text offset from the top
//-----------------------------------------------------------------------------
int CFuncMoveLinear::DrawDebugTextOverlays(void)
{
int text_offset = BaseClass::DrawDebugTextOverlays();
if (m_debugOverlays & OVERLAY_TEXT_BIT)
{
char tempstr[512];
float flTravelDist = (m_vecPosition1 - m_vecPosition2).Length();
float flCurDist = (m_vecPosition1 - GetLocalOrigin()).Length();
Q_snprintf(tempstr,sizeof(tempstr),"Current Pos: %3.3f",flCurDist/flTravelDist);
EntityText(text_offset,tempstr,0);
text_offset++;
float flTargetDist = (m_vecPosition1 - m_vecFinalDest).Length();
Q_snprintf(tempstr,sizeof(tempstr),"Target Pos: %3.3f",flTargetDist/flTravelDist);
EntityText(text_offset,tempstr,0);
text_offset++;
}
return text_offset;
}
| [
"bernta1@msn.com"
] | bernta1@msn.com |
7adfff0b073ab9b9513ca702389c9d3736e8bd5f | 908e429f6653179c2bce7545c4554ac94769a21f | /problem_solving/medium/lilys_homework.cpp | 4be122bc193f0e947e150d3798e891563a6a320b | [] | no_license | transeos/hackerrank | 80a98d0309eec3c27b3c6b2f7f289919f281314e | fea574ea3a818d4069947cf1eb93c0ac498d1171 | refs/heads/master | 2022-07-02T03:59:24.348850 | 2022-06-11T16:26:07 | 2022-06-11T16:26:07 | 186,157,157 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,251 | cpp | // -*- C++ -*-
//
//*****************************************************************
//
// hackerrank: https://www.hackerrank.com/challenges/lilys-homework/problem
//
// WARRANTY:
// Use all material in this file at your own risk.
//
// Created by Hiranmoy on 26/05/22.
//
//*****************************************************************
#include "utils.h"
#include <bits/stdc++.h>
#include <catch2/catch.hpp>
using std::cin;
using std::cout;
using std::endl;
using std::ofstream;
using std::string;
using std::vector;
/*
* Complete the 'lilysHomework' function below.
*
* The function is expected to return an INTEGER.
* The function accepts INTEGER_ARRAY arr as parameter.
*/
int32_t lilysHomework(vector<int> arr) {
return 0;
}
TEST_CASE("lilys_homework", "[problem_solving][medium][ToDo]") {
ofstream fout(getenv("OUTPUT_PATH"));
string n_temp;
getline(cin, n_temp);
int n = stoi(ltrim(rtrim(n_temp)));
string arr_temp_temp;
getline(cin, arr_temp_temp);
vector<string> arr_temp = split(rtrim(arr_temp_temp));
vector<int> arr(n);
for (int i = 0; i < n; i++) {
int arr_item = stoi(arr_temp[i]);
arr[i] = arr_item;
}
int result = lilysHomework(arr);
fout << result << "\n";
fout.close();
}
| [
"hiranmoy.iitkgp@gmail.com"
] | hiranmoy.iitkgp@gmail.com |
36e28ae83fb4c9db28b1fa8d7bebedb8234bb1df | 054826b3e02d026c77c7d3e8574578fdf7edc897 | /Day01/B - love song.cpp | 471c22fb25f409e131edf9d62b7524f78945931d | [] | no_license | 123pk/100DaysCoding-Part-3 | 599b1ebcfa15d3013758db28a7ad4b6411fe90be | 0382ce2e3d9b2c77f3bf5cd869ffeccf2ab48f49 | refs/heads/main | 2023-07-18T20:14:33.888371 | 2021-09-26T15:33:42 | 2021-09-26T15:33:42 | 378,564,802 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,345 | cpp | /*
Platform :- Codeforces
Contest :- Codeforces Round 627 Div 2
Problem :- B - Love song
Approach :- We can store occurence of each word of alphabet at each index of string , as there are 26 alphabets our time complexity will be O(n*26) which will work,
now for each [l,r] we will find two array one storing occurence of each alphabet at index 'l' and other at 'r', we will find [ Ar[i] - Al[i]] which will give us
occurenece of each alphabet in range [l,r], now we will run a loop from 'a' to 'z' and update our answer by [ count*(index_of_corresponding_letter_in_alphabet)]
*/
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,q;
cin>>n>>q;
string s;
cin>>s;
vector<vector<int>>P;
vector<int>temp(26);
for(int i=0;i<s.size();++i){
temp[s[i]-'a']++;
P.push_back(temp);
}
map<char,int>Q;
for(char ch='a';ch<='z';++ch){
Q[ch]=(ch-'a')+1;
}
for(int i=0;i<q;++i){
int l,r;
cin>>l>>r;
l--;
r--;
vector<int>x=P[r];
if(l){
vector<int>y=P[l-1];
for(int j=0;j<26;++j){
x[j]-=y[j];
}
}
long long ans=0;
for(int j=0;j<26;++j){
if(x[j]){
ans+=(x[j]*(j+1));
}
}
cout<<ans<<"\n";
}
}
| [
"noreply@github.com"
] | 123pk.noreply@github.com |
e19fe172ca77365c848aebdba7300eea9c806ab6 | be1ccd9d8a9fbf4e5527256ca5bd93ee2e24c51e | /Sources/common/erm/rendering/data_structs/IndexData.h | 213837e82d07fbd068523f9c081ade806fbc2a0f | [
"MIT"
] | permissive | JALB91/ERM | f0f56c6fa99ef3d43bfe5074663fe76a8d7d36d6 | 4e739301b87dfcde3c85d6f52a83f09c4f69565f | refs/heads/master | 2023-01-09T07:49:10.080693 | 2022-07-29T22:15:45 | 2022-07-29T22:15:45 | 171,048,441 | 5 | 1 | MIT | 2021-03-10T20:41:38 | 2019-02-16T20:26:31 | C++ | UTF-8 | C++ | false | false | 82 | h | #pragma once
#include <cstdint>
namespace erm {
typedef uint32_t IndexData;
}
| [
"damiano.calcagni@gmail.com"
] | damiano.calcagni@gmail.com |
1d295cc1150e4cc6d88327a550302570445075e8 | 4019481ad68088df711ee89817b5fc4046407f20 | /PGSceneFinalProject/Mesh.hpp | eb6fcc23f4873a5b2b13994ebaf364cff6baedd5 | [] | no_license | MarcusGitAccount/OpenGL_Scene_Project_TerrainGeneration | 89d56761c6ef4c4ef15af1151c6533068466ef35 | 02a85c12302426edfcbed9645064b2f7b21b49af | refs/heads/master | 2020-12-01T15:39:39.671448 | 2020-01-11T21:18:33 | 2020-01-11T21:18:33 | 230,684,838 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,044 | hpp | //
// Mesh.hpp
// Lab4
//
// Created by CGIS on 27/10/2016.
// Copyright © 2016 CGIS. All rights reserved.
//
#ifndef Mesh_hpp
#define Mesh_hpp
#include <stdio.h>
#include "glm/glm.hpp"
#include "GLEW/glew.h"
#include <string>
#include <vector>
#include "Shader.hpp"
namespace gps {
struct Vertex
{
glm::vec3 Position;
glm::vec3 Normal;
glm::vec2 TexCoords;
};
struct Texture
{
GLuint id;
//ambientTexture, diffuseTexture, specularTexture
std::string type;
std::string path;
};
struct Material
{
glm::vec3 ambient;
glm::vec3 diffuse;
glm::vec3 specular;
};
class Mesh
{
public:
std::vector<Vertex> vertices;
std::vector<GLuint> indices;
std::vector<Texture> textures;
Mesh();
Mesh(std::vector<Vertex> vertices, std::vector<GLuint> indices, std::vector<Texture> textures);
void Draw(gps::Shader shader);
private:
/* Render data */
GLuint VAO, VBO, EBO;
// Initializes all the buffer objects/arrays
void setupMesh();
};
}
#endif /* Mesh_hpp */
| [
"pop_marcus_98@yahoo.com"
] | pop_marcus_98@yahoo.com |
655a6fb7ad918c70f5c64ccb4ed555943d883f13 | 948d555823c2d123601ff6c149869be377521282 | /SDK/SoT_SlateReflector_classes.hpp | e40314c89d70b7d3e93185eefcb57c06b0e52ee6 | [] | no_license | besimbicer89/SoT-SDK | 2acf79303c65edab01107ab4511e9b9af8ab9743 | 3a4c6f3b77c1045b7ef0cddd064350056ef7d252 | refs/heads/master | 2022-04-24T01:03:37.163407 | 2020-04-27T12:45:47 | 2020-04-27T12:45:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,676 | hpp | #pragma once
// SeaOfThieves (1.6.4) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// Class SlateReflector.WidgetReflectorNodeBase
// 0x0058 (0x0080 - 0x0028)
class UWidgetReflectorNodeBase : public UObject
{
public:
struct FGeometry Geometry; // 0x0028(0x0034) (IsPlainOldData)
unsigned char UnknownData00[0x4]; // 0x005C(0x0004) MISSED OFFSET
TArray<class UWidgetReflectorNodeBase*> ChildNodes; // 0x0060(0x0010) (ZeroConstructor)
struct FLinearColor Tint; // 0x0070(0x0010) (ZeroConstructor, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class SlateReflector.WidgetReflectorNodeBase");
return ptr;
}
};
// Class SlateReflector.LiveWidgetReflectorNode
// 0x0018 (0x0098 - 0x0080)
class ULiveWidgetReflectorNode : public UWidgetReflectorNodeBase
{
public:
unsigned char UnknownData00[0x18]; // 0x0080(0x0018) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class SlateReflector.LiveWidgetReflectorNode");
return ptr;
}
};
// Class SlateReflector.SnapshotWidgetReflectorNode
// 0x0118 (0x0198 - 0x0080)
class USnapshotWidgetReflectorNode : public UWidgetReflectorNodeBase
{
public:
struct FText CachedWidgetType; // 0x0080(0x0038)
struct FText CachedWidgetVisibilityText; // 0x00B8(0x0038)
struct FText CachedWidgetReadableLocation; // 0x00F0(0x0038)
struct FString CachedWidgetFile; // 0x0128(0x0010) (ZeroConstructor)
int CachedWidgetLineNumber; // 0x0138(0x0004) (ZeroConstructor, IsPlainOldData)
struct FName CachedWidgetAssetName; // 0x013C(0x0008) (ZeroConstructor, IsPlainOldData)
struct FVector2D CachedWidgetDesiredSize; // 0x0144(0x0008) (ZeroConstructor, IsPlainOldData)
unsigned char UnknownData00[0x4]; // 0x014C(0x0004) MISSED OFFSET
struct FSlateColor CachedWidgetForegroundColor; // 0x0150(0x0030)
struct FString CachedWidgetAddress; // 0x0180(0x0010) (ZeroConstructor)
bool CachedWidgetEnabled; // 0x0190(0x0001) (ZeroConstructor, IsPlainOldData)
unsigned char UnknownData01[0x7]; // 0x0191(0x0007) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class SlateReflector.SnapshotWidgetReflectorNode");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"getpeyton@gmail.com"
] | getpeyton@gmail.com |
f5f23f4c69eed3fb611ec4db5803832ba4a73dbb | d7f1601570c8780874b3fff905df55199e6a3704 | /tests/src/astro/electromagnetism/unitTestCannonBallRadiationPressureAccelerationAndForce.cpp | ad239fc4ea4dc0f4c0107690a5c28506e4ba25eb | [] | permissive | elmarputs/tudat | 751c662a785378791601c1f12259c6f928d72e17 | 677a30d378a2b82dd1f7ae2a2bf3d0e92f7db734 | refs/heads/master | 2022-07-04T02:05:53.649610 | 2021-10-06T19:21:50 | 2021-10-06T19:21:50 | 126,502,320 | 0 | 0 | BSD-3-Clause | 2018-12-03T19:23:23 | 2018-03-23T15:12:29 | C++ | UTF-8 | C++ | false | false | 22,128 | cpp | /* Copyright (c) 2010-2019, Delft University of Technology
* All rigths reserved
*
* This file is part of the Tudat. Redistribution and use in source and
* binary forms, with or without modification, are permitted exclusively
* under the terms of the Modified BSD license. You should have received
* a copy of the license with this file. If not, please or visit:
* http://tudat.tudelft.nl/LICENSE.
*
* References
* Ganeff, M.I. Solar radiation pressure benchmark data script,
* solarRadiationPressureBenchmarkData.m, available at http://tudat.tudelft.nl, 2012.
* Giancoli, D.C. Physics for Scientists and Engineers with Modern Physics
* Fourth Edition. New Jersey: Prentice-Hall, Inc., 1985.
* Hirsh, S.M. Solar radiation pressure benchmark data script,
* solarRadiationUnitTests.cpp, available at
* https://github.com/sethhirsh/solarRadiationUnitTests, 2013.
* Irizarry, V. The effect of solar radiation pressure on Ulysses orbit,
* http://ccar.colorado.edu/asen5050/projects/projects_2001/aponte/Ulysses.htm, 2001,
* last accessed: 7th October, 2013.
* Willmott, P. General astro Library, http://www.amsat-bda.org/GAL_Downloads.html,
* 2011, last accessed: 7th October, 2013.
*
*/
#define BOOST_TEST_MAIN
#include <cmath>
#include <limits>
#include <boost/make_shared.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/unit_test.hpp>
#include <Eigen/Core>
#include "tudat/basics/testMacros.h"
#include "tudat/astro/electromagnetism/cannonBallRadiationPressureForce.h"
#include "tudat/astro/electromagnetism/cannonBallRadiationPressureAcceleration.h"
namespace tudat
{
namespace unit_tests
{
BOOST_AUTO_TEST_SUITE( test_radiation_pressure_acceleration_and_force_models )
// Set radiation pressure at 1 AU [N/m^2].
const double radiationPressureAtOneAU = 4.56e-6;
// Set 1 AU in metres [m].
const double astronomicalUnitInMeters = 1.49598e11;
//! Test implementation of radiation force model.
BOOST_AUTO_TEST_CASE( testRadiationPressureForceModelGaneffData )
{
// Benchmark data is obtained from MATLAB script (Ganeff, 2012).
// Set expected radiation pressure force [N].
const Eigen::Vector3d expectedRadiationPressureForce =
Eigen::Vector3d( -0.975383093968723e-6, -0.975383093968723e-6, 0.0 );
// Set radiation pressure coefficient (1 + emissivity).
const double radiationPressureCoefficient = 1.0 + 0.21;
// Set area on target that is subject to radiation pressure [m^2].
const double areaSubjectToRadiationPressure = 0.5;
// Set position vector [m].
Eigen::Vector3d positionVectorToSource
= Eigen::Vector3d( astronomicalUnitInMeters, astronomicalUnitInMeters, 0.0 );
// Set radiation pressure at target [N/m^2].
const double radiationPressureAtTarget = radiationPressureAtOneAU
* astronomicalUnitInMeters * astronomicalUnitInMeters
/ positionVectorToSource.squaredNorm( );
// Normalize position vector to get vector pointing to source in non-dimensional units.
positionVectorToSource.normalize( );
// Compute radiation pressure force [N].
const Eigen::Vector3d computedRadiationPressureForce
= electromagnetism::computeCannonBallRadiationPressureForce(
radiationPressureAtTarget, positionVectorToSource,
areaSubjectToRadiationPressure, radiationPressureCoefficient );
// Compare computed and expected radiation pressure force vectors.
BOOST_CHECK_EQUAL( computedRadiationPressureForce.z( ),
expectedRadiationPressureForce.z( ) );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRadiationPressureForce.segment( 0, 2 ),
expectedRadiationPressureForce.segment( 0, 2 ),
1.0e-15 );
}
//! Test acceleration model on sample satellite at approximately 1 AU away from the Sun.
BOOST_AUTO_TEST_CASE( testRadiationAccelerationModelEarth )
{
// Benchmark data is obtained using the General astro Library (Willmott, 2011).
// Set expected radiation pressure acceleration [m/s^2].
const Eigen::Vector3d expectedRadiationPressureAcceleration =
Eigen::Vector3d( -2.964e-06, 0.0, 0.0 );
// Set radiation pressure coefficient (1 + emissivity).
const double radiationPressureCoefficient = 1.0 + 0.3;
// Set area on target that is subject to radiation pressure [m^2].
const double areaSubjectToRadiationPressure = 2.0;
// Set position vector [m].
Eigen::Vector3d positionVectorToSource
= Eigen::Vector3d( astronomicalUnitInMeters, 0.0, 0.0 );
// Set radiation pressure at target [N/m^2].
const double radiationPressureAtTarget = radiationPressureAtOneAU
* astronomicalUnitInMeters * astronomicalUnitInMeters
/ positionVectorToSource.squaredNorm( );
// Normalize position vector to get vector pointing to source in non-dimensional units.
positionVectorToSource.normalize( );
// Set mass of accelerated body [kg].
const double mass = 4.0;
// Compute radiation pressure acceleration [m/s^2].
const Eigen::Vector3d computedRadiationPressureAcceleration
= electromagnetism::computeCannonBallRadiationPressureAcceleration(
radiationPressureAtTarget, positionVectorToSource,
areaSubjectToRadiationPressure, radiationPressureCoefficient, mass );
// Compare computed and expected radiation pressure acceleration vectors
TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRadiationPressureAcceleration,
expectedRadiationPressureAcceleration,
1.0e-15 );
}
//! Test acceleration model on sample satellite at approximately the position of Venus with respect
//! to the Sun.
BOOST_AUTO_TEST_CASE( testRadiationAccelerationModelVenus )
{
// Benchmark data is obtained using the General astro Library (Willmott, 2011).
// Tests satellite at approximately the distance of Venus away from the Sun.
// Set the distance from the Sun to Venus.
const double distanceSunToVenus = 0.732 * astronomicalUnitInMeters;
// Set expected radiation pressure acceleration [m/s^2].
const Eigen::Vector3d expectedRadiationPressureAcceleration =
Eigen::Vector3d( -2.05147517201883e-05,
-2.05147517201883e-05,
0.0 );
// Set radiation pressure coefficient (1 + emissivity).
const double radiationPressureCoefficient = 1.0 + 0.5;
// Set area on target that is subject to radiation pressure [m^2].
const double areaSubjectToRadiationPressure = 0.005;
// Set position vector [m].
Eigen::Vector3d positionVectorToSource
= Eigen::Vector3d( distanceSunToVenus / std::sqrt( 2.0 ),
distanceSunToVenus / std::sqrt( 2.0 ),
0.0 );
// Set radiation pressure at target [N/m^2].
const double radiationPressureAtTarget = radiationPressureAtOneAU
* astronomicalUnitInMeters * astronomicalUnitInMeters
/ positionVectorToSource.squaredNorm( );
// Normalize position vector to get vector pointing to source in non-dimensional units.
positionVectorToSource.normalize( );
// Set mass of accelerated body [kg].
const double mass = 0.0022;
// Compute radiation pressure acceleration [m/s^2].
const Eigen::Vector3d computedRadiationPressureAcceleration
= electromagnetism::computeCannonBallRadiationPressureAcceleration(
radiationPressureAtTarget, positionVectorToSource,
areaSubjectToRadiationPressure, radiationPressureCoefficient, mass );
// Compare computed and expected radiation pressure acceleration vectors.
BOOST_CHECK_SMALL( computedRadiationPressureAcceleration.z( ),
std::numeric_limits< double >::min( ) );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRadiationPressureAcceleration.segment( 0, 2 ),
expectedRadiationPressureAcceleration.segment( 0, 2 ),
1.0e-14 );
}
//! Test force model on sample planet at approximately the position of Uranus with respect to the
//! Sun.
BOOST_AUTO_TEST_CASE( testRadiationForceModelUranus )
{
// Benchmark data is obtained using the General astro Library (Willmott, 2011).
// Tests satellite at approximately the distance of Uranus away from the Sun.
// Set expected radiation pressure force [N].
const Eigen::Vector3d expectedRadiationPressureForce =
Eigen::Vector3d( -4470411.61112176,
-4470411.61112176,
0.0 );
// Set radiation pressure coefficient (1 + emissivity).
const double radiationPressureCoefficient = 1.0 + 0.8;
// Set area on target that is subject to radiation pressure [m^2].
const double areaSubjectToRadiationPressure = 69939064094327.4;
// Set position vector [m].
Eigen::Vector3d positionVectorToSource
= Eigen::Vector3d( 9.529 * astronomicalUnitInMeters / std::sqrt( 2.0 ),
9.529 * astronomicalUnitInMeters / std::sqrt( 2.0 ),
0.0 );
// Set radiation pressure at target [N/m^2].
const double radiationPressureAtTarget = radiationPressureAtOneAU
* astronomicalUnitInMeters * astronomicalUnitInMeters
/ positionVectorToSource.squaredNorm( );
// Normalize position vector to get vector pointing to source in non-dimensional units.
positionVectorToSource.normalize( );
// Compute radiation pressure force [N].
const Eigen::Vector3d computedRadiationPressureForce
= electromagnetism::computeCannonBallRadiationPressureForce(
radiationPressureAtTarget, positionVectorToSource,
areaSubjectToRadiationPressure, radiationPressureCoefficient );
// Compare computed and expected radiation pressure force vectors.
TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRadiationPressureForce,
expectedRadiationPressureForce,
1.0e-14 );
}
//! Test force model on random satellite at a random distance with respect to the
//! Sun.
BOOST_AUTO_TEST_CASE( testRadiationForceModelRandom )
{
// Benchmark data is obtained using the General astro Library (Willmott, 2011).
// Tests satellite at random distance from the Sun.
// Set expected radiation pressure force [N].
const Eigen::Vector3d expectedRadiationPressureForce =
Eigen::Vector3d( -3043733.21422537,
-2929936.30441141,
-473166.433773283 );
// Set radiation pressure coefficient (1 + emissivity).
const double radiationPressureCoefficient = 1.0 + 0.4058;
// Set area on target that is subject to radiation pressure [m^2].
const double areaSubjectToRadiationPressure = 514701.9505;
// Set position vector [m].
Eigen::Vector3d positionVectorToSource
= Eigen::Vector3d( 94359740.25,
90831886.1,
14668782.92 );
// Set radiation pressure at target [N/m^2].
const double radiationPressureAtTarget = radiationPressureAtOneAU
* astronomicalUnitInMeters * astronomicalUnitInMeters
/ positionVectorToSource.squaredNorm( );
// Normalize position vector to get vector pointing to source in non-dimensional units.
positionVectorToSource.normalize( );
// Compute radiation pressure force [N].
const Eigen::Vector3d computedRadiationPressureForce
= electromagnetism::computeCannonBallRadiationPressureForce(
radiationPressureAtTarget, positionVectorToSource,
areaSubjectToRadiationPressure, radiationPressureCoefficient );
// Compare computed and expected radiation pressure force vectors.
TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRadiationPressureForce,
expectedRadiationPressureForce,
1.0e-14 );
}
//! Test radiation force model on a hand at approximately 1 AU from the Sun.
BOOST_AUTO_TEST_CASE( testRadiationForceModelGiancoliData )
{
// Benchmark data is obtained from Physics for Scientists and Engineers
// with Modern Physics Volume 2 (Ch. 31, Ex. 7) (Giancoli, 1985).
// Set expected radiation pressure force [N].
const Eigen::Vector3d expectedRadiationPressureForce =
Eigen::Vector3d( 6.0e-8, 0.0, 0.0 );
// Set radiation pressure coefficient (1 + emissivity).
const double radiationPressureCoefficient = 1.0 + 0.0;
// Set area on target that is subject to radiation pressure [m^2].
const double areaSubjectToRadiationPressure = 0.02;
// Set position vector [m].
Eigen::Vector3d positionVectorToSource
= Eigen::Vector3d( astronomicalUnitInMeters, 0.0, 0.0 );
// Set radiation pressure at target [N/m^2].
const double radiationPressureAtTarget = radiationPressureAtOneAU
* astronomicalUnitInMeters * astronomicalUnitInMeters
/ positionVectorToSource.squaredNorm( );
// Normalize position vector to get vector pointing to source in non-dimensional units.
positionVectorToSource.normalize( );
// Compute radiation pressure force [N].
const Eigen::Vector3d computedRadiationPressureForce
= electromagnetism::computeCannonBallRadiationPressureForce(
radiationPressureAtTarget, positionVectorToSource,
areaSubjectToRadiationPressure, radiationPressureCoefficient );
// Compare computed and expected radiation pressure force vectors.
BOOST_CHECK_SMALL( std::fabs( computedRadiationPressureForce.x( )
- expectedRadiationPressureForce.x( ) ),
1.0e-6 );
BOOST_CHECK_SMALL( computedRadiationPressureForce.y( ),
std::numeric_limits< double >::min( ) );
BOOST_CHECK_SMALL( computedRadiationPressureForce.z( ),
std::numeric_limits< double >::min( ) );
}
//! Test radiation acceleration model on Ulysses satellite at 1AU.
BOOST_AUTO_TEST_CASE( testRadiationAccelerationModelUlysses )
{
// Benchmark data obtained from (Irizarry, 2001).
// Set expected radiation pressure acceleration [m/s^2].
const Eigen::Vector3d expectedRadiationPressureAcceleration
= Eigen::Vector3d( -1.713e-7, 0.0, 0.0 );
// Set radiation pressure coefficient (1 + emissivity).
const double radiationPressureCoefficient = 1.0 + 0.327;
// Set area on target that is subject to radiation pressure [m^2].
const double areaSubjectToRadiationPressure = 10.59;
// Set position vector [m].
Eigen::Vector3d positionVectorToSource
= Eigen::Vector3d( astronomicalUnitInMeters, 0.0, 0.0 );
// Set radiation pressure at target [N/m^2].
const double radiationPressureAtTarget = radiationPressureAtOneAU
* astronomicalUnitInMeters * astronomicalUnitInMeters
/ positionVectorToSource.squaredNorm( );
// Normalize position vector to get vector pointing to source in non-dimensional units.
positionVectorToSource.normalize( );
// Set mass of accelerated body [kg].
const double mass = 370.0;
// Compute radiation pressure acceleration [m/s^2].
const Eigen::Vector3d computedRadiationPressureAcceleration
= electromagnetism::computeCannonBallRadiationPressureAcceleration(
radiationPressureAtTarget, positionVectorToSource,
areaSubjectToRadiationPressure, radiationPressureCoefficient, mass );
// Compare computed and expected radiation pressure acceleration vectors.
BOOST_CHECK_SMALL( std::fabs( computedRadiationPressureAcceleration.x( )
- expectedRadiationPressureAcceleration.x( ) ),
1.0e-8 );
BOOST_CHECK_SMALL( computedRadiationPressureAcceleration.y( ),
std::numeric_limits< double >::min( ) );
BOOST_CHECK_SMALL( computedRadiationPressureAcceleration.z( ),
std::numeric_limits< double >::min( ) );
}
//! Test class implementation of radiation pressure acceleration model.
// Set position of source of radiation pressure at origin [m].
static Eigen::Vector3d sourcePosition = Eigen::Vector3d::Zero( );
// Get position of source of radiation pressure [m].
Eigen::Vector3d getSourcePosition( ) { return sourcePosition; }
// Set position of accelerated body [m].
static Eigen::Vector3d acceleratedBodyPosition
= Eigen::Vector3d( -astronomicalUnitInMeters, 0.0, 0.0 );
// Get position of accelerated body [m].
Eigen::Vector3d getAcceleratedBodyPosition( ) { return acceleratedBodyPosition; }
// Get vector from accelerated body to source [m].
Eigen::Vector3d getVectorToSource( )
{
return getSourcePosition( ) - getAcceleratedBodyPosition( );
}
// Set radiation pressure at location of acceleration body [N/m^2].
static double radiationPressure = radiationPressureAtOneAU
* astronomicalUnitInMeters * astronomicalUnitInMeters / getVectorToSource( ).squaredNorm( );
// Get radiation pressure at location of acceleration body [N/m^2].
double getRadiationPressure( ) { return radiationPressure; }
// Set radiation pressure coefficient.
static double radiationPressureCoefficient = 1.0 + 0.3;
// Get radiation pressure coefficient.
double getRadiationPressureCoefficient( ) { return radiationPressureCoefficient; }
// Set area subject to radiation pressure [m^2].
static double areaSubjectToRadiationPressure = 2.0;
// Get area subject to radiation pressure [m^2].
double getAreaSubjectToRadiationPressure( ) { return areaSubjectToRadiationPressure; }
// Set mass of accelerated body [kg].
static double massOfAcceleratedBody = 4.0;
// Get mass of acceleration body [kg].
double getMassOfAcceleratedBody( ) { return massOfAcceleratedBody; }
//! Test radiation pressure acceleration model constructor.
BOOST_AUTO_TEST_CASE( testRadiationPressureAccelerationModelClassConstructor )
{
// Declare and initialize cannon-ball radiation pressure acceleration model.
electromagnetism::CannonBallRadiationPressurePointer radiationPressureModel
= std::make_shared< electromagnetism::CannonBallRadiationPressureAcceleration >(
&getSourcePosition, &getAcceleratedBodyPosition, &getRadiationPressure,
&getRadiationPressureCoefficient, &getAreaSubjectToRadiationPressure,
&getMassOfAcceleratedBody );
// Set expected radiation pressure acceleration [m/s^2].
const Eigen::Vector3d expectedRadiationPressureAcceleration
= Eigen::Vector3d( -2.964e-06, 0.0, 0.0 );
// Compute radiation pressure acceleration [m/s^2].
const Eigen::Vector3d computedRadiationPressureAcceleration
= radiationPressureModel->getAcceleration( );
// Compare computed and expected radiation pressure acceleration vectors.
TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRadiationPressureAcceleration,
expectedRadiationPressureAcceleration,
1.0e-15 );
}
//! Test radiation pressure acceleration model update-members function.
BOOST_AUTO_TEST_CASE( testRadiationPressureAccelerationModelClassUpdateMembers )
{
// Declare and initialize cannon-ball radiation pressure acceleration model.
electromagnetism::CannonBallRadiationPressurePointer radiationPressureModel
= std::make_shared< electromagnetism::CannonBallRadiationPressureAcceleration >(
&getSourcePosition, &getAcceleratedBodyPosition, &getRadiationPressure,
&getRadiationPressureCoefficient, &getAreaSubjectToRadiationPressure,
&getMassOfAcceleratedBody );
// Set expected radiation pressure acceleration [m/s^2].
const Eigen::Vector3d expectedRadiationPressureAcceleration
= Eigen::Vector3d( -2.05147517201883e-05,
-2.05147517201883e-05,
0.0 );
// Set the distance from the Sun to Venus [m].
const double distanceSunToVenus = 0.732 * astronomicalUnitInMeters;
// Update position of accelerated body [m].
acceleratedBodyPosition = Eigen::Vector3d( -distanceSunToVenus / std::sqrt( 2.0 ),
-distanceSunToVenus / std::sqrt( 2.0 ),
0.0 );
// Update radiation pressure at location of accelerated body [N/m^2].
radiationPressure = radiationPressureAtOneAU
* astronomicalUnitInMeters * astronomicalUnitInMeters
/ getVectorToSource( ).squaredNorm( );
// Update radiation pressure coefficient.
radiationPressureCoefficient = 1.0 + 0.5;
// Update area subject to radiation pressure [m^2].
areaSubjectToRadiationPressure = 0.005;
// Update mass of accelerated body [kg].
massOfAcceleratedBody = 0.0022;
// Update class members.
radiationPressureModel->updateMembers( );
// Compute radiation pressure acceleration [m/s^2].
const Eigen::Vector3d computedRadiationPressureAcceleration
= radiationPressureModel->getAcceleration( );
// Compare computed and expected radiation pressure acceleration vectors.
BOOST_CHECK_SMALL( computedRadiationPressureAcceleration.z( ),
std::numeric_limits< double >::min( ) );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRadiationPressureAcceleration.segment( 0, 2 ),
expectedRadiationPressureAcceleration.segment( 0, 2 ),
1.0e-14 );
}
BOOST_AUTO_TEST_SUITE_END( )
} // namespace unit_tests
} // namespace tudat
| [
"g.h.garrett13@gmail.com"
] | g.h.garrett13@gmail.com |
f710b6fa4c888c6c3491a477eee24c2bbec5becb | ce9feabb3909e1c0517f4a0127701069363173df | /vnext/local-cli/generator-windows/templates/cpp/src/AutolinkedNativeModules.g.h | 6608d9c46d0ab533497b394e7983e70ee537b7b7 | [
"MIT"
] | permissive | acoates-ms/react-native-windows | bbdc88fd85186e35033d47df1e104feb2a3c7f90 | 146f22499cd48d381b113d7ec8427d4eacf1f8b0 | refs/heads/notmaster | 2023-08-17T04:56:32.785656 | 2020-05-15T20:27:27 | 2020-05-15T20:27:27 | 169,125,078 | 4 | 1 | NOASSERTION | 2023-09-12T15:38:49 | 2019-02-04T18:16:47 | C++ | UTF-8 | C++ | false | false | 367 | h | // AutolinkedNativeModules.g.h -- contents generated by "react-native run-windows"
#include "pch.h"
#pragma once
// clang-format off
namespace winrt::Microsoft::ReactNative
{
static void RegisterAutolinkedNativeModulePackages(winrt::Windows::Foundation::Collections::IVector<winrt::Microsoft::ReactNative::IReactPackageProvider> const& packageProviders)
{
}
}
| [
"noreply@github.com"
] | acoates-ms.noreply@github.com |
cc215483a32f91b8847f46ef8303310c272f6132 | 88ae8695987ada722184307301e221e1ba3cc2fa | /third_party/skia/tests/RasterPipelineBuilderTest.cpp | 93b54048cc6c42864eb234f96380ffa074f22209 | [
"BSD-3-Clause",
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 40,214 | cpp | /*
* Copyright 2022 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/core/SkStream.h"
#include "src/base/SkArenaAlloc.h"
#include "src/base/SkStringView.h"
#include "src/core/SkOpts.h"
#include "src/core/SkRasterPipeline.h"
#include "src/sksl/codegen/SkSLRasterPipelineBuilder.h"
#include "src/sksl/tracing/SkSLDebugTracePriv.h"
#include "tests/Test.h"
#ifdef SK_ENABLE_SKSL_IN_RASTER_PIPELINE
static sk_sp<SkData> get_program_dump(SkSL::RP::Program& program) {
SkDynamicMemoryWStream stream;
program.dump(&stream);
return stream.detachAsData();
}
static std::string_view as_string_view(sk_sp<SkData> dump) {
return std::string_view(static_cast<const char*>(dump->data()), dump->size());
}
static void check(skiatest::Reporter* r, SkSL::RP::Program& program, std::string_view expected) {
// Verify that the program matches expectations.
sk_sp<SkData> dump = get_program_dump(program);
REPORTER_ASSERT(r, as_string_view(dump) == expected,
"Output did not match expectation:\n%.*s",
(int)dump->size(), static_cast<const char*>(dump->data()));
}
static SkSL::RP::SlotRange one_slot_at(SkSL::RP::Slot index) {
return SkSL::RP::SlotRange{index, 1};
}
static SkSL::RP::SlotRange two_slots_at(SkSL::RP::Slot index) {
return SkSL::RP::SlotRange{index, 2};
}
static SkSL::RP::SlotRange three_slots_at(SkSL::RP::Slot index) {
return SkSL::RP::SlotRange{index, 3};
}
static SkSL::RP::SlotRange four_slots_at(SkSL::RP::Slot index) {
return SkSL::RP::SlotRange{index, 4};
}
static SkSL::RP::SlotRange five_slots_at(SkSL::RP::Slot index) {
return SkSL::RP::SlotRange{index, 5};
}
static SkSL::RP::SlotRange ten_slots_at(SkSL::RP::Slot index) {
return SkSL::RP::SlotRange{index, 10};
}
DEF_TEST(RasterPipelineBuilder, r) {
// Create a very simple nonsense program.
SkSL::RP::Builder builder;
builder.store_src_rg(two_slots_at(0));
builder.store_src(four_slots_at(2));
builder.store_dst(four_slots_at(4));
builder.store_device_xy01(four_slots_at(6));
builder.init_lane_masks();
builder.enableExecutionMaskWrites();
builder.mask_off_return_mask();
builder.mask_off_loop_mask();
builder.reenable_loop_mask(one_slot_at(4));
builder.disableExecutionMaskWrites();
builder.load_src(four_slots_at(1));
builder.load_dst(four_slots_at(3));
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/10,
/*numUniformSlots=*/0);
check(r, *program,
R"(store_src_rg v0..1 = src.rg
store_src v2..5 = src.rgba
store_dst v4..7 = dst.rgba
store_device_xy01 v6..9 = DeviceCoords.xy01
init_lane_masks CondMask = LoopMask = RetMask = true
mask_off_return_mask RetMask &= ~(CondMask & LoopMask & RetMask)
mask_off_loop_mask LoopMask &= ~(CondMask & LoopMask & RetMask)
reenable_loop_mask LoopMask |= v4
load_src src.rgba = v1..4
load_dst dst.rgba = v3..6
)");
}
DEF_TEST(RasterPipelineBuilderPushPopMaskRegisters, r) {
// Create a very simple nonsense program.
SkSL::RP::Builder builder;
REPORTER_ASSERT(r, !builder.executionMaskWritesAreEnabled());
builder.enableExecutionMaskWrites();
REPORTER_ASSERT(r, builder.executionMaskWritesAreEnabled());
builder.push_condition_mask(); // push into 0
builder.push_loop_mask(); // push into 1
builder.push_return_mask(); // push into 2
builder.merge_condition_mask(); // set the condition-mask to 1 & 2
builder.merge_inv_condition_mask(); // set the condition-mask to 1 & ~2
builder.pop_condition_mask(); // pop from 2
builder.merge_loop_mask(); // mask off the loop-mask against 1
builder.push_condition_mask(); // push into 2
builder.pop_condition_mask(); // pop from 2
builder.pop_loop_mask(); // pop from 1
builder.pop_return_mask(); // pop from 0
builder.push_condition_mask(); // push into 0
builder.pop_and_reenable_loop_mask(); // pop from 0
REPORTER_ASSERT(r, builder.executionMaskWritesAreEnabled());
builder.disableExecutionMaskWrites();
REPORTER_ASSERT(r, !builder.executionMaskWritesAreEnabled());
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/0,
/*numUniformSlots=*/0);
check(r, *program,
R"(store_condition_mask $0 = CondMask
store_loop_mask $1 = LoopMask
store_return_mask $2 = RetMask
merge_condition_mask CondMask = $1 & $2
merge_inv_condition_mask CondMask = $1 & ~$2
load_condition_mask CondMask = $2
merge_loop_mask LoopMask &= $1
store_condition_mask $2 = CondMask
load_condition_mask CondMask = $2
load_loop_mask LoopMask = $1
load_return_mask RetMask = $0
store_condition_mask $0 = CondMask
reenable_loop_mask LoopMask |= $0
)");
}
DEF_TEST(RasterPipelineBuilderCaseOp, r) {
// Create a very simple nonsense program.
SkSL::RP::Builder builder;
builder.push_constant_i(123); // push a test value
builder.push_constant_i(~0); // push an all-on default mask
builder.case_op(123); // do `case 123:`
builder.case_op(124); // do `case 124:`
builder.discard_stack(2);
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/0,
/*numUniformSlots=*/0);
check(r, *program,
R"(copy_constant $0 = 0x0000007B (1.723597e-43)
copy_constant $1 = 0xFFFFFFFF
case_op if ($0 == 0x0000007B) { LoopMask = true; $1 = false; }
case_op if ($0 == 0x0000007C) { LoopMask = true; $1 = false; }
)");
}
DEF_TEST(RasterPipelineBuilderPushPopSrcDst, r) {
// Create a very simple nonsense program.
SkSL::RP::Builder builder;
builder.push_src_rgba();
builder.push_dst_rgba();
builder.pop_src_rgba();
builder.exchange_src();
builder.exchange_src();
builder.exchange_src();
builder.pop_dst_rgba();
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/0,
/*numUniformSlots=*/0);
check(r, *program,
R"(store_src $0..3 = src.rgba
store_dst $4..7 = dst.rgba
load_src src.rgba = $4..7
exchange_src swap(src.rgba, $0..3)
load_dst dst.rgba = $0..3
)");
}
DEF_TEST(RasterPipelineBuilderInvokeChild, r) {
// Create a very simple nonsense program.
SkSL::RP::Builder builder;
builder.invoke_shader(1);
builder.invoke_color_filter(2);
builder.invoke_blender(3);
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/0,
/*numUniformSlots=*/0);
check(r, *program,
R"(invoke_shader invoke_shader 0x00000001
invoke_color_filter invoke_color_filter 0x00000002
invoke_blender invoke_blender 0x00000003
)");
}
DEF_TEST(RasterPipelineBuilderPushPopTempImmediates, r) {
// Create a very simple nonsense program.
SkSL::RP::Builder builder;
builder.set_current_stack(1);
builder.push_constant_i(999); // push into 2
builder.set_current_stack(0);
builder.push_constant_f(13.5f); // push into 0
builder.push_clone_from_stack(one_slot_at(0), /*otherStackID=*/1, /*offsetFromStackTop=*/1);
// push into 1 from 2
builder.discard_stack(1); // discard 2
builder.push_constant_u(357); // push into 2
builder.set_current_stack(1);
builder.push_clone_from_stack(one_slot_at(0), /*otherStackID=*/0, /*offsetFromStackTop=*/1);
// push into 3 from 0
builder.discard_stack(2); // discard 2 and 3
builder.set_current_stack(0);
builder.push_constant_f(1.2f); // push into 2
builder.pad_stack(3); // pad slots 3,4,5
builder.push_constant_f(3.4f); // push into 6
builder.discard_stack(7); // discard 0 through 6
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/1,
/*numUniformSlots=*/0);
check(r, *program,
R"(copy_constant $2 = 0x000003E7 (1.399897e-42)
copy_constant $0 = 0x41580000 (13.5)
copy_constant $1 = 0x00000165 (5.002636e-43)
)");
}
DEF_TEST(RasterPipelineBuilderPushPopIndirect, r) {
// Create a very simple nonsense program.
SkSL::RP::Builder builder;
builder.set_current_stack(1);
builder.push_constant_i(3);
builder.set_current_stack(0);
builder.push_slots_indirect(two_slots_at(0), /*dynamicStack=*/1, ten_slots_at(0));
builder.push_slots_indirect(four_slots_at(10), /*dynamicStack=*/1, ten_slots_at(10));
builder.push_uniform_indirect(one_slot_at(0), /*dynamicStack=*/1, five_slots_at(0));
builder.push_uniform_indirect(three_slots_at(5), /*dynamicStack=*/1, five_slots_at(5));
builder.swizzle_copy_stack_to_slots_indirect(three_slots_at(6), /*dynamicStackID=*/1,
ten_slots_at(0), {2, 1, 0},
/*offsetFromStackTop=*/3);
builder.copy_stack_to_slots_indirect(three_slots_at(4), /*dynamicStackID=*/1, ten_slots_at(0));
builder.pop_slots_indirect(five_slots_at(0), /*dynamicStackID=*/1, ten_slots_at(0));
builder.pop_slots_indirect(five_slots_at(10), /*dynamicStackID=*/1, ten_slots_at(10));
builder.set_current_stack(1);
builder.discard_stack(1);
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/20,
/*numUniformSlots=*/10);
check(r, *program,
R"(copy_constant $10 = 0x00000003 (4.203895e-45)
copy_from_indirect_unmasked $0..1 = Indirect(v0..1 + $10)
copy_from_indirect_unmasked $2..5 = Indirect(v10..13 + $10)
copy_from_indirect_uniform_unm $6 = Indirect(u0 + $10)
copy_from_indirect_uniform_unm $7..9 = Indirect(u5..7 + $10)
swizzle_copy_to_indirect_maske Indirect(v6..8 + $10).zyx = Mask($7..9)
copy_to_indirect_masked Indirect(v4..6 + $10) = Mask($7..9)
copy_to_indirect_masked Indirect(v0..4 + $10) = Mask($5..9)
copy_to_indirect_masked Indirect(v10..14 + $10) = Mask($0..4)
)");
}
DEF_TEST(RasterPipelineBuilderCopySlotsMasked, r) {
// Create a very simple nonsense program.
SkSL::RP::Builder builder;
builder.copy_slots_masked(two_slots_at(0), two_slots_at(2));
builder.copy_slots_masked(four_slots_at(1), four_slots_at(5));
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/9,
/*numUniformSlots=*/0);
check(r, *program,
R"(copy_2_slots_masked v0..1 = Mask(v2..3)
copy_4_slots_masked v1..4 = Mask(v5..8)
)");
}
DEF_TEST(RasterPipelineBuilderCopySlotsUnmasked, r) {
// Create a very simple nonsense program.
SkSL::RP::Builder builder;
builder.copy_slots_unmasked(three_slots_at(0), three_slots_at(2));
builder.copy_slots_unmasked(five_slots_at(1), five_slots_at(5));
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/10,
/*numUniformSlots=*/0);
check(r, *program,
R"(copy_3_slots_unmasked v0..2 = v2..4
copy_4_slots_unmasked v1..4 = v5..8
copy_slot_unmasked v5 = v9
)");
}
DEF_TEST(RasterPipelineBuilderPushPopSlots, r) {
// Create a very simple nonsense program.
SkSL::RP::Builder builder;
builder.push_slots(four_slots_at(10)); // push from 10~13 into $0~$3
builder.copy_stack_to_slots(one_slot_at(5), 3); // copy from $1 into 5
builder.pop_slots_unmasked(two_slots_at(20)); // pop from $2~$3 into 20~21 (unmasked)
builder.enableExecutionMaskWrites();
builder.copy_stack_to_slots_unmasked(one_slot_at(4), 2); // copy from $0 into 4
builder.push_slots(three_slots_at(30)); // push from 30~32 into $2~$4
builder.pop_slots(five_slots_at(0)); // pop from $0~$4 into 0~4 (masked)
builder.disableExecutionMaskWrites();
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/50,
/*numUniformSlots=*/0);
check(r, *program,
R"(copy_4_slots_unmasked $0..3 = v10..13
copy_slot_unmasked v5 = $1
copy_2_slots_unmasked v20..21 = $2..3
copy_slot_unmasked v4 = $0
copy_3_slots_unmasked $2..4 = v30..32
copy_4_slots_masked v0..3 = Mask($0..3)
copy_slot_masked v4 = Mask($4)
)");
}
DEF_TEST(RasterPipelineBuilderDuplicateSelectAndSwizzleSlots, r) {
// Create a very simple nonsense program.
SkSL::RP::Builder builder;
builder.push_constant_f(1.0f); // push into 0
builder.push_duplicates(1); // duplicate into 1
builder.push_duplicates(2); // duplicate into 2~3
builder.push_duplicates(3); // duplicate into 4~6
builder.push_duplicates(5); // duplicate into 7~11
builder.select(4); // select from 4~7 and 8~11 into 4~7
builder.select(3); // select from 2~4 and 5~7 into 2~4
builder.select(1); // select from 3 and 4 into 3
builder.swizzle_copy_stack_to_slots(four_slots_at(1), {3, 2, 1, 0}, 4);
builder.swizzle_copy_stack_to_slots(four_slots_at(0), {0, 1, 3}, 3);
builder.swizzle(4, {3, 2, 1, 0}); // reverse the order of 0~3 (value.wzyx)
builder.swizzle(4, {1, 2}); // eliminate elements 0 and 3 (value.yz)
builder.swizzle(2, {0}); // eliminate element 1 (value.x)
builder.discard_stack(1); // balance stack
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/6,
/*numUniformSlots=*/0);
check(r, *program,
R"(splat_4_constants $0..3 = 0x3F800000 (1.0)
splat_4_constants $4..7 = 0x3F800000 (1.0)
splat_4_constants $8..11 = 0x3F800000 (1.0)
copy_4_slots_masked $4..7 = Mask($8..11)
copy_3_slots_masked $2..4 = Mask($5..7)
copy_slot_masked $3 = Mask($4)
swizzle_copy_4_slots_masked (v1..4).wzyx = Mask($0..3)
swizzle_copy_3_slots_masked (v0..3).xyw = Mask($1..3)
swizzle_4 $0..3 = ($0..3).wzyx
swizzle_2 $0..1 = ($0..2).yz
)");
}
DEF_TEST(RasterPipelineBuilderTransposeMatrix, r) {
// Create a very simple nonsense program.
SkSL::RP::Builder builder;
builder.push_constant_f(1.0f); // push into 0
builder.push_duplicates(15); // duplicate into 1~15
builder.transpose(2, 2); // transpose a 2x2 matrix
builder.transpose(3, 3); // transpose a 3x3 matrix
builder.transpose(4, 4); // transpose a 4x4 matrix
builder.transpose(2, 4); // transpose a 2x4 matrix
builder.transpose(4, 3); // transpose a 4x3 matrix
builder.discard_stack(16); // balance stack
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/0,
/*numUniformSlots=*/0);
check(r, *program,
R"(splat_4_constants $0..3 = 0x3F800000 (1.0)
splat_4_constants $4..7 = 0x3F800000 (1.0)
splat_4_constants $8..11 = 0x3F800000 (1.0)
splat_4_constants $12..15 = 0x3F800000 (1.0)
swizzle_3 $13..15 = ($13..15).yxz
shuffle $8..15 = ($8..15)[2 5 0 3 6 1 4 7]
shuffle $1..15 = ($1..15)[3 7 11 0 4 8 12 1 5 9 13 2 6 10 14]
shuffle $9..15 = ($9..15)[3 0 4 1 5 2 6]
shuffle $5..15 = ($5..15)[2 5 8 0 3 6 9 1 4 7 10]
)");
}
DEF_TEST(RasterPipelineBuilderDiagonalMatrix, r) {
// Create a very simple nonsense program.
SkSL::RP::Builder builder;
builder.push_constant_f(0.0f); // push into 0
builder.push_constant_f(1.0f); // push into 1
builder.diagonal_matrix(2, 2); // generate a 2x2 diagonal matrix
builder.discard_stack(4); // balance stack
builder.push_constant_f(0.0f); // push into 0
builder.push_constant_f(2.0f); // push into 1
builder.diagonal_matrix(4, 4); // generate a 4x4 diagonal matrix
builder.discard_stack(16); // balance stack
builder.push_constant_f(0.0f); // push into 0
builder.push_constant_f(3.0f); // push into 1
builder.diagonal_matrix(2, 3); // generate a 2x3 diagonal matrix
builder.discard_stack(6); // balance stack
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/0,
/*numUniformSlots=*/0);
check(r, *program,
R"(copy_constant $0 = 0
copy_constant $1 = 0x3F800000 (1.0)
swizzle_4 $0..3 = ($0..3).yxxy
copy_constant $0 = 0
copy_constant $1 = 0x40000000 (2.0)
shuffle $0..15 = ($0..15)[1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1]
copy_constant $0 = 0
copy_constant $1 = 0x40400000 (3.0)
shuffle $0..5 = ($0..5)[1 0 0 0 1 0]
)");
}
DEF_TEST(RasterPipelineBuilderMatrixResize, r) {
// Create a very simple nonsense program.
SkSL::RP::Builder builder;
builder.push_constant_f(1.0f); // synthesize a 2x2 matrix
builder.push_constant_f(2.0f);
builder.push_constant_f(3.0f);
builder.push_constant_f(4.0f);
builder.matrix_resize(2, 2, 4, 4); // resize 2x2 matrix into 4x4
builder.matrix_resize(4, 4, 2, 2); // resize 4x4 matrix back into 2x2
builder.matrix_resize(2, 2, 2, 4); // resize 2x2 matrix into 2x4
builder.matrix_resize(2, 4, 4, 2); // resize 2x4 matrix into 4x2
builder.matrix_resize(4, 2, 3, 3); // resize 4x2 matrix into 3x3
builder.discard_stack(9); // balance stack
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/0,
/*numUniformSlots=*/0);
check(r, *program,
R"(copy_constant $0 = 0x3F800000 (1.0)
copy_constant $1 = 0x40000000 (2.0)
copy_constant $2 = 0x40400000 (3.0)
copy_constant $3 = 0x40800000 (4.0)
copy_constant $4 = 0
copy_constant $5 = 0x3F800000 (1.0)
shuffle $2..15 = ($2..15)[2 2 0 1 2 2 2 2 3 2 2 2 2 3]
shuffle $2..3 = ($2..3)[2 3]
copy_constant $4 = 0
shuffle $2..7 = ($2..7)[2 2 0 1 2 2]
copy_constant $8 = 0
shuffle $2..7 = ($2..7)[2 3 6 6 6 6]
copy_constant $8 = 0
copy_constant $9 = 0x3F800000 (1.0)
shuffle $2..8 = ($2..8)[6 0 1 6 2 3 7]
)");
}
DEF_TEST(RasterPipelineBuilderBranches, r) {
#if SK_HAS_MUSTTAIL
// We have guaranteed tail-calling, and don't need to rewind the stack.
static constexpr char kExpectationWithKnownExecutionMask[] =
R"(jump jump +9 (label 3 at #10)
label label 0
copy_constant v0 = 0
label label 0x00000001
copy_constant v1 = 0
jump jump -4 (label 0 at #2)
label label 0x00000002
copy_constant v2 = 0
jump jump -7 (label 0 at #2)
label label 0x00000003
branch_if_no_active_lanes_eq branch -4 (label 2 at #7) if no lanes of v2 == 0
branch_if_no_active_lanes_eq branch -10 (label 0 at #2) if no lanes of v2 == 0x00000001 (1.401298e-45)
)";
static constexpr char kExpectationWithExecutionMaskWrites[] =
R"(jump jump +10 (label 3 at #11)
label label 0
copy_constant v0 = 0
label label 0x00000001
copy_constant v1 = 0
branch_if_no_lanes_active branch_if_no_lanes_active -2 (label 1 at #4)
branch_if_all_lanes_active branch_if_all_lanes_active -5 (label 0 at #2)
label label 0x00000002
copy_constant v2 = 0
branch_if_any_lanes_active branch_if_any_lanes_active -8 (label 0 at #2)
label label 0x00000003
branch_if_no_active_lanes_eq branch -4 (label 2 at #8) if no lanes of v2 == 0
branch_if_no_active_lanes_eq branch -11 (label 0 at #2) if no lanes of v2 == 0x00000001 (1.401298e-45)
)";
#else
// We don't have guaranteed tail-calling, so we rewind the stack immediately before any backward
// branches.
static constexpr char kExpectationWithKnownExecutionMask[] =
R"(jump jump +11 (label 3 at #12)
label label 0
copy_constant v0 = 0
label label 0x00000001
copy_constant v1 = 0
stack_rewind
jump jump -5 (label 0 at #2)
label label 0x00000002
copy_constant v2 = 0
stack_rewind
jump jump -9 (label 0 at #2)
label label 0x00000003
stack_rewind
branch_if_no_active_lanes_eq branch -6 (label 2 at #8) if no lanes of v2 == 0
stack_rewind
branch_if_no_active_lanes_eq branch -14 (label 0 at #2) if no lanes of v2 == 0x00000001 (1.401298e-45)
)";
static constexpr char kExpectationWithExecutionMaskWrites[] =
R"(jump jump +13 (label 3 at #14)
label label 0
copy_constant v0 = 0
label label 0x00000001
copy_constant v1 = 0
stack_rewind
branch_if_no_lanes_active branch_if_no_lanes_active -3 (label 1 at #4)
stack_rewind
branch_if_all_lanes_active branch_if_all_lanes_active -7 (label 0 at #2)
label label 0x00000002
copy_constant v2 = 0
stack_rewind
branch_if_any_lanes_active branch_if_any_lanes_active -11 (label 0 at #2)
label label 0x00000003
stack_rewind
branch_if_no_active_lanes_eq branch -6 (label 2 at #10) if no lanes of v2 == 0
stack_rewind
branch_if_no_active_lanes_eq branch -16 (label 0 at #2) if no lanes of v2 == 0x00000001 (1.401298e-45)
)";
#endif
for (bool enableExecutionMaskWrites : {false, true}) {
// Create a very simple nonsense program.
SkSL::RP::Builder builder;
int label1 = builder.nextLabelID();
int label2 = builder.nextLabelID();
int label3 = builder.nextLabelID();
int label4 = builder.nextLabelID();
if (enableExecutionMaskWrites) {
builder.enableExecutionMaskWrites();
}
builder.jump(label4);
builder.label(label1);
builder.zero_slots_unmasked(one_slot_at(0));
builder.label(label2);
builder.zero_slots_unmasked(one_slot_at(1));
builder.branch_if_no_lanes_active(label2);
builder.branch_if_no_lanes_active(label3);
builder.branch_if_all_lanes_active(label1);
builder.label(label3);
builder.zero_slots_unmasked(one_slot_at(2));
builder.branch_if_any_lanes_active(label1);
builder.branch_if_any_lanes_active(label1);
builder.label(label4);
builder.branch_if_no_active_lanes_on_stack_top_equal(0, label3);
builder.branch_if_no_active_lanes_on_stack_top_equal(0, label2);
builder.branch_if_no_active_lanes_on_stack_top_equal(1, label1);
builder.branch_if_no_active_lanes_on_stack_top_equal(1, label4);
if (enableExecutionMaskWrites) {
builder.disableExecutionMaskWrites();
}
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/3,
/*numUniformSlots=*/0);
check(r, *program, enableExecutionMaskWrites ? kExpectationWithExecutionMaskWrites
: kExpectationWithKnownExecutionMask);
}
}
DEF_TEST(RasterPipelineBuilderBinaryFloatOps, r) {
using BuilderOp = SkSL::RP::BuilderOp;
SkSL::RP::Builder builder;
builder.push_constant_f(10.0f);
builder.push_duplicates(30);
builder.binary_op(BuilderOp::add_n_floats, 1);
builder.binary_op(BuilderOp::sub_n_floats, 2);
builder.binary_op(BuilderOp::mul_n_floats, 3);
builder.binary_op(BuilderOp::div_n_floats, 4);
builder.binary_op(BuilderOp::max_n_floats, 3);
builder.binary_op(BuilderOp::min_n_floats, 2);
builder.binary_op(BuilderOp::cmplt_n_floats, 5);
builder.binary_op(BuilderOp::cmple_n_floats, 4);
builder.binary_op(BuilderOp::cmpeq_n_floats, 3);
builder.binary_op(BuilderOp::cmpne_n_floats, 2);
builder.discard_stack(2);
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/0,
/*numUniformSlots=*/0);
check(r, *program,
R"(splat_4_constants $0..3 = 0x41200000 (10.0)
splat_4_constants $4..7 = 0x41200000 (10.0)
splat_4_constants $8..11 = 0x41200000 (10.0)
splat_4_constants $12..15 = 0x41200000 (10.0)
splat_4_constants $16..19 = 0x41200000 (10.0)
splat_4_constants $20..23 = 0x41200000 (10.0)
splat_4_constants $24..27 = 0x41200000 (10.0)
splat_2_constants $28..29 = 0x41200000 (10.0)
add_imm_float $29 += 0x41200000 (10.0)
sub_2_floats $26..27 -= $28..29
mul_3_floats $22..24 *= $25..27
div_4_floats $17..20 /= $21..24
max_3_floats $15..17 = max($15..17, $18..20)
min_2_floats $14..15 = min($14..15, $16..17)
cmplt_n_floats $6..10 = lessThan($6..10, $11..15)
cmple_4_floats $3..6 = lessThanEqual($3..6, $7..10)
cmpeq_3_floats $1..3 = equal($1..3, $4..6)
cmpne_2_floats $0..1 = notEqual($0..1, $2..3)
)");
}
DEF_TEST(RasterPipelineBuilderBinaryIntOps, r) {
using BuilderOp = SkSL::RP::BuilderOp;
SkSL::RP::Builder builder;
builder.push_constant_i(123);
builder.push_duplicates(40);
builder.binary_op(BuilderOp::bitwise_and_n_ints, 1);
builder.binary_op(BuilderOp::bitwise_xor_n_ints, 2);
builder.binary_op(BuilderOp::bitwise_or_n_ints, 3);
builder.binary_op(BuilderOp::add_n_ints, 2);
builder.binary_op(BuilderOp::sub_n_ints, 3);
builder.binary_op(BuilderOp::mul_n_ints, 4);
builder.binary_op(BuilderOp::div_n_ints, 5);
builder.binary_op(BuilderOp::max_n_ints, 4);
builder.binary_op(BuilderOp::min_n_ints, 3);
builder.binary_op(BuilderOp::cmplt_n_ints, 1);
builder.binary_op(BuilderOp::cmple_n_ints, 2);
builder.binary_op(BuilderOp::cmpeq_n_ints, 3);
builder.binary_op(BuilderOp::cmpne_n_ints, 4);
builder.discard_stack(4);
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/0,
/*numUniformSlots=*/0);
check(r, *program,
R"(splat_4_constants $0..3 = 0x0000007B (1.723597e-43)
splat_4_constants $4..7 = 0x0000007B (1.723597e-43)
splat_4_constants $8..11 = 0x0000007B (1.723597e-43)
splat_4_constants $12..15 = 0x0000007B (1.723597e-43)
splat_4_constants $16..19 = 0x0000007B (1.723597e-43)
splat_4_constants $20..23 = 0x0000007B (1.723597e-43)
splat_4_constants $24..27 = 0x0000007B (1.723597e-43)
splat_4_constants $28..31 = 0x0000007B (1.723597e-43)
splat_4_constants $32..35 = 0x0000007B (1.723597e-43)
splat_4_constants $36..39 = 0x0000007B (1.723597e-43)
bitwise_and_imm_int $39 &= 0x0000007B
bitwise_xor_2_ints $36..37 ^= $38..39
bitwise_or_3_ints $32..34 |= $35..37
add_2_ints $31..32 += $33..34
sub_3_ints $27..29 -= $30..32
mul_4_ints $22..25 *= $26..29
div_n_ints $16..20 /= $21..25
max_4_ints $13..16 = max($13..16, $17..20)
min_3_ints $11..13 = min($11..13, $14..16)
cmplt_int $12 = lessThan($12, $13)
cmple_2_ints $9..10 = lessThanEqual($9..10, $11..12)
cmpeq_3_ints $5..7 = equal($5..7, $8..10)
cmpne_4_ints $0..3 = notEqual($0..3, $4..7)
)");
}
DEF_TEST(RasterPipelineBuilderBinaryUIntOps, r) {
using BuilderOp = SkSL::RP::BuilderOp;
SkSL::RP::Builder builder;
builder.push_constant_u(456);
builder.push_duplicates(21);
builder.binary_op(BuilderOp::div_n_uints, 6);
builder.binary_op(BuilderOp::cmplt_n_uints, 5);
builder.binary_op(BuilderOp::cmple_n_uints, 4);
builder.binary_op(BuilderOp::max_n_uints, 3);
builder.binary_op(BuilderOp::min_n_uints, 2);
builder.discard_stack(2);
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/0,
/*numUniformSlots=*/0);
check(r, *program,
R"(splat_4_constants $0..3 = 0x000001C8 (6.389921e-43)
splat_4_constants $4..7 = 0x000001C8 (6.389921e-43)
splat_4_constants $8..11 = 0x000001C8 (6.389921e-43)
splat_4_constants $12..15 = 0x000001C8 (6.389921e-43)
splat_4_constants $16..19 = 0x000001C8 (6.389921e-43)
splat_2_constants $20..21 = 0x000001C8 (6.389921e-43)
div_n_uints $10..15 /= $16..21
cmplt_n_uints $6..10 = lessThan($6..10, $11..15)
cmple_4_uints $3..6 = lessThanEqual($3..6, $7..10)
max_3_uints $1..3 = max($1..3, $4..6)
min_2_uints $0..1 = min($0..1, $2..3)
)");
}
DEF_TEST(RasterPipelineBuilderUnaryOps, r) {
using BuilderOp = SkSL::RP::BuilderOp;
SkSL::RP::Builder builder;
builder.push_constant_i(456);
builder.push_duplicates(4);
builder.unary_op(BuilderOp::cast_to_float_from_int, 1);
builder.unary_op(BuilderOp::cast_to_float_from_uint, 2);
builder.unary_op(BuilderOp::cast_to_int_from_float, 3);
builder.unary_op(BuilderOp::cast_to_uint_from_float, 4);
builder.unary_op(BuilderOp::cos_float, 4);
builder.unary_op(BuilderOp::tan_float, 3);
builder.unary_op(BuilderOp::sin_float, 2);
builder.unary_op(BuilderOp::sqrt_float, 1);
builder.unary_op(BuilderOp::abs_int, 2);
builder.unary_op(BuilderOp::floor_float, 3);
builder.unary_op(BuilderOp::ceil_float, 4);
builder.discard_stack(5);
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/0,
/*numUniformSlots=*/0);
check(r, *program,
R"(splat_4_constants $0..3 = 0x000001C8 (6.389921e-43)
copy_constant $4 = 0x000001C8 (6.389921e-43)
cast_to_float_from_int $4 = IntToFloat($4)
cast_to_float_from_2_uints $3..4 = UintToFloat($3..4)
cast_to_int_from_3_floats $2..4 = FloatToInt($2..4)
cast_to_uint_from_4_floats $1..4 = FloatToUint($1..4)
cos_float $1 = cos($1)
cos_float $2 = cos($2)
cos_float $3 = cos($3)
cos_float $4 = cos($4)
tan_float $2 = tan($2)
tan_float $3 = tan($3)
tan_float $4 = tan($4)
sin_float $3 = sin($3)
sin_float $4 = sin($4)
sqrt_float $4 = sqrt($4)
abs_2_ints $3..4 = abs($3..4)
floor_3_floats $2..4 = floor($2..4)
ceil_4_floats $1..4 = ceil($1..4)
)");
}
DEF_TEST(RasterPipelineBuilderUniforms, r) {
using BuilderOp = SkSL::RP::BuilderOp;
// Create a very simple nonsense program.
SkSL::RP::Builder builder;
builder.push_uniform(one_slot_at(0)); // push into 0
builder.push_uniform(two_slots_at(1)); // push into 1~2
builder.push_uniform(three_slots_at(3)); // push into 3~5
builder.push_uniform(four_slots_at(6)); // push into 6~9
builder.push_uniform(five_slots_at(0)); // push into 10~14
builder.unary_op(BuilderOp::abs_int, 1); // perform work so the program isn't eliminated
builder.discard_stack(15); // balance stack
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/0,
/*numUniformSlots=*/10);
check(r, *program,
R"(copy_4_uniforms $0..3 = u0..3
copy_4_uniforms $4..7 = u4..7
copy_2_uniforms $8..9 = u8..9
copy_4_uniforms $10..13 = u0..3
copy_uniform $14 = u4
abs_int $14 = abs($14)
)");
}
DEF_TEST(RasterPipelineBuilderPushZeros, r) {
using BuilderOp = SkSL::RP::BuilderOp;
// Create a very simple nonsense program.
SkSL::RP::Builder builder;
builder.push_zeros(1); // push into 0
builder.push_zeros(2); // push into 1~2
builder.push_zeros(3); // push into 3~5
builder.push_zeros(4); // push into 6~9
builder.push_zeros(5); // push into 10~14
builder.unary_op(BuilderOp::abs_int, 1); // perform work so the program isn't eliminated
builder.discard_stack(15); // balance stack
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/0,
/*numUniformSlots=*/10);
check(r, *program,
R"(splat_4_constants $0..3 = 0
splat_4_constants $4..7 = 0
splat_4_constants $8..11 = 0
splat_3_constants $12..14 = 0
abs_int $14 = abs($14)
)");
}
DEF_TEST(RasterPipelineBuilderTernaryFloatOps, r) {
using BuilderOp = SkSL::RP::BuilderOp;
SkSL::RP::Builder builder;
builder.push_constant_f(0.75f);
builder.push_duplicates(8);
builder.ternary_op(BuilderOp::mix_n_floats, 3);
builder.discard_stack(3);
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/0,
/*numUniformSlots=*/0);
check(r, *program,
R"(splat_4_constants $0..3 = 0x3F400000 (0.75)
splat_4_constants $4..7 = 0x3F400000 (0.75)
copy_constant $8 = 0x3F400000 (0.75)
mix_3_floats $0..2 = mix($3..5, $6..8, $0..2)
)");
}
DEF_TEST(RasterPipelineBuilderAutomaticStackRewinding, r) {
using BuilderOp = SkSL::RP::BuilderOp;
SkSL::RP::Builder builder;
builder.push_constant_i(1);
builder.push_duplicates(2000);
builder.unary_op(BuilderOp::abs_int, 1); // perform work so the program isn't eliminated
builder.discard_stack(2001);
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/0,
/*numUniformSlots=*/0);
sk_sp<SkData> dump = get_program_dump(*program);
#if SK_HAS_MUSTTAIL
// We have guaranteed tail-calling, so we never use `stack_rewind`.
REPORTER_ASSERT(r, !skstd::contains(as_string_view(dump), "stack_rewind"));
#else
// We can't guarantee tail-calling, so we should automatically insert `stack_rewind` stages into
// long programs.
REPORTER_ASSERT(r, skstd::contains(as_string_view(dump), "stack_rewind"));
#endif
}
DEF_TEST(RasterPipelineBuilderTraceOps, r) {
for (bool provideDebugTrace : {false, true}) {
SkSL::RP::Builder builder;
// Create a trace mask stack on stack-ID 123.
builder.set_current_stack(123);
builder.push_constant_i(~0);
// Emit trace ops.
builder.trace_enter(123, 2);
builder.trace_scope(123, +1);
builder.trace_line(123, 456);
builder.trace_var(123, two_slots_at(3));
builder.trace_scope(123, -1);
builder.trace_exit(123, 2);
// Discard the trace mask.
builder.discard_stack(1);
if (!provideDebugTrace) {
// Test the output when no DebugTrace info is provided.
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/20,
/*numUniformSlots=*/0);
check(r, *program,
R"(copy_constant $0 = 0xFFFFFFFF
trace_enter TraceEnter(???) when $0 is true
trace_scope TraceScope(+1) when $0 is true
trace_line TraceLine(456) when $0 is true
trace_var TraceVar(v3..4) when $0 is true
trace_scope TraceScope(-1) when $0 is true
trace_exit TraceExit(???) when $0 is true
)");
} else {
// Test the output when we supply a populated DebugTrace.
SkSL::DebugTracePriv trace;
trace.fFuncInfo = {{"FunctionA"}, {"FunctionB"}, {"FunctionC"}, {"FunctionD"}};
SkSL::SlotDebugInfo slot;
slot.name = "Var0";
trace.fSlotInfo.push_back(slot);
slot.name = "Var1";
trace.fSlotInfo.push_back(slot);
slot.name = "Var2";
trace.fSlotInfo.push_back(slot);
slot.name = "Var3";
trace.fSlotInfo.push_back(slot);
slot.name = "Var4";
trace.fSlotInfo.push_back(slot);
std::unique_ptr<SkSL::RP::Program> program = builder.finish(/*numValueSlots=*/20,
/*numUniformSlots=*/0,
&trace);
check(r, *program,
R"(copy_constant $0 = 0xFFFFFFFF
trace_enter TraceEnter(FunctionC) when $0 is true
trace_scope TraceScope(+1) when $0 is true
trace_line TraceLine(456) when $0 is true
trace_var TraceVar(Var3, Var4) when $0 is true
trace_scope TraceScope(-1) when $0 is true
trace_exit TraceExit(FunctionC) when $0 is true
)");
}
}
}
#endif // SK_ENABLE_SKSL_IN_RASTER_PIPELINE
| [
"jengelh@inai.de"
] | jengelh@inai.de |
2d82f9af56bd8788534de8d2b424dd134cfa5639 | 05b78e1d23b44b5e1140bdfd809cb05fd669b235 | /code_cpp/engine_objects/mesh.h | 35c82413923edb6477e732a5e1cf3fceb4239fdc | [] | no_license | nasoym/fall_again_fall_better_engine | f0bdbd9bb30232cfaaa0a756016c4002f99f6ae5 | 0cc77d8f1f8a7f2634047591d0a1081aa8026180 | refs/heads/master | 2021-01-16T21:48:28.362945 | 2014-12-10T20:20:42 | 2014-12-10T20:20:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,987 | h | #ifndef _MESH_H
#define _MESH_H
#include <Ogre.h>
using namespace Ogre;
#include <vector>
#include <string>
#include "gui_shape.h"
class Engine;
class GuiContainer;
class Actor;
struct BoneBody {
Bone* bone;
Actor* body;
Joint*joint;
GuiContainer* container;
BoneBody(Bone* b) : bone(b),body(0),joint(0), container(0) {}
};
class MeshObject : public GuiShape {
public:
MeshObject(Engine*,const char*);
//virtual ~MeshObject();
virtual MeshObject* isMesh(){return this;}
virtual ObjectType getType(){ return MESH;}
void setupAllBones();
virtual void guiUpdate();
void updateBone(Bone* bone);
Bone* findRootBone();
Bone* getBoneParent(Bone* bone);
void boneSetPosition(Bone* bone,Vec3 vec3);
void boneSetOrientation(Bone* bone,Quat quat,bool rotated=true);
Actor* getBodyOfBone(Bone* bone);
Joint* getJointOfBone(Bone* bone);
Bone* getBoneOfBody(Actor* body);
void setBodyForBone(Bone* bone,Actor* body);
void setJointForBone(Bone* bone,Joint* joint);
Bone* getBoneFromName(std::string boneName);
Bone* getRootBone(){return mRootBone;}
//Debug
void setContainerForBone(Bone* bone,GuiContainer* container);
GuiContainer* getContainerOfBone(Bone* bone);
void createAllDebugObjects();
void createDebugForBone(Bone* bone);
// Python Api
std::string getFileName(){return mMeshFileName;}
int getNumberOfBones();
Actor* getBodyByIndex(int);
Joint* getJointByIndex(int);
std::string getBoneNameByIndex(int);
Actor* getBodyOfBoneName(std::string);
Joint* getJointOfBoneName(std::string);
void setBodyForBoneName(std::string,Actor*);
void setJointForBoneName(std::string,Joint*);
Vec3 getBoneNamePosition(std::string);
Quat getBoneNameOrientation(std::string,bool rotated=true);
float getBoneNameSize(std::string);
std::string getBoneNameParentName(std::string);
int getBoneNameChildren(std::string);
Vec3 getBoneNameLocalPosition(std::string);
Quat getBoneNameLocalOrientation(std::string);
std::string getBoneNameChildName(std::string boneName,int index);
std::string getRootBoneName(){return mRootBone->getName();}
Vec3 getMeshScale();
Vec3 getBonePosition(Bone* bone);
Quat getBoneOrientation(Bone* bone,bool rotated=true);
float getBoneSize(Bone* bone);
void calcLocalPosOfRootBone();
void setLocalPos(Vec3 vec){mLocalPos = vec;}
void setLocalQuat(Quat quat){mLocalQuat = quat;}
Vec3 getLocalPos(){ return mLocalPos;}
Quat getLocalQuat(){ return mLocalQuat;}
void setRotationX(float val){mRotationX=val;}
void setRotationY(float val){mRotationY=val;}
void setRotationZ(float val){mRotationZ=val;}
private:
std::vector<BoneBody> mBoneBodies;
Bone* mRootBone;
Vec3 mLocalPos;
Quat mLocalQuat;
std::string mMeshFileName;
GuiContainer* mRootShape;
float mRotationX;
float mRotationY;
float mRotationZ;
};
#endif
| [
"sinan@test.tmp"
] | sinan@test.tmp |
75bfcac4e9928a0fdae1defa0e95e018cb0cf0b4 | c610aa29c4195963768d4c3a3f0ca4350615206a | /src/base64.h | 6d1baf4ac9815307f177849293c17cb5f492d85a | [
"MIT"
] | permissive | bizzbyster/nghttp2 | a04de01c7db8aed3ddd218a7880aaa8799acebb0 | ecc4290d3dba768aa5abb224afdfc5955224c0a5 | refs/heads/master | 2020-12-31T00:09:33.144648 | 2014-01-07T17:15:46 | 2014-01-07T17:15:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,895 | h | /*
* nghttp2 - HTTP/2.0 C Library
*
* Copyright (c) 2013 Tatsuhiro Tsujikawa
*
* 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 BASE64_H
#define BASE64_H
#include <string>
namespace nghttp2 {
namespace base64 {
template<typename InputIterator>
std::string encode(InputIterator first, InputIterator last)
{
static const char CHAR_TABLE[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/',
};
std::string res;
size_t len = last-first;
if(len == 0) {
return res;
}
size_t r = len%3;
InputIterator j = last-r;
char temp[4];
while(first != j) {
int n = static_cast<unsigned char>(*first++) << 16;
n += static_cast<unsigned char>(*first++) << 8;
n += static_cast<unsigned char>(*first++);
temp[0] = CHAR_TABLE[n >> 18];
temp[1] = CHAR_TABLE[(n >> 12) & 0x3fu];
temp[2] = CHAR_TABLE[(n >> 6) & 0x3fu];
temp[3] = CHAR_TABLE[n & 0x3fu];
res.append(temp, sizeof(temp));
}
if(r == 2) {
int n = static_cast<unsigned char>(*first++) << 16;
n += static_cast<unsigned char>(*first++) << 8;
temp[0] = CHAR_TABLE[n >> 18];
temp[1] = CHAR_TABLE[(n >> 12) & 0x3fu];
temp[2] = CHAR_TABLE[(n >> 6) & 0x3fu];
temp[3] = '=';
res.append(temp, sizeof(temp));
} else if(r == 1) {
int n = static_cast<unsigned char>(*first++) << 16;
temp[0] = CHAR_TABLE[n >> 18];
temp[1] = CHAR_TABLE[(n >> 12) & 0x3fu];
temp[2] = '=';
temp[3] = '=';
res.append(temp, sizeof(temp));
}
return res;
}
template<typename InputIterator>
InputIterator getNext
(InputIterator first,
InputIterator last,
const int* tbl)
{
for(; first != last; ++first) {
if(tbl[static_cast<size_t>(*first)] != -1 || *first == '=') {
break;
}
}
return first;
}
template<typename InputIterator>
std::string decode(InputIterator first, InputIterator last)
{
static const int INDEX_TABLE[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
std::string res;
InputIterator k[4];
int eq = 0;
for(; first != last;) {
for(int i = 1; i <= 4; ++i) {
k[i-1] = getNext(first, last, INDEX_TABLE);
if(k[i-1] == last) {
// If i == 1, input may look like this: "TWFu\n" (i.e.,
// garbage at the end)
if(i != 1) {
res.clear();
}
return res;
} else if(*k[i-1] == '=' && eq == 0) {
eq = i;
}
first = k[i-1]+1;
}
if(eq) {
break;
}
int n = (INDEX_TABLE[static_cast<unsigned char>(*k[0])] << 18)+
(INDEX_TABLE[static_cast<unsigned char>(*k[1])] << 12)+
(INDEX_TABLE[static_cast<unsigned char>(*k[2])] << 6)+
INDEX_TABLE[static_cast<unsigned char>(*k[3])];
res += n >> 16;
res += n >> 8 & 0xffu;
res += n & 0xffu;
}
if(eq) {
if(eq <= 2) {
res.clear();
return res;
} else {
for(int i = eq; i <= 4; ++i) {
if(*k[i-1] != '=') {
res.clear();
return res;
}
}
if(eq == 3) {
int n = (INDEX_TABLE[static_cast<unsigned char>(*k[0])] << 18)+
(INDEX_TABLE[static_cast<unsigned char>(*k[1])] << 12);
res += n >> 16;
} else if(eq == 4) {
int n = (INDEX_TABLE[static_cast<unsigned char>(*k[0])] << 18)+
(INDEX_TABLE[static_cast<unsigned char>(*k[1])] << 12)+
(INDEX_TABLE[static_cast<unsigned char>(*k[2])] << 6);
res += n >> 16;
res += n >> 8 & 0xffu;
}
}
}
return res;
}
} // namespace base64
} // namespace nghttp2
#endif // BASE64_H
| [
"tatsuhiro.t@gmail.com"
] | tatsuhiro.t@gmail.com |
8c49649d167b350730b8b9e0171934595f2783c1 | a42e3ffa1f4eae517e2d631dce5e02939e9deed9 | /src/render/Texture.h | fa26346bb2d51d36b341380bddf8f391de385d2f | [] | no_license | Przemro/spooky | fab8b3d8dd7e015bf9fff77333d85a3c584ec28d | 81e57d7cf8301330d11eaa2013212024cc34abea | refs/heads/master | 2021-01-16T21:07:04.557060 | 2016-05-16T17:13:47 | 2016-05-16T17:13:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,529 | h | //
// Created by dar on 11/21/15.
//
#ifndef C003_TEXTURE_H
#define C003_TEXTURE_H
#pragma once
#include <string>
#include <map>
#include "opengl.h"
enum ETextureFiltering
{
TEXTURE_FILTER_MAG_NEAREST = 0, // Nearest criterion for magnification
TEXTURE_FILTER_MAG_BILINEAR, // Bilinear criterion for magnification
TEXTURE_FILTER_MIN_NEAREST, // Nearest criterion for minification
TEXTURE_FILTER_MIN_BILINEAR, // Bilinear criterion for minification
TEXTURE_FILTER_MIN_NEAREST_MIPMAP, // Nearest criterion for minification, but on closest mipmap
TEXTURE_FILTER_MIN_BILINEAR_MIPMAP, // Bilinear criterion for minification, but on closest mipmap
TEXTURE_FILTER_MIN_TRILINEAR, // Bilinear criterion for minification on two closest mipmaps, then averaged
};
class Texture
{
public:
Texture();
~Texture();
void createFromData(unsigned char* data);
bool loadTexture2D(std::string path, bool mipmaps = false);
void bindTexture(int bindId = 0);
void setFiltering(int filterMag, int filterMin);
void setSamplerParameter(GLenum parameter, GLenum value);
int getMinificationFilter() const;
int getMagnificationFilter() const;
int getWidth() const;
int getHeight() const;
int getChannels() const;
int getBoundId() const;
private:
int width, height, channels;
GLuint id;
bool mipmaps;
int boundId = -1;
int filterMin, filterMag;
std::string path;
static int boundTexId;
static int activeTexId;
};
#endif //C003_TEXTURE_H
| [
"darek.stojaczyk@gmail.com"
] | darek.stojaczyk@gmail.com |
422045acc635f61e9a703c3501eb5c34ea6e9306 | 61337b745c1ed7495df499248793e08998497cba | /web_server/Entry.h | eed07074afd6242976b9118ad93d5f895f0ece21 | [] | no_license | serifycode/web_server | bd7874d4ce52addde9281c1ad47ade78d9e62b60 | fc0e0eb78b312259d673fb1dc2f8f588f20bbdd2 | refs/heads/master | 2021-02-13T18:11:45.542375 | 2020-04-06T14:39:32 | 2020-04-06T14:39:32 | 244,717,485 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 550 | h | //弱指针保存connection,析构时shutdown
#ifndef ENTRY_H
#define ENTRY_H
#include "TcpConnection.h"
#include "copyable.h"
#include <memory>
class Entry : public copyable
{
public:
explicit Entry(const WeakTcpConnectionPtr& weakcon)
:weakcon_(weakcon)
{}
~Entry()
{
TcpConnectionPtr conn=weakcon_.lock();
if(conn)
conn->Shutdown();//跨线程
}
public:
WeakTcpConnectionPtr weakcon_;
};
typedef std::shared_ptr<Entry> EntryPtr;
typedef std::weak_ptr<Entry> WeakEntryPtr;
#endif | [
"2573654221@qq.com"
] | 2573654221@qq.com |
7e6d09a1c84e427e99dbd6d9ecb3e9a6c5f10be4 | 09aa1eb41c319fc1e2aa7206f0386594de198c0b | /内積の課題_01/Question/game/stdafx.h | cb6765f4b08631f8a06ecdfefc0436a989a91b3e | [] | no_license | nezumimusume/DirectX_2 | 7d22e155b9790ab07ac97481e68b3ae7a4f0d6b2 | ba4b76250b86ca09bb2a1be294e5f1b19030a09f | refs/heads/master | 2023-07-22T18:42:17.647383 | 2018-04-16T13:04:08 | 2018-04-16T13:04:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 411 | h | #pragma once
#include <d3d9.h>
#include <d3dx9effect.h>
#pragma warning( disable : 4996 )
#include <strsafe.h>
#pragma warning( default : 4996 )
#include <cstdlib>
#include <memory>
#include <vector>
#include <list>
#include <map>
#include "lib/System.h"
#include "lib/Camera.h"
#include "lib/SkinModel.h"
#include "lib/SkinModelData.h"
#include "lib/Animation.h"
#include "lib/Light.h"
#include "lib/util.h"
| [
"nezumimusume30@gmail.com"
] | nezumimusume30@gmail.com |
14d3f451d7bd2af9c11f2cffb6b8d5fe7d4c55cb | 3acf1a58ff5f88f4723f02dd911fb5820b7bbc1f | /Import/Import/OLD/Import 0.1.cpp | ed4a9b0e86625ea45ad40bb9e3813a22a1c9784f | [] | no_license | xiangbin1997/Facebull-1 | e378f339c4df692f9b64096a9c4f7140be4c68b0 | 1f484e192916a8eb92df93467a71669e799f472a | refs/heads/master | 2021-01-12T03:52:41.366061 | 2011-07-13T16:18:29 | 2011-07-13T16:18:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,740 | cpp | // Import.cpp : Defines the entry point for the console application.
//
#include "stdlib.h"
//#include "stdio.h"
#include "stdafx.h"
#include "line_count.h"
//#include "lookup_store.cpp"
//#ifndef FILE_IN "D:\\Matlab\\Assigments\\MATLAB\\Facebull\\06_3.in"
//#define FILE_IN "D:\\Matlab\\Assigments\\MATLAB\\Facebull\\06_3.in"
//#endif
//int *lookup_pointer;
//static int no_of_lines=0;
int main(int argc, _TCHAR* argv[])
{
int newMachine, a, newSource, newTarget, newCost, c, n;
FILE *file_pointer;
n=0;
file_pointer=fopen(FILE_IN,"r");
no_of_lines=line_count();
// Main part; Reads a line and calls lookup_store
rewind(file_pointer);
//// Initialise dummy node of lookup table; head is the pointer to the first node in the list
struct arc* head = initialise_lookup();
struct arc* tail = head;
while (c=getc(file_pointer) != EOF){
if (n++==0) {
ungetc(c,file_pointer);}
fscanf(file_pointer, "%*c");
if (fscanf(file_pointer, "%d", &newMachine) == EOF){break;}
fscanf(file_pointer, "%*1s");
fscanf(file_pointer, "%d", &newSource);
fscanf(file_pointer, "%*1s");
fscanf(file_pointer, "%d", &newTarget);
fscanf(file_pointer, "%d", &newCost);
printf("%d %s", head, "\n" );
head = lookup_store(head, newMachine, newSource, newTarget, newCost);
}
///////////////////////////// To disp whole list, iterate through
struct arc* head_temp=head;
for (int i=0; i<no_of_lines; i++){
printf("%d %d %d %d %s", (*head_temp).machine, (*head_temp).source, (*head_temp).target, (*head_temp).cost, "\n");
head_temp = (*head_temp).next;
}
head_temp=head;
////////////////////////////////////////////////////////
scanf("%d", &a);
fclose(file_pointer);
return 0;
}
| [
"a.f.gaungoo@gmail.com"
] | a.f.gaungoo@gmail.com |
628a0e44541fbeca703bbc92e50e1e1b7f399732 | 26ac7837de540d915cdfa7783a65dde9bd311e4b | /Source/TiAALS/Utilities/Images/IRIconBank/IRIconBank.hpp | 6f3d4d5652d8b5c300bb0dbb1eaeaf7f98e927b8 | [] | no_license | KeitaroTakahashi/TiAALS_FULL | cfdf98a81f5e95f35fb3c7f36837d35856cdcf88 | 21cbdd04c5caf7b7de7bcc638056ad5af9ded5b0 | refs/heads/master | 2023-02-20T17:43:19.929814 | 2021-01-23T13:57:54 | 2021-01-23T13:57:54 | 320,263,467 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,330 | hpp | //
// IRIconBank
// InteractiveAutomation - App
//
// Created by Keitaro on 02/05/2019.
//
#ifndef IRIconBank_hpp
#define IRIconBank_hpp
#include "JuceHeader.h"
#include "singletonClass.hpp"
class IRIconBank
{
public:
struct IRIconImage
{
Image white;
Image black;
Image gray;
Image small_white;
Image small_black;
Image small_gray;
};
struct IRLogoImage
{
Image small; // 177 x 345
Image medium; // 355 x 690
Image large; // 710 x 1380
};
IRIconBank();
~IRIconBank();
void loadImages();
IRIconImage getZoomIn() const { return this->icon_zoomIn; }
IRIconImage getZoomOut() const { return this->icon_zoomOut; }
IRIconImage getHorizontalMovable() const { return this->icon_horizontalMovable; }
IRIconImage getVerticalMovable() const { return this->icon_verticalMovable; }
IRIconImage getCrossMovable() const { return this->icon_crossMovable; }
IRIconImage getNotMovable() const { return this->icon_notMovable; }
IRIconImage getComment() const { return this->icon_comment; }
IRIconImage getBezier() const { return this->icon_bezier; }
IRIconImage getLinear() const { return this->icon_linear; }
IRIconImage loadImageAndReturn(String url);
IRIconImage loadImageWithSmallAndReturn(String url);
IRIconImage icon_addPage;
IRIconImage icon_addPage2;
IRIconImage icon_newSlide_noFrame;
IRIconImage icon_newSlide;
IRIconImage icon_deleteSlide;
IRIconImage icon_inspector;
IRIconImage icon_load;
IRIconImage icon_loop;
IRIconImage icon_newProject; // used
IRIconImage icon_object;
IRIconImage icon_object_type1;
IRIconImage icon_preference;
IRIconImage icon_save;
IRIconImage icon_save_noFrame;
IRIconImage icon_toNavigator;
IRIconImage icon_toObjectMenu;
IRIconImage icon_saveProject_noFrame;
IRIconImage icon_openProject_noFrame;
IRIconImage icon_saveasProject_noFrame;
IRIconImage icon_saveProject_arrow;
IRIconImage icon_saveasProject_arrow;
IRIconImage icon_openProject_arrow; // used
IRIconImage icon_close;
IRIconImage icon_text;
IRIconImage icon_chart;
IRIconImage icon_image;
IRIconImage icon_play;
IRIconImage icon_pause;
IRIconImage icon_stop;
IRIconImage icon_wav;
IRIconImage icon_rightBar;
IRIconImage icon_leftBar;
// square icon
IRIconImage icon_active;
IRIconImage icon_search;
//Event
IRIconImage icon_AudioEvent;
IRIconImage icon_ImageEvent;
IRIconImage icon_ShapeEvent;
IRIconImage icon_TextEvent;
// logo
IRLogoImage logo_darkMagenta;
IRLogoImage logo_darkBlue;
IRLogoImage logo_darkGreen;
IRLogoImage loadLogoImage(String url);
private:
IRIconImage loadImage(String url);
IRIconImage loadWithSmallImage(String url);
IRIconImage icon_zoomIn;
IRIconImage icon_zoomOut;
IRIconImage icon_horizontalMovable;
IRIconImage icon_verticalMovable;
IRIconImage icon_crossMovable;
IRIconImage icon_notMovable;
IRIconImage icon_comment;
IRIconImage icon_bezier;
IRIconImage icon_linear;
};
#endif /* IRIconBank_hpp */
| [
"neoterize@mac.com"
] | neoterize@mac.com |
d7936c66ac4ec93a732a4c886240a837e6b7c44e | 41ea20766b0c5d3da7e9e09a73e9655f8d4aa3f8 | /hr/hr26_disjointsets.cpp | 4df6f1dd3268aa23ae1457d22b49e5002cc5b78e | [] | no_license | Manthan-R-Sheth/CodingHub | e8b5592a604f1e4a6cf1f3f08a27ee8f3c965720 | 23862de9b483b78c9493ef1475ea070eebe02ace | refs/heads/master | 2021-01-23T23:45:55.265333 | 2018-02-24T11:24:06 | 2018-02-24T11:24:06 | 122,733,890 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,304 | cpp | #include<cmath>
#include<cstdio>
#include<vector>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<climits>
using namespace std;
// a structure to represent an edge in graph
int maxi=INT_MIN,mini=INT_MAX;
struct Edge
{
int src, dest;
};
// a structure to represent a graph
struct Graph
{
// V-> Number of vertices, E-> Number of edges
int V, E;
// graph is represented as an array of edges
struct Edge* edge;
};
struct subset
{
int parent;
int rank;
int height;
};
// Creates a graph with V vertices and E edges
struct Graph* createGraph(int V, int E)
{
struct Graph* graph = (struct Graph*) malloc( sizeof(struct Graph) );
graph->V = V;
graph->E = E;
graph->edge = (struct Edge*) malloc( graph->E * sizeof( struct Edge ) );
return graph;
}
// A utility function to find set of an element i
// (uses path compression technique)
int find(struct subset subsets[], int i)
{
// find root and make root as parent of i (path compression)
if (subsets[i].parent != i)
subsets[i].parent = find(subsets, subsets[i].parent);
return subsets[i].parent;
}
// A function that does union of two sets of x and y
// (uses union by rank)
void Union(struct subset subsets[], int g, int b)
{
int groot = find(subsets, g);
int broot = find(subsets, b);
// Attach smaller rank tree under root of high rank tree
// (Union by Rank)
if (subsets[groot].rank < subsets[broot].rank)
{
subsets[groot].parent = broot;
subsets[broot].height+=subsets[groot].height;
subsets[groot].height=1;
}
else
if (subsets[groot].rank > subsets[broot].rank)
{
subsets[broot].parent = groot;
subsets[groot].height+=subsets[broot].height;
subsets[broot].height=1;
}
// If ranks are same, then make one as root and increment
// its rank by one
else
{
subsets[broot].parent = groot;
subsets[groot].rank++;
subsets[groot].height+=subsets[broot].height;
subsets[broot].height=1;
}
}
// The main function to check whether a given graph contains cycle or not
pair<int,int> maxmin( struct Graph* graph )
{
int V = graph->V;
int E = graph->E;
// Allocate memory for creating V sets
struct subset *subsets = (struct subset*) malloc( V * sizeof(struct subset) );
for (int v = 0; v < V; ++v)
{
subsets[v].parent = v;
subsets[v].rank = 0;
subsets[v].height=1;
}
for(int e = 0; e < E; ++e)
{
int g = find(subsets, graph->edge[e].src);
int b = find(subsets, graph->edge[e].dest);
if(g!=b)
{
Union(subsets, g, b);
}
}
for (int v = 0; v < V; ++v)
{
if(subsets[v].height>maxi)
{
maxi=subsets[v].height;
}
if(subsets[v].height<mini && subsets[v].height>1)
{
mini=subsets[v].height;
}
}
return make_pair(mini,maxi);
}
// Driver program to test above functions
int main()
{
int n,g,b;
cin>>n;
struct Graph* graph = createGraph(2*n, n);
for(int i=0;i<n;i++)
{
cin>>g>>b;
graph->edge[i].src = g;
graph->edge[i].dest = b;
}
pair<int,int> ans=maxmin(graph);
cout<<ans.first<<" "<<ans.second<<endl;
} | [
"manthanrsheth96@gmail.com"
] | manthanrsheth96@gmail.com |
8e5989d36d822e9be6bc3695e38ecd598c70396a | ff0cc7e931d038a9bd9a56665b20cd8dab071959 | /src/Modules/BaseLib/libmodules/blIO/src/blV3DImageFileReader.cpp | 9ffe0b66e4de696576cbd7dbda025b969c5583f4 | [] | no_license | jakubsadura/Swiezy | 6ebf1637057c4dbb8fda5bfd3f57ef7eec92279b | bd32b7815b5c0206582916b62935ff49008ee371 | refs/heads/master | 2016-09-11T00:39:59.005668 | 2011-05-22T19:38:33 | 2011-05-22T19:38:33 | 1,784,754 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 13,977 | cpp | /*
* Copyright (c) 2009,
* Computational Image and Simulation Technologies in Biomedicine (CISTIB),
* Universitat Pompeu Fabra (UPF), Barcelona, Spain. All rights reserved.
* See license.txt file for details.
*/
#include "blV3DImageFileReader.h"
//--------------------------------------------------
blV3DImageFileReader::blV3DImageFileReader()
//--------------------------------------------------
{
// allocation and initialization of vectors representing Origin, Spacing and Dimensions
this->v3Origin.resize(3);
this->SetOrigin(0.0f, 0.0f, 0.0f);
this->v3Spacing.resize(3);
this->SetSpacing(0.0f, 0.0f, 0.0f);
this->v3Dimensions.resize(3);
this->SetDimensions(0.0f, 0.0f, 0.0f);
// initialization of scale factor
this->SetScale(1.0f);
// manual selection of origin, spacing, dimensions and scaling are disabled
this->SetOriginOff();
this->SetSpacingOff();
this->SetDimensionsOff();
this->SetScaleDataOff();
// initialization of fileName
this->SetFileName("");
// initialization of image data object to NULL
this->SetVTKDataObject(NULL);
// default value: no byte swapping is necessary
this->SetSwapOff();
// default value: unsigned short data type
this->SetType(BLV3Dushort);
// default value: no unit conversion is necessary
this->SetUnitConversion(BLV3DnoConv);
// default value: no verbose
this->SetVerboseOff();
// default value: initialization to 0 of the header size
this->SetHeaderSize(0);
// initialize the image object to NULL
this->SetVTKDataObject(NULL);
// initialize the image object to NULL
this->SetITKDataObject(NULL);
}
//--------------------------------------------------
blV3DImageFileReader::~blV3DImageFileReader()
//--------------------------------------------------
{
// restoring the default values to the object before destroying
this->SetOrigin(0.0f, 0.0f, 0.0f);
this->SetSpacing(0.0f, 0.0f, 0.0f);
this->SetDimensions(0.0f, 0.0f, 0.0f);
this->SetOriginOff();
this->SetSpacingOff();
this->SetDimensionsOff();
this->SetScaleDataOff();
this->SetFileName("");
this->SetVTKDataObject(NULL);
this->SetSwapOff();
this->SetType(BLV3Dushort);
this->SetUnitConversion(BLV3DnoConv);
this->SetScale(1.0f);
this->SetVerboseOff();
this->SetHeaderSize(0);
if (this->vtkImageObj != NULL) this->vtkImageObj->Delete();
this->SetVTKDataObject(NULL);
}
//--------------------------------------------------
void blV3DImageFileReader::Update()
//--------------------------------------------------
{
// read the data from the v3d file and update the member variables with the data describing its contents
this->ReadDataFromV3D();
// using the data read from the v3d file create a VTK object with the same characteristics and contents
this->CreateVTKDataObject();
this->CreateITKDataObject();
}
//--------------------------------------------------
void blV3DImageFileReader::ReadDataFromV3D()
//--------------------------------------------------
{
this->SetHeaderSize(40 + 6*8 + 6*4);
// open the header file
FILE * fp;
fp = fopen(this->fileName.c_str(), "r");
// read version
char buf[128];
ReadBytes( buf, sizeof(char), 10, fp);
buf[11] = '\0';
rewind(fp);
//int ver = ( buf[7] == '4' ) ? 4 : 3;
//int ver = atof( (const char*)buf[7] );
std::cout << buf << std::endl;
int ver = 4;
if (buf[7]=='3')
ver = 3;
else if (buf[7]=='4')
ver = 4;
else if (buf[7]=='6')
ver = 6;
// The rewind function positions the stream at the beginning of the file. It is
// equivalent to calling fseek or fseeko on the stream with an offset argument of 0L and
// a whence argument of SEEK_SET, except that the return value is discarded and the error
// indicator for the stream is reset.
// The fseek function is used to change the file position of the stream. The value of whence
// must be one of the constants SEEK_SET, SEEK_CUR, or SEEK_END, to indicate whether the
// offset is relative to the beginning of the file, the current file position, or the end
// of the file, respectively.
// Reads v3d versions 3 or 4
//if (ver == 3)
// ReadV3Dversion3(fp);
//else
// ReadV3Dversion4(fp);
switch ( ver )
{
case 3 :
// Process for ver = 3
ReadV3Dversion3(fp);
break;
case 4 :
// Process for test = 4
ReadV3Dversion4(fp);
break;
case 6 :
// Process for test = 4
ReadV3Dversion6(fp);
break;
default :
// Process for all other cases.
ReadV3Dversion4(fp);
}
fclose(fp);
}
//--------------------------------------------------
void blV3DImageFileReader::ReadV3Dversion3(FILE * fp)
//--------------------------------------------------
{
// read header
int nx, ny, nz; //number of voxel in X, Y, and Z
double x0, y0, z0; //origin
double x1, y1, z1;
double dx, dy, dz; //spacing (voxels size)
//Sets the position indicator associated with the stream at the beginning of file.
fseek(fp, 84, SEEK_SET);
ReadBytes( (void*)&x0, sizeof(double), 1, fp );
ReadBytes( (void*)&y0, sizeof(double), 1, fp );
ReadBytes( (void*)&z0, sizeof(double), 1, fp );
ReadBytes( (void*)&x1, sizeof(double), 1, fp );
ReadBytes( (void*)&y1, sizeof(double), 1, fp );
ReadBytes( (void*)&z1, sizeof(double), 1, fp );
ReadBytes( (void*)&nx, sizeof(int), 1, fp ); //Number Of Voxels in X direction
ReadBytes( (void*)&ny, sizeof(int), 1, fp ); //Number Of Voxels in Y direction
ReadBytes( (void*)&nz, sizeof(int), 1, fp ); //Number Of Voxels in Z direction
dx = (x1-x0)/((double)nx); //Spacing in X
dy = (y1-y0)/((double)ny); //Spacing in Y
dz = (z1-z0)/((double)nz); //Spacing in Z
x0 = 0.5*(x1 + x0);
y0 = 0.5*(y1 + y0);
z0 = 0.5*(z1 + z0);
this->SetHeaderSize(84 + 6 * 8 + 3 * 4);
if (!this->bDimensions) this->SetDimensions(nx, ny, nz);
if (!this->bSpacing) this->SetSpacing(dx, dy, dz);
if (!this->bOrigin) this->SetOrigin(x0, y0, z0);
if (this->blV3DUnitConvType == BLV3Dmm2cm) this->SetSpacing(dx/10.0f, dy/10.0f, dz/10.0f);
}
//--------------------------------------------------
void blV3DImageFileReader::ReadV3Dversion4(FILE * fp)
//--------------------------------------------------
{
// read header
int nx, ny, nz; //number of voxel in X, Y, and Z
int nd, np, nf;
double x0, y0, z0; //origin
double dx, dy, dz; //spacing (voxels size)
fseek(fp, 40, SEEK_SET);
ReadBytes( (void*)&nx, sizeof(int), 1, fp );
ReadBytes( (void*)&ny, sizeof(int), 1, fp );
ReadBytes( (void*)&nz, sizeof(int), 1, fp );
ReadBytes( (void*)&dx, sizeof(double), 1, fp );
ReadBytes( (void*)&dy, sizeof(double), 1, fp );
ReadBytes( (void*)&dz, sizeof(double), 1, fp );
ReadBytes( (void*)&x0, sizeof(double), 1, fp );
ReadBytes( (void*)&y0, sizeof(double), 1, fp );
ReadBytes( (void*)&z0, sizeof(double), 1, fp );
ReadBytes( (void*)&nd, sizeof(int), 1, fp );
ReadBytes( (void*)&np, sizeof(int), 1, fp );
ReadBytes( (void*)&nf, sizeof(int), 1, fp );
this->SetHeaderSize(40 + 3 * 4 + 6 * 8 + 3 * 4);
if (!this->bDimensions) this->SetDimensions(nx, ny, nz);
if (!this->bSpacing) this->SetSpacing(dx, dy, dz);
if (!this->bOrigin) this->SetOrigin(x0, y0, z0);
if (this->blV3DUnitConvType == BLV3Dmm2cm) this->SetSpacing(dx/10.0f, dy/10.0f, dz/10.0f);
}
//--------------------------------------------------
void blV3DImageFileReader::ReadV3Dversion6(FILE * fp)
//--------------------------------------------------
{
// read header
int nx, ny, nz; //number of voxel in X, Y, and Z
int nd, np, nf;
double x0, y0, z0; //origin
double dx, dy, dz; //spacing (voxels size)
fseek(fp, 40, SEEK_SET);
ReadBytes( (void*)&nx, sizeof(int), 1, fp );
ReadBytes( (void*)&ny, sizeof(int), 1, fp );
ReadBytes( (void*)&nz, sizeof(int), 1, fp );
ReadBytes( (void*)&dx, sizeof(double), 1, fp );
ReadBytes( (void*)&dy, sizeof(double), 1, fp );
ReadBytes( (void*)&dz, sizeof(double), 1, fp );
ReadBytes( (void*)&x0, sizeof(double), 1, fp );
ReadBytes( (void*)&y0, sizeof(double), 1, fp );
ReadBytes( (void*)&z0, sizeof(double), 1, fp );
ReadBytes( (void*)&nd, sizeof(int), 1, fp );
ReadBytes( (void*)&np, sizeof(int), 1, fp );
ReadBytes( (void*)&nf, sizeof(int), 1, fp );
this->SetHeaderSize(40 + 3 * 4 + 6 * 8 + 3 * 4 + 92); //in total 204
//not sure if the headers are like this!
if (!this->bDimensions) this->SetDimensions(nx, ny, nz);
if (!this->bSpacing) this->SetSpacing(dx, dy, dz);
if (!this->bOrigin) this->SetOrigin(x0, y0, z0);
if (this->blV3DUnitConvType == BLV3Dmm2cm) this->SetSpacing(dx/10.0f, dy/10.0f, dz/10.0f);
}
//--------------------------------------------------
void blV3DImageFileReader::ReadBytes(void *ptr, int size, int num, FILE * fp)
//--------------------------------------------------
{
fread( (void*)ptr, size, num, fp);
if(this->bSwapBytes == 1)
SwapBytes( (void*)ptr, size, num);
}
//--------------------------------------------------
void blV3DImageFileReader::SwapBytes(void *ptr, int size, int num)
//--------------------------------------------------
{
//For swaping header bytes
register int i, ii;
char c;
char *buf = (char*)ptr;
#define ZSWAP(A,B) {c = A; A = B; B = c;}
switch( size )
{
case 1: break;
case 2:
for(i = 0; i < num; i++)
{
ii = i + i;
ZSWAP( buf[ii+0], buf[ii+1] );
}
break;
case 4:
for(i = 0; i < num; i++)
{
ii = i + i + i + i;
ZSWAP( buf[ii+0], buf[ii+3] );
ZSWAP( buf[ii+1], buf[ii+2] );
}
break;
case 8:
for(i = 0; i < num; i++)
{
ii = i + i + i + i + i + i + i + i;
ZSWAP( buf[ii+0], buf[ii+7] );
ZSWAP( buf[ii+1], buf[ii+6] );
ZSWAP( buf[ii+2], buf[ii+5] );
ZSWAP( buf[ii+3], buf[ii+4] );
}
break;
}
#undef ZSWAP
}
//--------------------------------------------------
void blV3DImageFileReader::CreateVTKDataObject()
//--------------------------------------------------
{
vtkImageReader *reader = vtkImageReader::New();
// allocate memory for vtkImageData
this->vtkImageObj = vtkImageData::New();
reader->SetFileName(this->GetFileName().c_str());
reader->SetHeaderSize(this->GetHeaderSize());
reader->SetDataScalarType(this->blV3DType);
reader->SetSwapBytes(this->bSwapBytes);
reader->SetFileDimensionality(3);
reader->SetDataOrigin(this->v3Origin[0], this->v3Origin[1], this->v3Origin[2]);
reader->SetDataSpacing(this->v3Spacing[0], this->v3Spacing[1], this->v3Spacing[2]);
reader->SetDataExtent(0, this->v3Dimensions[0]-1, 0, this->v3Dimensions[1]-1, 0, this->v3Dimensions[2]-1);
reader->SetNumberOfScalarComponents(1);
reader->SetScalarArrayName("ImageFile");
reader->FileLowerLeftOn();
reader->Update();
if (this->bVerbose)
{
cout<< "v3d image data has:\n\t"
<< reader->GetOutput()->GetNumberOfPoints() << " Points\n\t"
<< reader->GetOutput()->GetNumberOfCells () << " Cells "
<< endl;
cerr << "Original image has "
<< "\nrange : " <<"\t" << reader->GetOutput()->GetScalarRange()[0]
<<"\t" << reader->GetOutput()->GetScalarRange()[1]
<<"\nData Object Type : " << reader->GetOutput()->GetDataObjectType()
<< endl;
}
if ( !this->bScaleData)
{
//this->SetVTKDataObject(reader->GetOutput());
vtkImageData* tmpImageData; //= vtkImageData::New();
tmpImageData = reader->GetOutput();
this->vtkImageObj->DeepCopy(tmpImageData);
}
else {
float rangeMin = (double)reader->GetOutput()->GetScalarRange()[0];
float rangeMax = (double)reader->GetOutput()->GetScalarRange()[1];
float scale = 1.0/(rangeMax - rangeMin);
// load voxels
// loading voxels into buffer
this->vtkImageObj->SetSpacing(this->v3Spacing[0], this->v3Spacing[1], this->v3Spacing[2]);
this->vtkImageObj->SetOrigin(this->v3Origin[0], this->v3Origin[1], this->v3Origin[2]);
this->vtkImageObj->SetDimensions(this->v3Dimensions[0],this->v3Dimensions[1],this->v3Dimensions[2]);
this->vtkImageObj->SetExtent(0, this->v3Dimensions[0]-1, 0, this->v3Dimensions[1]-1, 0, this->v3Dimensions[2]-1);
this->vtkImageObj->SetScalarTypeToFloat();
this->vtkImageObj->AllocateScalars();
this->vtkImageObj->Update();
vtkDataArray * scalars = reader->GetOutput()->GetPointData()->GetScalars();
float * scalars1 = (float *)this->vtkImageObj->GetScalarPointer();
unsigned int nVoxels = reader->GetOutput()->GetNumberOfPoints();
register unsigned int ptId;
for( ptId = 0; ptId < nVoxels; ptId++ )
{
scalars1[ptId] = scale * ( (float)scalars->GetComponent(ptId,0) - rangeMin);
}
}
if(this->bVerbose)
{
cout<< "v3d vtkImageObj data has:\n\t"
<< "Origin = [" << reader->GetOutput()->GetOrigin()[0] << " "
<< reader->GetOutput()->GetOrigin()[1] << " "
<< reader->GetOutput()->GetOrigin()[2] << " ]\n\t"
<< "Spacing = [" << reader->GetOutput()->GetSpacing()[0] << " "
<< reader->GetOutput()->GetSpacing()[1] << " "
<< reader->GetOutput()->GetSpacing()[2] << " ]\n\t"
<< "Dimension = [" << reader->GetOutput()->GetDimensions()[0] << " "
<< reader->GetOutput()->GetDimensions()[1] << " "
<< reader->GetOutput()->GetDimensions()[2] << " ]"
<< endl;
}
reader->Delete();
}
//--------------------------------------------------
void blV3DImageFileReader::CreateITKDataObject()
//--------------------------------------------------
{
typedef itk::VTKImageToImageFilter < base::UnsignedShortVolumeType > ConnectorType;
ConnectorType::Pointer connector = ConnectorType::New();
connector->SetInput((vtkImageData*)this->vtkImageObj);
connector->Update();
this->itkVolumeObj = connector->GetOutput();
}
#ifdef BASELIB_TESTING
namespace blTests
{
int blV3DImageFileReaderTest( string fileName )
{
cout << fileName << endl;
mvLib::blV3DImageFileReader::Pointer pV3DImageFileReader = mvLib::blV3DImageFileReader::New();
pV3DImageFileReader->SetVerboseOn();
pV3DImageFileReader->SetFileName(fileName);
try
{
pV3DImageFileReader->Update();
}
catch ( itk::ExceptionObject &err)
{
std::cout << "blV3DImageFileReaderTest::ExceptionObject caught !" << std::endl;
std::cout << err << std::endl;
return -1;
}
return 0;
}
} // blTests namespace
#endif // BASELIB_TESTING
| [
"spam@sadura.pl"
] | spam@sadura.pl |
6be5b577afbc5eddfb46e08cba073ea79cf0c264 | e46bd22112c15d9558ad9531deef183849636d62 | /UVA/Volume 118 (11800 - 11899)/11835 - Formula 1.cpp | f870e23bf4bca5bbf43135350c0dcb1ccd7bbb92 | [] | no_license | jariasf/Online-Judges-Solutions | 9082b89cc6d572477dbfb89ddd42f81ecdb2859a | 81745281bd0099b8d215754022e1818244407721 | refs/heads/master | 2023-04-29T20:56:32.925487 | 2023-04-21T04:59:27 | 2023-04-21T04:59:27 | 11,259,169 | 34 | 43 | null | 2020-10-01T01:41:21 | 2013-07-08T16:23:08 | C++ | UTF-8 | C++ | false | false | 1,463 | cpp | /*****************************************
***Problema: Formula 1
***ID: 11835
***Juez: UVA
***Tipo: Ad hoc
***Autor: Jhosimar George Arias Figueroa
******************************************/
#include <stdio.h>
#include <cstring>
#define MAX 108
int main(){
int g , n , s , k;
int a[ MAX ] , position[ 105 ][ MAX ] , points[ MAX ];
while( scanf("%d %d" , &g , &n ) , g|n ){
for( int j = 0 ; j < g ; ++j ){
for( int i = 0 ; i < n ; ++i ){
scanf("%d" , &position[ j ][ i ] );
}
}
scanf("%d" , &s );
while( s-- ){
scanf("%d" , &k );
memset( points , 0 , sizeof( points ) );
memset( a , 0 , sizeof( a ) );
for( int i = 0 ; i < k ; ++i ) scanf("%d" , &points[ i ]);
for( int i = 0 ; i < g ; ++i ){
for( int j = 0 ; j < n ; ++j ){
a[ j ] += points[ position[ i ][ j ] - 1 ];
}
}
int maxi = 0;
for( int i = 0 ; i < n ; ++i ){
if( a[ i ] > maxi ) maxi = a[ i ];
}
bool first = true;
for( int i = 0 ; i < n ; ++i ){
if( a[ i ] == maxi ){
if( !first ) printf(" ");
printf("%d" , i + 1 );
first = false;
}
}
printf("\n");
}
}
return 0;
}
| [
"jariasf03@gmail.com"
] | jariasf03@gmail.com |
9bbbd778899032c2ee859f2af7466aa7d909ec6c | 669d94bf6944e69a2fb1ae0667c4aede1ffa1615 | /Servo/Servo.ino | df4e766b4b6733299353769503e5f771a738fd5f | [] | no_license | kalte0/clubRPI | 569bfa2281410a1df85e0c0d494a377ff0f024bf | 3bd99e3035c0c90ead5b2b673354345dc97635f1 | refs/heads/master | 2021-03-13T07:36:09.101202 | 2020-06-12T16:00:43 | 2020-06-12T16:00:43 | 246,653,557 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 497 | ino | #include <Adafruit_LEDBackpack.h>
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver(0x40, Wire);
#define SERVO_FREQ 60 // Analog servos run at ~60 Hz updates
void setup() {
Serial.begin(9600);
pwm.begin();
pwm.setOscillatorFrequency(27000000);
pwm.setPWMFreq(SERVO_FREQ);
pwm.writeMicroseconds(0, 1500);
delay(6000);
}
void loop() {
pwm.writeMicroseconds(0,1900);
delay(3000);
pwm.writeMicroseconds(0,1100);
delay(3000);
}
| [
"renata@cyren.org"
] | renata@cyren.org |
2d1614d546dd4b6bad8f052c0a18f890c3680762 | 8a02f56077a3242e3bf7c0136eff08876bad7c8f | /ex_L3_6/main.cpp | d00364853963ddf0ca82586f7e00b089971d6ec0 | [
"MIT"
] | permissive | alfunx/UZH-BINF4213 | 0850b748f3836128699b64532650a3e184400ff4 | a4c8468a21807e61c827b32410508566664a27c1 | refs/heads/master | 2020-03-29T19:34:53.034757 | 2019-01-20T09:43:36 | 2019-01-20T09:43:36 | 150,270,680 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 707 | cpp | #include <functional>
#include <iostream>
using namespace std;
struct foo {
std::string name;
foo(std::string name) : name(name) { /* void */ }
void say_hello()
{
cout << "Hello, World! Here's " << name << "." << endl;
}
};
int main(int argc, char** argv)
{
vector<foo*> foobar;
foo bar("bar");
foo baz("baz");
foo qux("qux");
foobar.push_back(&bar);
foobar.push_back(&baz);
foobar.push_back(&qux);
for (vector<foo*>::iterator i = foobar.begin(); i < foobar.end(); i++)
(*i)->say_hello();
auto greet = std::mem_fun(&foo::say_hello);
for_each(foobar.begin(), foobar.end(), greet);
// or
for (auto f : foobar)
f->say_hello();
for (auto f : foobar)
greet(f);
return 0;
}
| [
"alphonse.mariya@hotmail.com"
] | alphonse.mariya@hotmail.com |
b9477a84114103058b8d2805d8e80ca6aa43b403 | 6d9a1f50a40da21b5bb24ae43cbc42ae992927b5 | /text_speed_thrust_current.cpp | 3b7c77fc6e03dc59dbd9ff19611ca0373b9d8a4b | [] | no_license | RioZon/gtkp_table | 719262ea1a3f724cd193bfa7c8875e473f2654d7 | 3c2bae505f0d7fc985628500d242f2684ff43cf8 | refs/heads/master | 2020-07-06T20:59:33.462273 | 2019-08-19T09:11:56 | 2019-08-19T09:11:56 | 203,137,275 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 399 | cpp | #include "text_speed_thrust_current.h"
TextSpeedThrustCurrent::TextSpeedThrustCurrent(TableText *tableText)
: Observer(tableText)
{
}
void TextSpeedThrustCurrent::update(const Event &event)
{
if (event.event != GAC_EV_NAD_SPEED || event.val == 12)
return;
tableText->setText(event.val > 0?
QString::number(event.val / 32.0 * 3.6, 'f', 1) : "");
}
| [
"usmirn@gmail.com"
] | usmirn@gmail.com |
cb0b933bcc5f28873373a23a4517d8e1720a2707 | b4bded995260fdc96470ae593c4bc4d9b5a98ca9 | /11.cpp | d50f0a5bb9d9e49c32784ff077fab9f20ba8cdd1 | [] | no_license | patricknicolosi/programmazione2 | a5dda894b68cb7f0c85e789baa5fbeb70d0ef35a | dac0170030f3a3e5e4455db424fd215ff80cf248 | refs/heads/master | 2023-05-15T12:43:27.227825 | 2021-06-06T16:27:00 | 2021-06-06T16:27:00 | 362,513,052 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,277 | cpp | #include<iostream>
using namespace std;
template <class T>
class NodeDl{
NodeDl<T>* prev;
NodeDl<T>* next;
T value;
public:
NodeDl(NodeDl<T>* prev, NodeDl<T>* next, T value) : prev(prev), next(next), value(value){}
NodeDl(T value) : NodeDl(NULL, NULL, value){}
NodeDl() : NodeDl(NULL, NULL, 0){}
void setNext(NodeDl<T>* newNext){
this->next = newNext;
}
void setPrev(NodeDl<T>* newPrev){
this->prev = newPrev;
}
NodeDl<T>* getNext() const{
return this->next;
}
NodeDl<T>* getPrev() const{
return this->prev;
}
T getValue() const{
return this->value;
}
friend ostream& operator << (ostream& stream, const NodeDl& n){
stream << n.getValue();
return stream;
}
};
template <class T>
class ListDl{
NodeDl<T>* head;
NodeDl<T>* tail;
public:
ListDl(NodeDl<T>* head, NodeDl<T>* tail) : head(head), tail(tail){}
ListDl() : ListDl(NULL, NULL){}
void addHead(T value){
NodeDl<T>* newNode = new NodeDl<T>(value);
if(head == NULL && tail == NULL){
this->head = newNode;
this->tail = newNode;
}
else{
newNode->setNext(head);
head->setPrev(newNode);
head = newNode;
}
}
void addTail(T value){
NodeDl<T>* newNode = new NodeDl<T>(value);
if(head == NULL && tail == NULL){
this->head = newNode;
this->tail = newNode;
}
else{
newNode->setPrev(tail);
tail->setNext(newNode);
tail = newNode;
}
}
void add(T value){
NodeDl<T>* newNode = new NodeDl<T>(value);
if(head == NULL && tail == NULL){
addHead(value);
return;
}
if(tail->getValue() <= value){
addTail(value);
return;
}
if(head->getValue() > value){
addHead(value);
return;
}
NodeDl<T>* currentNode = head;
NodeDl<T>* prevNode = head->getPrev();
while(currentNode->getValue() <= value){
prevNode = currentNode;
prevNode = currentNode->getPrev();
}
newNode->setPrev(prevNode);
newNode->setNext(currentNode);
prevNode->setNext(newNode);
currentNode->setPrev(newNode);
}
bool search(T value){
NodeDl<T>* currentNode = head;
while(currentNode != NULL){
if(currentNode->getValue() == value) return true;
currentNode = currentNode->getNext();
}
return false;
}
void remove(T value){
if(search(value)){
if(value == head->getValue()){ //Se il valore da togliere è la testa
head = head->getNext();
return;
}
if(value == head->getValue()){ //Se il valore da togliere è la coda
tail = tail->getPrev();
return;
}
//Se il valore da togliere non è ne in testa ne in coda ma è un nodo al centro
NodeDl<T>* currentNode = head;
NodeDl<T>* prevNode = head;
while(currentNode->getValue() != value) {
prevNode = currentNode;
currentNode = currentNode->getNext();
}
prevNode->setNext(currentNode->getNext());
currentNode->getNext()->setPrev(prevNode);
}
return;
}
friend ostream& operator << (ostream& stream, const ListDl& l){
NodeDl<T>* currentNode = l.head;
while(currentNode != NULL){
stream << *currentNode << " ";
currentNode = currentNode->getNext();
}
return stream;
}
};
int main(){
ListDl<int> l;
for(int i=0; i<5; i++){
l.add(i);
}
l.remove(2);
cout << l << endl;
} | [
"patricknicolosi99@gmail.com"
] | patricknicolosi99@gmail.com |
da2377bbc34dbdba8ba4505e74c7d239ff54468e | 655204b08baddde6c857f9ddcfe295bb84615193 | /Source/PhysicsEngine/PhysicsObject.h | 05a956d2eed7c98b3715a614d0dad1d729c0b2cf | [] | no_license | LASpencer/aie-Custom-Physics-Project | a5fb2a1e657b62ccd6c97475a2623a03944a0e5c | 385f6512d5f19407ede2cc63009c7c2f126d965d | refs/heads/master | 2021-05-04T16:28:41.732326 | 2018-03-04T23:34:52 | 2018-03-04T23:34:52 | 120,251,627 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,206 | h | #pragma once
#include "ExternalLibraries.h"
namespace physics {
enum ShapeType {
spring,
plane,
sphere,
obox
};
class PhysicsScene;
class PhysicsObject;
class RigidBody;
class Sphere;
class Box;
class Plane;
class ICollisionObserver;
typedef std::shared_ptr<PhysicsObject> PhysicsObjectPtr;
typedef std::weak_ptr<PhysicsObject> PhysicsObjectWeakPtr;
typedef std::shared_ptr<ICollisionObserver> CollisionObserverPtr;
typedef std::weak_ptr<ICollisionObserver> CollisionObserverWeakPtr;
struct Collision {
Collision(bool a_success = false, PhysicsObject* a_first = nullptr, PhysicsObject* a_second = nullptr, glm::vec2 a_normal = glm::vec2(0), glm::vec2 a_contact = glm::vec2(0), float a_depth = 0)
: success(a_success), first(a_first), second(a_second), normal(a_normal), contact(a_contact), depth(a_depth)
{};
// Whether the collision occurred
bool success;
PhysicsObject* first;
PhysicsObject* second;
// Collision normal pointed at first object
glm::vec2 normal;
// Contact point of collision
glm::vec2 contact;
// Depth by which objects interpenetrate
float depth;
operator bool() const { return success; }
// Returns collision with first and second objects swapped
Collision reverse() const {
return Collision(success, second, first, -normal, contact, depth);
}
};
// Abstract base class for all physical objects
class PhysicsObject : public std::enable_shared_from_this<PhysicsObject> {
protected:
PhysicsObject(float elasticity, float friction, glm::vec4 colour);
PhysicsObject(const PhysicsObject& other);
glm::vec4 m_colour; // Colour to draw object
float m_elasticity; // Coefficient of elasticity
float m_friction; // Coefficient of friction
unsigned int m_tags; // Bitmask for use by observers
bool m_alive; // True until object set as dead
bool m_trigger; // If true, no physical effect from collision
bool m_draw; // If true, gizmo will be created for rendering
std::vector<CollisionObserverWeakPtr> m_observers;
public:
virtual PhysicsObject* clone() = 0;
virtual void earlyUpdate(PhysicsScene* m_scene) = 0;
virtual void fixedUpdate(PhysicsScene* m_scene) = 0;
// Draw object with gizmos
virtual void makeGizmo(float timeRatio) = 0;
glm::vec4 getColour() { return m_colour; }
void setColour(glm::vec4 colour) { m_colour = colour; }
float getElasticity() { return m_elasticity; };
void setElasticity(float elasticity);
float getFriction() { return m_friction; }
void setFriction(float friction);
virtual bool isPointInside(glm::vec2 point) = 0;
// test collision against other object
// returns struct describing collision
virtual Collision checkCollision(PhysicsObject* other) = 0;
virtual Collision checkSphereCollision(Sphere* other) = 0;
virtual Collision checkBoxCollision(Box* other) = 0;
virtual Collision checkPlaneCollision(Plane* other) = 0;
virtual void resolveCollision(PhysicsObject* other, const Collision& col) = 0;
virtual void resolveRigidbodyCollision(RigidBody * other, const Collision& col) = 0;
virtual void resolvePlaneCollision(Plane* other, const Collision& col) = 0;
virtual ShapeType getShapeID() = 0;
virtual float calculateEnergy(PhysicsScene* m_scene) = 0;
virtual glm::vec2 calculateMomentum() = 0;
// Informs all observers that object was collided with
// collision = collision to send to observers
void broadcastCollision(const Collision& collision);
// Calculates the combined elasticity for a pair of objects
// e1,e2 = colliding objects
static float combineElasticity(PhysicsObject* e1, PhysicsObject* e2);
// Calculates the coefficient of friction for a pair of objects
// e1,e2 = colliding objects
static float combineFriction(PhysicsObject* e1, PhysicsObject* e2);
// Returns true if the object is set as static
virtual bool isStatic() = 0;
// Returns true if the object has not been killed
bool isAlive() { return m_alive; };
bool isTrigger() { return m_trigger; }
void setTrigger(bool value) { m_trigger = value; }
bool shouldDraw() { return m_draw; }
void setDraw(bool value) { m_draw = value; }
// Call to set object as dead, so scene and other objects
// referring to it can remove it
void kill();
// Call to set object as alive again, allowing it to be added back to the scene
virtual void resetAlive();
// Adds new observer to inform about collisions
// returns true if added, false if already observing
bool addObserver(const CollisionObserverPtr& observer);
// Removes observer from list
bool removeObserver(const CollisionObserverPtr& observer);
// Returns true if observer is in list of subscribers
bool isSubscribed(const CollisionObserverPtr& observer);
const std::vector<CollisionObserverWeakPtr>& getObservers() { return m_observers; }
unsigned int getTags() { return m_tags; }
void setTags(unsigned int tags);
// Sets passed bits to true in object's tags
void addTags(unsigned int tags);
// Sets passed bits to false in object's tags
void removeTags(unsigned int tags);
// Returns true if all bits passed are set to true in object's tags
bool hasTags(unsigned int tags);
};
} | [
"thrawn369@gmail.com"
] | thrawn369@gmail.com |
249464c5222a09602f97416c91750b3a16119667 | 949763c9456b4abcb89e5f9e9b38c82867a01b7e | /src/components/Input.cpp | c911b1ac80e44ae12731f33b14e8be467ec4c9f1 | [] | no_license | jjzhang166/DreamInEngine | beddb448fbfc9024c7a261ba02949ebf0d6f2e79 | d1df48e4b5922a7a48edc108c6dab56d53c24ba8 | refs/heads/master | 2023-06-06T12:54:12.760340 | 2021-07-01T16:55:46 | 2021-07-01T16:55:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30 | cpp | #include "components/Input.h"
| [
"valentin.dumas@viacesi.fr"
] | valentin.dumas@viacesi.fr |
49a5f9f6a0eb81626df034fac4374ff01bad4618 | 6b40e9cba1dd06cd31a289adff90e9ea622387ac | /Develop/Tools/Character_NET/AnimationHitSoundTabPage.h | 9affa1cc0c3f3a456f431b635a508c0d0f15fc0f | [] | no_license | AmesianX/SHZPublicDev | c70a84f9170438256bc9b2a4d397d22c9c0e1fb9 | 0f53e3b94a34cef1bc32a06c80730b0d8afaef7d | refs/heads/master | 2022-02-09T07:34:44.339038 | 2014-06-09T09:20:04 | 2014-06-09T09:20:04 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 5,382 | h | #pragma once
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
namespace Character_NET {
/// <summary>
/// AnimationHitSoundTabPage에 대한 요약입니다.
///
/// 경고: 이 클래스의 이름을 변경하면 이 클래스가 의존하는
/// 모든 .resx 파일과 관련된 관리되는 리소스 컴파일러 도구의
/// '리소스 파일 이름' 속성도 변경해야 합니다. 그렇지 않은 경우
/// 디자이너는 이 폼과 관련된 지역화된 리소스와
/// 올바르게 상호 작용할 수 없습니다.
/// </summary>
public ref class AnimationHitSoundTabPage : public System::Windows::Forms::Form
{
private:
bool m_bSoundLoad;
public:
AnimationHitSoundTabPage(void)
{
InitializeComponent();
//
//TODO: 생성자 코드를 여기에 추가합니다.
//
m_bSoundLoad = false;
}
void InitEffectList();
protected:
/// <summary>
/// 사용 중인 모든 리소스를 정리합니다.
/// </summary>
~AnimationHitSoundTabPage()
{
if (components)
{
delete components;
}
}
public: System::Windows::Forms::ComboBox^ HitSound_comboBox;
private: System::Windows::Forms::Button^ OK_button;
public: System::Windows::Forms::Label^ AnimationName_label;
private:
public:
protected:
protected:
protected:
public:
protected:
protected:
public:
private:
/// <summary>
/// 필수 디자이너 변수입니다.
/// </summary>
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
/// <summary>
/// 디자이너 지원에 필요한 메서드입니다.
/// 이 메서드의 내용을 코드 편집기로 수정하지 마십시오.
/// </summary>
void InitializeComponent(void)
{
this->HitSound_comboBox = (gcnew System::Windows::Forms::ComboBox());
this->OK_button = (gcnew System::Windows::Forms::Button());
this->AnimationName_label = (gcnew System::Windows::Forms::Label());
this->SuspendLayout();
//
// HitSound_comboBox
//
this->HitSound_comboBox->AutoCompleteMode = System::Windows::Forms::AutoCompleteMode::Suggest;
this->HitSound_comboBox->AutoCompleteSource = System::Windows::Forms::AutoCompleteSource::ListItems;
this->HitSound_comboBox->FormattingEnabled = true;
this->HitSound_comboBox->Location = System::Drawing::Point(16, 32);
this->HitSound_comboBox->Name = L"HitSound_comboBox";
this->HitSound_comboBox->Size = System::Drawing::Size(190, 20);
this->HitSound_comboBox->Sorted = true;
this->HitSound_comboBox->TabIndex = 0;
this->HitSound_comboBox->SelectedIndexChanged += gcnew System::EventHandler(this, &AnimationHitSoundTabPage::HitSound_comboBox_SelectedIndexChanged);
this->HitSound_comboBox->TextChanged += gcnew System::EventHandler(this, &AnimationHitSoundTabPage::HitSound_comboBox_TextChanged);
//
// OK_button
//
this->OK_button->Location = System::Drawing::Point(74, 68);
this->OK_button->Name = L"OK_button";
this->OK_button->Size = System::Drawing::Size(75, 23);
this->OK_button->TabIndex = 1;
this->OK_button->Text = L"적용";
this->OK_button->UseVisualStyleBackColor = true;
this->OK_button->Click += gcnew System::EventHandler(this, &AnimationHitSoundTabPage::OK_button_Click);
//
// AnimationName_label
//
this->AnimationName_label->AutoSize = true;
this->AnimationName_label->Location = System::Drawing::Point(14, 9);
this->AnimationName_label->Name = L"AnimationName_label";
this->AnimationName_label->Size = System::Drawing::Size(0, 12);
this->AnimationName_label->TabIndex = 2;
//
// AnimationHitSoundTabPage
//
this->AutoScaleDimensions = System::Drawing::SizeF(7, 12);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->BackColor = System::Drawing::SystemColors::Window;
this->ClientSize = System::Drawing::Size(231, 112);
this->ControlBox = false;
this->Controls->Add(this->AnimationName_label);
this->Controls->Add(this->OK_button);
this->Controls->Add(this->HitSound_comboBox);
this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::None;
this->MaximizeBox = false;
this->MinimizeBox = false;
this->Name = L"AnimationHitSoundTabPage";
this->ShowIcon = false;
this->ShowInTaskbar = false;
this->Text = L"AnimationHitSoundTabPage";
this->Load += gcnew System::EventHandler(this, &AnimationHitSoundTabPage::AnimationHitSoundTabPage_Load);
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
private: System::Void HitSoundAddbutton_Click(System::Object^ sender, System::EventArgs^ e);
private: System::Void AnimationHitSoundTabPage_Load(System::Object^ sender, System::EventArgs^ e);
private: System::Void HitSound_comboBox_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e);
private: System::Void HitSound_comboBox_TextChanged(System::Object^ sender, System::EventArgs^ e);
private: System::Void OK_button_Click(System::Object^ sender, System::EventArgs^ e);
};
}
| [
"shzdev@8fd9ef21-cdc5-48af-8625-ea2f38c673c4"
] | shzdev@8fd9ef21-cdc5-48af-8625-ea2f38c673c4 |
1769398a326b2853a6b090c307cd85ac75ad11f4 | 553bea24ece6c8f41642f8e8e567d20fb32f0ad9 | /src/utils/include/utils/input_grid_utils.h | f3eca301c9a7972f8eaddee25fb7b606775eda95 | [
"MIT"
] | permissive | pierre-dejoue/picross-solver | a12913c582cb9db49892665cec8267d51acb411a | 45be54dfa9b6a097ad977ddd5d95e47b79f35dd4 | refs/heads/main | 2023-08-30T21:00:38.979792 | 2023-08-26T20:20:17 | 2023-08-26T23:03:36 | 8,221,585 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 395 | h | #pragma once
#include <picross/picross.h>
#include <ostream>
namespace picross
{
void stream_input_grid_constraint(std::ostream& out, const InputGrid& input_grid, const LineId& line_id);
void stream_input_grid_line_id_and_constraint(std::ostream& out, const InputGrid& input_grid, const LineId& line_id);
void stream_input_grid_constraints(std::ostream& out, const InputGrid& input_grid);
}
| [
"pierre.dejoue@gmail.com"
] | pierre.dejoue@gmail.com |
1edd803e36b428c08fd90f95ac6051cc38b19c78 | 613bb55365d68e31ec68d3c101d4630681d1c8ee | /source/util/qqgame_util.cc | 07fcab5545dc742e7804d3f97ec87922abb49d5b | [] | no_license | changpinggou/NPAPI-ActiveX | db478bc7bfecc7d995a1dd3a380ff6bacf5891e4 | 805a311f457d64acc34ba818a495792679636205 | refs/heads/master | 2021-01-10T13:31:30.766738 | 2015-06-25T02:18:08 | 2015-06-25T02:18:08 | 36,733,400 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,884 | cc | #include "qqgame_util.h"
#include <WinVer.h>
#include <Shlwapi.h>
#include <atlstr.h>
namespace qqgame
{
bool CheckQQGameRunning(HWND* hMsgWnd)
{
return (*hMsgWnd = ::FindWindowEx(NULL, NULL, QQGAME_MAINFRAME_WNDCLASS, NULL)) != NULL;
}
bool CheckQQGameSetup(HWND* hMsgWnd)
{
return (*hMsgWnd = ::FindWindowEx(NULL, NULL, QQGAME_SETUP_WNDCLASS, NULL)) != NULL;
}
bool GetQQGwpExePath(std::wstring& QQGwpFullPath){
HKEY mq;
DWORD rec,rbt;
rec = REG_SZ;
rbt = MAX_PATH;
wchar_t buf[MAX_PATH] = {0};
long rs = RegOpenKeyEx(HKEY_CURRENT_USER, QQGAME_SUBKEY_PATH, 0, KEY_ALL_ACCESS, &mq);
if((rs==ERROR_SUCCESS) &&
(RegQueryValueEx(mq,L"HallDirectory",NULL,&rec,(LPBYTE)buf, &rbt) == ERROR_SUCCESS))
{
PathAppendW(buf, L"QQGwp.exe");
QQGwpFullPath = buf;
RegCloseKey(mq);
}
return !!PathFileExists(QQGwpFullPath.c_str());
}
bool GetQQGameHallInstallDir(std::wstring& QQGameHallInstallDir){
HKEY mq;
DWORD rec,rbt;
rec = REG_SZ;
rbt = MAX_PATH;
wchar_t buf[MAX_PATH] = {0};
long rs = RegOpenKeyEx(HKEY_CURRENT_USER, QQGAME_SUBKEY_PATH, 0, KEY_ALL_ACCESS, &mq);
if((rs==ERROR_SUCCESS) &&
(RegQueryValueEx(mq,L"HallDirectory",NULL,&rec,(LPBYTE)buf, &rbt) == ERROR_SUCCESS))
{
QQGameHallInstallDir = buf;
RegCloseKey(mq);
}
return !!PathFileExists(QQGameHallInstallDir.c_str());
}
bool LaunchQQGwpInternal(std::wstring& strExePath, const std::wstring& strParam)
{
std::wstring strCmdTemp = L"\"";
strCmdTemp += strParam;
strCmdTemp +=L"\"";
HINSTANCE ret = (HINSTANCE)ShellExecute(NULL, L"open", strExePath.c_str(), strCmdTemp.c_str(), NULL, SW_SHOWNORMAL);
return (DWORD)ret > 32 ? true : false;
}
bool GetQQGameCUVer(std::wstring& strCurVer)
{
std::wstring QQGameHallInstallPath;
GetQQGameHallInstallDir(QQGameHallInstallPath);
QQGameHallInstallPath +=L"\\";
QQGameHallInstallPath += QQGAME_MALL_EXE;
DWORD dwHandle = 0;
DWORD dwSize = 0;
dwSize = GetFileVersionInfoSize(QQGameHallInstallPath.c_str(),&dwHandle);
if (!dwSize)
{
return false;
}
BYTE *Buf = new BYTE[dwSize];
ZeroMemory(Buf,sizeof(BYTE)*dwSize);
if (GetFileVersionInfo(QQGameHallInstallPath.c_str(),NULL,dwSize,Buf))
{
ATL::CStringW szVersion;
VS_FIXEDFILEINFO *pvi;
VerQueryValue(Buf,_T("\\"),(LPVOID*)&pvi,(PUINT)&dwSize);
if (dwSize)
{
szVersion.Format(L"%d.%d.%d.%d",HIWORD(pvi->dwFileVersionMS),LOWORD(pvi->dwFileVersionMS),
HIWORD(pvi->dwFileVersionLS), LOWORD(pvi->dwFileVersionLS));
}
if (szVersion.GetLength() > 0)
{
strCurVer.append(szVersion.GetBuffer(0));
}
}
delete []Buf;
return true;
}
bool GetPluginCUVer(std::wstring& strCurVer)
{
wchar_t system_buffer[MAX_PATH];
system_buffer[0] = 0;
HMODULE this_module = reinterpret_cast<HMODULE>(&__ImageBase);
::GetModuleFileName(this_module, system_buffer, MAX_PATH);
DWORD dwHandle = 0;
DWORD dwSize = 0;
dwSize = GetFileVersionInfoSize(system_buffer,&dwHandle);
if (!dwSize)
{
return false;
}
BYTE *Buf = new BYTE[dwSize];
ZeroMemory(Buf,sizeof(BYTE)*dwSize);
if (GetFileVersionInfo(system_buffer,NULL,dwSize,Buf))
{
ATL::CStringW szVersion;
VS_FIXEDFILEINFO *pvi;
VerQueryValue(Buf,_T("\\"),(LPVOID*)&pvi,(PUINT)&dwSize);
if (dwSize)
{
szVersion.Format(L"%d.%d.%d.%d",HIWORD(pvi->dwFileVersionMS),LOWORD(pvi->dwFileVersionMS),
HIWORD(pvi->dwFileVersionLS), LOWORD(pvi->dwFileVersionLS));
}
if (szVersion.GetLength() > 0)
{
strCurVer.append(szVersion.GetBuffer(0));
}
}
delete []Buf;
return true;
}
} //namespace | [
"applechang@applechang-PC2.tencent.com"
] | applechang@applechang-PC2.tencent.com |
833a3e83c37dcef3cc7c9b982ec56180c9589094 | c1096f2729fcc2e76dfcc9d4d277cebb669ef50f | /generator/NES.h | 33d8fa36cc8ffc1a53cdb1019f4d2075a03fbcb8 | [] | no_license | mikeakohn/java_grinder | 8d67f183aebfc412bff8537b23ff8be99f86dea6 | 273d6e97f46d3fa442b33ae19a2b2cde16dc5c4b | refs/heads/master | 2023-08-15T13:17:50.551116 | 2023-06-20T21:44:37 | 2023-06-20T21:44:37 | 15,153,331 | 481 | 41 | null | 2020-01-28T02:30:24 | 2013-12-13T02:48:12 | C++ | UTF-8 | C++ | false | false | 1,165 | h | /**
* Java Grinder
* Author: Michael Kohn
* Email: mike@mikekohn.net
* Web: http://www.mikekohn.net/
* License: GPLv3
*
* Copyright 2014-2022 by Michael Kohn
*
*/
#ifndef JAVA_GRINDER_GENERATOR_NES_H
#define JAVA_GRINDER_GENERATOR_NES_H
#include "generator/M6502.h"
class NES : public M6502
{
public:
NES();
virtual ~NES();
virtual int open(const char *filename);
virtual int nes_setBackgroundPalette_II();
virtual int nes_setSpritePalette_II();
virtual int nes_setPattern_IaB();
virtual int nes_setNameTable_II();
virtual int nes_setNameTable_III();
virtual int nes_setScroll_II();
virtual int nes_waitVerticalBlank();
virtual int nes_setPPUCtrl_I();
virtual int nes_setPPUMask_I();
private:
void write_init();
void write_wait_vertical_blank();
void write_set_pattern();
void write_set_background_palette_II();
void write_set_name_table_II();
void write_set_name_table_III();
void write_set_scroll_II();
void write_interrupts();
void write_cartridge_info();
bool need_set_background_palette_II;
bool need_set_name_table_II;
bool need_set_name_table_III;
bool need_set_scroll_II;
};
#endif
| [
"mike@mikekohn.net"
] | mike@mikekohn.net |
880ea1d61180993952b9a8d48aa4c0dd27ff4a44 | 0c268ff10b68c4a24023ca646bb46c5a125eb84c | /Codeforces_Contest/Round_607_div2/b.cpp | e136f851fcf557f140dbcbaf5025bd52fd8f2f03 | [] | no_license | TzeHimSung/AcmDailyTraining | 497b9fb77c282f2f240634050e38f395cf1bedbc | 2a69fa38118e43cbeca44cb99369e6e094663ec8 | refs/heads/master | 2023-03-21T21:39:02.752317 | 2021-03-14T03:41:00 | 2021-03-14T03:41:00 | 159,670,822 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 998 | cpp | /* basic header */
#include <bits/stdc++.h>
/* define */
#define ll long long
#define dou double
#define pb emplace_back
#define mp make_pair
#define sot(a,b) sort(a+1,a+1+b)
#define rep1(i,a,b) for(int i=a;i<=b;++i)
#define rep0(i,a,b) for(int i=a;i<b;++i)
#define eps 1e-8
#define int_inf 0x3f3f3f3f
#define ll_inf 0x7f7f7f7f7f7f7f7f
#define lson (minpos<<1)
#define rson (minpos<<1|1)
/* namespace */
using namespace std;
/* header end */
int t;
string a,b;
int main() {
cin>>t;
while (t--){
cin>>a>>b;
if (a<b){
cout<<a<<'\n';
continue;
}
string s=a;
sort(s.begin(),s.end());
int flag=0;
for (int i=0;i<(int)a.size();i++){
// current char is not at the best position
if (a[i]>s[i]){
// it can swap with the back char only
for (int j=i+1;j<(int)a.size();j++){
swap(a[i],a[j]);
if (a<b){
cout<<a<<'\n';
flag=1;
i=(int)a.size();
break;
}
swap(a[i],a[j]);
}
}
}
if (!flag) puts("---");
}
return 0;
}
| [
"zxc98567@gmail.com"
] | zxc98567@gmail.com |
6e2aacc612f75966e1d7396a0a58ed08bf43ad01 | 00da795e529b9c8acd4e20dcedaa68db9015f449 | /checks/A.cpp | 535da96d94cb5f37eb1acecd459bac172a0b57ae | [] | no_license | nitish11/coding-practices | f557c24babc9ac210da429dfc184d9294feeeb27 | 85a38d71165b71c535f020fe2e7edd095588b854 | refs/heads/master | 2021-01-01T05:31:53.599731 | 2014-07-09T12:56:29 | 2014-07-09T12:56:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 59 | cpp | #include<process.h>
int main()
{
int i;
exit(1);
}
| [
"nitish.bhardwaj11@gmail.com"
] | nitish.bhardwaj11@gmail.com |
830de9d39b093a9d2479ce27c901b7b1268a9ded | 4bba4ba2b09da8c3d7affeb9738d5cd89a24e8be | /tools/benchmarks/sockperf-lite/src/Message.cpp | 08ec0664035c9c05cd445519f028d9f6e58901ab | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] | permissive | janekmi/ChelsioUwire | 617b24f664904f4d1fde83ab9d671c57e90bf8af | 6c1bd8d4760d4c53f9acdc4d8d05c3453282c3ac | refs/heads/master | 2021-01-17T18:33:49.449809 | 2016-10-21T10:43:24 | 2016-10-21T10:48:29 | 71,464,881 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,004 | cpp | /*
* Copyright (c) 2011 Mellanox Technologies Ltd.
* 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 Mellanox Technologies Ltd 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.
*
*/
#include "Message.h"
#include <malloc.h>
#include <string>
#include "common.h"
// static memebers initialization
/*static*/ uint64_t Message::ms_maxSequenceNo;
/*static*/ int Message::ms_maxSize;
//------------------------------------------------------------------------------
class MemException : public std::exception {
public:
MemException (const char *file, int line, const char * handler, size_t size) throw();
virtual ~MemException () throw(){}
virtual const char* what() const throw() { return m_what.c_str();}
private:
std::string m_what;
};
//------------------
MemException::MemException (const char *file, int line, const char * handler, size_t size) throw() {
const size_t LEN = 256;
char buf[LEN+1];
snprintf(buf, LEN, "%s:%d: %s failed allocating %d bytes",file, line, handler, (int)size);
buf[LEN] = '\0';
m_what = buf;
}
//------------------------------------------------------------------------------
/*static*/ void Message::initMaxSize(int size) throw (std::exception)
{
if (size < 0)
throw std::out_of_range("size < 0");
else if (ms_maxSize)
throw std::logic_error("MaxSize is already initialized");
else
ms_maxSize = size;
}
//------------------------------------------------------------------------------
/*static*/ void Message::initMaxSeqNo(uint64_t seqno) throw (std::exception)
{
if (ms_maxSequenceNo)
throw std::logic_error("MaxSeqNo is already initialized");
else
ms_maxSequenceNo = seqno;
}
//------------------------------------------------------------------------------
Message::Message() throw (std::exception) { //throws in case fatal error occurred
if (! ms_maxSize)
throw std::logic_error("MaxSize was NOT initialized");
if (ms_maxSize < MsgHeader::EFFECTIVE_SIZE)
throw std::out_of_range("maxSize < MsgHeader::EFFECTIVE_SIZE");
m_buf = MALLOC(ms_maxSize + 7); // extra +7 for enabling 8 alignment of m_sequence_number
if (! m_buf) {
throw MemException(__FILE__, __LINE__, "malloc", ms_maxSize);
}
setBuf();
for (int len = 0; len < ms_maxSize; len++)
m_addr[len] = (uint8_t) rand();
memset(m_header, 0, MsgHeader::EFFECTIVE_SIZE);
/*
log_msg("ms_maxSize=%d, m_buf=%p, alignment=%d, m_data=%p, m_header=%p", ms_maxSize, m_buf, alignment, m_data, m_header);
log_msg("header adresses: m_sequence_number=%p", &m_header->m_sequence_number);
//*/
}
//------------------------------------------------------------------------------
Message::~Message()
{
FREE (m_buf);
}
| [
"jan.m.michalski@intel.com"
] | jan.m.michalski@intel.com |
7052809ead2b7832dd6629e257fdbf4abd8a6ece | 78f4d90f21796d37de4469667bcb31fc1a7cdba7 | /Server1.1/Server1.1.ino | 8b2c225f5d43b7287cd56132c24030534c728db4 | [] | no_license | jaavargasar/IOT-tracker | aca9129af958859ea3dc0355f887a91f0c3f4ea0 | 95c37b8c45fe769eb863943c0bb85c335b001802 | refs/heads/master | 2020-04-27T06:17:47.472319 | 2019-03-08T06:40:09 | 2019-03-08T06:40:09 | 174,104,015 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,228 | ino | #include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <coap_server.h>
#define LED_BUILTIN 1
#define THRESHOLD -70
#define BUZZER_PIN 3
char* ssid = "Andres Iphone";
char* password = "andres18";
String ssid_pa = "TRACKER";
String last = "1";
IPAddress wifiIp(172, 20, 10, 10);
IPAddress wifiNet(255, 255, 255, 240);
IPAddress wifiGW(172, 20, 10, 1);
// CoAP server endpoint url callback
void callback_gps(coapPacket &packet, IPAddress ip, int port, int obs);
coapServer coap;
// CoAP server endpoint URL
void callback_gps(coapPacket *packet, IPAddress ip, int port,int obs) {
// send response
char p[packet->payloadlen + 1];
memcpy(p, packet->payload, packet->payloadlen);
p[packet->payloadlen] = NULL;
String message(p);
//Serial.print("Message=[");
//Serial.print(p);
//Serial.println("]\n");
if(!message.equals("") && !message.equals(last))
{
scanForAP();
}
char val[2];
message.toCharArray(val, message.length());
if(obs==1)
coap.sendResponse(val);
else
coap.sendResponse(ip,port,val);
last = message;
}
void setupWiFi(){
//Serial.print("Connecting to ");
//Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.config(wifiIp, wifiGW, wifiNet);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
//Serial.print(".");
}
//Serial.println("");
//Serial.println("WiFi connected");
//Serial.println("IP address: ");
//Serial.println(WiFi.localIP());
}
void scanForAP() {
// WiFi.scanNetworks will return the number of networks found
int n = WiFi.scanNetworks();
for (int i = 0; i < n; ++i) {
if(WiFi.SSID(i) == ssid_pa && WiFi.RSSI(i) > THRESHOLD){
//Serial.print(" (");
//Serial.print(WiFi.RSSI(i));
//Serial.println(")");
digitalWrite(LED_BUILTIN, HIGH);
noTone(BUZZER_PIN);
return;
}
}
tone(BUZZER_PIN, 100);
digitalWrite(LED_BUILTIN, LOW);
}
void setup() {
//Serial.begin(115200);
pinMode(BUZZER_PIN, FUNCTION_3);
pinMode(BUZZER_PIN, OUTPUT);
noTone(BUZZER_PIN);
setupWiFi();
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
coap.server(callback_gps, "gps");
coap.start();
}
void loop() {
coap.loop();
delay(5000);
}
| [
"noreply@github.com"
] | jaavargasar.noreply@github.com |
752d35c1a10fc8452186e31966ba1cc999d5f83a | e33dcca8fdd5ebda31443feddae99e58ed8bfa5a | /topcoder/SRM312-D1-500.cpp | cf12d481eb0f922f3a633a161fda9646064b2378 | [] | no_license | keyliin0/Competitive-Programming | 5e6c4f7f3d4be0aa80f01bd623fef88e34a4eb74 | bf93567ab73f7545883a3af43fb6dd8f5fe7ac51 | refs/heads/master | 2021-06-07T11:47:35.930727 | 2020-01-19T22:13:05 | 2020-01-19T22:13:05 | 140,153,796 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,823 | cpp | #include<bits/stdc++.h>
using namespace std;
#define loop(i,b,e) for(int i=b;i<=e;i++)
#define loop2(i,e,b) for(int i=e;i>=b;i--)
#define io ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define fi first
#define se second
#define X real()
#define Y imag()
#define cp(a,b) ( (conj(a)*(b)).imag() )
#define dp(a,b) ( (conj(a)*(b)).real() ) // a*b cos(T), if zero -> prep
#define length(a) (hypot((a).imag(), (a).real()))
#define rotateO(p,ang) ((p)*exp(point(0,ang)))
#define rotateA(p,ang,about) (rotateO(vec(about,p),ang)+about)
#define logg2 0.30102999566398119521373889472449L
typedef complex<double> point;
typedef long long ll;
typedef unsigned long long ull;
double PI = 3.141592653589793;
const double EPS = 1e-6;
//const int N = 1e6 + 5;
const ll mod = 1e9 + 7;
const int oo = 1e9;
int dx[] = { 0, 0, 1, -1, 1, -1, 1, -1 };
int dy[] = { 1, -1, 0, 0, -1, 1, 1, -1 };
const int N = 105;
int n, m, idx[N], low[N], T;
vector<vector<int> > g, g2;
vector<int> S;
bool vis[N];
int compID[N], sz[N], cmp;
int val[N], in[N];
void DFS(int u) {
idx[u] = low[u] = ++T;
S.push_back(u);
vis[u] = true;
for (int i = 0; i < g[u].size(); ++i) {
int v = g[u][i];
if (idx[v] == 0)
DFS(v);
if (vis[v])
low[u] = min(low[u], low[v]);
}
if (idx[u] == low[u]) {
while (true) {
int v = S.back();
S.pop_back();
vis[v] = false;
compID[v] = cmp;
sz[cmp]++;
if (v == u)
break;
}
++cmp;
}
}
class AntarcticaPolice {
public:
double minAverageCost(vector <int> costs, vector <string> roads) {
g.resize(roads.size() + 1);
g2.resize(roads.size() + 1);
for (int i = 0; i < roads.size(); i++) {
for (int j = 0; j < roads.size(); j++) {
if (i == j) continue;
if (roads[i][j] == 'Y')
g[i].push_back(j);
}
}
for (int i = 0; i < roads.size(); i++)
if (!idx[i]) DFS(i);
for (int i = 0; i < cmp; i++)
val[i] = oo;
for (int i = 0; i < roads.size(); i++) {
val[compID[i]] = min(val[compID[i]], costs[i]);
for (int j = 0; j < g[i].size(); j++) {
if (compID[i] != compID[g[i][j]]) {
g2[compID[i]].push_back(compID[g[i][j]]);
in[compID[g[i][j]]]++;
}
}
}
int cnt = 0, cst = 0;
vector<int> v;
for (int i = 0; i < cmp; i++) {
if (in[i] == 0) cst += val[i], cnt++;
else v.push_back(val[i]);
}
double ans = (double)cst / cnt;
while (v.size()) {
double curr = (double)cst / cnt;
int x = -1;
for (int i = 0; i < v.size(); i++) {
double c = (double)(cst + v[i]) / (cnt + 1);
if (c < curr) curr = c, x = i;
}
if (x == -1) break;
if (ans > curr) {
ans = curr;
cnt++;
cst += v[x];
v.erase(v.begin() + x);
}
else break;
}
return ans;
}
};
| [
"noreply@github.com"
] | keyliin0.noreply@github.com |
e10edb9ceec510cdbae4485240fb6cdc5204cfc5 | 4ea5083a2dc96943b12c61dbac9a44359d4a5760 | /OpenVPN Tunnel Provider/Vendors/asio/asio/detail/reactive_socket_service.hpp | 263adc8a6a10fe3537761b8a208923a09bf85ca7 | [] | no_license | shahzaibiqbal/openvpn-adapter | afff351a1d2fbcfe966042c060c13364986c954e | d316cd7ebd0d29d636c755d4e10721e2891b6431 | refs/heads/master | 2020-09-08T17:36:24.694975 | 2017-02-05T10:38:35 | 2017-02-05T10:38:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,604 | hpp | //
// detail/reactive_socket_service.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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)
//
#ifndef ASIO_DETAIL_REACTIVE_SOCKET_SERVICE_HPP
#define ASIO_DETAIL_REACTIVE_SOCKET_SERVICE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#if !defined(ASIO_HAS_IOCP)
#include "asio/buffer.hpp"
#include "asio/error.hpp"
#include "asio/io_context.hpp"
#include "asio/socket_base.hpp"
#include "asio/detail/buffer_sequence_adapter.hpp"
#include "asio/detail/memory.hpp"
#include "asio/detail/noncopyable.hpp"
#include "asio/detail/reactive_null_buffers_op.hpp"
#include "asio/detail/reactive_socket_accept_op.hpp"
#include "asio/detail/reactive_socket_connect_op.hpp"
#include "asio/detail/reactive_socket_recvfrom_op.hpp"
#include "asio/detail/reactive_socket_sendto_op.hpp"
#include "asio/detail/reactive_socket_service_base.hpp"
#include "asio/detail/reactor.hpp"
#include "asio/detail/reactor_op.hpp"
#include "asio/detail/socket_holder.hpp"
#include "asio/detail/socket_ops.hpp"
#include "asio/detail/socket_types.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
template <typename Protocol>
class reactive_socket_service :
public service_base<reactive_socket_service<Protocol> >,
public reactive_socket_service_base
{
public:
// The protocol type.
typedef Protocol protocol_type;
// The endpoint type.
typedef typename Protocol::endpoint endpoint_type;
// The native type of a socket.
typedef socket_type native_handle_type;
// The implementation type of the socket.
struct implementation_type :
reactive_socket_service_base::base_implementation_type
{
// Default constructor.
implementation_type()
: protocol_(endpoint_type().protocol())
{
}
// The protocol associated with the socket.
protocol_type protocol_;
};
// Constructor.
reactive_socket_service(asio::io_context& io_context)
: service_base<reactive_socket_service<Protocol> >(io_context),
reactive_socket_service_base(io_context)
{
}
// Destroy all user-defined handler objects owned by the service.
void shutdown()
{
this->base_shutdown();
}
// Move-construct a new socket implementation.
void move_construct(implementation_type& impl,
implementation_type& other_impl)
{
this->base_move_construct(impl, other_impl);
impl.protocol_ = other_impl.protocol_;
other_impl.protocol_ = endpoint_type().protocol();
}
// Move-assign from another socket implementation.
void move_assign(implementation_type& impl,
reactive_socket_service_base& other_service,
implementation_type& other_impl)
{
this->base_move_assign(impl, other_service, other_impl);
impl.protocol_ = other_impl.protocol_;
other_impl.protocol_ = endpoint_type().protocol();
}
// Move-construct a new socket implementation from another protocol type.
template <typename Protocol1>
void converting_move_construct(implementation_type& impl,
typename reactive_socket_service<
Protocol1>::implementation_type& other_impl)
{
this->base_move_construct(impl, other_impl);
impl.protocol_ = protocol_type(other_impl.protocol_);
other_impl.protocol_ = typename Protocol1::endpoint().protocol();
}
// Open a new socket implementation.
asio::error_code open(implementation_type& impl,
const protocol_type& protocol, asio::error_code& ec)
{
if (!do_open(impl, protocol.family(),
protocol.type(), protocol.protocol(), ec))
impl.protocol_ = protocol;
return ec;
}
// Assign a native socket to a socket implementation.
asio::error_code assign(implementation_type& impl,
const protocol_type& protocol, const native_handle_type& native_socket,
asio::error_code& ec)
{
if (!do_assign(impl, protocol.type(), native_socket, ec))
impl.protocol_ = protocol;
return ec;
}
// Get the native socket representation.
native_handle_type native_handle(implementation_type& impl)
{
return impl.socket_;
}
// Bind the socket to the specified local endpoint.
asio::error_code bind(implementation_type& impl,
const endpoint_type& endpoint, asio::error_code& ec)
{
socket_ops::bind(impl.socket_, endpoint.data(), endpoint.size(), ec);
return ec;
}
// Set a socket option.
template <typename Option>
asio::error_code set_option(implementation_type& impl,
const Option& option, asio::error_code& ec)
{
socket_ops::setsockopt(impl.socket_, impl.state_,
option.level(impl.protocol_), option.name(impl.protocol_),
option.data(impl.protocol_), option.size(impl.protocol_), ec);
return ec;
}
// Set a socket option.
template <typename Option>
asio::error_code get_option(const implementation_type& impl,
Option& option, asio::error_code& ec) const
{
std::size_t size = option.size(impl.protocol_);
socket_ops::getsockopt(impl.socket_, impl.state_,
option.level(impl.protocol_), option.name(impl.protocol_),
option.data(impl.protocol_), &size, ec);
if (!ec)
option.resize(impl.protocol_, size);
return ec;
}
// Get the local endpoint.
endpoint_type local_endpoint(const implementation_type& impl,
asio::error_code& ec) const
{
endpoint_type endpoint;
std::size_t addr_len = endpoint.capacity();
if (socket_ops::getsockname(impl.socket_, endpoint.data(), &addr_len, ec))
return endpoint_type();
endpoint.resize(addr_len);
return endpoint;
}
// Get the remote endpoint.
endpoint_type remote_endpoint(const implementation_type& impl,
asio::error_code& ec) const
{
endpoint_type endpoint;
std::size_t addr_len = endpoint.capacity();
if (socket_ops::getpeername(impl.socket_,
endpoint.data(), &addr_len, false, ec))
return endpoint_type();
endpoint.resize(addr_len);
return endpoint;
}
// Disable sends or receives on the socket.
asio::error_code shutdown(base_implementation_type& impl,
socket_base::shutdown_type what, asio::error_code& ec)
{
socket_ops::shutdown(impl.socket_, what, ec);
return ec;
}
// Send a datagram to the specified endpoint. Returns the number of bytes
// sent.
template <typename ConstBufferSequence>
size_t send_to(implementation_type& impl, const ConstBufferSequence& buffers,
const endpoint_type& destination, socket_base::message_flags flags,
asio::error_code& ec)
{
buffer_sequence_adapter<asio::const_buffer,
ConstBufferSequence> bufs(buffers);
return socket_ops::sync_sendto(impl.socket_, impl.state_,
bufs.buffers(), bufs.count(), flags,
destination.data(), destination.size(), ec);
}
// Wait until data can be sent without blocking.
size_t send_to(implementation_type& impl, const null_buffers&,
const endpoint_type&, socket_base::message_flags,
asio::error_code& ec)
{
// Wait for socket to become ready.
socket_ops::poll_write(impl.socket_, impl.state_, ec);
return 0;
}
// Start an asynchronous send. The data being sent must be valid for the
// lifetime of the asynchronous operation.
template <typename ConstBufferSequence, typename Handler>
void async_send_to(implementation_type& impl,
const ConstBufferSequence& buffers,
const endpoint_type& destination, socket_base::message_flags flags,
Handler& handler)
{
bool is_continuation =
asio_handler_cont_helpers::is_continuation(handler);
// Allocate and construct an operation to wrap the handler.
typedef reactive_socket_sendto_op<ConstBufferSequence,
endpoint_type, Handler> op;
typename op::ptr p = { asio::detail::addressof(handler),
op::ptr::allocate(handler), 0 };
p.p = new (p.v) op(impl.socket_, buffers, destination, flags, handler);
ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "socket",
&impl, impl.socket_, "async_send_to"));
start_op(impl, reactor::write_op, p.p, is_continuation, true, false);
p.v = p.p = 0;
}
// Start an asynchronous wait until data can be sent without blocking.
template <typename Handler>
void async_send_to(implementation_type& impl, const null_buffers&,
const endpoint_type&, socket_base::message_flags, Handler& handler)
{
bool is_continuation =
asio_handler_cont_helpers::is_continuation(handler);
// Allocate and construct an operation to wrap the handler.
typedef reactive_null_buffers_op<Handler> op;
typename op::ptr p = { asio::detail::addressof(handler),
op::ptr::allocate(handler), 0 };
p.p = new (p.v) op(handler);
ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "socket",
&impl, impl.socket_, "async_send_to(null_buffers)"));
start_op(impl, reactor::write_op, p.p, is_continuation, false, false);
p.v = p.p = 0;
}
// Receive a datagram with the endpoint of the sender. Returns the number of
// bytes received.
template <typename MutableBufferSequence>
size_t receive_from(implementation_type& impl,
const MutableBufferSequence& buffers,
endpoint_type& sender_endpoint, socket_base::message_flags flags,
asio::error_code& ec)
{
buffer_sequence_adapter<asio::mutable_buffer,
MutableBufferSequence> bufs(buffers);
std::size_t addr_len = sender_endpoint.capacity();
std::size_t bytes_recvd = socket_ops::sync_recvfrom(
impl.socket_, impl.state_, bufs.buffers(), bufs.count(),
flags, sender_endpoint.data(), &addr_len, ec);
if (!ec)
sender_endpoint.resize(addr_len);
return bytes_recvd;
}
// Wait until data can be received without blocking.
size_t receive_from(implementation_type& impl, const null_buffers&,
endpoint_type& sender_endpoint, socket_base::message_flags,
asio::error_code& ec)
{
// Wait for socket to become ready.
socket_ops::poll_read(impl.socket_, impl.state_, ec);
// Reset endpoint since it can be given no sensible value at this time.
sender_endpoint = endpoint_type();
return 0;
}
// Start an asynchronous receive. The buffer for the data being received and
// the sender_endpoint object must both be valid for the lifetime of the
// asynchronous operation.
template <typename MutableBufferSequence, typename Handler>
void async_receive_from(implementation_type& impl,
const MutableBufferSequence& buffers, endpoint_type& sender_endpoint,
socket_base::message_flags flags, Handler& handler)
{
bool is_continuation =
asio_handler_cont_helpers::is_continuation(handler);
// Allocate and construct an operation to wrap the handler.
typedef reactive_socket_recvfrom_op<MutableBufferSequence,
endpoint_type, Handler> op;
typename op::ptr p = { asio::detail::addressof(handler),
op::ptr::allocate(handler), 0 };
int protocol = impl.protocol_.type();
p.p = new (p.v) op(impl.socket_, protocol,
buffers, sender_endpoint, flags, handler);
ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "socket",
&impl, impl.socket_, "async_receive_from"));
start_op(impl,
(flags & socket_base::message_out_of_band)
? reactor::except_op : reactor::read_op,
p.p, is_continuation, true, false);
p.v = p.p = 0;
}
// Wait until data can be received without blocking.
template <typename Handler>
void async_receive_from(implementation_type& impl,
const null_buffers&, endpoint_type& sender_endpoint,
socket_base::message_flags flags, Handler& handler)
{
bool is_continuation =
asio_handler_cont_helpers::is_continuation(handler);
// Allocate and construct an operation to wrap the handler.
typedef reactive_null_buffers_op<Handler> op;
typename op::ptr p = { asio::detail::addressof(handler),
op::ptr::allocate(handler), 0 };
p.p = new (p.v) op(handler);
ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "socket",
&impl, impl.socket_, "async_receive_from(null_buffers)"));
// Reset endpoint since it can be given no sensible value at this time.
sender_endpoint = endpoint_type();
start_op(impl,
(flags & socket_base::message_out_of_band)
? reactor::except_op : reactor::read_op,
p.p, is_continuation, false, false);
p.v = p.p = 0;
}
// Accept a new connection.
template <typename Socket>
asio::error_code accept(implementation_type& impl,
Socket& peer, endpoint_type* peer_endpoint, asio::error_code& ec)
{
// We cannot accept a socket that is already open.
if (peer.is_open())
{
ec = asio::error::already_open;
return ec;
}
std::size_t addr_len = peer_endpoint ? peer_endpoint->capacity() : 0;
socket_holder new_socket(socket_ops::sync_accept(impl.socket_,
impl.state_, peer_endpoint ? peer_endpoint->data() : 0,
peer_endpoint ? &addr_len : 0, ec));
// On success, assign new connection to peer socket object.
if (new_socket.get() != invalid_socket)
{
if (peer_endpoint)
peer_endpoint->resize(addr_len);
if (!peer.assign(impl.protocol_, new_socket.get(), ec))
new_socket.release();
}
return ec;
}
#if defined(ASIO_HAS_MOVE)
// Accept a new connection.
typename Protocol::socket accept(implementation_type& impl,
io_context* peer_io_context, endpoint_type* peer_endpoint,
asio::error_code& ec)
{
typename Protocol::socket peer(
peer_io_context ? *peer_io_context : io_context_);
std::size_t addr_len = peer_endpoint ? peer_endpoint->capacity() : 0;
socket_holder new_socket(socket_ops::sync_accept(impl.socket_,
impl.state_, peer_endpoint ? peer_endpoint->data() : 0,
peer_endpoint ? &addr_len : 0, ec));
// On success, assign new connection to peer socket object.
if (new_socket.get() != invalid_socket)
{
if (peer_endpoint)
peer_endpoint->resize(addr_len);
if (!peer.assign(impl.protocol_, new_socket.get(), ec))
new_socket.release();
}
return peer;
}
#endif // defined(ASIO_HAS_MOVE)
// Start an asynchronous accept. The peer and peer_endpoint objects must be
// valid until the accept's handler is invoked.
template <typename Socket, typename Handler>
void async_accept(implementation_type& impl, Socket& peer,
endpoint_type* peer_endpoint, Handler& handler)
{
bool is_continuation =
asio_handler_cont_helpers::is_continuation(handler);
// Allocate and construct an operation to wrap the handler.
typedef reactive_socket_accept_op<Socket, Protocol, Handler> op;
typename op::ptr p = { asio::detail::addressof(handler),
op::ptr::allocate(handler), 0 };
p.p = new (p.v) op(impl.socket_, impl.state_, peer,
impl.protocol_, peer_endpoint, handler);
ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "socket",
&impl, impl.socket_, "async_accept"));
start_accept_op(impl, p.p, is_continuation, peer.is_open());
p.v = p.p = 0;
}
#if defined(ASIO_HAS_MOVE)
// Start an asynchronous accept. The peer_endpoint object must be valid until
// the accept's handler is invoked.
template <typename Handler>
void async_accept(implementation_type& impl,
asio::io_context* peer_io_context,
endpoint_type* peer_endpoint, Handler& handler)
{
bool is_continuation =
asio_handler_cont_helpers::is_continuation(handler);
// Allocate and construct an operation to wrap the handler.
typedef reactive_socket_move_accept_op<Protocol, Handler> op;
typename op::ptr p = { asio::detail::addressof(handler),
op::ptr::allocate(handler), 0 };
p.p = new (p.v) op(peer_io_context ? *peer_io_context : io_context_,
impl.socket_, impl.state_, impl.protocol_, peer_endpoint, handler);
ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "socket",
&impl, impl.socket_, "async_accept"));
start_accept_op(impl, p.p, is_continuation, false);
p.v = p.p = 0;
}
#endif // defined(ASIO_HAS_MOVE)
// Connect the socket to the specified endpoint.
asio::error_code connect(implementation_type& impl,
const endpoint_type& peer_endpoint, asio::error_code& ec)
{
socket_ops::sync_connect(impl.socket_,
peer_endpoint.data(), peer_endpoint.size(), ec);
return ec;
}
// Start an asynchronous connect.
template <typename Handler>
void async_connect(implementation_type& impl,
const endpoint_type& peer_endpoint, Handler& handler)
{
bool is_continuation =
asio_handler_cont_helpers::is_continuation(handler);
// Allocate and construct an operation to wrap the handler.
typedef reactive_socket_connect_op<Handler> op;
typename op::ptr p = { asio::detail::addressof(handler),
op::ptr::allocate(handler), 0 };
p.p = new (p.v) op(impl.socket_, handler);
ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "socket",
&impl, impl.socket_, "async_connect"));
start_connect_op(impl, p.p, is_continuation,
peer_endpoint.data(), peer_endpoint.size());
p.v = p.p = 0;
}
};
} // namespace detail
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // !defined(ASIO_HAS_IOCP)
#endif // ASIO_DETAIL_REACTIVE_SOCKET_SERVICE_HPP
| [
"ss.abramchuk@gmail.com"
] | ss.abramchuk@gmail.com |
a7f5b753aac995b00c2204f9f828213ce48f5b4b | be4d72c7501e70423b53082a7afae28c6a06f5c2 | /filled-triangles/rasterizer.cc | ecba332a9a624ffdb53029aca814c89b839cb765 | [] | no_license | ivankocienski/graphics | b411ef655a422e790356a734f6d936f814ac0c8c | 20a970ead64658fbe787719486e4d9eede1386a3 | refs/heads/master | 2020-08-07T13:51:04.332038 | 2014-11-27T17:20:50 | 2014-12-01T12:34:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,067 | cc |
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "rasterizer.hh"
// using http://forum.devmaster.net/t/advanced-rasterization/6145
static unsigned char *vbuff;
static int vpitch;
//static int vwidth;
//static int vheight;
static int vmaxx;
static int vmaxy;
void rast_setup( unsigned char *vb, int vp, int maxx, int maxy ) {
vbuff = vb;
vpitch = vp;
//vwidth = maxx;
//vheight = maxy;
vmaxx = maxx - 1;
vmaxy = maxy - 1;
}
void rast_fill_triangle( int x1, int y1, int x2, int y2, int x3, int y3 ) {
int x;
int y;
int min_x = x1;
if( x2 < min_x ) min_x = x2;
if( x3 < min_x ) min_x = x3;
int min_y = y1;
if( y2 < min_y ) min_y = y2;
if( y3 < min_y ) min_y = y3;
int max_x = x1;
if( x2 > max_x ) max_x = x2;
if( x3 > max_x ) max_x = x3;
int max_y = y1;
if( y2 > max_y ) max_y = y2;
if( y3 > max_y ) max_y = y3;
int dx12 = x1 - x2;
int dx23 = x2 - x3;
int dx31 = x3 - x1;
int dy12 = y1 - y2;
int dy23 = y2 - y3;
int dy31 = y3 - y1;
int c1 = dy12 * x1 - dx12 * y1;
int c2 = dy23 * x2 - dx23 * y2;
int c3 = dy31 * x3 - dx31 * y3;
int cy1 = c1 + dx12 * min_y - dy12 * min_x;
int cy2 = c2 + dx23 * min_y - dy23 * min_x;
int cy3 = c3 + dx31 * min_y - dy31 * min_x;
unsigned char *p = vbuff + (min_y * vpitch) + min_x;
int pad = vpitch - (max_x - min_x);
for( y = min_y; y < max_y; y++ ) {
int cx1 = cy1;
int cx2 = cy2;
int cx3 = cy3;
for( x = min_x; x < max_x; x++ ) {
if( cx1 > 0 && cx2 > 0 && cx3 > 0 ) *p = 255;
cx1 -= dy12;
cx2 -= dy23;
cx3 -= dy31;
p++;
}
cy1 += dx12;
cy2 += dx23;
cy3 += dx31;
p += pad;
}
}
static void draw_line( int x1, int x2, int y, unsigned char c ) {
if( x1 < 0 ) x1 = 0;
if( x2 > vmaxx) x2 = vmaxx;
int l = x2 - x1;
if( l < 1 ) return;
memset( vbuff + ( y * vpitch ) + x1, c, l );
}
static void draw_flat_tri( int xl, int yl, int xm, int ym, int xr, unsigned char c ) {
if( xl > xr ) {
int t = xr;
xr = xl;
xl = t;
}
float dy;
float slope_l = 0;
float slope_r = 0;
float c_x;
float c_y;
float e_x;
if( ym < yl ) {
// scanning from point to base
if( yl < 0 || ym > vmaxy ) return;
dy = yl - ym;
if( dy != 0 ) {
slope_l = (float)(xl - xm) / dy;
slope_r = (float)(xr - xm) / dy;
}
c_x = xm;
c_y = ym;
e_x = xm;
} else {
// scanning from base to point
if( ym < 0 || yl > vmaxy ) return;
dy = ym - yl;
if( dy != 0 ) {
slope_l = (float)(xm - xl) / dy;
slope_r = (float)(xm - xr) / dy;
}
c_x = xl;
c_y = yl;
e_x = xr;
}
// do we start to the left off screen?
if( e_x < 0 ) {
float steps_l = 0;
if( slope_r != 0 ) steps_l = (0 - e_x) / slope_r;
c_y += (int)steps_l;
e_x = 0;
c_x += steps_l * slope_l;
} else {
// do we start to the right of the screen?
if( c_x > vmaxx ) {
float steps_r = 0;
if( slope_l != 0 ) steps_r = (vmaxx - c_x) / slope_l;
c_y += (int)steps_r;
c_x = vmaxx;
e_x += steps_r * slope_r;
}
}
// if we are above the screen then adjust the start
if( c_y < 0 ) {
//printf("c_y<0\n");
float diff = 0 - c_y;
//printf(" c_y=%f\n", c_y );
//printf(" diff=%f\n", diff );
//printf(" slope_r=%f\n", slope_r );
//printf(" slope_l=%f\n", slope_l );
c_x += slope_l * diff;
if( c_x > vmaxx) return;
e_x += slope_r * diff;
c_y = 0;
//printf(" c_x=%f e_x=%f\n", c_x, e_x );
}
if( ym < yl ) {
// render it!
while( c_y < yl && c_y < vmaxy ) {
draw_line( c_x, e_x, c_y, c );
c_x += slope_l;
e_x += slope_r;
if( e_x < 0 || c_x > vmaxx) break;
c_y++;
}
} else {
while( c_y < vmaxy ) {
draw_line( c_x, e_x, c_y, c );
c_x += slope_l;
e_x += slope_r;
if( c_x > e_x ) break;
if( c_x > vmaxx) break;
if( e_x < 0) break;
c_y++;
}
}
}
void rast_fill_triangle2( int x1, int y1, int x2, int y2, int x3, int y3, unsigned char c ) {
int s1 = abs(y1 - y2);
int s2 = abs(y2 - y3);
int s3 = abs(y3 - y1);
if( s1 == 0 ) {
draw_flat_tri( x1, y1, x3, y3, x2, c );
return;
}
if( s2 == 0 ) {
draw_flat_tri( x2, y2, x1, y1, x3, c );
return;
}
if( s3 == 0 ) {
draw_flat_tri( x1, y1, x2, y2, x3, c );
return;
}
if( s1 > s2 && s1 > s3 ) {
// s1 is largest
if( y1 < y2 ) {
float slope = (float)(x2 - x1) / (float)(y2 - y1);
int ppy = y3;
int ppx = x1 + (float)(y3 - y1) * slope;
draw_flat_tri( ppx, ppy, x1, y1, x3, c );
draw_flat_tri( ppx, ppy, x2, y2, x3, c );
} else {
float slope = (float)(x1 - x2) / (float)(y1 - y2);
int ppy = y3;
int ppx = x2 + (float)(y3 - y2) * slope;
draw_flat_tri( ppx, ppy, x1, y1, x3, c );
draw_flat_tri( ppx, ppy, x2, y2, x3, c );
}
return;
}
if(s2 > s1 && s2 > s3) {
// s2 is the largest
if( y2 < y3 ) {
float slope = (float)(x3 - x2) / (float)(y3 - y2);
int ppy = y1;
int ppx = x2 + (float)(y1 - y2) * slope;
draw_flat_tri( ppx, ppy, x2, y2, x1, c );
draw_flat_tri( ppx, ppy, x3, y3, x1, c );
} else {
float slope = (float)(x2 - x3) / (float)(y2 - y3);
int ppy = y1;
int ppx = x3 + (float)(y1 - y3) * slope;
draw_flat_tri( ppx, ppy, x2, y2, x1, c );
draw_flat_tri( ppx, ppy, x3, y3, x1, c );
}
return;
}
// s3 must be largest
if( y3 < y1 ) {
float slope = (float)(x3 - x1) / (float)(y3 - y1);
int ppy = y2;
int ppx = x3 + (float)(y2 - y3) * slope;
draw_flat_tri( ppx, ppy, x3, y3, x2, c );
draw_flat_tri( ppx, ppy, x1, y1, x2, c );
} else {
float slope = (float)(x1 - x3) / (float)(y1 - y3);
int ppy = y2;
int ppx = x1 + (float)(y2 - y1) * slope;
draw_flat_tri( ppx, ppy, x1, y1, x2, c );
draw_flat_tri( ppx, ppy, x3, y3, x2, c );
}
}
| [
"ivan.kocienski@gmail.com"
] | ivan.kocienski@gmail.com |
c3d77e39158f62bf471f6bc21bf398a5a8c3557c | 6eda3762e8927773045da664a666cec154672c81 | /Controls/MathGraphCtrl/MathGraphCtl.cpp | f8f57080f57f5248170b81f78df554d724a6dd77 | [] | no_license | zvanjak/Old-Visual-C-projects | 6038207649c864047d1cafdf7b11fa049b9c2cb9 | 4031ab736498b9e7864d35f26f23b09c447e8714 | refs/heads/master | 2020-05-01T11:50:41.561933 | 2019-03-24T18:31:34 | 2019-03-24T18:31:34 | 177,453,065 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,354 | cpp | // MathGraphCtl.cpp : Implementation of the CMathGraphCtrl ActiveX Control class.
#include "stdafx.h"
#include "MathGraphCtrl.h"
#include "MathGraphCtl.h"
#include "MathGraphCtrlPpg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
IMPLEMENT_DYNCREATE(CMathGraphCtrl, COleControl)
/////////////////////////////////////////////////////////////////////////////
// Message map
BEGIN_MESSAGE_MAP(CMathGraphCtrl, COleControl)
//{{AFX_MSG_MAP(CMathGraphCtrl)
ON_WM_CREATE()
ON_WM_SIZE()
//}}AFX_MSG_MAP
ON_OLEVERB(AFX_IDS_VERB_PROPERTIES, OnProperties)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// Dispatch map
BEGIN_DISPATCH_MAP(CMathGraphCtrl, COleControl)
//{{AFX_DISPATCH_MAP(CMathGraphCtrl)
// NOTE - ClassWizard will add and remove dispatch map entries
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_DISPATCH_MAP
DISP_FUNCTION_ID(CMathGraphCtrl, "AboutBox", DISPID_ABOUTBOX, AboutBox, VT_EMPTY, VTS_NONE)
END_DISPATCH_MAP()
/////////////////////////////////////////////////////////////////////////////
// Event map
BEGIN_EVENT_MAP(CMathGraphCtrl, COleControl)
//{{AFX_EVENT_MAP(CMathGraphCtrl)
// NOTE - ClassWizard will add and remove event map entries
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_EVENT_MAP
END_EVENT_MAP()
/////////////////////////////////////////////////////////////////////////////
// Property pages
// TODO: Add more property pages as needed. Remember to increase the count!
BEGIN_PROPPAGEIDS(CMathGraphCtrl, 1)
PROPPAGEID(CMathGraphCtrlPropPage::guid)
END_PROPPAGEIDS(CMathGraphCtrl)
/////////////////////////////////////////////////////////////////////////////
// Initialize class factory and guid
IMPLEMENT_OLECREATE_EX(CMathGraphCtrl, "MATHGRAPHCTRL.MathGraphCtrl.1",
0x945b8405, 0x14c0, 0x11d2, 0x91, 0x54, 0, 0xc0, 0xdf, 0xe5, 0x28, 0x74)
/////////////////////////////////////////////////////////////////////////////
// Type library ID and version
IMPLEMENT_OLETYPELIB(CMathGraphCtrl, _tlid, _wVerMajor, _wVerMinor)
/////////////////////////////////////////////////////////////////////////////
// Interface IDs
const IID BASED_CODE IID_DMathGraphCtrl =
{ 0x945b8403, 0x14c0, 0x11d2, { 0x91, 0x54, 0, 0xc0, 0xdf, 0xe5, 0x28, 0x74 } };
const IID BASED_CODE IID_DMathGraphCtrlEvents =
{ 0x945b8404, 0x14c0, 0x11d2, { 0x91, 0x54, 0, 0xc0, 0xdf, 0xe5, 0x28, 0x74 } };
/////////////////////////////////////////////////////////////////////////////
// Control type information
static const DWORD BASED_CODE _dwMathGraphCtrlOleMisc =
OLEMISC_SIMPLEFRAME |
OLEMISC_ACTIVATEWHENVISIBLE |
OLEMISC_SETCLIENTSITEFIRST |
OLEMISC_INSIDEOUT |
OLEMISC_CANTLINKINSIDE |
OLEMISC_RECOMPOSEONRESIZE;
IMPLEMENT_OLECTLTYPE(CMathGraphCtrl, IDS_MATHGRAPHCTRL, _dwMathGraphCtrlOleMisc)
/////////////////////////////////////////////////////////////////////////////
// CMathGraphCtrl::CMathGraphCtrlFactory::UpdateRegistry -
// Adds or removes system registry entries for CMathGraphCtrl
BOOL CMathGraphCtrl::CMathGraphCtrlFactory::UpdateRegistry(BOOL bRegister)
{
// TODO: Verify that your control follows apartment-model threading rules.
// Refer to MFC TechNote 64 for more information.
// If your control does not conform to the apartment-model rules, then
// you must modify the code below, changing the 6th parameter from
// afxRegApartmentThreading to 0.
if (bRegister)
return AfxOleRegisterControlClass(
AfxGetInstanceHandle(),
m_clsid,
m_lpszProgID,
IDS_MATHGRAPHCTRL,
IDB_MATHGRAPHCTRL,
afxRegApartmentThreading,
_dwMathGraphCtrlOleMisc,
_tlid,
_wVerMajor,
_wVerMinor);
else
return AfxOleUnregisterClass(m_clsid, m_lpszProgID);
}
/////////////////////////////////////////////////////////////////////////////
// CMathGraphCtrl::CMathGraphCtrl - Constructor
CMathGraphCtrl::CMathGraphCtrl()
{
InitializeIIDs(&IID_DMathGraphCtrl, &IID_DMathGraphCtrlEvents);
EnableSimpleFrame();
// TODO: Initialize your control's instance data here.
}
/////////////////////////////////////////////////////////////////////////////
// CMathGraphCtrl::~CMathGraphCtrl - Destructor
CMathGraphCtrl::~CMathGraphCtrl()
{
// TODO: Cleanup your control's instance data here.
}
/////////////////////////////////////////////////////////////////////////////
// CMathGraphCtrl::OnDraw - Drawing function
void CMathGraphCtrl::OnDraw(
CDC* pdc, const CRect& rcBounds, const CRect& rcInvalid)
{
// TODO: Replace the following code with your own drawing code.
pdc->FillRect(rcBounds, CBrush::FromHandle((HBRUSH)GetStockObject(WHITE_BRUSH)));
pdc->Ellipse(rcBounds);
}
/////////////////////////////////////////////////////////////////////////////
// CMathGraphCtrl::DoPropExchange - Persistence support
void CMathGraphCtrl::DoPropExchange(CPropExchange* pPX)
{
ExchangeVersion(pPX, MAKELONG(_wVerMinor, _wVerMajor));
COleControl::DoPropExchange(pPX);
// TODO: Call PX_ functions for each persistent custom property.
}
/////////////////////////////////////////////////////////////////////////////
// CMathGraphCtrl::OnResetState - Reset control to default state
void CMathGraphCtrl::OnResetState()
{
COleControl::OnResetState(); // Resets defaults found in DoPropExchange
// TODO: Reset any other control state here.
}
/////////////////////////////////////////////////////////////////////////////
// CMathGraphCtrl::AboutBox - Display an "About" box to the user
void CMathGraphCtrl::AboutBox()
{
CDialog dlgAbout(IDD_ABOUTBOX_MATHGRAPHCTRL);
dlgAbout.DoModal();
}
/////////////////////////////////////////////////////////////////////////////
// CMathGraphCtrl message handlers
int CMathGraphCtrl::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (COleControl::OnCreate(lpCreateStruct) == -1)
return -1;
// TODO: Add your specialized creation code here
// m_ctrlGraph.Create("Caption jumbo", WS_VISIBLE, CRect(0,0,500,500), this, 0);
return 0;
}
/*
void CMathGraphCtrl::OnSize(UINT nType, int cx, int cy)
{
COleControl::OnSize(nType, cx, cy);
// TODO: Add your message handler code here
if( nType == SIZE_RESTORED )
{
CRect rect;
GetClientRect(&rect);
m_ctrlGraph.SetWindowPos(this, rect.left, rect.top, rect.right, rect.bottom, SWP_SHOWWINDOW );
}
}
*/
| [
"zvonimir.vanjak@gmail.com"
] | zvonimir.vanjak@gmail.com |
908391172671b65142f37df27c7ecb734cb8c3ad | 775bd9054f599f49b3e288da13e2679ff62e0097 | /Union/Union/UnionBase.cpp | f0e80011380fa16b59c9b0c871b5184c682ac3bb | [] | no_license | LProvalov/DataStructuresAndAlgorithms | e6e85f701ce08720c1ae6c585645cf837d49f8c2 | 9dbb48f4220fa925927bd6717b6c2019d8456f66 | refs/heads/master | 2020-03-29T08:56:24.432133 | 2018-09-21T09:28:29 | 2018-09-21T09:28:29 | 149,733,969 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 511 | cpp | #include "stdafx.h"
#include "UnionBase.h"
using namespace std;
void UnionBase::printStatus()
{
cout << " ";
for (int i = 0; i < size; i++) cout << i << " ";
cout << endl << "Id[]: ";
for (int i = 0; i < size; i++) {
cout << id[i] << " ";
};
cout << endl;
cout << "Sz[]: ";
for (int i = 0; i < size; i++) {
cout << sz[i] << " ";
};
cout << endl;
cout << "------------------------------" << endl;
}
UnionBase::UnionBase()
{
size = 0;
id = 0;
sz = 0;
}
UnionBase::~UnionBase()
{
}
| [
"lev.provalov@harman.com"
] | lev.provalov@harman.com |
65873d032ba20634db5523411ca0e3ef484549f0 | e17c43db9488f57cb835129fa954aa2edfdea8d5 | /Core/Methods/RSearchDirection/RHLRFSearchDirection.cpp | 14152d70bb12e219c56e8bf39ebcc281c9c87dd0 | [] | no_license | claudioperez/Rts | 6e5868ab8d05ea194a276b8059730dbe322653a7 | 3609161c34f19f1649b713b09ccef0c8795f8fe7 | refs/heads/master | 2022-11-06T15:57:39.794397 | 2020-06-27T23:00:11 | 2020-06-27T23:00:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,269 | cpp | /*********************************************************************
* *
* This file is posted by Dr. Stevan Gavrilovic (steva44@hotmail.com) *
* as a result of work performed in the research group of Professor *
* Terje Haukaas (terje@civil.ubc.ca) at the University of British *
* Columbia in Vancouver. The code is part of the computer program *
* Rts, which is an extension of the computer program Rt developed by *
* Dr. Mojtaba Mahsuli (mahsuli@sharif.edu) in the same group. *
* *
* The content of this file is the product of thesis-related work *
* performed at the University of British Columbia (UBC). Therefore, *
* the Rights and Ownership are held by UBC. *
* *
* Please be cautious when using this code. It is provided “as is” *
* without warranty of any kind, express or implied. *
* *
* Contributors to this file: *
* - Terje Haukaas *
* *
*********************************************************************/
#include "RHLRFSearchDirection.h"
#include "RMatrixOperations.h"
#include "RDomain.h"
#include <math.h>
RHLRFSearchDirection::RHLRFSearchDirection(QObject *parent, QString name)
: RSearchDirection(parent, name)
{
}
RHLRFSearchDirection::~RHLRFSearchDirection()
{
}
int RHLRFSearchDirection::getSearchDirection(QVector<double> const *u, double functionValue, QVector<double> const *gradientInStandardNormalSpace, QVector<double> *result)
{
// Create a matrix operations tool
RMatrixOperations theMatrixOperations(theDomain);
// Determine vector sizes
int size = gradientInStandardNormalSpace->size();
// Compute the norm of the gradient
double gradientNorm = theMatrixOperations.norm(gradientInStandardNormalSpace);
// Check that the norm is not zero
if (gradientNorm == 0.0) {
qCritical() << "Error: The norm of the gradient in the HLRF search direction is zero.";
for (int i=0; i<size; i++) {
(*result)[i] = 1.0;
}
return 0;
}
// Compute alpha-vector using BLAS: alpha = gradientInStandardNormalSpace * (-1 / gradientNorm)
QVector<double> alpha(size);
for (int i=0; i<size; i++) {
alpha[i] = -gradientInStandardNormalSpace->at(i)/gradientNorm;
}
// Compute the alpha.u using BLAS: alpha_times_u = alpha * u
double alpha_times_u = 0.0;
for (int i=0; i<u->size(); i++) {
alpha_times_u += alpha.at(i)*u->at(i);
}
// Compute the search direction vector using BLAS: direction = alpha * (functionValue / gradientNorm + alpha_times_u) - u
for (int i=0; i<size; i++) {
(*result)[i] = ((functionValue / gradientNorm + alpha_times_u) * alpha.at(i)) - u->at(i);
}
return 0;
}
| [
"steva44@hotmail.com"
] | steva44@hotmail.com |
757ae5cc5842d0c83bce373b4098656f6c646fff | 2e2865a18d2262d62275770ee546d5c3979e9d55 | /uva/976 - Bridge Building.cpp | c258654e599b1c1b8c32152a04cc16f24a937cbd | [] | no_license | mosta7il/Competitive-programming | 4b06f5ed7316ee5c57460eed4f9eb4e04f857167 | 59129ca2b0f9c2894aee68b4f2d12bc89741d3d7 | refs/heads/master | 2022-06-12T19:41:18.229376 | 2022-05-19T10:09:47 | 2022-05-19T10:09:47 | 100,424,868 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,087 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include<bits/stdc++.h>
using namespace std;
const long long OO = 1e9;
const long long mod = 1e9 + 7;
const long double EPS = (1e-18);
int dcmp(long double x, long double y) { return fabs(x - y) <= EPS ? 0 : x < y ? -1 : 1; }
int dx[] = { 0, 0, 1, -1, 1, 1, -1, -1 };
int dy[] = { 1, -1, 0, 0, -1, 1, 1, -1 };
void fast(){
#ifndef ONLINE_JUDGE
freopen("F:\\solving\\input.txt", "r", stdin);
freopen("F:\\solving\\output.txt", "w", stdout);
#endif
std::ios_base::sync_with_stdio(0);
cin.tie(NULL); cout.tie(NULL);
}
const long long MAX = 20 *1000 * 1000 + 1;
int t;
int n, m, b, d;
char g[1001][1001];
bool north[1001][1001], south[1001][1001];
int bestN[1001], bestS[1001];
bool isv(int i, int j){
return i >= 0 && j >= 0 && i < n&&j < m;
}
void Ndfs(int i, int j){
north[i][j] = 1;
for (int x = 0; x < 4; x++){
int ii = i + dx[x], jj = j + dy[x];
if (isv(ii, jj) && !north[ii][jj] && g[ii][jj] == '#')
Ndfs(ii, jj);
}
}
void Sdfs(int i, int j){
south[i][j] = 1;
for (int x = 0; x < 4; x++){
int ii = i + dx[x], jj = j + dy[x];
if (isv(ii, jj) && !south[ii][jj] && g[ii][jj] == '#')
Sdfs(ii, jj);
}
}
int mem[1001][101];
int rec(int idx , int rem){
if (idx >= m){
if (rem == 0)
return 0;
return 1e7;
}
int &ret = mem[idx][rem];
if (ret != -1)
return ret;
ret = 1e9;
ret = min(ret, rec(idx + 1, rem));
if (rem > 0){
ret = min(ret, rec(idx + d + 1, rem - 1) + abs(bestN[idx] - bestS[idx])-1);
}
return ret;
}
int main(){
fast();
//cin >> t;
while (cin >> n >> m >> b >> d){
memset(north, 0, sizeof north);
memset(south, 0, sizeof south);
memset(mem, -1, sizeof mem);
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
cin >> g[i][j];
}
}
Ndfs(0, 0);
Sdfs(n - 1, 0);
for (int i = 0; i < m; i++){
int lst = -1;
for (int j = 0; j < n; j++){
if (north[j][i])
lst = j;
}
bestN[i] = lst;
lst = -1;
for (int j = n - 1; j >= 0; j--){
if (south[j][i])
lst = j;
}
bestS[i] = lst;
}
cout << rec(0, b) << endl;
}
return 0;
}
| [
"noreply@github.com"
] | mosta7il.noreply@github.com |
8e25c2f4befef268970ec5a11c13b635ff4f2020 | 2203747ff325b78f25f34a558991418f455f8137 | /BmpFileShelter/CMyLCG.h | 4a3b31cfc96be6dbddc1689091a35068b2e0dae4 | [] | no_license | PavelKilik/BmpFileShelter | ce87920621bfa066a1a45a6401d2b72cc038ccbd | c0a366823cad1cbfb78efb2caa1dac26bfbb041a | refs/heads/master | 2020-03-30T12:48:46.268630 | 2018-10-15T04:20:00 | 2018-10-15T04:20:00 | 151,242,073 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 351 | h | #pragma once
class CMyLCG
{
private:
ULONG64 aParamM;
ULONG64 aParamA;
ULONG64 aParamC;
ULONG64 aValueX;
public:
CMyLCG();
CMyLCG(ULONG32 initParamA, ULONG32 initParamC);
~CMyLCG();
void InitializeParameters(ULONG32 initParamA, ULONG32 initParamC);
void Start(ULONG32 seed);
ULONG32 Next();
CString ToString(bool hexFormat = false);
};
| [
"Pavel Kilik@DESKTOP-NQ2E9PL"
] | Pavel Kilik@DESKTOP-NQ2E9PL |
d130007151bdd3bd50b96baeb4e6318280f15144 | 3817488ed22598117e7b96af336635ef9a925200 | /api/CTraderSpi.cpp | fa1c1455e2fa6efe13e9aa44e59ad6ae00b487b8 | [
"Apache-2.0"
] | permissive | go-xtrade/xtrade | 88d27627f357719eeb3652c5d837b5cd624e0d39 | 495d4267c7d2e9e141012821f49c297e4a70b2e8 | refs/heads/master | 2021-01-02T09:44:56.171713 | 2017-08-06T13:16:30 | 2017-08-06T13:16:30 | 99,287,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,541 | cpp | #include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
using namespace std;
#include <ThostFtdcTraderApi.h>
#include "CTraderSpi.hpp"
#include <time.h>
#include <unistd.h>
#include "_cgo_export.h"
#pragma warning(disable : 4996)
// USER_API参数
extern CThostFtdcTraderApi *pUserApi;
// 配置参数
extern char FRONT_ADDR[]; // 前置地址
extern char BROKER_ID[]; // 经纪公司代码
extern char INVESTOR_ID[]; // 投资者代码
extern char PASSWORD[]; // 用户密码
extern char INSTRUMENT_ID[]; // 合约代码
extern TThostFtdcPriceType LIMIT_PRICE; // 价格
extern TThostFtdcDirectionType DIRECTION; // 买卖方向
// 请求编号
extern int iRequestID;
// extern int OnLogin();
// 会话参数
TThostFtdcFrontIDType FRONT_ID; //前置编号
TThostFtdcSessionIDType SESSION_ID; //会话编号
TThostFtdcOrderRefType ORDER_REF; //报单引用
time_t lOrderTime;
time_t lOrderOkTime;
void CTraderSpi::OnFrontConnected()
{
cerr << "--->>> "
<< "OnFrontConnected:" << this->GetUserID()<< endl;
FrontConnectedCallback(this->GetUserID());
}
void CTraderSpi::ReqUserLogin()
{
CThostFtdcReqUserLoginField req;
memset(&req, 0, sizeof(req));
strcpy(req.BrokerID, BROKER_ID);
strcpy(req.UserID, INVESTOR_ID);
strcpy(req.Password, PASSWORD);
int iResult = pUserApi->ReqUserLogin(&req, ++iRequestID);
cerr << "--->>> 发送用户登录请求: " << ((iResult == 0) ? "成功" : "失败") << endl;
}
void CTraderSpi::OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin,
CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
UserLoginCallback(pRspUserLogin,pRspInfo,nRequestID,bIsLast);
cerr << "--->>> " << "OnRspUserLogin: " << pRspUserLogin->UserID << "bIsLast" << bIsLast << "MaxOrderRef : " << atoi(pRspUserLogin->MaxOrderRef) << endl;
}
void CTraderSpi::ReqSettlementInfoConfirm()
{
CThostFtdcSettlementInfoConfirmField req;
memset(&req, 0, sizeof(req));
strcpy(req.BrokerID, BROKER_ID);
strcpy(req.InvestorID, INVESTOR_ID);
int iResult = pUserApi->ReqSettlementInfoConfirm(&req, ++iRequestID);
cerr << "--->>> 投资者结算结果确认: " << ((iResult == 0) ? "成功" : "失败") << endl;
}
void CTraderSpi::OnRspSettlementInfoConfirm(CThostFtdcSettlementInfoConfirmField *pSettlementInfoConfirm, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
cerr << "--->>> "
<< "OnRspSettlementInfoConfirm" << endl;
if (bIsLast && !IsErrorRspInfo(pRspInfo))
{
///请求查询合约
ReqQryInstrument();
}
}
void CTraderSpi::ReqQryInstrument()
{
CThostFtdcQryInstrumentField req;
memset(&req, 0, sizeof(req));
strcpy(req.InstrumentID, INSTRUMENT_ID);
int iResult = pUserApi->ReqQryInstrument(&req, ++iRequestID);
cerr << "--->>> 请求查询合约: " << ((iResult == 0) ? "成功" : "失败") << endl;
}
void CTraderSpi::OnRspQryInstrument(CThostFtdcInstrumentField *pInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
cerr << "--->>> "
<< "OnRspQryInstrument" << endl;
if (bIsLast && !IsErrorRspInfo(pRspInfo))
{
///请求查询合约
ReqQryTradingAccount();
}
}
void CTraderSpi::ReqQryTradingAccount()
{
CThostFtdcQryTradingAccountField req;
memset(&req, 0, sizeof(req));
strcpy(req.BrokerID, BROKER_ID);
strcpy(req.InvestorID, INVESTOR_ID);
int iResult = pUserApi->ReqQryTradingAccount(&req, ++iRequestID);
cerr << "result:" << iResult << endl;
cerr << "--->>> 请求查询资金账户: " << ((iResult == 0) ? "成功" : "失败") << endl;
if (iResult == -3 || iResult == -2)
{
cerr << "retry aflter 1s:" << endl;
sleep(1);
ReqQryTradingAccount();
}
}
void CTraderSpi::OnRspQryTradingAccount(CThostFtdcTradingAccountField *pTradingAccount, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
cerr << "--->>> "
<< "OnRspQryTradingAccount" << "AccountId: " << pTradingAccount->AccountID << endl;
if (bIsLast && !IsErrorRspInfo(pRspInfo))
{
///请求查询投资者持仓
ReqQryInvestorPosition();
}
}
void CTraderSpi::ReqQryInvestorPosition()
{
CThostFtdcQryInvestorPositionField req;
memset(&req, 0, sizeof(req));
strcpy(req.BrokerID, BROKER_ID);
strcpy(req.InvestorID, INVESTOR_ID);
strcpy(req.InstrumentID, INSTRUMENT_ID);
int iResult = pUserApi->ReqQryInvestorPosition(&req, ++iRequestID);
cerr << "--->>> 请求查询投资者持仓: " << ((iResult == 0) ? "成功" : "失败") << endl;
}
void CTraderSpi::OnRspQryInvestorPosition(CThostFtdcInvestorPositionField *pInvestorPosition, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
cerr << "--->>> "
<< "OnRspQryInvestorPosition" << endl;
if (bIsLast && !IsErrorRspInfo(pRspInfo))
{
///报单录入请求
ReqOrderInsert();
}
}
void CTraderSpi::ReqOrderInsert()
{
CThostFtdcInputOrderField req;
memset(&req, 0, sizeof(req));
///经纪公司代码
strcpy(req.BrokerID, BROKER_ID);
///投资者代码
strcpy(req.InvestorID, INVESTOR_ID);
///合约代码
strcpy(req.InstrumentID, INSTRUMENT_ID);
///报单引用
strcpy(req.OrderRef, ORDER_REF);
///用户代码
// TThostFtdcUserIDType UserID;
///报单价格条件: 限价
req.OrderPriceType = THOST_FTDC_OPT_LimitPrice;
///买卖方向:
req.Direction = DIRECTION;
///组合开平标志: 开仓
req.CombOffsetFlag[0] = THOST_FTDC_OF_Open;
///组合投机套保标志
req.CombHedgeFlag[0] = THOST_FTDC_HF_Speculation;
///价格
req.LimitPrice = LIMIT_PRICE;
///数量: 1
req.VolumeTotalOriginal = 1;
///有效期类型: 当日有效
req.TimeCondition = THOST_FTDC_TC_GFD;
///GTD日期
// TThostFtdcDateType GTDDate;
///成交量类型: 任何数量
req.VolumeCondition = THOST_FTDC_VC_AV;
///最小成交量: 1
req.MinVolume = 1;
///触发条件: 立即
req.ContingentCondition = THOST_FTDC_CC_Immediately;
///止损价
// TThostFtdcPriceType StopPrice;
///强平原因: 非强平
req.ForceCloseReason = THOST_FTDC_FCC_NotForceClose;
///自动挂起标志: 否
req.IsAutoSuspend = 0;
///业务单元
// TThostFtdcBusinessUnitType BusinessUnit;
///请求编号
// TThostFtdcRequestIDType RequestID;
///用户强评标志: 否
req.UserForceClose = 0;
lOrderTime = time(NULL);
int iResult = pUserApi->ReqOrderInsert(&req, ++iRequestID);
cerr << "--->>> 报单录入请求: " << ((iResult == 0) ? "成功" : "失败") << endl;
}
void CTraderSpi::OnRspOrderInsert(CThostFtdcInputOrderField *pInputOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
cerr << "--->>> "
<< "OnRspOrderInsert" << endl;
IsErrorRspInfo(pRspInfo);
}
void CTraderSpi::ReqOrderAction(CThostFtdcOrderField *pOrder)
{
static bool ORDER_ACTION_SENT = false; //是否发送了报单
if (ORDER_ACTION_SENT)
return;
CThostFtdcInputOrderActionField req;
memset(&req, 0, sizeof(req));
///经纪公司代码
strcpy(req.BrokerID, pOrder->BrokerID);
///投资者代码
strcpy(req.InvestorID, pOrder->InvestorID);
///报单操作引用
// TThostFtdcOrderActionRefType OrderActionRef;
///报单引用
strcpy(req.OrderRef, pOrder->OrderRef);
///请求编号
// TThostFtdcRequestIDType RequestID;
///前置编号
req.FrontID = FRONT_ID;
///会话编号
req.SessionID = SESSION_ID;
///交易所代码
// TThostFtdcExchangeIDType ExchangeID;
///报单编号
// TThostFtdcOrderSysIDType OrderSysID;
///操作标志
req.ActionFlag = THOST_FTDC_AF_Delete;
///价格
// TThostFtdcPriceType LimitPrice;
///数量变化
// TThostFtdcVolumeType VolumeChange;
///用户代码
// TThostFtdcUserIDType UserID;
///合约代码
strcpy(req.InstrumentID, pOrder->InstrumentID);
lOrderTime = time(NULL);
int iResult = pUserApi->ReqOrderAction(&req, ++iRequestID);
cerr << "--->>> 报单操作请求: " << ((iResult == 0) ? "成功" : "失败") << endl;
ORDER_ACTION_SENT = true;
}
void CTraderSpi::OnRspOrderAction(CThostFtdcInputOrderActionField *pInputOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
cerr << "--->>> "
<< "OnRspOrderAction" << endl;
IsErrorRspInfo(pRspInfo);
}
///报单通知
void CTraderSpi::OnRtnOrder(CThostFtdcOrderField *pOrder)
{
cerr << "--->>> "
<< "OnRtnOrder" << endl;
lOrderOkTime = time(NULL);
time_t lTime = lOrderOkTime - lOrderTime;
cerr << "--->>> 报单到报单通知的时间差 = " << lTime << endl;
if (IsMyOrder(pOrder))
{
if (IsTradingOrder(pOrder))
{
//ReqOrderAction(pOrder);
}
else if (pOrder->OrderStatus == THOST_FTDC_OST_Canceled)
cout << "--->>> 撤单成功" << endl;
}
}
///成交通知
void CTraderSpi::OnRtnTrade(CThostFtdcTradeField *pTrade)
{
cerr << "--->>> "
<< "OnRtnTrade" << endl;
}
void CTraderSpi::OnFrontDisconnected(int nReason)
{
cerr << "--->>> "
<< "OnFrontDisconnected" << endl;
cerr << "--->>> Reason = " << nReason << endl;
}
void CTraderSpi::OnHeartBeatWarning(int nTimeLapse)
{
cerr << "--->>> "
<< "OnHeartBeatWarning" << endl;
cerr << "--->>> nTimerLapse = " << nTimeLapse << endl;
}
void CTraderSpi::OnRspError(CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
cerr << "--->>> "
<< "OnRspError" << endl;
IsErrorRspInfo(pRspInfo);
}
bool CTraderSpi::IsErrorRspInfo(CThostFtdcRspInfoField *pRspInfo)
{
// 如果ErrorID != 0, 说明收到了错误的响应
bool bResult = ((pRspInfo) && (pRspInfo->ErrorID != 0));
if (bResult)
cerr << "--->>> ErrorID=" << pRspInfo->ErrorID << ", ErrorMsg=" << pRspInfo->ErrorMsg << endl;
return bResult;
}
bool CTraderSpi::IsMyOrder(CThostFtdcOrderField *pOrder)
{
return ((pOrder->FrontID == FRONT_ID) &&
(pOrder->SessionID == SESSION_ID) &&
(strcmp(pOrder->OrderRef, ORDER_REF) == 0));
}
bool CTraderSpi::IsTradingOrder(CThostFtdcOrderField *pOrder)
{
return ((pOrder->OrderStatus != THOST_FTDC_OST_PartTradedNotQueueing) &&
(pOrder->OrderStatus != THOST_FTDC_OST_Canceled) &&
(pOrder->OrderStatus != THOST_FTDC_OST_AllTraded));
}
void CTraderSpi::SaveSession(Session *pSession){
this->session = pSession;
}
Session CTraderSpi::getSession(){
return *this->session;
}
char* CTraderSpi::GetUserID(){
return &this->UserID[0];
}
void CTraderSpi::SetUserID(char *pUserID){
strcpy(this->UserID , pUserID);
} | [
"wei9.li@changhong.com"
] | wei9.li@changhong.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.