hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6064f5b687ba443515a025188a429f86a472ff62 | 265 | hpp | C++ | include/RED4ext/Scripting/Natives/Generated/quest/MultiplayerAIDirectorStatus.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 42 | 2020-12-25T08:33:00.000Z | 2022-03-22T14:47:07.000Z | include/RED4ext/Scripting/Natives/Generated/quest/MultiplayerAIDirectorStatus.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 38 | 2020-12-28T22:36:06.000Z | 2022-02-16T11:25:47.000Z | include/RED4ext/Scripting/Natives/Generated/quest/MultiplayerAIDirectorStatus.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 20 | 2020-12-28T22:17:38.000Z | 2022-03-22T17:19:01.000Z | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
namespace RED4ext
{
namespace quest {
enum class MultiplayerAIDirectorStatus : uint32_t
{
Enabled = 0,
Disabled = 1,
};
} // namespace quest
} // namespace RED4ext
| 16.5625 | 57 | 0.716981 | jackhumbert |
6066be9157e675d1efbd42822cb8395eae13447d | 12,631 | hpp | C++ | libs/boost_1_72_0/boost/move/algo/detail/pdqsort.hpp | henrywarhurst/matrix | 317a2a7c35c1c7e3730986668ad2270dc19809ef | [
"BSD-3-Clause"
] | null | null | null | libs/boost_1_72_0/boost/move/algo/detail/pdqsort.hpp | henrywarhurst/matrix | 317a2a7c35c1c7e3730986668ad2270dc19809ef | [
"BSD-3-Clause"
] | null | null | null | libs/boost_1_72_0/boost/move/algo/detail/pdqsort.hpp | henrywarhurst/matrix | 317a2a7c35c1c7e3730986668ad2270dc19809ef | [
"BSD-3-Clause"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Orson Peters 2017.
// (C) Copyright Ion Gaztanaga 2017-2018.
// 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)
//
// See http://www.boost.org/libs/move for documentation.
//
//////////////////////////////////////////////////////////////////////////////
//
// This implementation of Pattern-defeating quicksort (pdqsort) was written
// by Orson Peters, and discussed in the Boost mailing list:
// http://boost.2283326.n4.nabble.com/sort-pdqsort-td4691031.html
//
// This implementation is the adaptation by Ion Gaztanaga of code originally in
// GitHub with permission from the author to relicense it under the Boost
// Software License (see the Boost mailing list for details).
//
// The original copyright statement is pasted here for completeness:
//
// pdqsort.h - Pattern-defeating quicksort.
// Copyright (c) 2015 Orson Peters
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the
// use of this software. Permission is granted to anyone to use this software
// for any purpose, including commercial applications, and to alter it and
// redistribute it freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the
// original software. If you use this software in a product, an
// acknowledgment in the product documentation would be appreciated but is
// not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as
// being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_MOVE_ALGO_PDQSORT_HPP
#define BOOST_MOVE_ALGO_PDQSORT_HPP
#ifndef BOOST_CONFIG_HPP
#include <boost/config.hpp>
#endif
#
#if defined(BOOST_HAS_PRAGMA_ONCE)
#pragma once
#endif
#include <boost/move/algo/detail/heap_sort.hpp>
#include <boost/move/algo/detail/insertion_sort.hpp>
#include <boost/move/detail/config_begin.hpp>
#include <boost/move/detail/iterator_traits.hpp>
#include <boost/move/detail/workaround.hpp>
#include <boost/move/utility_core.hpp>
#include <boost/move/adl_move_swap.hpp>
#include <cstddef>
namespace boost {
namespace movelib {
namespace pdqsort_detail {
// A simple pair implementation to avoid including <utility>
template <class T1, class T2> struct pair {
pair() {}
pair(const T1 &t1, const T2 &t2) : first(t1), second(t2) {}
T1 first;
T2 second;
};
enum {
// Partitions below this size are sorted using insertion sort.
insertion_sort_threshold = 24,
// Partitions above this size use Tukey's ninther to select the pivot.
ninther_threshold = 128,
// When we detect an already sorted partition, attempt an insertion sort that
// allows this
// amount of element moves before giving up.
partial_insertion_sort_limit = 8,
// Must be multiple of 8 due to loop unrolling, and < 256 to fit in unsigned
// char.
block_size = 64,
// Cacheline size, assumes power of two.
cacheline_size = 64
};
// Returns floor(log2(n)), assumes n > 0.
template <class Unsigned> Unsigned log2(Unsigned n) {
Unsigned log = 0;
while (n >>= 1)
++log;
return log;
}
// Attempts to use insertion sort on [begin, end). Will return false if more
// than partial_insertion_sort_limit elements were moved, and abort sorting.
// Otherwise it will successfully sort and return true.
template <class Iter, class Compare>
inline bool partial_insertion_sort(Iter begin, Iter end, Compare comp) {
typedef typename boost::movelib::iterator_traits<Iter>::value_type T;
typedef typename boost::movelib::iterator_traits<Iter>::size_type size_type;
if (begin == end)
return true;
size_type limit = 0;
for (Iter cur = begin + 1; cur != end; ++cur) {
if (limit > partial_insertion_sort_limit)
return false;
Iter sift = cur;
Iter sift_1 = cur - 1;
// Compare first so we can avoid 2 moves for an element already positioned
// correctly.
if (comp(*sift, *sift_1)) {
T tmp = boost::move(*sift);
do {
*sift-- = boost::move(*sift_1);
} while (sift != begin && comp(tmp, *--sift_1));
*sift = boost::move(tmp);
limit += size_type(cur - sift);
}
}
return true;
}
template <class Iter, class Compare>
inline void sort2(Iter a, Iter b, Compare comp) {
if (comp(*b, *a))
boost::adl_move_iter_swap(a, b);
}
// Sorts the elements *a, *b and *c using comparison function comp.
template <class Iter, class Compare>
inline void sort3(Iter a, Iter b, Iter c, Compare comp) {
sort2(a, b, comp);
sort2(b, c, comp);
sort2(a, b, comp);
}
// Partitions [begin, end) around pivot *begin using comparison function comp.
// Elements equal to the pivot are put in the right-hand partition. Returns the
// position of the pivot after partitioning and whether the passed sequence
// already was correctly partitioned. Assumes the pivot is a median of at least
// 3 elements and that [begin, end) is at least insertion_sort_threshold long.
template <class Iter, class Compare>
pdqsort_detail::pair<Iter, bool> partition_right(Iter begin, Iter end,
Compare comp) {
typedef typename boost::movelib::iterator_traits<Iter>::value_type T;
// Move pivot into local for speed.
T pivot(boost::move(*begin));
Iter first = begin;
Iter last = end;
// Find the first element greater than or equal than the pivot (the median of
// 3 guarantees this exists).
while (comp(*++first, pivot))
;
// Find the first element strictly smaller than the pivot. We have to guard
// this search if there was no element before *first.
if (first - 1 == begin)
while (first < last && !comp(*--last, pivot))
;
else
while (!comp(*--last, pivot))
;
// If the first pair of elements that should be swapped to partition are the
// same element, the passed in sequence already was correctly partitioned.
bool already_partitioned = first >= last;
// Keep swapping pairs of elements that are on the wrong side of the pivot.
// Previously swapped pairs guard the searches, which is why the first
// iteration is special-cased above.
while (first < last) {
boost::adl_move_iter_swap(first, last);
while (comp(*++first, pivot))
;
while (!comp(*--last, pivot))
;
}
// Put the pivot in the right place.
Iter pivot_pos = first - 1;
*begin = boost::move(*pivot_pos);
*pivot_pos = boost::move(pivot);
return pdqsort_detail::pair<Iter, bool>(pivot_pos, already_partitioned);
}
// Similar function to the one above, except elements equal to the pivot are put
// to the left of the pivot and it doesn't check or return if the passed
// sequence already was partitioned. Since this is rarely used (the many equal
// case), and in that case pdqsort already has O(n) performance, no block
// quicksort is applied here for simplicity.
template <class Iter, class Compare>
inline Iter partition_left(Iter begin, Iter end, Compare comp) {
typedef typename boost::movelib::iterator_traits<Iter>::value_type T;
T pivot(boost::move(*begin));
Iter first = begin;
Iter last = end;
while (comp(pivot, *--last))
;
if (last + 1 == end)
while (first < last && !comp(pivot, *++first))
;
else
while (!comp(pivot, *++first))
;
while (first < last) {
boost::adl_move_iter_swap(first, last);
while (comp(pivot, *--last))
;
while (!comp(pivot, *++first))
;
}
Iter pivot_pos = last;
*begin = boost::move(*pivot_pos);
*pivot_pos = boost::move(pivot);
return pivot_pos;
}
template <class Iter, class Compare>
void pdqsort_loop(
Iter begin, Iter end, Compare comp,
typename boost::movelib::iterator_traits<Iter>::size_type bad_allowed,
bool leftmost = true) {
typedef typename boost::movelib::iterator_traits<Iter>::size_type size_type;
// Use a while loop for tail recursion elimination.
while (true) {
size_type size = size_type(end - begin);
// Insertion sort is faster for small arrays.
if (size < insertion_sort_threshold) {
insertion_sort(begin, end, comp);
return;
}
// Choose pivot as median of 3 or pseudomedian of 9.
size_type s2 = size / 2;
if (size > ninther_threshold) {
sort3(begin, begin + s2, end - 1, comp);
sort3(begin + 1, begin + (s2 - 1), end - 2, comp);
sort3(begin + 2, begin + (s2 + 1), end - 3, comp);
sort3(begin + (s2 - 1), begin + s2, begin + (s2 + 1), comp);
boost::adl_move_iter_swap(begin, begin + s2);
} else
sort3(begin + s2, begin, end - 1, comp);
// If *(begin - 1) is the end of the right partition of a previous partition
// operation there is no element in [begin, end) that is smaller than
// *(begin - 1). Then if our pivot compares equal to *(begin - 1) we change
// strategy, putting equal elements in the left partition, greater elements
// in the right partition. We do not have to recurse on the left partition,
// since it's sorted (all equal).
if (!leftmost && !comp(*(begin - 1), *begin)) {
begin = partition_left(begin, end, comp) + 1;
continue;
}
// Partition and get results.
pdqsort_detail::pair<Iter, bool> part_result =
partition_right(begin, end, comp);
Iter pivot_pos = part_result.first;
bool already_partitioned = part_result.second;
// Check for a highly unbalanced partition.
size_type l_size = size_type(pivot_pos - begin);
size_type r_size = size_type(end - (pivot_pos + 1));
bool highly_unbalanced = l_size < size / 8 || r_size < size / 8;
// If we got a highly unbalanced partition we shuffle elements to break many
// patterns.
if (highly_unbalanced) {
// If we had too many bad partitions, switch to heapsort to guarantee O(n
// log n).
if (--bad_allowed == 0) {
boost::movelib::heap_sort(begin, end, comp);
return;
}
if (l_size >= insertion_sort_threshold) {
boost::adl_move_iter_swap(begin, begin + l_size / 4);
boost::adl_move_iter_swap(pivot_pos - 1, pivot_pos - l_size / 4);
if (l_size > ninther_threshold) {
boost::adl_move_iter_swap(begin + 1, begin + (l_size / 4 + 1));
boost::adl_move_iter_swap(begin + 2, begin + (l_size / 4 + 2));
boost::adl_move_iter_swap(pivot_pos - 2,
pivot_pos - (l_size / 4 + 1));
boost::adl_move_iter_swap(pivot_pos - 3,
pivot_pos - (l_size / 4 + 2));
}
}
if (r_size >= insertion_sort_threshold) {
boost::adl_move_iter_swap(pivot_pos + 1, pivot_pos + (1 + r_size / 4));
boost::adl_move_iter_swap(end - 1, end - r_size / 4);
if (r_size > ninther_threshold) {
boost::adl_move_iter_swap(pivot_pos + 2,
pivot_pos + (2 + r_size / 4));
boost::adl_move_iter_swap(pivot_pos + 3,
pivot_pos + (3 + r_size / 4));
boost::adl_move_iter_swap(end - 2, end - (1 + r_size / 4));
boost::adl_move_iter_swap(end - 3, end - (2 + r_size / 4));
}
}
} else {
// If we were decently balanced and we tried to sort an already
// partitioned sequence try to use insertion sort.
if (already_partitioned &&
partial_insertion_sort(begin, pivot_pos, comp) &&
partial_insertion_sort(pivot_pos + 1, end, comp))
return;
}
// Sort the left partition first using recursion and do tail recursion
// elimination for the right-hand partition.
pdqsort_loop<Iter, Compare>(begin, pivot_pos, comp, bad_allowed, leftmost);
begin = pivot_pos + 1;
leftmost = false;
}
}
} // namespace pdqsort_detail
template <class Iter, class Compare>
void pdqsort(Iter begin, Iter end, Compare comp) {
if (begin == end)
return;
typedef typename boost::movelib::iterator_traits<Iter>::size_type size_type;
pdqsort_detail::pdqsort_loop<Iter, Compare>(
begin, end, comp, pdqsort_detail::log2(size_type(end - begin)));
}
} // namespace movelib
} // namespace boost
#include <boost/move/detail/config_end.hpp>
#endif // BOOST_MOVE_ALGO_PDQSORT_HPP
| 34.416894 | 80 | 0.656243 | henrywarhurst |
6067424429414088effc449a9c689b47ae88ea88 | 9,998 | cc | C++ | src/mips64/debug-mips64.cc | arv/v8 | 79eb72c648fa215c0eac5917df63315d7f890ebc | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | 20 | 2015-08-26T06:46:00.000Z | 2019-02-27T09:05:58.000Z | src/mips64/debug-mips64.cc | HBOCodeLabs/v8 | 79eb72c648fa215c0eac5917df63315d7f890ebc | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null | src/mips64/debug-mips64.cc | HBOCodeLabs/v8 | 79eb72c648fa215c0eac5917df63315d7f890ebc | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | 2 | 2015-08-26T05:49:35.000Z | 2020-02-03T20:22:43.000Z | // Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/v8.h"
#if V8_TARGET_ARCH_MIPS64
#include "src/codegen.h"
#include "src/debug.h"
namespace v8 {
namespace internal {
void BreakLocation::SetDebugBreakAtReturn() {
// Mips return sequence:
// mov sp, fp
// lw fp, sp(0)
// lw ra, sp(4)
// addiu sp, sp, 8
// addiu sp, sp, N
// jr ra
// nop (in branch delay slot)
// Make sure this constant matches the number if instructions we emit.
DCHECK(Assembler::kJSReturnSequenceInstructions == 7);
CodePatcher patcher(pc(), Assembler::kJSReturnSequenceInstructions);
// li and Call pseudo-instructions emit 6 + 2 instructions.
patcher.masm()->li(v8::internal::t9, Operand(reinterpret_cast<int64_t>(
debug_info_->GetIsolate()->builtins()->Return_DebugBreak()->entry())),
ADDRESS_LOAD);
patcher.masm()->Call(v8::internal::t9);
// Place nop to match return sequence size.
patcher.masm()->nop();
// TODO(mips): Open issue about using breakpoint instruction instead of nops.
// patcher.masm()->bkpt(0);
}
void BreakLocation::SetDebugBreakAtSlot() {
DCHECK(IsDebugBreakSlot());
// Patch the code changing the debug break slot code from:
// nop(DEBUG_BREAK_NOP) - nop(1) is sll(zero_reg, zero_reg, 1)
// nop(DEBUG_BREAK_NOP)
// nop(DEBUG_BREAK_NOP)
// nop(DEBUG_BREAK_NOP)
// nop(DEBUG_BREAK_NOP)
// nop(DEBUG_BREAK_NOP)
// to a call to the debug break slot code.
// li t9, address (4-instruction sequence on mips64)
// call t9 (jalr t9 / nop instruction pair)
CodePatcher patcher(pc(), Assembler::kDebugBreakSlotInstructions);
patcher.masm()->li(v8::internal::t9,
Operand(reinterpret_cast<int64_t>(
debug_info_->GetIsolate()->builtins()->Slot_DebugBreak()->entry())),
ADDRESS_LOAD);
patcher.masm()->Call(v8::internal::t9);
}
#define __ ACCESS_MASM(masm)
static void Generate_DebugBreakCallHelper(MacroAssembler* masm,
RegList object_regs,
RegList non_object_regs) {
{
FrameScope scope(masm, StackFrame::INTERNAL);
// Load padding words on stack.
__ li(at, Operand(Smi::FromInt(LiveEdit::kFramePaddingValue)));
__ Dsubu(sp, sp,
Operand(kPointerSize * LiveEdit::kFramePaddingInitialSize));
for (int i = LiveEdit::kFramePaddingInitialSize - 1; i >= 0; i--) {
__ sd(at, MemOperand(sp, kPointerSize * i));
}
__ li(at, Operand(Smi::FromInt(LiveEdit::kFramePaddingInitialSize)));
__ push(at);
// TODO(plind): This needs to be revised to store pairs of smi's per
// the other 64-bit arch's.
// Store the registers containing live values on the expression stack to
// make sure that these are correctly updated during GC. Non object values
// are stored as a smi causing it to be untouched by GC.
DCHECK((object_regs & ~kJSCallerSaved) == 0);
DCHECK((non_object_regs & ~kJSCallerSaved) == 0);
DCHECK((object_regs & non_object_regs) == 0);
for (int i = 0; i < kNumJSCallerSaved; i++) {
int r = JSCallerSavedCode(i);
Register reg = { r };
if ((object_regs & (1 << r)) != 0) {
__ push(reg);
}
if ((non_object_regs & (1 << r)) != 0) {
__ PushRegisterAsTwoSmis(reg);
}
}
#ifdef DEBUG
__ RecordComment("// Calling from debug break to runtime - come in - over");
#endif
__ PrepareCEntryArgs(0); // No arguments.
__ PrepareCEntryFunction(ExternalReference::debug_break(masm->isolate()));
CEntryStub ceb(masm->isolate(), 1);
__ CallStub(&ceb);
// Restore the register values from the expression stack.
for (int i = kNumJSCallerSaved - 1; i >= 0; i--) {
int r = JSCallerSavedCode(i);
Register reg = { r };
if ((non_object_regs & (1 << r)) != 0) {
__ PopRegisterAsTwoSmis(reg, at);
}
if ((object_regs & (1 << r)) != 0) {
__ pop(reg);
}
if (FLAG_debug_code &&
(((object_regs |non_object_regs) & (1 << r)) == 0)) {
__ li(reg, kDebugZapValue);
}
}
// Don't bother removing padding bytes pushed on the stack
// as the frame is going to be restored right away.
// Leave the internal frame.
}
// Now that the break point has been handled, resume normal execution by
// jumping to the target address intended by the caller and that was
// overwritten by the address of DebugBreakXXX.
ExternalReference after_break_target =
ExternalReference::debug_after_break_target_address(masm->isolate());
__ li(t9, Operand(after_break_target));
__ ld(t9, MemOperand(t9));
__ Jump(t9);
}
void DebugCodegen::GenerateCallICStubDebugBreak(MacroAssembler* masm) {
// Register state for CallICStub
// ----------- S t a t e -------------
// -- a1 : function
// -- a3 : slot in feedback array (smi)
// -----------------------------------
Generate_DebugBreakCallHelper(masm, a1.bit() | a3.bit(), 0);
}
void DebugCodegen::GenerateLoadICDebugBreak(MacroAssembler* masm) {
Register receiver = LoadDescriptor::ReceiverRegister();
Register name = LoadDescriptor::NameRegister();
Register slot = LoadDescriptor::SlotRegister();
RegList regs = receiver.bit() | name.bit() | slot.bit();
Generate_DebugBreakCallHelper(masm, regs, 0);
}
void DebugCodegen::GenerateStoreICDebugBreak(MacroAssembler* masm) {
Register receiver = StoreDescriptor::ReceiverRegister();
Register name = StoreDescriptor::NameRegister();
Register value = StoreDescriptor::ValueRegister();
Generate_DebugBreakCallHelper(
masm, receiver.bit() | name.bit() | value.bit(), 0);
}
void DebugCodegen::GenerateKeyedLoadICDebugBreak(MacroAssembler* masm) {
// Calling convention for keyed IC load (from ic-mips64.cc).
GenerateLoadICDebugBreak(masm);
}
void DebugCodegen::GenerateKeyedStoreICDebugBreak(MacroAssembler* masm) {
// Calling convention for IC keyed store call (from ic-mips64.cc).
Register receiver = StoreDescriptor::ReceiverRegister();
Register name = StoreDescriptor::NameRegister();
Register value = StoreDescriptor::ValueRegister();
Generate_DebugBreakCallHelper(
masm, receiver.bit() | name.bit() | value.bit(), 0);
}
void DebugCodegen::GenerateCompareNilICDebugBreak(MacroAssembler* masm) {
// Register state for CompareNil IC
// ----------- S t a t e -------------
// -- a0 : value
// -----------------------------------
Generate_DebugBreakCallHelper(masm, a0.bit(), 0);
}
void DebugCodegen::GenerateReturnDebugBreak(MacroAssembler* masm) {
// In places other than IC call sites it is expected that v0 is TOS which
// is an object - this is not generally the case so this should be used with
// care.
Generate_DebugBreakCallHelper(masm, v0.bit(), 0);
}
void DebugCodegen::GenerateCallFunctionStubDebugBreak(MacroAssembler* masm) {
// Register state for CallFunctionStub (from code-stubs-mips.cc).
// ----------- S t a t e -------------
// -- a1 : function
// -----------------------------------
Generate_DebugBreakCallHelper(masm, a1.bit(), 0);
}
void DebugCodegen::GenerateCallConstructStubDebugBreak(MacroAssembler* masm) {
// Calling convention for CallConstructStub (from code-stubs-mips.cc).
// ----------- S t a t e -------------
// -- a0 : number of arguments (not smi)
// -- a1 : constructor function
// -----------------------------------
Generate_DebugBreakCallHelper(masm, a1.bit() , a0.bit());
}
void DebugCodegen::GenerateCallConstructStubRecordDebugBreak(
MacroAssembler* masm) {
// Calling convention for CallConstructStub (from code-stubs-mips.cc).
// ----------- S t a t e -------------
// -- a0 : number of arguments (not smi)
// -- a1 : constructor function
// -- a2 : feedback array
// -- a3 : feedback slot (smi)
// -----------------------------------
Generate_DebugBreakCallHelper(masm, a1.bit() | a2.bit() | a3.bit(), a0.bit());
}
void DebugCodegen::GenerateSlot(MacroAssembler* masm) {
// Generate enough nop's to make space for a call instruction. Avoid emitting
// the trampoline pool in the debug break slot code.
Assembler::BlockTrampolinePoolScope block_trampoline_pool(masm);
Label check_codesize;
__ bind(&check_codesize);
__ RecordDebugBreakSlot();
for (int i = 0; i < Assembler::kDebugBreakSlotInstructions; i++) {
__ nop(MacroAssembler::DEBUG_BREAK_NOP);
}
DCHECK_EQ(Assembler::kDebugBreakSlotInstructions,
masm->InstructionsGeneratedSince(&check_codesize));
}
void DebugCodegen::GenerateSlotDebugBreak(MacroAssembler* masm) {
// In the places where a debug break slot is inserted no registers can contain
// object pointers.
Generate_DebugBreakCallHelper(masm, 0, 0);
}
void DebugCodegen::GeneratePlainReturnLiveEdit(MacroAssembler* masm) {
__ Ret();
}
void DebugCodegen::GenerateFrameDropperLiveEdit(MacroAssembler* masm) {
ExternalReference restarter_frame_function_slot =
ExternalReference::debug_restarter_frame_function_pointer_address(
masm->isolate());
__ li(at, Operand(restarter_frame_function_slot));
__ sw(zero_reg, MemOperand(at, 0));
// We do not know our frame height, but set sp based on fp.
__ Dsubu(sp, fp, Operand(kPointerSize));
__ Pop(ra, fp, a1); // Return address, Frame, Function.
// Load context from the function.
__ ld(cp, FieldMemOperand(a1, JSFunction::kContextOffset));
// Get function code.
__ ld(at, FieldMemOperand(a1, JSFunction::kSharedFunctionInfoOffset));
__ ld(at, FieldMemOperand(at, SharedFunctionInfo::kCodeOffset));
__ Daddu(t9, at, Operand(Code::kHeaderSize - kHeapObjectTag));
// Re-run JSFunction, a1 is function, cp is context.
__ Jump(t9);
}
const bool LiveEdit::kFrameDropperSupported = true;
#undef __
} } // namespace v8::internal
#endif // V8_TARGET_ARCH_MIPS64
| 33.438127 | 80 | 0.663133 | arv |
606cfbf5d512d352beedacd65728b048862463f2 | 2,219 | cpp | C++ | meeting-qt/meeting-app/meeting_app.cpp | GrowthEase/- | 5cc7cab95fc309049de8023ff618219dff22d773 | [
"MIT"
] | 48 | 2022-03-02T07:15:08.000Z | 2022-03-31T08:37:33.000Z | meeting-qt/meeting-app/meeting_app.cpp | chandarlee/Meeting | 9350fdea97eb2cdda28b8bffd9c4199de15460d9 | [
"MIT"
] | 1 | 2022-02-16T01:54:05.000Z | 2022-02-16T01:54:05.000Z | meeting-qt/meeting-app/meeting_app.cpp | chandarlee/Meeting | 9350fdea97eb2cdda28b8bffd9c4199de15460d9 | [
"MIT"
] | 9 | 2022-03-01T13:41:37.000Z | 2022-03-10T06:05:23.000Z | /**
* @copyright Copyright (c) 2021 NetEase, Inc. All rights reserved.
* Use of this source code is governed by a MIT license that can be found in the LICENSE file.
*/
#include "meeting_app.h"
#include <QUrl>
#include <QUrlQuery>
#include "nemeeting_sdk_manager.h"
MeetingApp::MeetingApp(int& argc, char** argv)
: QApplication(argc, argv) {}
void MeetingApp::setBugList(const char* argv) {
QString strPath = QFileInfo(argv).absolutePath().append("/config/custom.json");
if (!QFile::exists(strPath)) {
qWarning() << "custom strPath is null.";
} else {
bool bRet = qputenv("QT_OPENGL_BUGLIST", strPath.toUtf8());
if (!bRet) {
qWarning() << "set setBugList failed.";
}
}
#if 0
bool bRet = qputenv("QT_LOGGING_RULES", "qt.qpa.gl = true");
if (!bRet) {
qWarning() << "set qt.qpa.gl failed.";
}
#endif
}
bool MeetingApp::notify(QObject* watched, QEvent* event) {
if (watched == this && event->type() == QEvent::ApplicationStateChange) {
auto ev = static_cast<QApplicationStateChangeEvent*>(event);
YXLOG(Info) << "Application state changed: " << ev->applicationState() << YXLOGEnd;
if (_prevAppState == Qt::ApplicationActive && ev->applicationState() == Qt::ApplicationActive) {
emit dockClicked();
}
_prevAppState = ev->applicationState();
}
// This event only happended on macOS
if (watched == this && event->type() == QEvent::FileOpen) {
QFileOpenEvent* fileEvent = static_cast<QFileOpenEvent*>(event);
if (!fileEvent->url().isEmpty()) {
YXLOG(Info) << "Received custom scheme url request: " << fileEvent->url().toString().toStdString() << YXLOGEnd;
QUrl url(fileEvent->url().toString());
QUrlQuery urlQuery(url.query());
emit loginWithSSO(urlQuery.queryItemValue(kSSOAppKey) , urlQuery.queryItemValue(kSSOToken));
}
else if (!fileEvent->file().isEmpty())
{
YXLOG(Info) << "Received custom scheme file request: " << fileEvent->file().toStdString() << YXLOGEnd;
}
return false;
}
return QApplication::notify(watched, event);
}
| 36.983333 | 123 | 0.618297 | GrowthEase |
606dfc2cc247e232be3f548da59c54583d7a89bc | 4,267 | hpp | C++ | samples/deeplearning/gxm/include/Accuracy.hpp | mjanderson09/libxsmm | d8359effcbe456e1e7625c0b9b0cf5533ee0e370 | [
"BSD-3-Clause"
] | 1 | 2018-06-29T03:07:54.000Z | 2018-06-29T03:07:54.000Z | samples/deeplearning/gxm/include/Accuracy.hpp | qq332982511/libxsmm | e376c569252c042193ad2215857c35cfb598ec45 | [
"BSD-3-Clause"
] | 4 | 2018-03-19T18:18:22.000Z | 2018-07-05T05:09:09.000Z | samples/deeplearning/gxm/include/Accuracy.hpp | qq332982511/libxsmm | e376c569252c042193ad2215857c35cfb598ec45 | [
"BSD-3-Clause"
] | 5 | 2017-06-28T21:48:18.000Z | 2018-04-10T04:07:38.000Z | /******************************************************************************
** Copyright (c) 2017-2018, Intel Corporation **
** All rights reserved. **
** **
** Redistribution and use in source and binary forms, with or without **
** modification, are permitted provided that the following conditions **
** are met: **
** 1. Redistributions of source code must retain the above copyright **
** notice, this list of conditions and the following disclaimer. **
** 2. Redistributions in binary form must reproduce the above copyright **
** notice, this list of conditions and the following disclaimer in the **
** documentation and/or other materials provided with the distribution. **
** 3. Neither the name of the copyright holder nor the names of its **
** contributors may be used to endorse or promote products derived **
** from this software without specific prior written permission. **
** **
** THIS SOFTWARE IS PROVIDED BY THE 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. **
******************************************************************************/
/* Sasikanth Avancha, Dhiraj Kalamkar (Intel Corp.)
******************************************************************************/
#pragma once
#include <string>
#include "Node.hpp"
#include "Engine.hpp"
#include "Params.hpp"
#include "Tensor.hpp"
#include "proto/gxm.pb.h"
using namespace std;
using namespace gxm;
class AccuracyParams : public NNParams
{
public:
AccuracyParams(void) {}
virtual ~AccuracyParams(void) {}
void set_axis(int axis) { axis_ = axis; }
int get_axis() { return axis_; }
void set_top_k(int top_k) { top_k_ = top_k; }
int get_top_k() { return top_k_; }
protected:
int axis_, top_k_;
};
static MLParams* parseAccuracyParams(NodeParameter* np)
{
AccuracyParams *p = new AccuracyParams();
AccuracyParameter ap = np->accuracy_param();
// Set name of node
assert(!np->name().empty());
p->set_node_name(np->name());
//Set node type (Convolution, FullyConnected, etc)
assert(!np->type().empty());
p->set_node_type(np->type());
//Set tensor names
//Set tensor names
for(int i=0; i<np->bottom_size(); i++)
{
assert(!np->bottom(i).empty());
p->set_bottom_names(np->bottom(i));
}
//Set Mode for the node
assert((np->mode() == TRAIN) || (np->mode() == TEST));
p->set_mode(np->mode());
int axis = ap.axis();
p->set_axis(axis);
int top_k = ap.top_k();
p->set_top_k(top_k);
return p;
}
class AccuracyNode : public NNNode
{
public:
AccuracyNode(AccuracyParams* p, MLEngine* e);
virtual ~AccuracyNode(void) {}
protected:
void forwardPropagate();
vector<Tensor*> tenBot_;
vector<TensorBuf*> tenBotData_;
string node_name_, node_type_;
Shape ts_;
int top_k_, train_batch_count_, test_batch_count_;
double avg_train_acc_, avg_test_acc_;
MLEngine *eptr_;
#if 1
vector<float> max_val;
vector<int> max_id;
vector<std::pair<float, int> > bot_data_vec;
#endif
void shape_setzero(Shape* s)
{
for(int i=0; i<MAX_DIMS; i++)
s->dims[i] = 0;
}
};
| 34.691057 | 79 | 0.581673 | mjanderson09 |
606f9e19312fd2dd1be16d7527250852c016d8ff | 614 | cpp | C++ | code/tests/rlbox_glue/test_dylib_sandbox_glue.cpp | arkivm/rlbox_sandboxing_api | ad4513b1d88a17680bab8c2cac5783c1b616f686 | [
"MIT"
] | 207 | 2019-08-09T19:41:38.000Z | 2022-03-08T09:19:27.000Z | code/tests/rlbox_glue/test_dylib_sandbox_glue.cpp | arkivm/rlbox_sandboxing_api | ad4513b1d88a17680bab8c2cac5783c1b616f686 | [
"MIT"
] | 37 | 2019-08-09T03:21:17.000Z | 2022-03-07T22:16:14.000Z | code/tests/rlbox_glue/test_dylib_sandbox_glue.cpp | arkivm/rlbox_sandboxing_api | ad4513b1d88a17680bab8c2cac5783c1b616f686 | [
"MIT"
] | 15 | 2020-02-26T10:56:31.000Z | 2022-03-18T03:06:45.000Z | // NOLINTNEXTLINE
#define RLBOX_USE_EXCEPTIONS
#define RLBOX_ENABLE_DEBUG_ASSERTIONS
#define RLBOX_SINGLE_THREADED_INVOCATIONS
#include "rlbox_dylib_sandbox.hpp"
// NOLINTNEXTLINE
#define TestName "rlbox_dylib_sandbox"
// NOLINTNEXTLINE
#define TestType rlbox::rlbox_dylib_sandbox
#ifndef GLUE_LIB_PATH
# error "Missing definition for GLUE_LIB_PATH"
#endif
#if defined(_WIN32)
// NOLINTNEXTLINE
# define CreateSandbox(sandbox) sandbox.create_sandbox(L"" GLUE_LIB_PATH)
#else
// NOLINTNEXTLINE
# define CreateSandbox(sandbox) sandbox.create_sandbox(GLUE_LIB_PATH)
#endif
#include "test_sandbox_glue.inc.cpp"
| 24.56 | 74 | 0.825733 | arkivm |
607326b0aa6631d3f0987d47713b778501cb2b04 | 24,565 | cpp | C++ | Beeftext/Group/GroupList.cpp | xmidev/Beeftext | 17dfcc74bf51c20186c35d34a3c2c39175d4fadd | [
"MIT"
] | null | null | null | Beeftext/Group/GroupList.cpp | xmidev/Beeftext | 17dfcc74bf51c20186c35d34a3c2c39175d4fadd | [
"MIT"
] | null | null | null | Beeftext/Group/GroupList.cpp | xmidev/Beeftext | 17dfcc74bf51c20186c35d34a3c2c39175d4fadd | [
"MIT"
] | null | null | null | /// \file
/// \author Xavier Michelon
///
/// \brief Implementation of combo group list class
///
/// Copyright (c) Xavier Michelon. All rights reserved.
/// Licensed under the MIT License. See LICENSE file in the project root for full license information.
#include "stdafx.h"
#include "GroupList.h"
#include "Combo/ComboManager.h"
#include "MimeDataUtils.h"
#include "BeeftextGlobals.h"
#include <XMiLib/Exception.h>
namespace {
QString defaultGroupName() { return QObject::tr("Default Group"); } ///< The default group name
QString defaultGroupDescription() { return QObject::tr("The default group."); } ///< The default group description
}
//**********************************************************************************************************************
/// \param[in] first The first group
/// \param[in] second The second group
//**********************************************************************************************************************
void swap(GroupList& first, GroupList& second) noexcept
{
first.groups_.swap(second.groups_);
std::swap(first.dropType_, second.dropType_);
}
//**********************************************************************************************************************
/// \param[in] parent The parent object of the instance
//**********************************************************************************************************************
GroupList::GroupList(QObject* parent)
: QAbstractListModel(parent)
, dropType_(GroupDrop)
{
}
//**********************************************************************************************************************
/// \param[in] ref The reference group to copy
//**********************************************************************************************************************
GroupList::GroupList(GroupList const& ref)
: QAbstractListModel(ref.parent())
, groups_(ref.groups_)
, dropType_(ref.dropType_)
{
}
//**********************************************************************************************************************
/// \param[in] ref The reference group to copy
//**********************************************************************************************************************
GroupList::GroupList(GroupList&& ref) noexcept
: QAbstractListModel(ref.parent())
, groups_(std::move(ref.groups_))
, dropType_(ref.dropType_)
{
}
//**********************************************************************************************************************
/// \param[in] ref The reference group to copy
/// \return A reference to the instance
//**********************************************************************************************************************
GroupList& GroupList::operator=(GroupList const& ref)
{
if (&ref != this)
{
groups_ = ref.groups_;
dropType_ = ref.dropType_;
}
return *this;
}
//**********************************************************************************************************************
/// \param[in] ref The reference group to copy
/// \return A reference to the instance
//**********************************************************************************************************************
GroupList& GroupList::operator=(GroupList&& ref) noexcept
{
if (&ref != this)
{
groups_ = std::move(ref.groups_);
dropType_ = ref.dropType_;
}
return *this;
}
//**********************************************************************************************************************
/// \param[in] index The index of the group
/// \return The group a the specified index
//**********************************************************************************************************************
SpGroup& GroupList::operator[](qint32 index)
{
return groups_[static_cast<quint32>(index)];
}
//**********************************************************************************************************************
/// \param[in] index The index of the group
/// \return The group a the specified index
//**********************************************************************************************************************
SpGroup const& GroupList::operator[](qint32 index) const
{
return groups_[static_cast<quint32>(index)];
}
//**********************************************************************************************************************
/// \return The number of groups in the list
//**********************************************************************************************************************
qint32 GroupList::size() const
{
return static_cast<qint32>(groups_.size());
}
//**********************************************************************************************************************
/// \return true if and only if the list is empty
//**********************************************************************************************************************
bool GroupList::isEmpty() const
{
return groups_.empty();
}
//**********************************************************************************************************************
//
//**********************************************************************************************************************
void GroupList::clear()
{
groups_.clear();
}
//**********************************************************************************************************************
/// return true if and only if a group with this UUID is already in the list
//**********************************************************************************************************************
bool GroupList::contains(SpGroup const& group) const
{
return group ? this->end() != this->findByUuid(group->uuid()) : false;
}
//**********************************************************************************************************************
/// \return true if the group is valid and not already in the list
//**********************************************************************************************************************
bool GroupList::canGroupBeAdded(SpGroup const& group) const
{
return group && group->isValid() && !this->contains(group);
}
//**********************************************************************************************************************
/// \param[in] group The group to add
/// \return true if the group has been successfully added
//**********************************************************************************************************************
bool GroupList::append(SpGroup const& group)
{
if (!canGroupBeAdded(group))
{
globals::debugLog().addError("Cannot add group (null or duplicate).");
return false;
}
this->beginInsertRows(QModelIndex(), static_cast<qint32>(groups_.size()) + 1,
static_cast<qint32>(groups_.size()) + 1);
groups_.push_back(group);
this->endInsertRows();
return true;
}
//**********************************************************************************************************************
/// \param[in] group The group to add
//**********************************************************************************************************************
// ReSharper disable once CppInconsistentNaming
void GroupList::push_back(SpGroup const& group)
{
this->beginInsertRows(QModelIndex(), static_cast<qint32>(groups_.size()) + 1,
static_cast<qint32>(groups_.size()) + 1);
groups_.push_back(group);
this->endInsertRows();
}
//**********************************************************************************************************************
/// \param[in] index the index of the group to erase
//**********************************************************************************************************************
void GroupList::erase(qint32 index)
{
this->beginRemoveRows(QModelIndex(), index + 1, index + 1);
groups_.erase(groups_.begin() + index);
this->endRemoveRows();
}
//**********************************************************************************************************************
/// \param[in] uuid The UUID of the combo to find
/// \return An iterator to the found group or end() if not found
//**********************************************************************************************************************
GroupList::iterator GroupList::findByUuid(QUuid const& uuid)
{
return std::find_if(this->begin(), this->end(), [&](SpGroup const& group) -> bool
{ return group && uuid == group->uuid(); });
}
//**********************************************************************************************************************
/// \param[in] uuid The UUID of the combo to find
/// \return A constant iterator to the found group or end() if not found
//**********************************************************************************************************************
GroupList::const_iterator GroupList::findByUuid(QUuid const& uuid) const
{
return std::find_if(this->begin(), this->end(), [&](SpGroup const& group) -> bool
{ return group && uuid == group->uuid(); });
}
//**********************************************************************************************************************
/// \return An iterator to the beginning of the list
//**********************************************************************************************************************
GroupList::iterator GroupList::begin()
{
return groups_.begin();
}
//**********************************************************************************************************************
/// \return A constant iterator to the beginning of the list
//**********************************************************************************************************************
GroupList::const_iterator GroupList::begin() const
{
return groups_.begin();
}
//**********************************************************************************************************************
/// \return An iterator to the end of the list
//**********************************************************************************************************************
GroupList::iterator GroupList::end()
{
return groups_.end();
}
//**********************************************************************************************************************
/// \return A constant iterator to the end of the list
//**********************************************************************************************************************
GroupList::const_iterator GroupList::end() const
{
return groups_.end();
}
//**********************************************************************************************************************
/// \return An iterator to the reverse beginning of the list
//**********************************************************************************************************************
GroupList::reverse_iterator GroupList::rbegin()
{
return groups_.rbegin();
}
//**********************************************************************************************************************
/// \return A constant iterator to the reverse beginning of the list
//**********************************************************************************************************************
GroupList::const_reverse_iterator GroupList::rbegin() const
{
return groups_.rbegin();
}
//**********************************************************************************************************************
/// \return An iterator to the reverse end of the list
//**********************************************************************************************************************
GroupList::reverse_iterator GroupList::rend()
{
return groups_.rend();
}
//**********************************************************************************************************************
/// \return A constant iterator to the reverse end of the list
//**********************************************************************************************************************
GroupList::const_reverse_iterator GroupList::rend() const
{
return groups_.rend();
}
//**********************************************************************************************************************
/// \return A JSON array containing the combo list
//**********************************************************************************************************************
QJsonArray GroupList::toJsonArray() const
{
QJsonArray result;
for (SpGroup const& group: groups_)
result.append(group->toJsonObject());
return result;
}
//**********************************************************************************************************************
/// \param[in] array The JSON array to parse
/// \param[in] formatVersion The JSON file format version
/// \param[out] outErrorMessage if not null and the function returns false, this variable hold a description of the
/// error on exit
/// \return true if and only if the array was parsed successfully
//**********************************************************************************************************************
bool GroupList::readFromJsonArray(QJsonArray const& array, qint32 formatVersion, QString* outErrorMessage)
{
try
{
this->clear();
for (QJsonValue const& value : array)
{
if (!value.isObject())
throw xmilib::Exception("The group list is invalid.");
SpGroup const group = Group::create(value.toObject(), formatVersion);
if ((!group) || (!group->isValid()))
throw xmilib::Exception("The group list contains an invalid group.");
if (!this->append(group))
throw xmilib::Exception("Could not append one of the groups to the group list.");
}
return true;
}
catch (xmilib::Exception const& e)
{
if (outErrorMessage)
*outErrorMessage = e.qwhat();
return false;
}
}
//**********************************************************************************************************************
/// \return true if the group list was empty and had to be filled with a default group
//**********************************************************************************************************************
bool GroupList::ensureNotEmpty()
{
bool const empty = groups_.empty();
if (empty)
groups_.push_back(Group::create(defaultGroupName(), defaultGroupDescription()));
return empty;
}
//**********************************************************************************************************************
/// \param[in] title The title of the menu
/// \param[in] disabledGroups The list of groups that should be disabled
/// \param[in] parent The parent widget of the menu
/// \return A menu containing the list of groups
//**********************************************************************************************************************
QMenu* GroupList::createMenu(QString const& title, std::set<SpGroup> const& disabledGroups, QWidget* parent)
{
QMenu* menu = new QMenu(title, parent);
this->fillMenu(menu, disabledGroups);
return menu;
}
//**********************************************************************************************************************
/// \param[in] menu The menu
/// \param[in] disabledGroups The list of groups that should be disabled
//**********************************************************************************************************************
void GroupList::fillMenu(QMenu* menu, std::set<SpGroup> const& disabledGroups)
{
menu->clear();
for (SpGroup const& group : groups_)
{
if (!group)
continue;
QAction* action = new QAction(group->name(), menu);
action->setData(QVariant::fromValue(group));
action->setEnabled(!disabledGroups.count(group));
menu->addAction(action);
}
}
//**********************************************************************************************************************
/// The drop type is a bit of a hack. The flags() model function determines if an item should accept a drop,
/// but it should return a different value depending on what is dragged (combo or group)
//**********************************************************************************************************************
void GroupList::setDropType(EDropType dropType)
{
dropType_ = dropType;
}
//**********************************************************************************************************************
/// \param[in] uuids The list of UUID of the dropped combos
/// \param[in] index the index of the group the combos were dropped on
//**********************************************************************************************************************
bool GroupList::processComboListDrop(QList<QUuid> const& uuids, qint32 index)
{
if ((index < 0) || (index >= qint32(groups_.size())) || (!groups_[static_cast<quint32>(index)]) ||uuids.isEmpty())
return false;
SpGroup const& group = groups_[static_cast<quint32>(index)];
ComboList& comboList = ComboManager::instance().comboListRef();
bool changed = false;
for (QUuid const& uuid : uuids)
{
ComboList::iterator const it = comboList.findByUuid(uuid);
if ((it == comboList.end()) || ((*it)->group() == group))
continue;
(*it)->setGroup(group);
changed = true;
}
if (changed)
emit combosChangedGroup();
return changed;
}
//**********************************************************************************************************************
/// \param[in] groupIndex The index of the dropped group in the list
/// \param[in] dropIndex The index at which the group has been drop
//**********************************************************************************************************************
bool GroupList::processGroupDrop(qint32 groupIndex, qint32 dropIndex)
{
qint32 const listSize = static_cast<qint32>(groups_.size());
if ((dropIndex < 0) || (groupIndex < 0) || (groupIndex >= listSize))
return false;
SpGroup const group = groups_[static_cast<quint32>(groupIndex)];
if (!group)
return false;
// phase 1: copy the group to it news location
if ((dropIndex == groupIndex) || (dropIndex == groupIndex + 1)) // no effect
return false;
this->beginInsertRows(QModelIndex(), dropIndex, dropIndex);
groups_.insert(groups_.begin() + dropIndex, group);
this->endInsertRows();
// phase 2: remove the old item
qint32 const removeIndex = groupIndex + ((dropIndex >= 0) && (dropIndex < groupIndex) ? 1 : 0); // the srcIndex may have been shifted by the insertion of the copy
this->beginRemoveRows(QModelIndex(), removeIndex + 1, removeIndex + 1);
groups_.erase(groups_.begin() + removeIndex);
this->endRemoveRows();
this->beginResetModel();
this->endResetModel();
// emit a notification signal
const_iterator const newPosIt = this->findByUuid(group->uuid());
if (newPosIt == this->end())
throw xmilib::Exception("Internal error: %1(): could not located moved group.");
emit groupMoved(group, newPosIt - this->begin());
return true;
}
//**********************************************************************************************************************
//
//**********************************************************************************************************************
int GroupList::rowCount(const QModelIndex &) const
{
return static_cast<qint32>(groups_.size()) + 1;
}
//**********************************************************************************************************************
/// \param[in] index The model index
/// \param[in] role The role
/// \return the model data for the given role at the given index
//**********************************************************************************************************************
QVariant GroupList::data(QModelIndex const& index, int role) const
{
// note entry at index 0 is special entry "<All combos>"
QString allCombosStr = tr("<All combos>");
qint32 const groupCount = static_cast<qint32>(groups_.size());
qint32 const row = index.row();
if ((row < 0) || (row > groupCount))
return QVariant();
switch (role)
{
case Qt::DisplayRole:
{
if (0 == row)
return allCombosStr;
SpGroup const& group = groups_[static_cast<quint32>(row) - 1];
return group ? group->name() : QString();
}
case Qt::ToolTipRole:
{
if (0 == row)
return allCombosStr;
SpGroup const& group = groups_[static_cast<quint32>(row) - 1];
return group ? group->description() : QString();
}
case Qt::FontRole:
{
if (0 != row)
return QVariant();
// we use italic to hight special <All combos> entry
QFont font;
font.setItalic(true);
return font;
}
case Qt::ForegroundRole:
{
if (0 == row)
return QVariant();
SpGroup const& group = groups_[static_cast<quint32>(row) - 1];
return group->enabled() ? QVariant() : globals::disabledTextColor();
}
default: return QVariant();
}
}
//**********************************************************************************************************************
/// \return The supported drop actions
//**********************************************************************************************************************
Qt::DropActions GroupList::supportedDropActions() const
{
return Qt::MoveAction;
}
//**********************************************************************************************************************
/// \param[in] index The index of the item
/// \return The item flags
//**********************************************************************************************************************
Qt::ItemFlags GroupList::flags(QModelIndex const& index) const
{
Qt::ItemFlags const defaultFlags = QAbstractListModel::flags(index);
// The drop behavior is dictated by the validity of the index, an invalid index means the dropping target is
// between two valid items
if (dropType_ == GroupDrop) /// user is dragging a group
{
if (index.isValid()) // group cannot be drop onto other items
return Qt::ItemIsDragEnabled | defaultFlags;
return Qt::ItemIsDropEnabled | defaultFlags; // group can be dropped in between items
}
// user is dragging combos
if (index.isValid() && index.row() > 0) // combos can be dropped onto other items but not on the first ("all combos")
return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | defaultFlags;
return defaultFlags; // combos cannot be dropped between item
}
//**********************************************************************************************************************
/// \return The list of supported MIME type for dropping
//**********************************************************************************************************************
QStringList GroupList::mimeTypes() const
{
return QStringList() << kGroupIndexMimeType << kUuuidListMimeType;
}
//**********************************************************************************************************************
/// \param[in] indexes The indexes
/// \return The MIME data for the given indexes
//**********************************************************************************************************************
QMimeData* GroupList::mimeData(const QModelIndexList &indexes) const
{
return groupIndexToMimeData(indexes.isEmpty() ? -1 : qMax<qint32>(-1, indexes[0].row() - 1)); // row - 1 because entry at index 0 is special entry "<All combos>"
}
//**********************************************************************************************************************
/// \param[in] data The MIME data
/// \param[in] row The row
/// \param[in] parent The parent index
/// \return true if and only if the drop was successfully processed
//**********************************************************************************************************************
bool GroupList::dropMimeData(QMimeData const*data, Qt::DropAction, int row, int,
QModelIndex const& parent)
{
if (!data)
return false;
if (data->hasFormat(kUuuidListMimeType))
return processComboListDrop(mimeDataToUuidList(*data), parent.row() - 1); // row - 1 because entry at index 0 is special entry "<All combos>"
return processGroupDrop(mimeDataToGroupIndex(*data), row - 1); // row - 1 because entry at index 0 is special entry "<All combos>"
}
| 41.285714 | 165 | 0.405699 | xmidev |
6074165c0802ac63a4e66751de461abdd50a1fef | 2,048 | cpp | C++ | Source/src/Main.cpp | Akita-Interactive/Hachiko-Engine | 0e3e0377ac5c8f5b15c525c8fcff384e9c92c14b | [
"MIT"
] | 5 | 2022-02-10T23:31:11.000Z | 2022-02-11T19:32:38.000Z | Source/src/Main.cpp | Akita-Interactive/Hachiko-Engine | 0e3e0377ac5c8f5b15c525c8fcff384e9c92c14b | [
"MIT"
] | null | null | null | Source/src/Main.cpp | Akita-Interactive/Hachiko-Engine | 0e3e0377ac5c8f5b15c525c8fcff384e9c92c14b | [
"MIT"
] | null | null | null | #include "core/hepch.h"
#include "instrumentation/MemoryLeaks.h"
enum class MainStates
{
MAIN_CREATION,
MAIN_START,
MAIN_UPDATE,
MAIN_FINISH,
MAIN_EXIT
};
Hachiko::Application* App = nullptr;
int main(int argc, char** argv)
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
int main_return = EXIT_FAILURE;
auto state = MainStates::MAIN_CREATION;
while (state != MainStates::MAIN_EXIT)
{
switch (state)
{
case MainStates::MAIN_CREATION: HE_LOG("Application Creation --------------");
App = new Hachiko::Application();
state = MainStates::MAIN_START;
break;
case MainStates::MAIN_START: HE_LOG("Application Init --------------");
if (App->Init() == false)
{
HE_LOG("Application Init exits with error -----");
state = MainStates::MAIN_EXIT;
}
else
{
state = MainStates::MAIN_UPDATE;
HE_LOG("Application Update --------------");
}
break;
case MainStates::MAIN_UPDATE:
{
OPTICK_FRAME("MainThread");
const UpdateStatus update_return = App->Update();
if (update_return == UpdateStatus::UPDATE_ERROR)
{
HE_LOG("Application Update exits with error -----");
state = MainStates::MAIN_EXIT;
}
if (update_return == UpdateStatus::UPDATE_STOP)
state = MainStates::MAIN_FINISH;
}
break;
case MainStates::MAIN_FINISH: HE_LOG("Application CleanUp --------------");
if (App->CleanUp() == false)
{
HE_LOG("Application CleanUp exits with error -----");
}
else
main_return = EXIT_SUCCESS;
state = MainStates::MAIN_EXIT;
break;
}
}
delete App;
HE_LOG("Bye :)\n");
return main_return;
}
| 25.6 | 86 | 0.517578 | Akita-Interactive |
6077d375e89864b8b6850e6541af14d71314e618 | 1,833 | cpp | C++ | examples/simpleMultithread.cpp | Klirxel/DataFlowFramework | 5da51e794a4dac613e1fed96d3e8da68af6d7203 | [
"BSL-1.0"
] | null | null | null | examples/simpleMultithread.cpp | Klirxel/DataFlowFramework | 5da51e794a4dac613e1fed96d3e8da68af6d7203 | [
"BSL-1.0"
] | null | null | null | examples/simpleMultithread.cpp | Klirxel/DataFlowFramework | 5da51e794a4dac613e1fed96d3e8da68af6d7203 | [
"BSL-1.0"
] | null | null | null | /*
* Copyright Schwenk, Kurt <Kurt.Schwenk@gmx.de> 2020
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
#include <iostream>
#include <dataflow/dataflow.h>
using namespace dataflow;
//Simple example showing multithread capability.
//
// DataflowGraph:
//
// Worker1
// NumberGenerator ---channel1 --> Worker2 ---channel2--> ConsoleWriter
// Worker3
//
int main()
{
//Definition Channels
ChannelThreadSafe<int> channel1;
ChannelThreadSafe<int> channel2;
//Definiton Executor
const auto threads = 4;
const auto inactivityBeforeDestruction = 200ms;
ExecutorMultithread executor { threads, inactivityBeforeDestruction };
//Definiton NumberGenerator
auto counter = [count = 0]() mutable { return count++; };
GeneratorBlock numberGenerator { counter, ChannelBundle { channel1 } };
//Definition Worker 1/2/3
constexpr auto delay = 300ms;
constexpr auto worker = [delay](int val) { std::this_thread::sleep_for(delay); return val; };
Block worker1 { ChannelBundle { channel1 }, worker, ChannelBundle { channel2 }, executor };
Block worker2 { ChannelBundle { channel1 }, worker, ChannelBundle { channel2 }, executor };
Block worker3 { ChannelBundle { channel1 }, worker, ChannelBundle { channel2 }, executor };
//Definition ConsoleWriter
constexpr auto writer = [](int val) { std::cout << "Output: " << val << '\n'; };
SinkBlock consoleWriter { ChannelBundle { channel2 }, writer, executor };
//Start Generator
const auto period = 100ms;
const auto offset = 0ms;
const auto cycles = 10;
numberGenerator.start(period, offset, cycles);
}
| 33.944444 | 97 | 0.661757 | Klirxel |
607faaf09411c3a1c5bebaa4ad001fef83c4a0ce | 716 | cpp | C++ | CppPrimer/Content/Ch10_GenericAlgorithm/Ch10_03_lambda_05.cpp | ltimaginea/Cpp-Primer | a894d90cee2128a992c589c5c855457a6b5d71de | [
"MIT"
] | 1 | 2022-03-22T08:02:37.000Z | 2022-03-22T08:02:37.000Z | CppPrimer/Content/Ch10_GenericAlgorithm/Ch10_03_lambda_05.cpp | ltimaginea/Cpp-Primer | a894d90cee2128a992c589c5c855457a6b5d71de | [
"MIT"
] | null | null | null | CppPrimer/Content/Ch10_GenericAlgorithm/Ch10_03_lambda_05.cpp | ltimaginea/Cpp-Primer | a894d90cee2128a992c589c5c855457a6b5d71de | [
"MIT"
] | null | null | null | #include <iostream>
#include <future>
#include <thread>
using namespace std;
/*
* C++14还添加了广义捕获的概念,因此可以捕获表达式的结果,而不是对局部变量的直接拷贝或引用。最常见的方法是通过移动只移动的类型来捕获类型,而不是通过引用来捕获。
* 这里,promise通过p=std::move(p)捕获移到Lambda中,因此可以安全地分离线程,从而不用担心对局部变量的悬空引用。构建Lambda之后,p处于转移过来的状态,这就是为什么需要提前获得future的原因。
*/
future<int> spawn_async_task()
{
std::promise<int> p;
auto f = p.get_future();
std::thread t([p = std::move(p)](){ p.set_value(find_the_answer()); });
t.detach();
return f;
}
int main()
{
/*
* C++14后,Lambda表达式可以是真正通用Lamdba了,参数类型被声明为auto而不是指定类型。这种情况下,函数调用运算也是一个模板。当调用Lambda时,参数的类型可从提供的参数中推导出来。
*/
auto f = [](auto x) {cout << x << endl; };
f(233);
f("C++14 lambda");
return 0;
} | 23.096774 | 113 | 0.671788 | ltimaginea |
60839bed0c96cbdc5f8a5b7a994d962bda6f82ee | 13,493 | hpp | C++ | tiny_fs/utilities.hpp | iamOgunyinka/tinydircpp | a147889c418dc6f81f868a56c13fe797dbf58357 | [
"MIT"
] | 12 | 2015-06-29T14:06:08.000Z | 2022-02-21T14:47:46.000Z | tiny_fs/utilities.hpp | iamOgunyinka/tinydircpp | a147889c418dc6f81f868a56c13fe797dbf58357 | [
"MIT"
] | 2 | 2015-05-28T02:37:52.000Z | 2019-01-31T14:20:54.000Z | tiny_fs/utilities.hpp | iamOgunyinka/tinydircpp | a147889c418dc6f81f868a56c13fe797dbf58357 | [
"MIT"
] | 3 | 2017-06-20T05:13:34.000Z | 2020-03-02T00:28:29.000Z | /*
Copyright (c) 2019 - Joshua Ogunyinka
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.
*/
#pragma once
#include <stdexcept>
#include <chrono>
#include <ctime>
#include <system_error>
#include <codecvt>
#include <locale>
#include <type_traits>
#include <cstdlib>
#include <algorithm>
#ifdef _WIN32
#include <Windows.h>
#define SLASH "\\"
#define WSLASH L"\\"
#else
#include <sys/stat.h>
#define SLASH "/"
#define WSLASH L"/"
#endif // _WIN32
#ifdef _MSC_VER
#pragma warning(disable: 4996)
#define TINY_CHAR16_T unsigned short
#define TINY_CHAR32_T unsigned int
#else
#define TINY_CHAR16_T char16_t
#define TINY_CHAR32_T char32_t
#endif // _MSC_VER
#ifdef _WIN32
#define IS_DIR_SEPARATOR(c) (c=='\\')
#define IS_DIR_SEPARATORW(c) (c==L'\\')
#else
#define IS_DIR_SEPARATOR(c) (c=='/')
#endif
namespace tinydircpp
{
namespace fs {
using file_time_type = std::chrono::time_point<std::chrono::system_clock>;
using space_info = struct {
std::uintmax_t available;
std::uintmax_t capacity;
std::uintmax_t free;
};
template<typename T>
using str_t = std::basic_string<T, std::char_traits<T>>;
class path {
public:
using value_type = wchar_t;
using string_type = str_t<value_type>;
public:
path() = default;
~path() = default;
path( path && p ) : pathname_{ std::move( p.pathname_ ) } {}
path( path const & p ) : pathname_{ p.pathname_ } {}
explicit path( std::wstring const & pathname );
explicit path( std::string const & pathname );
explicit path( std::u16string const & pathname );
explicit path( std::u32string const & pathname );
explicit path( wchar_t const * pathname );
explicit path( char const * pathname );
template<typename InputIterator>
path( InputIterator begin, InputIterator end );
path& operator=( path const & p );
path& operator=( path && p );
template<typename Source>
path& operator=( Source const & source )
{
*this = path{ source };
return *this;
}
template<typename Source>
path& assign( Source const & source )
{
*this = source;
return *this;
}
template<typename InputIterator>
path& assign( InputIterator beg, InputIterator end )
{
*this = path{ beg, end };
return *this;
}
void clear() noexcept
{
pathname_.clear();
}
friend path operator/( path const & p, path const & rel_path );
path& operator/=( path const & p );
bool operator<( path const & p ) const
{
return pathname_ < p.pathname_;
}
bool operator>( path const & p ) const
{
return pathname_ > p.pathname_;
}
bool operator<=( path const & p ) const
{
return pathname_ <= p.pathname_;
}
bool operator>=( path const & p ) const
{
return pathname_ >= p.pathname_;
}
/*
path& operator +=( std::string const & str );
path& operator+=( path const & p );
path& operator+=( char p );
path& remove_filename();
path& replace_filename_with( path const & new_filename );
path& replace_extension( path const & );
int compare( path const & ) const noexcept;
int compare( std::string const & ) const noexcept;
path root_name() const;
path root_directory() const;
path relative_path() const;
*/
path extension() const;
path filename() const;
operator string_type()
{
return pathname_;
}
std::u32string u32string() const;
std::u16string u16string() const;
std::wstring wstring() const;
std::string string() const;
bool empty() const
{
return pathname_.empty();
}
string_type const & native() const noexcept
{
return pathname_;
}
value_type const * c_str() const noexcept
{
return pathname_.c_str();
}
operator string_type() const
{
return pathname_;
}
/*
bool has_root_name() const;
bool has_root_directory() const;
bool has_filename() const;
bool is_absolute() const;
bool is_relative() const; */
private:
str_t<value_type> pathname_ {}; // basic-string
};
enum class filesystem_error_codes
{
directory_name_unobtainable = 0x80,
unknown_io_error,
handle_not_opened,
could_not_obtain_size,
could_not_obtain_time,
hardlink_count_error,
invalid_set_file_pointer,
set_filetime_error,
no_link,
operation_cancelled
};
std::error_code make_error_code( filesystem_error_codes code );
namespace details {
struct invalid_filename : public std::runtime_error {
invalid_filename( char const * error_message ) : std::runtime_error{ error_message }{}
};
struct name_too_long : public std::runtime_error {
name_too_long( char const * error_message ) : std::runtime_error{ error_message }{}
};
struct smart_handle {
smart_handle( HANDLE h ) : h_{ h } {}
smart_handle( smart_handle const & ) = delete;
smart_handle( smart_handle && ) = delete;
smart_handle& operator=( smart_handle const & ) = delete;
smart_handle& operator=( smart_handle && ) = delete;
~smart_handle()
{
if ( h_ != INVALID_HANDLE_VALUE ) CloseHandle( h_ );
}
operator bool()
{
return h_ != INVALID_HANDLE_VALUE;
}
operator HANDLE() { return h_; }
private:
HANDLE h_;
};
std::string get_windows_error( DWORD error_code );
file_time_type Win32FiletimeToChronoTime( FILETIME const &pFiletime );
FILETIME ChronoTimeToWin32Filetime( file_time_type const & ftt );
template<typename T>
bool is_filename( str_t<T> const & str )
{
std::locale locale_{};
return std::all_of( std::begin( str ), std::end( str ), [&]( T const & ch ) {
return std::isalnum( ch, locale_ ) || ( T( '.' ) == ch ) || ( T( '_' ) == ch ) || ( T( '-' ) == ch );
} );
}
void convert_to( str_t<wchar_t> const & from, str_t<char32_t> & to );
void convert_to( str_t<char32_t> const & from, str_t<wchar_t> & to );
void convert_to( str_t<wchar_t> const & from, str_t<char> & to );
void convert_to( str_t<char16_t> const & from, str_t<char> & to );
void convert_to( str_t<char32_t> const & from, str_t<char> & to );
void convert_to( str_t<char> const & from, str_t<char16_t> & to );
void convert_to( str_t<char> const & from, str_t<char32_t> & to );
void convert_to( str_t<char> const &from, str_t<char> & to );
void convert_to( str_t<char> const & from, str_t<wchar_t> & to );
}
template<typename InputIterator>
path::path( InputIterator begin, InputIterator end ) : // we delegate the task to a ctor taking a string type
path{ str_t<typename std::iterator_traits<InputIterator>::value_type>{ begin, end } }
{
}
class filesystem_error : public std::system_error {
public:
filesystem_error( std::string const & what, std::error_code ec ) : filesystem_error{ what, {}, ec } {}
filesystem_error( std::string const & what, path const & p, std::error_code ec ) :
filesystem_error{ what, p, {}, ec }
{
}
filesystem_error( std::string const & what, path const & p1, path const & p2, std::error_code ec ) :
std::system_error{ ec, what }, first_path{ p1 }, second_path{ p2 }{}
path const & path1() const { return first_path; }
path const & path2() const { return second_path; }
using std::system_error::what;
private:
path const first_path;
path const second_path;
};
enum class file_type : int {
none = 0,
not_found = -1,
regular = 1,
directory,
symlink,
block,
character,
fifo,
socket,
unknown
};
enum class copy_options : int {
none = 0,
skip_existing = 0x1,
overwrite_existing = 0x2,
update_existing = 0x4,
recursive = 0x8,
copy_symlinks = 0x10,
skip_symlinks = 0x20,
directories_only = 0x40,
create_symlinks = 0x80,
create_hardlinks = 0x100
};
enum class perms : int {
none = 0,
owner_read = 256,
owner_write = 128,
owner_exec = 64,
owner_all = owner_read | owner_write | owner_exec,
group_read = 32,
group_write = 16,
group_exec = 8,
group_all = group_read | group_write | group_exec,
others_read = 4,
others_write = 2,
others_exec = 1,
others_all = others_read | others_write | others_exec,
all = 511,
set_uid = 2048,
set_gid = 1024,
mask = 512,
unknown = 0xFFFF,
symlink_perms = 0x4000
};
//supposed to be in <ntifs.h> but weirdly this header isn't available to use but MSDN shows what it looks like
struct REPARSE_DATA_BUFFER
{
ULONG ReparseTag;
USHORT ReparseDataLength;
USHORT Reserved;
union {
struct {
USHORT SubstituteNameOffset;
USHORT SubstituteNameLength;
USHORT PrintNameOffset;
USHORT PrintNameLength;
ULONG Flags;
WCHAR PathBuffer[ 1 ];
} SymbolicLinkReparseBuffer;
struct {
USHORT SubstituteNameOffset;
USHORT SubstituteNameLength;
USHORT PrintNameOffset;
USHORT PrintNameLength;
WCHAR PathBuffer[ 1 ];
} MountPointReparseBuffer;
struct {
UCHAR DataBuffer[ 1 ];
} GenericReparseBuffer;
};
};
struct filesystem_time {
unsigned short year;
unsigned short month;
unsigned short day_of_week;
unsigned short day;
unsigned short hour;
unsigned short minute;
unsigned short second;
unsigned short milliseconds;
};
file_time_type fstime_to_stdtime( filesystem_time const & );
filesystem_time stdtime_to_fstime( file_time_type const & );
enum class permissions_status : int {
replace_bits = 0,
add_bits = 1,
remove_bits = 2,
follow_symlinks = 4
};
}
}
namespace std
{
template<>
struct is_error_code_enum<tinydircpp::fs::filesystem_error_codes> : public true_type
{
};
}
| 34.073232 | 121 | 0.543689 | iamOgunyinka |
6084ace8ad71f884de7348c21c35da29b4af00d8 | 3,635 | hpp | C++ | src/shared/traits/gta3/iii.hpp | gtaisbetterthanfn/modloader | 18f85c2766d4e052a452c7b1d8f5860a6daac24b | [
"MIT"
] | 186 | 2015-01-18T05:46:11.000Z | 2022-03-22T10:03:44.000Z | src/shared/traits/gta3/iii.hpp | AlisonMDL/modloader | 18f85c2766d4e052a452c7b1d8f5860a6daac24b | [
"MIT"
] | 82 | 2015-01-14T01:02:04.000Z | 2022-03-20T23:55:59.000Z | src/shared/traits/gta3/iii.hpp | AlisonMDL/modloader | 18f85c2766d4e052a452c7b1d8f5860a6daac24b | [
"MIT"
] | 34 | 2015-01-07T11:17:00.000Z | 2022-02-28T00:16:20.000Z | /*
* Copyright (C) 2016 LINK/2012 <dma_2012@hotmail.com>
* Licensed under the MIT License, see LICENSE at top level directory.
*
* Most of things game version dependent (not being addressed by the addr translator) should be handled by the game trait
*
*/
#pragma once
#include "base.hpp"
struct TraitsIII : TraitsGTA
{
// Pools
using VehiclePool_t = CPool<typename std::aligned_storage<0x5A8, 1>::type>;
using PedPool_t = CPool<typename std::aligned_storage<0x5F0, 1>::type>;
using ObjectPool_t = CPool<typename std::aligned_storage<0x19C, 1>::type>;
using BuildingPool_t = CPool<typename std::aligned_storage<0x64, 1>::type>;
using DummyPool_t = CPool<typename std::aligned_storage<0x70, 1>::type>;
// Indices range
const id_t dff_start = 0;
const id_t txd_start = injector::lazy_object<0x5B62CF, unsigned int>::get(); // uint32_t not working properly on GCC here
const id_t max_models = txd_start;
const id_t dff_end = txd_start;
// Type of entities
enum class EntityType : uint8_t
{
Nothing, Building, Vehicle, Ped, Object, Dummy, NotInPools
};
// Type of models
enum class ModelType : uint8_t
{
Atomic = 1, Mlo = 2, Time = 3,
Clump = 4, Vehicle = 5, Ped = 6, XtraComps = 7,
};
// Type of CVehicle
enum class VehicleType : uint8_t
{
Automobile = 0, Bike = 0xFF,
};
// VTables
static const size_t vmt_SetModelIndex = 3;
static const size_t vmt_DeleteRwObject = 6;
// Gets the entity model id
static id_t GetEntityModel(void* entity)
{
return ReadOffset<uint16_t>(entity, 0x5C);
}
// Gets the entity type
static EntityType GetEntityType(void* entity)
{
return EntityType(ReadOffset<uint8_t>(entity, 0x50) & 0x7);
}
// Gets the entity RwObject pointer
static void* GetEntityRwObject(void* entity)
{
return ReadOffset<void*>(entity, 0x4C);
}
// Gets the ped intelligence pointer from a ped entity
static void*& GetPedIntelligence(void* entity)
{
DoesNotExistInThisGame();
return ReadOffset<void*>(entity, 0); // to be able to compile in VS2013
}
// Gets the ped task manaager pointer from a ped entity
static void* GetPedTaskManager(void* entity)
{
DoesNotExistInThisGame();
return ReadOffset<void*>(entity, 0); // to be able to compile in VS2013
}
// Gets the type of a CVehicle entity.
static VehicleType GetVehicleType(void* entity)
{
return VehicleType(ReadOffset<uint32_t>(entity, 644));
}
// Gets the model information structure from it's id
static void* GetModelInfo(id_t id)
{
auto& p = injector::lazy_object<0x408897, void**>::get();
return p[id];
}
// Gets the model type (Building, Ped, Vehicle, etc) from the model id
static ModelType GetModelType(id_t id)
{
auto m = GetModelInfo(id);
return ModelType(ReadOffset<uint8_t>(m, 42));
}
// Gets the model id tex dictionary index
static id_t GetModelTxdIndex(id_t id)
{
if(auto m = GetModelInfo(id)) return ReadOffset<uint16_t>(m, 40);
return -1;
}
// Gets the usage count of the specified model id
static int GetModelUsageCount(id_t id)
{
if(auto m = GetModelInfo(id)) return ReadOffset<uint16_t>(m, 38);
return 0;
}
/*
// Gets the hash of the name of the specified model
static uint32_t GetModelKey(id_t id)
{
if(auto m = GetModelInfo(id)) return ReadOffset<uint32_t>(m, 0x04);
return 0;
}
*/
};
| 28.398438 | 126 | 0.646217 | gtaisbetterthanfn |
608893c315af904d04883754fd84e6d1c51eea45 | 652 | cpp | C++ | demo/arduino-due/blink-poll/main.cpp | wovo/hwcpp | 2462db6b360e585fd0c8c8c23fac2e5db24f52a0 | [
"BSL-1.0"
] | 21 | 2017-05-24T21:44:29.000Z | 2021-03-24T05:41:14.000Z | demo/arduino-due/blink-poll/main.cpp | wovo/hwcpp | 2462db6b360e585fd0c8c8c23fac2e5db24f52a0 | [
"BSL-1.0"
] | 3 | 2017-11-21T14:44:13.000Z | 2018-03-02T11:55:05.000Z | demo/arduino-due/blink-poll/main.cpp | wovo/hwcpp | 2462db6b360e585fd0c8c8c23fac2e5db24f52a0 | [
"BSL-1.0"
] | 2 | 2018-02-23T12:13:45.000Z | 2019-07-10T17:29:15.000Z | #include "hwcpp.hpp"
using target = hwcpp::target<>;
template< hwcpp::can_pin_out _led, typename interval >
struct blinker :
interval:: template callback< struct blinker< _led, interval > >
{
using led = hwcpp::pin_out< _led >;
static inline bool led_state = 0;
static void init(){
led::init();
interval::template callback< struct blinker< _led, interval > >::init();
}
static void main(){
led_state = ! led_state;
led::set( led_state );
}
};
using blink = blinker< target::led, target::timing::ms< 200 > >;
int main(){
blink::init();
target::timing::callbacks::run();
} | 23.285714 | 75 | 0.608896 | wovo |
608ca8da0b5a727550fd7a7faaaa49c7ddd0ade6 | 2,760 | cc | C++ | verilog/analysis/checkers/interface_name_style_rule.cc | ColtonProvias/verible | ded8ad5e03d0eca2125d9ae3ba6c4f07919b4565 | [
"Apache-2.0"
] | 2 | 2019-12-21T21:47:32.000Z | 2020-10-11T06:42:45.000Z | verilog/analysis/checkers/interface_name_style_rule.cc | ColtonProvias/verible | ded8ad5e03d0eca2125d9ae3ba6c4f07919b4565 | [
"Apache-2.0"
] | null | null | null | verilog/analysis/checkers/interface_name_style_rule.cc | ColtonProvias/verible | ded8ad5e03d0eca2125d9ae3ba6c4f07919b4565 | [
"Apache-2.0"
] | 2 | 2021-11-06T07:35:11.000Z | 2021-11-26T04:06:25.000Z | // Copyright 2017-2020 The Verible Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "verilog/analysis/checkers/interface_name_style_rule.h"
#include <set>
#include <string>
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "common/analysis/citation.h"
#include "common/analysis/lint_rule_status.h"
#include "common/analysis/matcher/bound_symbol_manager.h"
#include "common/strings/naming_utils.h"
#include "common/text/symbol.h"
#include "common/text/syntax_tree_context.h"
#include "verilog/CST/module.h"
#include "verilog/CST/type.h"
#include "verilog/analysis/lint_rule_registry.h"
namespace verilog {
namespace analysis {
VERILOG_REGISTER_LINT_RULE(InterfaceNameStyleRule);
using verible::GetStyleGuideCitation;
using verible::LintRuleStatus;
using verible::LintViolation;
using verible::SyntaxTreeContext;
absl::string_view InterfaceNameStyleRule::Name() {
return "interface-name-style";
}
const char InterfaceNameStyleRule::kTopic[] = "interface-conventions";
const char InterfaceNameStyleRule::kMessage[] =
"Interface names must use lower_snake_case naming convention "
"and end with _if.";
std::string InterfaceNameStyleRule::GetDescription(
DescriptionType description_type) {
return absl::StrCat(
"Checks that ", Codify("interface", description_type),
" names use lower_snake_case naming convention and end with '_if'. See ",
GetStyleGuideCitation(kTopic), ".");
}
void InterfaceNameStyleRule::HandleSymbol(const verible::Symbol& symbol,
const SyntaxTreeContext& context) {
verible::matcher::BoundSymbolManager manager;
absl::string_view name;
const verible::TokenInfo* identifier_token;
if (matcher_interface_.Matches(symbol, &manager)) {
identifier_token = &GetInterfaceNameToken(symbol);
name = identifier_token->text();
if (!verible::IsLowerSnakeCaseWithDigits(name) ||
!absl::EndsWith(name, "_if")) {
violations_.insert(LintViolation(*identifier_token, kMessage, context));
}
}
}
LintRuleStatus InterfaceNameStyleRule::Report() const {
return LintRuleStatus(violations_, Name(), GetStyleGuideCitation(kTopic));
}
} // namespace analysis
} // namespace verilog
| 34.5 | 79 | 0.749275 | ColtonProvias |
6093fe9b81ba3aaf2ab96ad527d447982323a153 | 3,511 | tcc | C++ | include/xflens/cxxblas/level1/asum.tcc | muncasterconsulting/xtensor-blas | a63b47e4f120ad7a4f48d7d64e3e422268b987f5 | [
"BSD-3-Clause"
] | 93 | 2017-04-20T14:24:01.000Z | 2019-10-09T17:41:15.000Z | include/xflens/cxxblas/level1/asum.tcc | muncasterconsulting/xtensor-blas | a63b47e4f120ad7a4f48d7d64e3e422268b987f5 | [
"BSD-3-Clause"
] | 81 | 2017-04-21T14:54:15.000Z | 2019-10-03T08:55:07.000Z | include/xflens/cxxblas/level1/asum.tcc | muncasterconsulting/xtensor-blas | a63b47e4f120ad7a4f48d7d64e3e422268b987f5 | [
"BSD-3-Clause"
] | 33 | 2017-04-20T14:17:54.000Z | 2019-08-22T02:05:30.000Z | /*
* Copyright (c) 2009, Michael Lehn
*
* 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 FLENS development group 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.
*/
#ifndef CXXBLAS_LEVEL1_ASUM_TCC
#define CXXBLAS_LEVEL1_ASUM_TCC 1
#include <cmath>
#include "xflens/cxxblas/cxxblas.h"
namespace cxxblas {
template <typename IndexType, typename X, typename T>
void
asum_generic(IndexType n, const X *x, IndexType incX, T &absSum)
{
CXXBLAS_DEBUG_OUT("asum_generic");
using std::abs;
absSum = 0;
for (IndexType i=0; i<n; ++i, x+=incX) {
absSum += abs(cxxblas::real(*x)) + abs(cxxblas::imag(*x));
}
}
template <typename IndexType, typename X, typename T>
void
asum(IndexType n, const X *x, IndexType incX, T &absSum)
{
if (incX<0) {
x -= incX*(n-1);
}
asum_generic(n, x, incX, absSum);
}
#ifdef HAVE_CBLAS
// sasum
template <typename IndexType>
typename If<IndexType>::isBlasCompatibleInteger
asum(IndexType n, const float *x, IndexType incX, float &absSum)
{
CXXBLAS_DEBUG_OUT("[" BLAS_IMPL "] cblas_sasum");
absSum = cblas_sasum(n, x, incX);
}
// dasum
template <typename IndexType>
typename If<IndexType>::isBlasCompatibleInteger
asum(IndexType n, const double *x, IndexType incX, double &absSum)
{
CXXBLAS_DEBUG_OUT("[" BLAS_IMPL "] cblas_dasum");
absSum = cblas_dasum(n, x, incX);
}
// scasum
template <typename IndexType>
typename If<IndexType>::isBlasCompatibleInteger
asum(IndexType n, const ComplexFloat *x, IndexType incX, float &absSum)
{
CXXBLAS_DEBUG_OUT("[" BLAS_IMPL "] cblas_scasum");
absSum = cblas_scasum(n, reinterpret_cast<const float *>(x), incX);
}
// dzasum
template <typename IndexType>
typename If<IndexType>::isBlasCompatibleInteger
asum(IndexType n, const ComplexDouble *x, IndexType incX, double &absSum)
{
CXXBLAS_DEBUG_OUT("[" BLAS_IMPL "] cblas_dzasum");
absSum = cblas_dzasum(n, reinterpret_cast<const double *>(x), incX);
}
#endif // HAVE_CBLAS
} // namespace cxxblas
#endif // CXXBLAS_LEVEL1_ASUM_TCC
| 31.348214 | 75 | 0.721732 | muncasterconsulting |
6097e9b7e4a8e6bdc6326b9bf7a20a4f1cf3c8f1 | 22,297 | cpp | C++ | Source/Voxel/Private/VoxelRender/VoxelProceduralMeshComponent.cpp | SolarStormInteractive/VoxelPlugin | b0b8a1838262227fa586fbcb1b46a6184cdf1e8c | [
"MIT"
] | null | null | null | Source/Voxel/Private/VoxelRender/VoxelProceduralMeshComponent.cpp | SolarStormInteractive/VoxelPlugin | b0b8a1838262227fa586fbcb1b46a6184cdf1e8c | [
"MIT"
] | null | null | null | Source/Voxel/Private/VoxelRender/VoxelProceduralMeshComponent.cpp | SolarStormInteractive/VoxelPlugin | b0b8a1838262227fa586fbcb1b46a6184cdf1e8c | [
"MIT"
] | null | null | null | // Copyright 2020 Phyronnaz
#include "VoxelRender/VoxelProceduralMeshComponent.h"
#include "VoxelRender/VoxelProceduralMeshSceneProxy.h"
#include "VoxelRender/VoxelAsyncPhysicsCooker.h"
#include "VoxelRender/VoxelProcMeshBuffers.h"
#include "VoxelRender/VoxelMaterialInterface.h"
#include "VoxelRender/VoxelToolRendering.h"
#include "VoxelRender/IVoxelRenderer.h"
#include "VoxelRender/IVoxelProceduralMeshComponent_PhysicsCallbackHandler.h"
#include "VoxelDebug/VoxelDebugManager.h"
#include "VoxelWorldRootComponent.h"
#include "VoxelMessages.h"
#include "VoxelMinimal.h"
#include "IVoxelPool.h"
#include "PhysicsEngine/PhysicsSettings.h"
#include "PhysicsEngine/BodySetup.h"
#include "AI/NavigationSystemHelpers.h"
#include "AI/NavigationSystemBase.h"
#include "Async/Async.h"
#include "DrawDebugHelpers.h"
#include "Materials/Material.h"
DEFINE_VOXEL_MEMORY_STAT(STAT_VoxelPhysXTriangleMeshesMemory);
static TAutoConsoleVariable<int32> CVarShowCollisionsUpdates(
TEXT("voxel.renderer.ShowCollisionsUpdates"),
0,
TEXT("If true, will show the chunks that finished updating collisions"),
ECVF_Default);
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void IVoxelProceduralMeshComponent_PhysicsCallbackHandler::TickHandler()
{
VOXEL_FUNCTION_COUNTER();
check(IsInGameThread());
FCallback Callback;
while (Queue.Dequeue(Callback))
{
if (Callback.Component.IsValid())
{
Callback.Component->PhysicsCookerCallback(Callback.CookerId);
}
}
}
void IVoxelProceduralMeshComponent_PhysicsCallbackHandler::CookerCallback(uint64 CookerId, TWeakObjectPtr<UVoxelProceduralMeshComponent> Component)
{
Queue.Enqueue({ CookerId, Component });
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void UVoxelProceduralMeshComponent::Init(
int32 InDebugLOD,
uint32 InDebugChunkId,
const FVoxelPriorityHandler& InPriorityHandler,
const TVoxelWeakPtr<IVoxelProceduralMeshComponent_PhysicsCallbackHandler>& InPhysicsCallbackHandler,
const FVoxelRendererSettings& RendererSettings)
{
ensure(InPhysicsCallbackHandler.IsValid());
if (UniqueId != 0)
{
// Make sure we don't have any convex collision left
UpdateConvexMeshes({}, {}, {});
}
bInit = true;
UniqueId = UNIQUE_ID();
LOD = InDebugLOD;
DebugChunkId = InDebugChunkId;
PriorityHandler = InPriorityHandler;
PhysicsCallbackHandler = InPhysicsCallbackHandler;
Pool = RendererSettings.Pool;
ToolRenderingManager = RendererSettings.ToolRenderingManager;
PriorityDuration = RendererSettings.PriorityDuration;
CollisionTraceFlag = RendererSettings.CollisionTraceFlag;
NumConvexHullsPerAxis = RendererSettings.NumConvexHullsPerAxis;
bCleanCollisionMesh = RendererSettings.bCleanCollisionMeshes;
bClearProcMeshBuffersOnFinishUpdate = RendererSettings.bStaticWorld && !RendererSettings.bRenderWorld; // We still need the buffers if we are rendering!
DistanceFieldSelfShadowBias = RendererSettings.DistanceFieldSelfShadowBias;
}
void UVoxelProceduralMeshComponent::ClearInit()
{
ensure(ProcMeshSections.Num() == 0);
bInit = false;
}
UVoxelProceduralMeshComponent::UVoxelProceduralMeshComponent()
{
Mobility = EComponentMobility::Movable;
CastShadow = true;
bUseAsOccluder = true;
bCanEverAffectNavigation = true;
bAllowReregistration = false; // Slows down the editor when editing properties
bCastShadowAsTwoSided = true;
bHasCustomNavigableGeometry = EHasCustomNavigableGeometry::EvenIfNotCollidable;
// Fix for details crash
BodyInstance.SetMassOverride(100, true);
}
UVoxelProceduralMeshComponent::~UVoxelProceduralMeshComponent()
{
if (AsyncCooker)
{
AsyncCooker->CancelAndAutodelete();
AsyncCooker = nullptr;
}
DEC_VOXEL_MEMORY_STAT_BY(STAT_VoxelPhysXTriangleMeshesMemory, TriangleMeshesMemory);
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
bool UVoxelProceduralMeshComponent::AreVoxelCollisionsFrozen()
{
return bAreCollisionsFrozen;
}
void UVoxelProceduralMeshComponent::SetVoxelCollisionsFrozen(bool bFrozen)
{
VOXEL_FUNCTION_COUNTER();
if (bFrozen != bAreCollisionsFrozen)
{
if (bFrozen)
{
bAreCollisionsFrozen = true;
OnFreezeVoxelCollisionChanged.Broadcast(true);
}
else
{
bAreCollisionsFrozen = false;
for (auto& Component : PendingCollisions)
{
if (Component.IsValid())
{
Component->UpdateCollision();
}
}
PendingCollisions.Reset();
OnFreezeVoxelCollisionChanged.Broadcast(false);
}
}
}
void UVoxelProceduralMeshComponent::AddOnFreezeVoxelCollisionChanged(const FOnFreezeVoxelCollisionChanged::FDelegate& NewDelegate)
{
OnFreezeVoxelCollisionChanged.Add(NewDelegate);
}
bool UVoxelProceduralMeshComponent::bAreCollisionsFrozen = false;
TSet<TWeakObjectPtr<UVoxelProceduralMeshComponent>> UVoxelProceduralMeshComponent::PendingCollisions;
FOnFreezeVoxelCollisionChanged UVoxelProceduralMeshComponent::OnFreezeVoxelCollisionChanged;
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void UVoxelProceduralMeshComponent::SetDistanceFieldData(const TVoxelSharedPtr<const FDistanceFieldVolumeData>& InDistanceFieldData)
{
if (DistanceFieldData == InDistanceFieldData)
{
return;
}
DistanceFieldData = InDistanceFieldData;
GetScene()->UpdatePrimitiveDistanceFieldSceneData_GameThread(this);
MarkRenderStateDirty();
}
void UVoxelProceduralMeshComponent::SetProcMeshSection(int32 Index, FVoxelProcMeshSectionSettings Settings, TUniquePtr<FVoxelProcMeshBuffers> Buffers, EVoxelProcMeshSectionUpdate Update)
{
VOXEL_FUNCTION_COUNTER();
if (!ensure(ProcMeshSections.IsValidIndex(Index)))
{
return;
}
Buffers->UpdateStats();
ProcMeshSections[Index].Settings = Settings;
// Due to InitResources etc, we must make sure we are the only component using this buffers, hence the TUniquePtr
// However the buffer is shared between the component and the proxy
ProcMeshSections[Index].Buffers = MakeShareable(Buffers.Release());
if (Update == EVoxelProcMeshSectionUpdate::UpdateNow)
{
FinishSectionsUpdates();
}
}
int32 UVoxelProceduralMeshComponent::AddProcMeshSection(FVoxelProcMeshSectionSettings Settings, TUniquePtr<FVoxelProcMeshBuffers> Buffers, EVoxelProcMeshSectionUpdate Update)
{
VOXEL_FUNCTION_COUNTER();
check(Buffers.IsValid());
ensure(Settings.bSectionVisible || Settings.bEnableCollisions || Settings.bEnableNavmesh);
if (Buffers->GetNumIndices() == 0)
{
return -1;
}
const int32 Index = ProcMeshSections.Emplace();
SetProcMeshSection(Index, Settings, MoveTemp(Buffers), Update);
return Index;
}
void UVoxelProceduralMeshComponent::ReplaceProcMeshSection(FVoxelProcMeshSectionSettings Settings, TUniquePtr<FVoxelProcMeshBuffers> Buffers, EVoxelProcMeshSectionUpdate Update)
{
VOXEL_FUNCTION_COUNTER();
check(Buffers.IsValid());
ensure(Settings.bSectionVisible || Settings.bEnableCollisions || Settings.bEnableNavmesh);
int32 SectionIndex = -1;
for (int32 Index = 0; Index < ProcMeshSections.Num(); Index++)
{
if (ProcMeshSections[Index].Settings == Settings)
{
ensure(SectionIndex == -1);
SectionIndex = Index;
}
}
if (SectionIndex == -1)
{
AddProcMeshSection(Settings, MoveTemp(Buffers), Update);
}
else
{
SetProcMeshSection(SectionIndex, Settings, MoveTemp(Buffers), Update);
}
}
void UVoxelProceduralMeshComponent::ClearSections(EVoxelProcMeshSectionUpdate Update)
{
VOXEL_FUNCTION_COUNTER();
ProcMeshSections.Empty();
if (Update == EVoxelProcMeshSectionUpdate::UpdateNow)
{
FinishSectionsUpdates();
}
}
void UVoxelProceduralMeshComponent::FinishSectionsUpdates()
{
VOXEL_FUNCTION_COUNTER();
bool bNeedToComputeCollisions = false;
bool bNeedToComputeNavigation = false;
{
TArray<FGuid> NewGuids;
TMap<FGuid, FVoxelProcMeshSectionSettings> NewGuidToSettings;
{
int32 NumGuids = 0;
for (auto& Section : ProcMeshSections)
{
NumGuids += Section.Buffers->Guids.Num();
}
NewGuids.Reserve(NumGuids);
NewGuidToSettings.Reserve(NumGuids);
}
for (auto& Section : ProcMeshSections)
{
for (auto& Guid : Section.Buffers->Guids)
{
NewGuids.Add(Guid);
ensure(!NewGuidToSettings.Contains(Guid));
NewGuidToSettings.Add(Guid, Section.Settings);
}
}
NewGuids.Sort();
if (ProcMeshSectionsSortedGuids != NewGuids)
{
bNeedToComputeCollisions = true;
bNeedToComputeNavigation = true;
}
else
{
for (auto& Guid : NewGuids)
{
const auto& Old = ProcMeshSectionsGuidToSettings[Guid];
const auto& New = NewGuidToSettings[Guid];
bNeedToComputeCollisions |= Old.bEnableCollisions != New.bEnableCollisions;
bNeedToComputeNavigation |= Old.bEnableNavmesh != New.bEnableNavmesh;
}
}
ProcMeshSectionsSortedGuids = MoveTemp(NewGuids);
ProcMeshSectionsGuidToSettings = MoveTemp(NewGuidToSettings);
}
UpdatePhysicalMaterials();
UpdateLocalBounds();
MarkRenderStateDirty();
if (bNeedToComputeCollisions)
{
UpdateCollision();
}
if (bNeedToComputeNavigation)
{
UpdateNavigation();
}
if (bClearProcMeshBuffersOnFinishUpdate)
{
ProcMeshSections.Reset();
}
LastFinishSectionsUpdatesTime = FPlatformTime::Seconds();
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
FPrimitiveSceneProxy* UVoxelProceduralMeshComponent::CreateSceneProxy()
{
// Sometimes called outside of the render thread at EndPlay
VOXEL_ASYNC_FUNCTION_COUNTER();
for (auto& Section : ProcMeshSections)
{
if (Section.Settings.bSectionVisible || FVoxelDebugManager::ShowCollisionAndNavmeshDebug())
{
return new FVoxelProceduralMeshSceneProxy(this);
}
}
if (DistanceFieldData.IsValid())
{
return new FVoxelProceduralMeshSceneProxy(this);
}
return nullptr;
}
UBodySetup* UVoxelProceduralMeshComponent::GetBodySetup()
{
return BodySetup;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
UMaterialInterface* UVoxelProceduralMeshComponent::GetMaterialFromCollisionFaceIndex(int32 FaceIndex, int32& OutSectionIndex) const
{
// Look for element that corresponds to the supplied face
int32 TotalFaceCount = 0;
for (int32 SectionIndex = 0; SectionIndex < ProcMeshSections.Num(); SectionIndex++)
{
const FVoxelProcMeshSection& Section = ProcMeshSections[SectionIndex];
const int32 NumFaces = Section.Buffers->GetNumIndices() / 3;
TotalFaceCount += NumFaces;
if (FaceIndex < TotalFaceCount)
{
OutSectionIndex = SectionIndex;
return GetMaterial(SectionIndex);
}
}
OutSectionIndex = 0;
return nullptr;
}
int32 UVoxelProceduralMeshComponent::GetNumMaterials() const
{
int32 Num = ProcMeshSections.Num();
const auto ToolRenderingManagerPinned = ToolRenderingManager.Pin();
if (ToolRenderingManagerPinned.IsValid())
{
Num += ToolRenderingManagerPinned->GetToolsMaterials().Num();
}
return Num;
}
UMaterialInterface* UVoxelProceduralMeshComponent::GetMaterial(int32 Index) const
{
if (!ensure(Index >= 0)) return nullptr;
if (Index < ProcMeshSections.Num())
{
auto& MaterialPtr = ProcMeshSections[Index].Settings.Material;
if (MaterialPtr.IsValid())
{
return MaterialPtr->GetMaterial();
}
else
{
return UPrimitiveComponent::GetMaterial(Index);
}
}
else
{
Index -= ProcMeshSections.Num();
const auto ToolRenderingManagerPinned = ToolRenderingManager.Pin();
if (ToolRenderingManagerPinned.IsValid())
{
const auto& Materials = ToolRenderingManagerPinned->GetToolsMaterials();
if (Materials.IsValidIndex(Index) && ensure(Materials[Index].IsValid()))
{
return Materials[Index]->GetMaterial();
}
}
return nullptr;
}
}
void UVoxelProceduralMeshComponent::GetUsedMaterials(TArray<UMaterialInterface*>& OutMaterials, bool bGetDebugMaterials) const
{
for (auto& Section : ProcMeshSections)
{
if (Section.Settings.Material.IsValid())
{
OutMaterials.Add(Section.Settings.Material->GetMaterial());
}
}
const auto ToolRenderingManagerPinned = ToolRenderingManager.Pin();
if (ToolRenderingManagerPinned.IsValid())
{
const auto& Materials = ToolRenderingManagerPinned->GetToolsMaterials();
for (auto& Material : Materials)
{
if (ensure(Material.IsValid()))
{
OutMaterials.Add(Material->GetMaterial());
}
}
}
}
FMaterialRelevance UVoxelProceduralMeshComponent::GetMaterialRelevance(ERHIFeatureLevel::Type InFeatureLevel) const
{
FMaterialRelevance Result;
const auto Apply = [&](auto* MaterialInterface)
{
if (MaterialInterface)
{
// MaterialInterface will be null in force delete
Result |= MaterialInterface->GetRelevance_Concurrent(InFeatureLevel);
}
};
for (auto& Section : ProcMeshSections)
{
if (Section.Settings.Material.IsValid())
{
Apply(Section.Settings.Material->GetMaterial());
}
else
{
Apply(UMaterial::GetDefaultMaterial(MD_Surface));
}
}
const auto ToolRenderingManagerPinned = ToolRenderingManager.Pin();
if (ToolRenderingManagerPinned.IsValid())
{
const auto& Materials = ToolRenderingManagerPinned->GetToolsMaterials();
for (auto& Material : Materials)
{
if (ensure(Material.IsValid()))
{
Apply(Material->GetMaterial());
}
}
}
return Result;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
bool UVoxelProceduralMeshComponent::DoCustomNavigableGeometryExport(FNavigableGeometryExport& GeomExport) const
{
VOXEL_FUNCTION_COUNTER();
for (auto& Section : ProcMeshSections)
{
if (Section.Settings.bEnableNavmesh)
{
TArray<FVector> Vertices;
// TODO is that copy needed
{
auto& PositionBuffer = Section.Buffers->VertexBuffers.PositionVertexBuffer;
Vertices.SetNumUninitialized(PositionBuffer.GetNumVertices());
for (int32 Index = 0; Index < Vertices.Num(); Index++)
{
Vertices[Index] = PositionBuffer.VertexPosition(Index);
}
}
TArray<int32> Indices;
// Copy needed because int32 vs uint32
{
auto& IndexBuffer = Section.Buffers->IndexBuffer;
Indices.SetNumUninitialized(IndexBuffer.GetNumIndices());
for (int32 Index = 0; Index < Indices.Num(); Index++)
{
Indices[Index] = IndexBuffer.GetIndex(Index);
}
}
GeomExport.ExportCustomMesh(Vertices.GetData(), Vertices.Num(), Indices.GetData(), Indices.Num(), GetComponentTransform());
}
}
return false;
}
FBoxSphereBounds UVoxelProceduralMeshComponent::CalcBounds(const FTransform& LocalToWorld) const
{
return FBoxSphereBounds(LocalBounds.TransformBy(LocalToWorld));
}
void UVoxelProceduralMeshComponent::OnComponentDestroyed(bool bDestroyingHierarchy)
{
UPrimitiveComponent::OnComponentDestroyed(bDestroyingHierarchy);
if (bInit)
{
// Clear convex collisions
UpdateConvexMeshes({}, {}, {}, true);
}
// Destroy async cooker
if (AsyncCooker)
{
AsyncCooker->CancelAndAutodelete();
AsyncCooker = nullptr;
}
// Clear memory
ProcMeshSections.Reset();
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void UVoxelProceduralMeshComponent::UpdatePhysicalMaterials()
{
VOXEL_FUNCTION_COUNTER();
FBodyInstance* BodyInst = GetBodyInstance();
if (BodyInst && BodyInst->IsValidBodyInstance())
{
BodyInst->UpdatePhysicalMaterials();
}
}
void UVoxelProceduralMeshComponent::UpdateLocalBounds()
{
VOXEL_FUNCTION_COUNTER();
FBox LocalBox(ForceInit);
for (auto& Section : ProcMeshSections)
{
LocalBox += Section.Buffers->LocalBounds;
}
LocalBounds = LocalBox.IsValid ? FBoxSphereBounds(LocalBox) : FBoxSphereBounds(ForceInit); // fallback to reset box sphere bounds
// Update global bounds
UpdateBounds();
// Need to send to render thread
MarkRenderTransformDirty();
}
void UVoxelProceduralMeshComponent::UpdateNavigation()
{
VOXEL_FUNCTION_COUNTER();
if (CanEverAffectNavigation() && IsRegistered() && GetWorld() && GetWorld()->GetNavigationSystem() && FNavigationSystem::WantsComponentChangeNotifies())
{
bNavigationRelevant = IsNavigationRelevant();
FNavigationSystem::UpdateComponentData(*this);
}
}
void UVoxelProceduralMeshComponent::UpdateCollision()
{
VOXEL_FUNCTION_COUNTER();
if (!ensure(GetWorld()))
{
return;
}
if (bAreCollisionsFrozen)
{
PendingCollisions.Add(this);
return;
}
// Cancel existing task
if (AsyncCooker)
{
AsyncCooker->CancelAndAutodelete();
AsyncCooker = nullptr;
ensure(BodySetupBeingCooked);
}
if (!BodySetupBeingCooked)
{
BodySetupBeingCooked = NewObject<UBodySetup>(this);
}
BodySetupBeingCooked->ClearPhysicsMeshes();
if (ProcMeshSections.FindByPredicate([](auto& Section) { return Section.Settings.bEnableCollisions; }))
{
auto PoolPtr = Pool.Pin();
if (ensure(PoolPtr.IsValid()))
{
AsyncCooker = new FVoxelAsyncPhysicsCooker(this);
PoolPtr->QueueTask(EVoxelTaskType::CollisionCooking, AsyncCooker);
}
}
else
{
UpdateConvexMeshes({}, {}, {});
FinishCollisionUpdate();
}
}
void UVoxelProceduralMeshComponent::FinishCollisionUpdate()
{
VOXEL_FUNCTION_COUNTER();
ensure(BodySetupBeingCooked);
Swap(BodySetup, BodySetupBeingCooked);
RecreatePhysicsState();
if (BodySetupBeingCooked)
{
BodySetupBeingCooked->ClearPhysicsMeshes();
}
if (CVarShowCollisionsUpdates.GetValueOnGameThread() &&
ProcMeshSections.FindByPredicate([](auto& Section) { return Section.Settings.bEnableCollisions; }))
{
const auto Box = Bounds.GetBox();
DrawDebugBox(GetWorld(), Box.GetCenter(), Box.GetExtent(), FColor::Red, false, 0.1);
}
}
void UVoxelProceduralMeshComponent::UpdateConvexMeshes(
const FBox& ConvexBounds,
TArray<FKConvexElem>&& ConvexElements,
TArray<physx::PxConvexMesh*>&& ConvexMeshes,
bool bCanFail)
{
VOXEL_FUNCTION_COUNTER();
ensure(UniqueId != 0);
ensure(ConvexElements.Num() == ConvexMeshes.Num());
if (CollisionTraceFlag == ECollisionTraceFlag::CTF_UseComplexAsSimple)
{
ensure(ConvexElements.Num() == 0);
return;
}
auto* Owner = GetOwner();
ensure(Owner || bCanFail);
if (!Owner) return;
auto* Root = Cast<UVoxelWorldRootComponent>(Owner->GetRootComponent());
ensure(Root || bCanFail);
if (!Root) return;
ensure(Root->CollisionTraceFlag == CollisionTraceFlag);
Root->UpdateConvexCollision(UniqueId, ConvexBounds, MoveTemp(ConvexElements), MoveTemp(ConvexMeshes));
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
#if ENGINE_MINOR_VERSION >= 24
class UMRMeshComponent
{
public:
static void FinishCreatingPhysicsMeshes(UBodySetup* Body, const TArray<physx::PxConvexMesh*>& ConvexMeshes, const TArray<physx::PxConvexMesh*>& ConvexMeshesNegX, const TArray<physx::PxTriangleMesh*>& TriMeshes)
{
Body->FinishCreatingPhysicsMeshes_PhysX(ConvexMeshes, ConvexMeshesNegX, TriMeshes);
}
};
#endif
void UVoxelProceduralMeshComponent::PhysicsCookerCallback(uint64 CookerId)
{
VOXEL_FUNCTION_COUNTER();
check(IsInGameThread());
if (!AsyncCooker || CookerId != AsyncCooker->UniqueId)
{
LOG_VOXEL(VeryVerbose, TEXT("Late async cooker callback, ignoring it"));
return;
}
if (!ensure(AsyncCooker->IsDone())) return;
if (!AsyncCooker->IsSuccessful())
{
//LOG_VOXEL(Warning, TEXT("Async cooker wasn't successful, ignoring it"));
return;
}
if (!ensure(BodySetupBeingCooked)) return;
FVoxelAsyncPhysicsCooker::FCookResult& CookResult = AsyncCooker->CookResult;
BodySetupBeingCooked->bGenerateMirroredCollision = false;
BodySetupBeingCooked->CollisionTraceFlag = CollisionTraceFlag;
{
VOXEL_SCOPE_COUNTER("ClearPhysicsMeshes");
BodySetupBeingCooked->ClearPhysicsMeshes();
}
{
VOXEL_SCOPE_COUNTER("FinishCreatingPhysicsMeshes");
#if ENGINE_MINOR_VERSION < 24
BodySetupBeingCooked->FinishCreatingPhysicsMeshes({}, {}, CookResult.TriangleMeshes);
#else
UMRMeshComponent::FinishCreatingPhysicsMeshes(BodySetupBeingCooked, {}, {}, CookResult.TriangleMeshes);
#endif
}
UpdateConvexMeshes(CookResult.ConvexBounds, MoveTemp(CookResult.ConvexElems), MoveTemp(CookResult.ConvexMeshes));
DEC_VOXEL_MEMORY_STAT_BY(STAT_VoxelPhysXTriangleMeshesMemory, TriangleMeshesMemory);
TriangleMeshesMemory = CookResult.TriangleMeshesMemoryUsage;
INC_VOXEL_MEMORY_STAT_BY(STAT_VoxelPhysXTriangleMeshesMemory, TriangleMeshesMemory);
AsyncCooker->CancelAndAutodelete();
AsyncCooker = nullptr;
FinishCollisionUpdate();
} | 29.146405 | 212 | 0.669059 | SolarStormInteractive |
60994c4f1d100b9b17e714a2f1a5b94d8474e8dc | 4,913 | cpp | C++ | src/caffe/test/test_transformer_layer.cpp | ducha-aiki/caffe | c9b0c544d97f331ccb2f33fc2b649b360ee59c41 | [
"BSD-2-Clause"
] | 31 | 2015-05-30T12:48:14.000Z | 2019-04-26T07:56:51.000Z | src/caffe/test/test_transformer_layer.cpp | ducha-aiki/caffe | c9b0c544d97f331ccb2f33fc2b649b360ee59c41 | [
"BSD-2-Clause"
] | 1 | 2015-04-03T13:39:00.000Z | 2015-04-03T13:39:00.000Z | src/caffe/test/test_transformer_layer.cpp | ducha-aiki/caffe | c9b0c544d97f331ccb2f33fc2b649b360ee59c41 | [
"BSD-2-Clause"
] | 10 | 2015-03-04T03:13:05.000Z | 2022-03-28T06:13:21.000Z | #include <cmath>
#include <cstring>
#include <vector>
#include "gtest/gtest.h"
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/filler.hpp"
#include "caffe/vision_layers.hpp"
#include "caffe/test/test_caffe_main.hpp"
#include "caffe/test/test_gradient_check_util.hpp"
namespace caffe {
template <typename TypeParam>
class TransformerLayerTest : public MultiDeviceTest<TypeParam> {
typedef typename TypeParam::Dtype Dtype;
protected:
TransformerLayerTest()
: blob_data_(new Blob<Dtype>(2, 3, 5, 5)),
blob_theta_(new Blob<Dtype>(vector<int>{ 2, 6 })),
blob_top_(new Blob<Dtype>()) {
// fill the values
FillerParameter filler_param;
filler_param.set_value(1);
GaussianFiller<Dtype> filler(filler_param);
filler.Fill(this->blob_data_);
filler_param.set_value(0);
ConstantFiller<Dtype> constant_filler(filler_param);
constant_filler.Fill(this->blob_theta_);
/*this->blob_theta_->mutable_cpu_data()[0] = 1;
this->blob_theta_->mutable_cpu_data()[4] = 1;*/
this->blob_theta_->mutable_cpu_data()[0] = sqrt(2) / 2;
this->blob_theta_->mutable_cpu_data()[1] = sqrt(2) / 2;
this->blob_theta_->mutable_cpu_data()[2] = -0.1;
this->blob_theta_->mutable_cpu_data()[3] = -sqrt(2) / 2;
this->blob_theta_->mutable_cpu_data()[4] = sqrt(2) / 2;
this->blob_theta_->mutable_cpu_data()[5] = 0.1;
this->blob_theta_->mutable_cpu_data()[0+6] = sqrt(2) / 2;
this->blob_theta_->mutable_cpu_data()[1+6] = sqrt(2) / 2;
this->blob_theta_->mutable_cpu_data()[2+6] = 0.1;
this->blob_theta_->mutable_cpu_data()[3+6] = -sqrt(2) / 2;
this->blob_theta_->mutable_cpu_data()[4+6] = sqrt(2) / 2;
this->blob_theta_->mutable_cpu_data()[5+6] = 0.1;
/*this->blob_theta_->mutable_cpu_data()[0+6] = 1;
this->blob_theta_->mutable_cpu_data()[4+6] = 1;*/
blob_bottom_vec_.push_back(blob_data_);
blob_bottom_vec_.push_back(blob_theta_);
blob_top_vec_.push_back(blob_top_);
}
virtual ~TransformerLayerTest() { delete blob_data_; delete blob_theta_; delete blob_top_; }
Blob<Dtype>* const blob_data_;
Blob<Dtype>* const blob_theta_;
Blob<Dtype>* const blob_top_;
vector<Blob<Dtype>*> blob_bottom_vec_;
vector<Blob<Dtype>*> blob_top_vec_;
};
TYPED_TEST_CASE(TransformerLayerTest, TestDtypesAndDevices);
TYPED_TEST(TransformerLayerTest, TestForward) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
TransformerLayer<Dtype> layer(layer_param);
layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_);
// Test sum
for (int n = 0; n < this->blob_data_->num(); ++n) {
for (int c = 0; c < this->blob_data_->channels(); ++c) {
for (int i = 0; i < this->blob_data_->height(); ++i) {
for (int j = 0; j < this->blob_data_->width(); ++j) {
Dtype x = (i / (Dtype)this->blob_data_->height() * 2 - 1) * this->blob_theta_->cpu_data()[0 + n * 6] + (j / (Dtype)this->blob_data_->width() * 2 - 1) * this->blob_theta_->cpu_data()[1 + n * 6] + this->blob_theta_->cpu_data()[2 + n * 6];
x = x * this->blob_data_->height() / 2 + (Dtype)this->blob_data_->height() / 2;
Dtype y = (i / (Dtype)this->blob_data_->height() * 2 - 1) * this->blob_theta_->cpu_data()[3 + n * 6] + (j / (Dtype)this->blob_data_->width() * 2 - 1) * this->blob_theta_->cpu_data()[4 + n * 6] + this->blob_theta_->cpu_data()[5 + n * 6];
y = y * this->blob_data_->width() / 2 + (Dtype)this->blob_data_->width() / 2;
if (x >= 0 && x <= this->blob_data_->height() - 1 && y >= 0 && y <= this->blob_data_->width() - 1)
{
Dtype value = 0, y1, y2;
y1 = this->blob_data_->data_at(n, c, floor(x), floor(y)) * (1 - (x - floor(x)))+ this->blob_data_->data_at(n, c, ceil(x), floor(y)) * (1 - (ceil(x) - x));
if (floor(x) == ceil(x)) y1 /= 2;
if (floor(y) == ceil(y)) value = y1;
else
{
y2 = this->blob_data_->data_at(n, c, floor(x), ceil(y)) * (1 - (x - floor(x))) + this->blob_data_->data_at(n, c, ceil(x), ceil(y)) * (1 - (ceil(x) - x));
if (floor(x) == ceil(x)) y2 /= 2;
value = y1 * (1 - (y - floor(y))) + y2 * (1 - (ceil(y) - y));
}
//LOG(INFO) << "(" << n << " " << c << " " << i << " " << j << ")("<<x<<"," <<y<< ")(" << value << "," << this->blob_top_->data_at(n, c, i, j) << ")";
CHECK(abs(value - this->blob_top_->data_at(n, c, i, j)) < 1e-4) << "(" << n << " " << c << " " << i << " " << j << ")" << "(" << value << "," << this->blob_top_->data_at(n, c, i, j)<<")";
}
}
}
}
}
}
TYPED_TEST(TransformerLayerTest, TestGradient) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
TransformerLayer<Dtype> layer(layer_param);
GradientChecker<Dtype> checker(1e-2, 1e-3);
checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_,
this->blob_top_vec_,-1);
}
} // namespace caffe
| 43.477876 | 242 | 0.620395 | ducha-aiki |
609b3532fcb028c52112524835f4eeb7c7b8a711 | 4,775 | cpp | C++ | fod/FingerprintInscreen.cpp | Micha-Btz/device_xiaomi_grus | d516af03a8e7a73a34e72ef882fa6869e8ef34c3 | [
"Apache-2.0"
] | 5 | 2020-09-22T19:04:32.000Z | 2021-01-22T18:38:14.000Z | fod/FingerprintInscreen.cpp | Micha-Btz/device_xiaomi_grus | d516af03a8e7a73a34e72ef882fa6869e8ef34c3 | [
"Apache-2.0"
] | 1 | 2021-01-17T22:26:47.000Z | 2021-01-18T13:23:20.000Z | fod/FingerprintInscreen.cpp | Micha-Btz/device_xiaomi_grus | d516af03a8e7a73a34e72ef882fa6869e8ef34c3 | [
"Apache-2.0"
] | 24 | 2020-04-22T09:22:31.000Z | 2021-07-23T23:35:37.000Z | /*
* Copyright (C) 2019 The LineageOS Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "FingerprintInscreenService"
#include "FingerprintInscreen.h"
#include <android-base/logging.h>
#include <fstream>
#include <cmath>
#define COMMAND_NIT 10
#define PARAM_NIT_FOD 3
#define PARAM_NIT_NONE 0
#define DISPPARAM_PATH "/sys/class/drm/card0-DSI-1/disp_param"
#define DISPPARAM_FOD_BACKLIGHT_HBM "0x1D007FF"
#define DISPPARAM_FOD_BACKLIGHT_RESET "0x2D01000"
#define FOD_STATUS_PATH "/sys/devices/virtual/touch/tp_dev/fod_status"
#define FOD_STATUS_ON 1
#define FOD_STATUS_OFF 0
#define FOD_SENSOR_X 455
#define FOD_SENSOR_Y 1920
#define FOD_SENSOR_SIZE 173
#define BRIGHTNESS_PATH "/sys/class/backlight/panel0-backlight/brightness"
namespace {
template <typename T>
static T get(const std::string& path, const T& def) {
std::ifstream file(path);
T result;
file >> result;
return file.fail() ? def : result;
}
template <typename T>
static void set(const std::string& path, const T& value) {
std::ofstream file(path);
file << value;
}
} // anonymous namespace
namespace vendor {
namespace lineage {
namespace biometrics {
namespace fingerprint {
namespace inscreen {
namespace V1_0 {
namespace implementation {
/*
map the polynomial function here based on the discovered points
ALPHA = 1.0 | BRIGHTNESS = 0
ALPHA = 0.7 | BRIGHTNESS = 150
ALPHA = 0.5 | BRIGHTNESS = 475
ALPHA = 0.3 | BRIGHTNESS = 950
ALPHA = 0.0 | BRIGHTNESS = 2047
*/
float p1 = 7.747 * pow(10, -8);
float p2 = -0.0004924;
float p3 = 0.6545;
float p4 = 58.82;
float q1 = 58.82;
FingerprintInscreen::FingerprintInscreen() {
xiaomiFingerprintService = IXiaomiFingerprint::getService();
this->mPressed = false;
}
Return<int32_t> FingerprintInscreen::getPositionX() {
return FOD_SENSOR_X;
}
Return<int32_t> FingerprintInscreen::getPositionY() {
return FOD_SENSOR_Y;
}
Return<int32_t> FingerprintInscreen::getSize() {
return FOD_SENSOR_SIZE;
}
Return<void> FingerprintInscreen::onStartEnroll() {
return Void();
}
Return<void> FingerprintInscreen::onFinishEnroll() {
return Void();
}
Return<void> FingerprintInscreen::onPress() {
if (!this->mPressed) {
set(DISPPARAM_PATH, DISPPARAM_FOD_BACKLIGHT_HBM);
xiaomiFingerprintService->extCmd(COMMAND_NIT, PARAM_NIT_FOD);
this->mPressed = true;
}
return Void();
}
Return<void> FingerprintInscreen::onRelease() {
if (this->mPressed) {
set(DISPPARAM_PATH, DISPPARAM_FOD_BACKLIGHT_RESET);
xiaomiFingerprintService->extCmd(COMMAND_NIT, PARAM_NIT_NONE);
this->mPressed = false;
}
return Void();
}
Return<void> FingerprintInscreen::onShowFODView() {
set(FOD_STATUS_PATH, FOD_STATUS_ON);
return Void();
}
Return<void> FingerprintInscreen::onHideFODView() {
xiaomiFingerprintService->extCmd(COMMAND_NIT, PARAM_NIT_NONE);
set(DISPPARAM_PATH, DISPPARAM_FOD_BACKLIGHT_RESET);
set(FOD_STATUS_PATH, FOD_STATUS_OFF);
return Void();
}
Return<bool> FingerprintInscreen::handleAcquired(int32_t acquiredInfo, int32_t vendorCode) {
LOG(ERROR) << "acquiredInfo: " << acquiredInfo << ", vendorCode: " << vendorCode << "\n";
return false;
}
Return<bool> FingerprintInscreen::handleError(int32_t error, int32_t vendorCode) {
LOG(ERROR) << "error: " << error << ", vendorCode: " << vendorCode << "\n";
return false;
}
Return<void> FingerprintInscreen::setLongPressEnabled(bool) {
return Void();
}
Return<int32_t> FingerprintInscreen::getDimAmount(int32_t /*brightness*/) {
int realBrightness = get(BRIGHTNESS_PATH, 0);
float alpha;
alpha = (p1 * pow(realBrightness, 3) + p2 * pow(realBrightness, 2) + p3 * realBrightness + p4) / (realBrightness + q1);
return 255 * alpha;
}
Return<bool> FingerprintInscreen::shouldBoostBrightness() {
return false;
}
Return<void> FingerprintInscreen::setCallback(const sp<::vendor::lineage::biometrics::fingerprint::inscreen::V1_0::IFingerprintInscreenCallback>& callback) {
(void) callback;
return Void();
}
} // namespace implementation
} // namespace V1_0
} // namespace inscreen
} // namespace fingerprint
} // namespace biometrics
} // namespace lineage
} // namespace vendor
| 26.675978 | 157 | 0.720209 | Micha-Btz |
609d9b74bb2a0d9e88bcdb0dc8073e5f26c8c677 | 4,142 | cpp | C++ | src/game/client/tf2/c_tf_class_commando.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 6 | 2022-01-23T09:40:33.000Z | 2022-03-20T20:53:25.000Z | src/game/client/tf2/c_tf_class_commando.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | null | null | null | src/game/client/tf2/c_tf_class_commando.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 1 | 2022-02-06T21:05:23.000Z | 2022-02-06T21:05:23.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "c_tf_class_commando.h"
#include "usercmd.h"
//=============================================================================
//
// Commando Data Table
//
BEGIN_RECV_TABLE_NOBASE( C_PlayerClassCommando, DT_PlayerClassCommandoData )
RecvPropInt ( RECVINFO( m_ClassData.m_bCanBullRush ) ),
RecvPropInt ( RECVINFO( m_ClassData.m_bBullRush ) ),
RecvPropVector ( RECVINFO( m_ClassData.m_vecBullRushDir ) ),
RecvPropVector ( RECVINFO( m_ClassData.m_vecBullRushViewDir ) ),
RecvPropVector ( RECVINFO( m_ClassData.m_vecBullRushViewGoalDir ) ),
RecvPropFloat ( RECVINFO( m_ClassData.m_flBullRushTime ) ),
RecvPropFloat ( RECVINFO( m_ClassData.m_flDoubleTapForwardTime ) ),
END_RECV_TABLE()
BEGIN_PREDICTION_DATA_NO_BASE( C_PlayerClassCommando )
DEFINE_PRED_TYPEDESCRIPTION( m_ClassData, PlayerClassCommandoData_t ),
END_PREDICTION_DATA()
C_PlayerClassCommando::C_PlayerClassCommando( C_BaseTFPlayer *pPlayer ) :
C_PlayerClass( pPlayer )
{
m_ClassData.m_bCanBullRush = false;
m_ClassData.m_bBullRush = false;
m_ClassData.m_vecBullRushDir.Init();
m_ClassData.m_vecBullRushViewDir.Init();
m_ClassData.m_vecBullRushViewGoalDir.Init();
m_ClassData.m_flBullRushTime = COMMANDO_TIME_INVALID;
m_ClassData.m_flDoubleTapForwardTime = COMMANDO_TIME_INVALID;
}
C_PlayerClassCommando::~C_PlayerClassCommando()
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void C_PlayerClassCommando::ClassThink( void )
{
CheckBullRushState();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void C_PlayerClassCommando::PostClassThink( void )
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void C_PlayerClassCommando::ClassPreDataUpdate( void )
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void C_PlayerClassCommando::ClassOnDataChanged( void )
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void C_PlayerClassCommando::CreateMove( float flInputSampleTime, CUserCmd *pCmd )
{
if ( m_ClassData.m_bBullRush )
{
pCmd->viewangles = m_ClassData.m_vecBullRushViewDir;
QAngle angles = m_ClassData.m_vecBullRushViewDir;
engine->SetViewAngles( angles );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool C_PlayerClassCommando::CanGetInVehicle( void )
{
if ( m_ClassData.m_bBullRush )
return false;
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void C_PlayerClassCommando::CheckBullRushState( void )
{
if ( m_ClassData.m_bBullRush )
{
InterpolateBullRushViewAngles();
}
}
void C_PlayerClassCommando::InterpolateBullRushViewAngles( void )
{
// Determine the fraction.
if ( m_ClassData.m_flBullRushTime < COMMANDO_BULLRUSH_VIEWDELTA_TEST )
{
m_ClassData.m_vecBullRushViewDir = m_ClassData.m_vecBullRushViewGoalDir;
return;
}
float flFraction = 1.0f - ( ( m_ClassData.m_flBullRushTime - COMMANDO_BULLRUSH_VIEWDELTA_TEST ) / COMMANDO_BULLRUSH_VIEWDELTA_TIME );
QAngle angCurrent;
InterpolateAngles( m_ClassData.m_vecBullRushViewDir, m_ClassData.m_vecBullRushViewGoalDir, angCurrent, flFraction );
NormalizeAngles( angCurrent );
m_ClassData.m_vecBullRushViewDir = angCurrent;
}
| 32.359375 | 134 | 0.538146 | cstom4994 |
60a097f68086cbe4796387647d788327cf2a66ed | 54,428 | cpp | C++ | ComputeApplication/ComputeApp.cpp | Markyparky56/Toroidal-Volumetric-World | 6fd07736af88a347268cfaa01f3119b1596f8faa | [
"Apache-2.0"
] | null | null | null | ComputeApplication/ComputeApp.cpp | Markyparky56/Toroidal-Volumetric-World | 6fd07736af88a347268cfaa01f3119b1596f8faa | [
"Apache-2.0"
] | null | null | null | ComputeApplication/ComputeApp.cpp | Markyparky56/Toroidal-Volumetric-World | 6fd07736af88a347268cfaa01f3119b1596f8faa | [
"Apache-2.0"
] | null | null | null | #include "ComputeApp.hpp"
#include <glm/gtc/matrix_transform.hpp>
#include "coordinatewrap.hpp"
#include "syncout.hpp"
#include <random>
bool ComputeApp::Initialise(VulkanInterface::WindowParameters windowParameters)
{
// Setup some basic data
gameTime = 0.0;
settingsLastChangeTimes = { 0.f };
lockMouse = false;
reseedTerrain = false;
camera.SetPosition({ 0.f, 32.f, 0.f });
camera.LookAt({ 0.f, 0.f, 0.f }, { 0.f, 0.f, -1.f }, { 0.f, 1.f, 0.f });
camera.SetRotation(0.f, 180.f, 0.f);
nextFrameIndex = 0;
POINT pt;
pt.x = static_cast<LONG>(screenCentre.x);
pt.y = static_cast<LONG>(screenCentre.y);
ClientToScreen(static_cast<HWND>(hWnd), &pt);
SetCursorPos(pt.x, pt.y);
MouseState.Position.X = pt.x;
MouseState.Position.Y = pt.y;
hWnd = windowParameters.HWnd;
if (!setupVulkanAndCreateSwapchain(windowParameters))
{
return false;
}
screenCentre = { static_cast<float>(swapchain.size.width)/2, static_cast<float>(swapchain.size.height)/2 };
if (!setupTaskflow())
{
return false;
}
// Prepare setup tasks
bool resVMA, resCmdBufs, resRenderpass, resGpipe, resChnkMngr, resTerGen, resECS, resSurface;
auto[vma, commandBuffers, renderpass, gpipeline, frameres, chunkmanager, terraingen, surface, ecs] = systemTaskflow->emplace(
[&]() { resVMA = initialiseVulkanMemoryAllocator(); },
[&]() { resCmdBufs = setupCommandPoolAndBuffers(); },
[&]() { resRenderpass = setupRenderPass(); },
[&]() {
if (!resRenderpass) { resGpipe = false; return; }
resGpipe = setupGraphicsPipeline(); },
[&]() { setupFrameResources(); },
[&]() {
if (!resECS && !resVMA) { resChnkMngr = false; return; }
resChnkMngr = setupChunkManager(); },
[&]() { resTerGen = setupTerrainGenerator(); },
[&]() { resSurface = setupSurfaceExtractor(); },
[&]() { resECS = setupECS(); }
);
// Task dependencies
vma.precede(gpipeline);
vma.precede(chunkmanager);
vma.precede(frameres);
renderpass.precede(gpipeline);
ecs.precede(chunkmanager);
commandBuffers.precede(surface);
commandBuffers.precede(frameres);
// Execute and wait for completion
systemTaskflow->dispatch().get();
if (!resVMA || !resCmdBufs || !resRenderpass || !resGpipe || !resChnkMngr || !resTerGen || !resSurface || !resECS)
{
return false;
}
return true;
}
bool ComputeApp::InitMetrics()
{
logging = true;
logFile = createLogFile();
if (!logFile.is_open())
{
return false;
}
else
{
// Write data headings to first line, csv format
logFile << "key,heightElapsed,volumeElapsed,surfaceElapsed,timeElapsed,timeSinceRegistered" << std::endl;
return true;
}
}
bool ComputeApp::Update()
{
gameTime += TimerState.GetDeltaTime();
if (reseedTerrain)
{
syncout() << "Reseeding terrain, wait for device idle\n";
vkDeviceWaitIdle(*vulkanDevice); // Wait for idle (eck)
syncout() << "Waiting for compute taskflow to complete\n";
computeTaskflow->wait_for_all(); // Flush compute tasks
chunkManager->clear(); // Destroy old chunks
syncout() << "Reseeding terrain generator" << std::endl;
terrainGen->SetSeed(std::random_device()()); // Reseed terrain generator
reseedTerrain = false;
// Then continue as usual
}
auto[userUpdate, spawnChunks, renderList] = updateTaskflow->emplace(
[&]() { updateUser(); },
[&]() { checkForNewChunks(); },
[&]() { getChunkRenderList(); }
);
userUpdate.precede(spawnChunks);
userUpdate.precede(renderList);
spawnChunks.precede(renderList);
updateTaskflow->dispatch().get();
{
static float updateRefreshTimer = 0.f;
updateRefreshTimer += TimerState.GetDeltaTime();
if (updateRefreshTimer > 30.f)
{
updateTaskflow.reset(new tf::Taskflow(2));
updateRefreshTimer = 0.f;
}
}
drawChunks();
return true;
}
bool ComputeApp::Resize()
{
if (!createSwapchain(
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT
, true
, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)
)
{
return false;
}
if (!VulkanInterface::CreateFramebuffersForFrameResources(
*vulkanDevice
, renderPass
, swapchain
, frameResources)
)
{
return false;
}
return true;
}
bool ComputeApp::setupVulkanAndCreateSwapchain(VulkanInterface::WindowParameters windowParameters)
{
// Load Library
if (!VulkanInterface::LoadVulkanLoaderLibrary(vulkanLibrary))
{
return false;
}
// Get vkGetInstanceProcAddr function
if (!VulkanInterface::LoadVulkanFunctionGetter(vulkanLibrary))
{
return false;
}
// Load the global vulkan functions
if (!VulkanInterface::LoadGlobalVulkanFunctions())
{
return false;
}
// Create a Vulkan Instance tailored to our needs with required extensions (and validation layers if in debug)
VulkanInterface::InitVulkanHandle(vulkanInstance);
if (!VulkanInterface::CreateVulkanInstance(desiredInstanceExtensions, desiredLayers, "Compute Pipeline App", *vulkanInstance))
{
return false;
}
// Load Instance-level functions
if (!VulkanInterface::LoadInstanceLevelVulkanFunctions(*vulkanInstance, desiredInstanceExtensions))
{
return false;
}
// If we're in debug we can attach out debug callback function now
#if defined(_DEBUG) || defined(RELEASE_MODE_VALIDATION_LAYERS)
if (!VulkanInterface::SetupDebugCallback(*vulkanInstance, debugCallback, callback))
{
return false;
}
#endif
// Create presentation surface
VulkanInterface::InitVulkanHandle(*vulkanInstance, presentationSurface);
if (!VulkanInterface::CreatePresentationSurface(*vulkanInstance, windowParameters, *presentationSurface))
{
return false;
}
// Get available physical device
std::vector<VkPhysicalDevice> physicalDevices;
VulkanInterface::EnumerateAvailablePhysicalDevices(*vulkanInstance, physicalDevices);
for (auto & physicalDevice : physicalDevices)
{
VkPhysicalDeviceFeatures features;
VkPhysicalDeviceProperties properties;
VulkanInterface::GetFeaturesAndPropertiesOfPhysicalDevice(physicalDevice, features, properties);
syncout() << "Checking Device " << properties.deviceName << std::endl;
// Try to find a device which supports all our desired capabilities (graphics, compute, present);
// Make sure we have graphics on this devie
if (!VulkanInterface::SelectIndexOfQueueFamilyWithDesiredCapabilities(physicalDevice, VK_QUEUE_GRAPHICS_BIT, graphicsQueueParameters.familyIndex))
{
syncout() << "Does not support Graphics Queue" << std::endl;
continue;
}
if (!VulkanInterface::SelectQueueFamilyThatSupportsPresentationToGivenSurface(physicalDevice, *presentationSurface, presentQueueParameters.familyIndex))
{
syncout() << "Does not support present" << std::endl;
continue;
}
// Check how many concurrent threads we have available (like 4 or 8, depending on cpu)
auto numConcurrentThreads = std::thread::hardware_concurrency();
// We want to reserve one for rendering and allocate the rest for compute
uint32_t numComputeThreads = numConcurrentThreads - 1;
if (numComputeThreads < 1)
{
syncout() << "Number of compute threads is too low" << std::endl;
return false; // Bail, this isn't going to end well with a single thread
}
if (graphicsQueueParameters.familyIndex == computeQueueParameters.familyIndex
&& graphicsQueueParameters.familyIndex == presentQueueParameters.familyIndex)
// Yay, probably a nvidia GPU, all queues are capable at doing everything, only possible thing to improve on this
// is to find if we have a dedicated transfer queue and work out how to use that properly.
// Will use the same queue family for all commands for now.
{
std::vector<float> queuePriorities = { 1.f, 1.f, 1.f }; // One for the graphics queue, one for transfer, one for the present queue
// Check how many compute queues we can have
std::vector<VkQueueFamilyProperties> queueFamilies;
if (!VulkanInterface::CheckAvailableQueueFamiliesAndTheirProperties(physicalDevice, queueFamilies))
{
syncout() << "Failed to check available queue families" << std::endl;
return false;
}
// Construct requestedQueues vector
std::vector<VulkanInterface::QueueInfo> requestedQueues = {
{graphicsQueueParameters.familyIndex, queuePriorities} // One graphics queue, one transfer queue
};
VulkanInterface::InitVulkanHandle(vulkanDevice);
if (!VulkanInterface::CreateLogicalDevice(physicalDevice, requestedQueues, desiredDeviceExtensions, desiredLayers, &desiredDeviceFeatures, *vulkanDevice))
{
syncout() << "Failed to create logical device" << std::endl;
// Try again, maybe there's a better device?
continue;
}
else
{
vulkanPhysicalDevice = physicalDevice;
VulkanInterface::LoadDeviceLevelVulkanFunctions(*vulkanDevice, desiredDeviceExtensions);
// Retrieve graphics queue handle
vkGetDeviceQueue(*vulkanDevice, graphicsQueueParameters.familyIndex, 0, &graphicsQueue);
// Retrieve the transfer queue handle
// TODO: Find optimal transfer queue
vkGetDeviceQueue(*vulkanDevice, graphicsQueueParameters.familyIndex, 1, &transferQueue);
// Retrieve "present queue" handle
vkGetDeviceQueue(*vulkanDevice, graphicsQueueParameters.familyIndex, 2, &presentQueue);
break;
}
}
else // A more involved setup... coming soon to an application near you
{
syncout() << "Unsupported graphics card :(" << std::endl;
continue;
}
}
// Check we actually created a device...
if (!vulkanDevice)
{
syncout() << "Failed to create a vulkan device" << std::endl;
cleanupVulkan();
return false;
}
// Create that swapchain
if (!createSwapchain( VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT
, true
, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT))
{
syncout() << "Failed to create swapchain" << std::endl;
return false;
}
return true;
}
bool ComputeApp::setupTaskflow()
{
tfExecutor = std::make_shared<tf::Taskflow::Executor>(std::thread::hardware_concurrency()); // maybe -1?
updateTaskflow = std::make_unique<tf::Taskflow>(2);
graphicsTaskflow = std::make_unique<tf::Taskflow>(std::thread::hardware_concurrency()-2);
computeTaskflow = std::make_unique<tf::Taskflow>(std::thread::hardware_concurrency()-2);
systemTaskflow = std::make_unique<tf::Taskflow>(std::thread::hardware_concurrency());
return true;
}
bool ComputeApp::initialiseVulkanMemoryAllocator()
{
VmaAllocatorCreateInfo allocatorInfo = {};
allocatorInfo.physicalDevice = vulkanPhysicalDevice;
allocatorInfo.device = *vulkanDevice;
VkResult result = vmaCreateAllocator(&allocatorInfo, &allocator);
if (result != VK_SUCCESS)
{
return false;
}
else
{
return true;
}
}
bool ComputeApp::setupCommandPoolAndBuffers()
{
uint32_t numWorkers = static_cast<uint32_t>(graphicsTaskflow->num_workers());
commandPools = std::make_unique<TaskflowCommandPools>(
&*vulkanDevice
, graphicsQueueParameters.familyIndex
, numWorkers);
return true;
}
bool ComputeApp::setupRenderPass()
{
std::vector<VkAttachmentDescription> attachmentDescriptions = {
{
0,
swapchain.format,
VK_SAMPLE_COUNT_1_BIT,
VK_ATTACHMENT_LOAD_OP_CLEAR,
VK_ATTACHMENT_STORE_OP_STORE,
VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VK_ATTACHMENT_STORE_OP_DONT_CARE,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_PRESENT_SRC_KHR
},
{
0,
VK_FORMAT_D16_UNORM,
VK_SAMPLE_COUNT_1_BIT,
VK_ATTACHMENT_LOAD_OP_CLEAR,
VK_ATTACHMENT_STORE_OP_DONT_CARE,
VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VK_ATTACHMENT_STORE_OP_DONT_CARE,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL
}
};
VkAttachmentReference depthAttachment = {
1,
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL
};
std::vector<VulkanInterface::SubpassParameters> subpassParameters = {
{
VK_PIPELINE_BIND_POINT_GRAPHICS,
{}, // InputAttachments
{
{
0,
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL
}
}, // ColorAttachments
{}, // ResolveAttachments
&depthAttachment,
{}
}
};
std::vector<VkSubpassDependency> subpassDependecies = {
{
VK_SUBPASS_EXTERNAL,
0,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
VK_ACCESS_MEMORY_READ_BIT,
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
VK_DEPENDENCY_BY_REGION_BIT
},
{
0,
VK_SUBPASS_EXTERNAL,
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
VK_ACCESS_MEMORY_READ_BIT,
VK_DEPENDENCY_BY_REGION_BIT
}
};
if (!VulkanInterface::CreateRenderPass(*vulkanDevice, attachmentDescriptions, subpassParameters, subpassDependecies, renderPass))
{
return false;
}
return true;
}
bool ComputeApp::setupGraphicsPipeline()
{
// 1 for each frame index
viewprojUBuffers.resize(3);
modelUBuffers.resize(3);
lightUBuffers.resize(3);
viewprojAllocs.resize(3);
modelAllocs.resize(3);
lightAllocs.resize(3);
for (int i = 0; i < 3; i++)
{
if (!VulkanInterface::CreateBuffer(allocator
, sizeof(ViewProj)
, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT
, viewprojUBuffers[i]
, VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT
, VMA_MEMORY_USAGE_UNKNOWN
, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT
, VK_NULL_HANDLE, viewprojAllocs[i]))
{
return false;
}
VkPhysicalDeviceProperties props;
vkGetPhysicalDeviceProperties(vulkanPhysicalDevice, &props);
size_t deviceAlignment = props.limits.minUniformBufferOffsetAlignment;
dynamicAlignment = (sizeof(PerChunkData) / deviceAlignment) * deviceAlignment + ((sizeof(PerChunkData) % deviceAlignment) > 0 ? deviceAlignment : 0);
// Always mapped model buffer for easy copy
if (!VulkanInterface::CreateBuffer(allocator
, dynamicAlignment * 256
, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT
, modelUBuffers[i]
, VMA_ALLOCATION_CREATE_MAPPED_BIT | VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT
, VMA_MEMORY_USAGE_UNKNOWN
, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT
, VK_NULL_HANDLE, modelAllocs[i]))
{
return false;
}
if (!VulkanInterface::CreateBuffer(allocator
, sizeof(LightData)
, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT
, lightUBuffers[i]
, VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT
, VMA_MEMORY_USAGE_UNKNOWN
, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT
, VK_NULL_HANDLE, lightAllocs[i]))
{
return false;
}
}
// Descriptor set with uniform buffer
std::vector<VkDescriptorSetLayoutBinding> descriptorSetLayoutBindings = {
{ // ViewProj
0, // uint32_t binding
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // VkDescriptorType descriptorType
1, // uint32_t descriptorCount
VK_SHADER_STAGE_VERTEX_BIT, // VkShaderStageFlags stageFlags
nullptr // const VkSampler * pImmutableSamplers
},
{ // Model
1,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC,
1,
VK_SHADER_STAGE_VERTEX_BIT,
nullptr
},
{ // Light
2,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
1,
VK_SHADER_STAGE_FRAGMENT_BIT,
nullptr
}
};
if (!VulkanInterface::CreateDescriptorSetLayout(*vulkanDevice, descriptorSetLayoutBindings, descriptorSetLayout))
{
return false;
}
VkDescriptorPoolSize descriptorPoolSizeUB = {
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // VkDescriptorType type
2*3 // uint32_t descriptorCount
};
VkDescriptorPoolSize descriptorPoolSizeUBD = {
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, // VkDescriptorType type
1*3 // uint32_t descriptorCount
};
if (!VulkanInterface::CreateDescriptorPool(*vulkanDevice, false, 3, { descriptorPoolSizeUB, descriptorPoolSizeUBD }, descriptorPool))
{
return false;
}
if (!VulkanInterface::AllocateDescriptorSets(*vulkanDevice, descriptorPool, { descriptorSetLayout, descriptorSetLayout, descriptorSetLayout }, descriptorSets))
{
return false;
}
for (int i = 0; i < 3; i++)
{
VulkanInterface::BufferDescriptorInfo viewProjDescriptorUpdate = {
descriptorSets[i], // VkDescriptorSet TargetDescriptorSet
0, // uint32_t TargetDescriptorBinding
0, // uint32_t TargetArrayElement
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // VkDescriptorType TargetDescriptorType
{ // std::vector<VkDescriptorBufferInfo> BufferInfos
{
viewprojUBuffers[0], // VkBuffer buffer
0, // VkDeviceSize offset
VK_WHOLE_SIZE // VkDeviceSize range
}
}
};
VulkanInterface::BufferDescriptorInfo modelDescriptorUpdate = {
descriptorSets[i], // VkDescriptorSet TargetDescriptorSet
1, // uint32_t TargetDescriptorBinding
0, // uint32_t TargetArrayElement
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, // VkDescriptorType TargetDescriptorType
{ // std::vector<VkDescriptorBufferInfo> BufferInfos
{
modelUBuffers[0], // VkBuffer buffer
0, // VkDeviceSize offset
VK_WHOLE_SIZE // VkDeviceSize range
}
}
};
VulkanInterface::BufferDescriptorInfo lightDescriptorUpdate = {
descriptorSets[i], // VkDescriptorSet TargetDescriptorSet
2, // uint32_t TargetDescriptorBinding
0, // uint32_t TargetArrayElement
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // VkDescriptorType TargetDescriptorType
{ // std::vector<VkDescriptorBufferInfo> BufferInfos
{
lightUBuffers[0], // VkBuffer buffer
0, // VkDeviceSize offset
VK_WHOLE_SIZE // VkDeviceSize range
}
}
};
VulkanInterface::UpdateDescriptorSets(*vulkanDevice, {}, { viewProjDescriptorUpdate, modelDescriptorUpdate, lightDescriptorUpdate }, {}, {});
}
std::vector<unsigned char> vertex_shader_spirv;
if (!VulkanInterface::GetBinaryFileContents("Data/vert.spv", vertex_shader_spirv)) {
return false;
}
VkShaderModule vertex_shader_module;
if (!VulkanInterface::CreateShaderModule(*vulkanDevice, vertex_shader_spirv, vertex_shader_module)) {
return false;
}
std::vector<unsigned char> fragment_shader_spirv;
if (!VulkanInterface::GetBinaryFileContents("Data/frag.spv", fragment_shader_spirv)) {
return false;
}
VkShaderModule fragment_shader_module;
if (!VulkanInterface::CreateShaderModule(*vulkanDevice, fragment_shader_spirv, fragment_shader_module)) {
return false;
}
std::vector<VulkanInterface::ShaderStageParameters> shader_stage_params = {
{
VK_SHADER_STAGE_VERTEX_BIT, // VkShaderStageFlagBits ShaderStage
vertex_shader_module, // VkShaderModule ShaderModule
"main", // char const * EntryPointName;
nullptr // VkSpecializationInfo const * SpecializationInfo;
},
{
VK_SHADER_STAGE_FRAGMENT_BIT, // VkShaderStageFlagBits ShaderStage
fragment_shader_module, // VkShaderModule ShaderModule
"main", // char const * EntryPointName
nullptr // VkSpecializationInfo const * SpecializationInfo
}
};
std::vector<VkPipelineShaderStageCreateInfo> shader_stage_create_infos;
SpecifyPipelineShaderStages(shader_stage_params, shader_stage_create_infos);
std::vector<VkVertexInputBindingDescription> vertex_input_binding_descriptions = {
{
0, // uint32_t binding
6 * sizeof(float), // uint32_t stride
VK_VERTEX_INPUT_RATE_VERTEX // VkVertexInputRate inputRate
}
};
std::vector<VkVertexInputAttributeDescription> vertex_attribute_descriptions = {
{
0, // uint32_t location
0, // uint32_t binding
VK_FORMAT_R32G32B32_SFLOAT, // VkFormat format
0 // uint32_t offset
},
{
1,
0,
VK_FORMAT_R32G32B32_SFLOAT,
3 * sizeof(float)
}
};
VkPipelineVertexInputStateCreateInfo vertex_input_state_create_info;
VulkanInterface::SpecifyPipelineVertexInputState(vertex_input_binding_descriptions, vertex_attribute_descriptions, vertex_input_state_create_info);
VkPipelineInputAssemblyStateCreateInfo input_assembly_state_create_info;
VulkanInterface::SpecifyPipelineInputAssemblyState(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, false, input_assembly_state_create_info);
VulkanInterface::ViewportInfo viewport_infos = {
{ // std::vector<VkViewport> Viewports
{
0.0f, // float x
0.0f, // float y
500.0f, // float width
500.0f, // float height
0.0f, // float minDepth
1.0f // float maxDepth
}
},
{ // std::vector<VkRect2D> Scissors
{
{ // VkOffset2D offset
0, // int32_t x
0 // int32_t y
},
{ // VkExtent2D extent
500, // uint32_t width
500 // uint32_t height
}
}
}
};
VkPipelineViewportStateCreateInfo viewport_state_create_info;
VulkanInterface::SpecifyPipelineViewportAndScissorTestState(viewport_infos, viewport_state_create_info);
VkPipelineRasterizationStateCreateInfo rasterization_state_create_info;
VulkanInterface::SpecifyPipelineRasterisationState(false, false, VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, false, 0.0f, 0.0f, 0.0f, 1.0f, rasterization_state_create_info);
VkPipelineMultisampleStateCreateInfo multisample_state_create_info;
VulkanInterface::SpecifyPipelineMultisampleState(VK_SAMPLE_COUNT_1_BIT, false, 0.0f, nullptr, false, false, multisample_state_create_info);
std::vector<VkPipelineColorBlendAttachmentState> attachment_blend_states = {
{
false, // VkBool32 blendEnable
VK_BLEND_FACTOR_ONE, // VkBlendFactor srcColorBlendFactor
VK_BLEND_FACTOR_ONE, // VkBlendFactor dstColorBlendFactor
VK_BLEND_OP_ADD, // VkBlendOp colorBlendOp
VK_BLEND_FACTOR_ONE, // VkBlendFactor srcAlphaBlendFactor
VK_BLEND_FACTOR_ONE, // VkBlendFactor dstAlphaBlendFactor
VK_BLEND_OP_ADD, // VkBlendOp alphaBlendOp
VK_COLOR_COMPONENT_R_BIT | // VkColorComponentFlags colorWriteMask
VK_COLOR_COMPONENT_G_BIT |
VK_COLOR_COMPONENT_B_BIT |
VK_COLOR_COMPONENT_A_BIT
}
};
VkPipelineColorBlendStateCreateInfo blend_state_create_info;
VulkanInterface::SpecifyPipelineBlendState(false, VK_LOGIC_OP_COPY, attachment_blend_states, { 1.0f, 1.0f, 1.0f, 1.0f }, blend_state_create_info);
std::vector<VkDynamicState> dynamic_states = {
VK_DYNAMIC_STATE_VIEWPORT,
VK_DYNAMIC_STATE_SCISSOR
};
VkPipelineDynamicStateCreateInfo dynamic_state_create_info;
VulkanInterface::SpecifyPipelineDynamicStates(dynamic_states, dynamic_state_create_info);
if (!VulkanInterface::CreatePipelineLayout(*vulkanDevice
, { descriptorSetLayout, descriptorSetLayout, descriptorSetLayout }
, { }
, graphicsPipelineLayout)
)
{
return false;
}
VkPipelineDepthStencilStateCreateInfo depthStencilStateCreateInfo;
VulkanInterface::SpecifyPipelineDepthAndStencilState(true, true, VK_COMPARE_OP_LESS_OR_EQUAL, false, 0.f, 1.f, false, {}, {}, depthStencilStateCreateInfo);
VkGraphicsPipelineCreateInfo graphics_pipeline_create_info;
VulkanInterface::SpecifyGraphicsPipelineCreationParameters(0
, shader_stage_create_infos
, vertex_input_state_create_info
, input_assembly_state_create_info
, nullptr
, &viewport_state_create_info
, rasterization_state_create_info
, &multisample_state_create_info
, &depthStencilStateCreateInfo
, &blend_state_create_info
, &dynamic_state_create_info
, graphicsPipelineLayout
, renderPass
, 0
, VK_NULL_HANDLE
, -1
, graphics_pipeline_create_info
);
std::vector<VkPipeline> graphics_pipeline;
if (!VulkanInterface::CreateGraphicsPipelines(*vulkanDevice, { graphics_pipeline_create_info }, VK_NULL_HANDLE, graphics_pipeline)) {
return false;
}
graphicsPipeline = graphics_pipeline[0];
VulkanInterface::DestroyShaderModule(*vulkanDevice, vertex_shader_module);
VulkanInterface::DestroyShaderModule(*vulkanDevice, fragment_shader_module);
return true;
}
bool ComputeApp::setupFrameResources()
{
if (!VulkanInterface::CreateCommandPool(*vulkanDevice, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, graphicsQueueParameters.familyIndex, frameResourcesCmdPool))
{
return false;
}
if (!VulkanInterface::AllocateCommandBuffers(*vulkanDevice, frameResourcesCmdPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, numFrames, frameResourcesCmdBuffers))
{
return false;
}
for (uint32_t i = 0; i < numFrames; i++)
{
VulkanHandle(VkSemaphore) imageAcquiredSemaphore;
VulkanInterface::InitVulkanHandle(vulkanDevice, imageAcquiredSemaphore);
VulkanHandle(VkSemaphore) readyToPresentSemaphore;
VulkanInterface::InitVulkanHandle(vulkanDevice, readyToPresentSemaphore);
VulkanHandle(VkFence) drawingFinishedFence;
VulkanInterface::InitVulkanHandle(vulkanDevice, drawingFinishedFence);
VulkanHandle(VkImageView) depthAttachment;
VulkanInterface::InitVulkanHandle(vulkanDevice, depthAttachment);
depthImages.emplace_back(VkImage());
if (!VulkanInterface::CreateSemaphore(*vulkanDevice, *imageAcquiredSemaphore))
{
return false;
}
if (!VulkanInterface::CreateSemaphore(*vulkanDevice, *readyToPresentSemaphore))
{
return false;
}
if (!VulkanInterface::CreateFence(*vulkanDevice, true, *drawingFinishedFence))
{
return false;
}
frameResources.push_back(
{
frameResourcesCmdBuffers[i],
std::move(imageAcquiredSemaphore),
std::move(readyToPresentSemaphore),
std::move(drawingFinishedFence),
std::move(depthAttachment),
VulkanHandle(VkFramebuffer)()
}
);
VmaAllocation depthAllocation;
if (!VulkanInterface::Create2DImageAndView(*vulkanDevice
, allocator
, VK_FORMAT_D16_UNORM
, swapchain.size
, 1, 1
, VK_SAMPLE_COUNT_1_BIT
, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT
, VK_IMAGE_ASPECT_DEPTH_BIT
, depthImages.back()
, *frameResources[i].depthAttachment
, VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT
, VMA_MEMORY_USAGE_GPU_ONLY
, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT
, VK_NULL_HANDLE
, depthAllocation))
{
return false;
}
depthImagesAllocations.push_back(depthAllocation);
}
if (!VulkanInterface::CreateFramebuffersForFrameResources(*vulkanDevice, renderPass, swapchain, frameResources))
{
return false;
}
return true;
}
bool ComputeApp::setupChunkManager()
{
chunkManager = std::make_unique<ChunkManager>(registry.get(), ®istryMutex, &allocator, &*vulkanDevice);
return true;
}
bool ComputeApp::setupTerrainGenerator()
{
terrainGen = std::make_unique<TerrainGenerator>();
terrainGen->SetSeed(4422);
return true;
}
bool ComputeApp::setupSurfaceExtractor()
{
surfaceExtractor = std::make_unique<SurfaceExtractor>(&*vulkanDevice, &transferQueue, &transferQMutex, commandPools.get());
return true;
}
bool ComputeApp::setupECS()
{
registry = std::make_unique<entt::DefaultRegistry>();
registry->reserve(512);
return true;
}
void ComputeApp::shutdownVulkanMemoryAllocator()
{
if (allocator)
{
for (int i = 0; i < depthImages.size(); i++)
{
vmaDestroyImage(allocator, depthImages[i], depthImagesAllocations[i]);
}
vmaDestroyAllocator(allocator);
allocator = VK_NULL_HANDLE;
}
}
void ComputeApp::shutdownChunkManager()
{
chunkManager->clear();
}
void ComputeApp::shutdownGraphicsPipeline()
{
for (int i = 0; i < 3; i++)
{
vmaDestroyBuffer(allocator, viewprojUBuffers[i], viewprojAllocs[i]);
vmaDestroyBuffer(allocator, modelUBuffers[i], modelAllocs[i]);
vmaDestroyBuffer(allocator, lightUBuffers[i], lightAllocs[i]);
}
}
void ComputeApp::cleanupVulkan()
{
// VulkanHandle is useful for catching forgotten objects and ones with scoped/short-lifetimes,
// but for the final shutdown we need to be explicit
for (auto & frameRes : frameResources)
{
VulkanInterface::DestroySemaphore(*vulkanDevice, *frameRes.imageAcquiredSemaphore);
VulkanInterface::DestroySemaphore(*vulkanDevice, *frameRes.readyToPresentSemaphore);
VulkanInterface::DestroyFence(*vulkanDevice, *frameRes.drawingFinishedFence);
VulkanInterface::DestroyImageView(*vulkanDevice, *frameRes.depthAttachment);
VulkanInterface::DestroyFramebuffer(*vulkanDevice, *frameRes.framebuffer);
}
VulkanInterface::DestroySwapchain(*vulkanDevice, *swapchain.handle);
for (auto & imageView : swapchain.imageViews)
{
VulkanInterface::DestroyImageView(*vulkanDevice, *imageView);
}
VulkanInterface::DestroyCommandPool(*vulkanDevice, frameResourcesCmdPool);
VulkanInterface::DestroyDescriptorPool(*vulkanDevice, imGuiDescriptorPool);
VulkanInterface::DestroyRenderPass(*vulkanDevice, renderPass);
// Cleanup command buffers
commandPools->cleanup();
// Shutdown inline graphics pipeline
VulkanInterface::DestroyDescriptorSetLayout(*vulkanDevice, descriptorSetLayout);
VulkanInterface::DestroyDescriptorPool(*vulkanDevice, descriptorPool);
VulkanInterface::DestroyPipeline(*vulkanDevice, graphicsPipeline);
VulkanInterface::DestroyPipelineLayout(*vulkanDevice, graphicsPipelineLayout);
vkDestroyDevice(*vulkanDevice, nullptr); *vulkanDevice = VK_NULL_HANDLE;
#if defined(_DEBUG) || defined(RELEASE_MODE_VALIDATION_LAYERS)
vkDestroyDebugUtilsMessengerEXT(*vulkanInstance, callback, nullptr); callback = VK_NULL_HANDLE;
#endif
vkDestroySurfaceKHR(*vulkanInstance, *presentationSurface, nullptr); *presentationSurface = VK_NULL_HANDLE;
vkDestroyInstance(*vulkanInstance, nullptr); *vulkanInstance = VK_NULL_HANDLE;
VulkanInterface::ReleaseVulkanLoaderLibrary(vulkanLibrary);
}
void ComputeApp::OnMouseEvent()
{
}
void ComputeApp::updateUser()
{
bool moveLeft = (KeyboardState.Keys['A'].IsDown);
bool moveRight = (KeyboardState.Keys['D'].IsDown);
bool moveForward = (KeyboardState.Keys['W'].IsDown);
bool moveBackwards = (KeyboardState.Keys['S'].IsDown);
bool moveUp = (KeyboardState.Keys['Q'].IsDown);
bool moveDown = (KeyboardState.Keys['E'].IsDown);
bool toggleMouseLock = (KeyboardState.Keys[VK_F1].IsDown);
bool lookLeft = KeyboardState.Keys[VK_LEFT].IsDown;
bool lookRight = KeyboardState.Keys[VK_RIGHT].IsDown;
bool lookUp = KeyboardState.Keys[VK_UP].IsDown;
bool lookDown = KeyboardState.Keys[VK_DOWN].IsDown;
bool reseed = (KeyboardState.Keys[VK_F2].IsDown);
if (reseed)
{
if (gameTime >= settingsLastChangeTimes.reseed + 5.f)
{
reseedTerrain = true;
settingsLastChangeTimes.reseed = static_cast<float>(gameTime);
}
}
if (toggleMouseLock)
{
if (gameTime >= settingsLastChangeTimes.toggleMouseLock + buttonPressGracePeriod)
{
lockMouse = !lockMouse;
settingsLastChangeTimes.toggleMouseLock = static_cast<float>(gameTime);
if (lockMouse)
while (ShowCursor(FALSE) > 0);
else
ShowCursor(TRUE);
}
}
float dt = TimerState.GetDeltaTime();
camera.SetFrameTime(dt);
// Handle movement controls
auto camPos = camera.GetPosition();
if (moveLeft || moveRight)
{
if (moveLeft && !moveRight)
{
camera.StrafeLeft();
}
else if (moveRight && !moveLeft)
{
camera.StrafeRight();
}
}
if (moveForward || moveBackwards)
{
if (moveForward && !moveBackwards)
{
camera.MoveForward();
}
else if (moveBackwards && !moveForward)
{
camera.MoveBackward();
}
}
if (moveUp || moveDown)
{
if (moveUp && !moveDown)
{
camera.MoveUpward();
}
else if (moveDown && !moveUp)
{
camera.MoveDownward();
}
}
// Handle look controls
if (lockMouse)
{
mouseDelta = { MouseState.Position.X - swapchain.size.width / 2, MouseState.Position.Y - swapchain.size.height / 2 };
camera.Turn(-mouseDelta.x, -mouseDelta.y);
}
else
{
if (lookLeft || lookRight)
{
if (lookLeft && !lookRight)
{
camera.TurnLeft();
}
else if (lookRight && !lookLeft)
{
camera.TurnRight();
}
}
if (lookUp || lookDown)
{
if (lookUp && !lookDown)
{
camera.TurnUp();
}
else if (lookDown && !lookUp)
{
camera.TurnDown();
}
}
}
glm::vec3 pos = camera.GetPosition();
WrapCoordinates(pos);
camera.SetPosition(pos);
camera.Update();
if (lockMouse)
{
POINT pt;
pt.x = static_cast<LONG>(screenCentre.x);
pt.y = static_cast<LONG>(screenCentre.y);
ClientToScreen(static_cast<HWND>(hWnd), &pt);
SetCursorPos(pt.x, pt.y);
}
}
void ComputeApp::checkForNewChunks()
{
static float despawnTimer = 0.f;
despawnTimer += TimerState.GetDeltaTime();
if (despawnTimer > 1.f)
{
VulkanInterface::WaitUntilAllCommandsSubmittedToQueueAreFinished(graphicsQueue); // Ouch
chunkManager->despawnChunks(camera.GetPosition());
despawnTimer = 0.f;
}
auto chunkList = chunkManager->getChunkSpawnList(camera.GetPosition());
for (auto & chunk : chunkList)
{
if (chunk.second == ChunkManager::ChunkStatus::NotLoadedCached)
{
if (logging)
{
tp registered = hr_clock::now();
computeTaskflow->emplace([=, &logFile = logFile]() {
logEntryData data;
data.registered = registered;
loadFromChunkCache(chunk.first, data);
data.end = hr_clock::now();
insertEntry(logFile, data);
});
}
else
{
computeTaskflow->emplace([=]() {
loadFromChunkCache(chunk.first);
});
}
}
else if (chunk.second == ChunkManager::ChunkStatus::NotLoadedNotCached)
{
if (logging)
{
tp registered = hr_clock::now();
computeTaskflow->emplace([=, &logFile = logFile]() {
logEntryData data;
data.registered = registered;
generateChunk(chunk.first, data);
data.end = hr_clock::now();
insertEntry(logFile, data);
});
}
else
{
computeTaskflow->emplace([=]() {
generateChunk(chunk.first);
});
}
}
}
computeTaskflow->dispatch();
}
void ComputeApp::getChunkRenderList()
{
constexpr float screenDepth = static_cast<float>(TechnicalChunkDim * chunkViewDistance)*1.25f;
camera.GetViewMatrix(view);
proj = glm::perspective(glm::radians(90.f), static_cast<float>(swapchain.size.width) / static_cast<float>(swapchain.size.height), 0.1f, screenDepth);
proj[1][1] *= -1; // Correct projection for vulkan
frustum.Construct(screenDepth, proj, view);
chunkRenderList.clear();
chunkRenderList.reserve(256); // Revise size when frustum culling implemented
int i = 0;
registryMutex.lock();
// Sort chunks by world position so if we truncate the renderlist we preserve the closest chunks
registry->sort<WorldPosition>([&](auto const & lhs, auto const & rhs) {
return sqrdToroidalDistance(camera.GetPosition(), lhs.pos) < sqrdToroidalDistance(camera.GetPosition(), rhs.pos);
});
registry->view<WorldPosition, VolumeData, ModelData, AABB>().each(
[=, &i=i, ®istry=registry, &chunkRenderList=chunkRenderList, &camera=camera](const uint32_t entity, auto&&...)
{
auto[pos, modelData] = registry->get<WorldPosition, ModelData>(entity);
// Check if we need to shift chunk position by world dimension
glm::vec3 chunkPos = pos.pos;
CorrectChunkPosition(camera.GetPosition(), chunkPos);
if (modelData.indexCount > 0 && chunkIsWithinFrustum(entity) && chunkRenderList.size() < 256)
{
chunkRenderList.push_back(entity);
// Calculate model matrix for chunk
VmaAllocationInfo modelInfo;
vmaGetAllocationInfo(allocator, modelAllocs[nextFrameIndex], &modelInfo);
char * chunkDataPtr = static_cast<char*>(modelInfo.pMappedData);
glm::mat4 model = glm::translate(glm::mat4(1.f), chunkPos);
PerChunkData data = {
model
};
memcpy(&chunkDataPtr[i*dynamicAlignment], &data, sizeof(PerChunkData));
i++; // Move to next aligned position
}
}
);
registryMutex.unlock();
vmaFlushAllocation(allocator, modelAllocs[nextFrameIndex], 0, VK_WHOLE_SIZE);
VulkanInterface::BufferDescriptorInfo viewProjDescriptorUpdate = {
descriptorSets[nextFrameIndex], // VkDescriptorSet TargetDescriptorSet
0, // uint32_t TargetDescriptorBinding
0, // uint32_t TargetArrayElement
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // VkDescriptorType TargetDescriptorType
{ // std::vector<VkDescriptorBufferInfo> BufferInfos
{
viewprojUBuffers[nextFrameIndex], // VkBuffer buffer
0, // VkDeviceSize offset
VK_WHOLE_SIZE // VkDeviceSize range
}
}
};
VulkanInterface::BufferDescriptorInfo modelDescriptorUpdate = {
descriptorSets[nextFrameIndex], // VkDescriptorSet TargetDescriptorSet
1, // uint32_t TargetDescriptorBinding
0, // uint32_t TargetArrayElement
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, // VkDescriptorType TargetDescriptorType
{ // std::vector<VkDescriptorBufferInfo> BufferInfos
{
modelUBuffers[nextFrameIndex], // VkBuffer buffer
0, // VkDeviceSize offset
VK_WHOLE_SIZE // VkDeviceSize range
}
}
};
VulkanInterface::BufferDescriptorInfo lightDescriptorUpdate = {
descriptorSets[nextFrameIndex], // VkDescriptorSet TargetDescriptorSet
2, // uint32_t TargetDescriptorBinding
0, // uint32_t TargetArrayElement
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // VkDescriptorType TargetDescriptorType
{ // std::vector<VkDescriptorBufferInfo> BufferInfos
{
lightUBuffers[nextFrameIndex], // VkBuffer buffer
0, // VkDeviceSize offset
VK_WHOLE_SIZE // VkDeviceSize range
}
}
};
VulkanInterface::WaitForFences(*vulkanDevice, { *frameResources[nextFrameIndex].drawingFinishedFence }, false, std::numeric_limits<uint64_t>::max());
VulkanInterface::UpdateDescriptorSets(*vulkanDevice, {}, { viewProjDescriptorUpdate, modelDescriptorUpdate, lightDescriptorUpdate }, {}, {});
}
bool ComputeApp::drawChunks()
{
auto framePrep = [&](VkCommandBuffer commandBuffer, uint32_t imageIndex, VkFramebuffer framebuffer)
{
if (chunkRenderList.size() > 0)
{
if (!VulkanInterface::BeginCommandBufferRecordingOp(commandBuffer, VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, nullptr))
{
return false;
}
if (presentQueueParameters.familyIndex != graphicsQueueParameters.familyIndex)
{
VulkanInterface::ImageTransition imageTransitionBeforeDrawing = {
swapchain.images[imageIndex],
VK_ACCESS_MEMORY_READ_BIT,
VK_ACCESS_MEMORY_READ_BIT,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
presentQueueParameters.familyIndex,
graphicsQueueParameters.familyIndex,
VK_IMAGE_ASPECT_COLOR_BIT
};
VulkanInterface::SetImageMemoryBarrier(commandBuffer
, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT
, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT
, { imageTransitionBeforeDrawing }
);
}
// Draw
VulkanInterface::BeginRenderPass(commandBuffer, renderPass, framebuffer
, { {0,0}, swapchain.size } // Render Area (full frame size)
, { {0.5f, 0.5f, 0.5f, 1.f}, {1.f, 0.f } } // Clear Color, one for our draw area, one for our depth stencil
, VK_SUBPASS_CONTENTS_INLINE
);
VulkanInterface::BindPipelineObject(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, graphicsPipeline);
VkViewport viewport = {
0.f,
0.f,
static_cast<float>(swapchain.size.width),
static_cast<float>(swapchain.size.height),
0.f,
1.f
};
VulkanInterface::SetViewportStateDynamically(commandBuffer, 0, { viewport });
VkRect2D scissor = {
{
0, 0
},
{
swapchain.size.width,
swapchain.size.height
}
};
VulkanInterface::SetScissorStateDynamically(commandBuffer, 0, { scissor });
VmaAllocationInfo viewprojInfo;
vmaGetAllocationInfo(allocator, viewprojAllocs[imageIndex], &viewprojInfo);
VmaAllocationInfo lightInfo;
vmaGetAllocationInfo(allocator, lightAllocs[imageIndex], &lightInfo);
void * viewprojPtr;
ViewProj viewProj = {
view,
proj
};
vmaMapMemory(allocator, viewprojAllocs[imageIndex], &viewprojPtr);
memcpy(viewprojPtr, &viewProj, sizeof(ViewProj));
vmaUnmapMemory(allocator, viewprojAllocs[imageIndex]);
vmaFlushAllocation(allocator, viewprojAllocs[imageIndex], 0, VK_WHOLE_SIZE);
for (int i = 0; i < chunkRenderList.size(); i++)
{
registryMutex.lock();
ModelData modelData = registry->get<ModelData>(chunkRenderList[i]);
uint32_t dynamicOffset = i * static_cast<uint32_t>(dynamicAlignment);
VulkanInterface::BindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, graphicsPipelineLayout, 0, { descriptorSets[imageIndex] }, { dynamicOffset });
VulkanInterface::BindVertexBuffers(commandBuffer, 0, { {modelData.vertexBuffer, 0} });
VulkanInterface::BindIndexBuffer(commandBuffer, modelData.indexBuffer, 0, VK_INDEX_TYPE_UINT32);
VulkanInterface::DrawIndexedGeometry(commandBuffer, modelData.indexCount, 1, 0, 0, 0);
registryMutex.unlock();
}
VulkanInterface::EndRenderPass(commandBuffer);
if (presentQueueParameters.familyIndex != graphicsQueueParameters.familyIndex)
{
VulkanInterface::ImageTransition imageTransitionBeforePresent = {
swapchain.images[imageIndex],
VK_ACCESS_MEMORY_READ_BIT,
VK_ACCESS_MEMORY_READ_BIT,
VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
graphicsQueueParameters.familyIndex,
presentQueueParameters.familyIndex,
VK_IMAGE_ASPECT_COLOR_BIT
};
VulkanInterface::SetImageMemoryBarrier(commandBuffer
, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT
, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT
, { imageTransitionBeforePresent });
}
if (!VulkanInterface::EndCommandBufferRecordingOp(commandBuffer))
{
return false;
}
}
return true;
};
if (chunkRenderList.size() > 0)
{
LightData lightData;
lightData.lightDir = glm::vec3(-0.2f, -1.0f, -0.3f);
lightData.viewPos = camera.GetPosition();
lightData.lightAmbientColour = glm::vec3(0.2f, 0.2f, 0.2f);
lightData.lightDiffuseColour = glm::vec3(0.5f, 0.5f, 0.5f);
lightData.lightSpecularColour = glm::vec3(1.f, 1.f, 1.f);
lightData.objectColour = glm::vec3(1.f, 0.0f, 1.0f);
auto[mutex, transferCmdBuf] = commandPools->transferPools.getBuffer(nextFrameIndex);
// Technically only required once with static data, but if the lighting data were dynamic this makes sense
if (!VulkanInterface::UseStagingBufferToUpdateBufferWithDeviceLocalMemoryBound(
*vulkanDevice
, allocator
, sizeof(LightData)
, &lightData
, lightUBuffers[nextFrameIndex]
, 0
, 0
, VK_ACCESS_UNIFORM_READ_BIT
, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT
, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT
, transferQueue
, &transferQMutex
, *transferCmdBuf
, {}))
{
mutex->unlock();
return false;
}
mutex->unlock();
static uint32_t frameIndex = 0;
FrameResources & currentFrame = frameResources[frameIndex];
if (!VulkanInterface::WaitForFences(*vulkanDevice, { *currentFrame.drawingFinishedFence }, false, std::numeric_limits<uint64_t>::max()))
{
return false;
}
if (!VulkanInterface::ResetFences(*vulkanDevice, { *currentFrame.drawingFinishedFence }))
{
return false;
}
if (!VulkanInterface::PrepareSingleFrameOfAnimation(*vulkanDevice
, graphicsQueue
, presentQueue
, *swapchain.handle
, {}
, *currentFrame.imageAcquiredSemaphore
, *currentFrame.readyToPresentSemaphore
, *currentFrame.drawingFinishedFence
, framePrep
, currentFrame.commandBuffer
, currentFrame.framebuffer)
)
{
return false;
}
frameIndex = (frameIndex + 1) % frameResources.size();
nextFrameIndex = frameIndex;
return true;
}
else
{
//mutex->unlock();
return true;
}
}
bool ComputeApp::chunkIsWithinFrustum(uint32_t const entity)
{
auto[pos, aabb] = registry->get<WorldPosition, AABB>(entity);
glm::vec3 chunkPos = pos.pos;
CorrectChunkPosition(camera.GetPosition(), chunkPos);
return frustum.CheckCube(chunkPos, 32) || frustum.CheckCube(chunkPos, 16); // Oversized aabb for frustum check
}
void ComputeApp::loadFromChunkCache(EntityHandle handle)
{
registryMutex.lock();
glm::vec3 pos;
if (registry->valid(handle)) // Verify handle is still valid
{
pos = registry->get<WorldPosition>(handle).pos;
}
else
{
registryMutex.unlock();
return;
}
registryMutex.unlock();
ChunkCacheData data;
if (chunkManager->getChunkVolumeDataFromCache(chunkManager->chunkKey(pos), data)) // Retrieve data from cache
{
registryMutex.lock();
auto & volume = registry->get<VolumeData>(handle);
volume.volume = data;
registryMutex.unlock();
surfaceExtractor->extractSurface(handle, registry.get(), ®istryMutex, nextFrameIndex);
registryMutex.lock();
auto & model = registry->get<ModelData>(handle);
syncout() << handle << " generated, " << model.indexCount / 3 << " triangles\n";
registryMutex.unlock();
}
else // Chunk has fallen out of the cache
{
generateChunk(handle);
}
}
void ComputeApp::generateChunk(EntityHandle handle)
{
if (!ready) return; // Catch if we're about to shutdown
if (!registry->valid(handle)) return; // Chunk has been unloaded
else
{
registry->get<VolumeData>(handle).generating = true; // Mark volume as generating to stop it being unloaded during generation
}
//std::cout << handle << std::endl;
auto pos = registry->get<WorldPosition>(handle);
ChunkCacheData data = terrainGen->getChunkVolume(pos.pos);
registryMutex.lock();
{
auto & volume = registry->get<VolumeData>(handle);
volume.volume = data;
}
registryMutex.unlock();
surfaceExtractor->extractSurface(handle, registry.get(), ®istryMutex, nextFrameIndex);
registryMutex.lock();
{
auto[model, volume] = registry->get<ModelData, VolumeData>(handle);
volume.generating = false;
syncout() << handle << " generated, " << model.indexCount / 3 << " triangles\n";
}
registryMutex.unlock();
}
void ComputeApp::loadFromChunkCache(EntityHandle handle, logEntryData & logData)
{
registryMutex.lock();
glm::vec3 pos;
if (registry->valid(handle)) // Verify handle is still valid
{
pos = registry->get<WorldPosition>(handle).pos;
logData.key = chunkManager->chunkKey(pos);
}
else
{
registryMutex.unlock();
return;
}
registryMutex.unlock();
ChunkCacheData data;
if (chunkManager->getChunkVolumeDataFromCache(chunkManager->chunkKey(pos), data)) // Retrieve data from cache
{
registryMutex.lock();
auto & volume = registry->get<VolumeData>(handle);
volume.volume = data;
registryMutex.unlock();
surfaceExtractor->extractSurface(handle, registry.get(), ®istryMutex, nextFrameIndex);
registryMutex.lock();
auto & model = registry->get<ModelData>(handle);
syncout() << handle << " generated, " << model.indexCount / 3 << " triangles\n";
registryMutex.unlock();
logData.loadedFromCache = true;
}
else // Chunk has fallen out of the cache
{
generateChunk(handle, logData);
}
}
void ComputeApp::generateChunk(EntityHandle handle, logEntryData & logData)
{
if (!ready) return; // Catch if we're about to shutdown
if (!registry->valid(handle)) return; // Chunk has been unloaded
else
{
registry->get<VolumeData>(handle).generating = true; // Mark volume as generating to stop it being unloaded during generation
}
logData.start = hr_clock::now();
logData.loadedFromCache = false;
//std::cout << handle << std::endl;
auto pos = registry->get<WorldPosition>(handle);
logData.key = chunkManager->chunkKey(pos.pos);
ChunkCacheData data = terrainGen->getChunkVolume(pos.pos, logData);
registryMutex.lock();
{
auto & volume = registry->get<VolumeData>(handle);
volume.volume = data;
}
registryMutex.unlock();
logData.surfaceStart = hr_clock::now();
surfaceExtractor->extractSurface(handle, registry.get(), ®istryMutex, nextFrameIndex);
logData.surfaceEnd = hr_clock::now();
registryMutex.lock();
{
auto[model, volume] = registry->get<ModelData, VolumeData>(handle);
volume.generating = false;
syncout() << handle << " generated, " << model.indexCount / 3 << " triangles\n";
}
registryMutex.unlock();
}
void ComputeApp::Shutdown()
{
if (ready)
{
computeTaskflow->wait_for_all();
VulkanInterface::WaitForAllSubmittedCommandsToBeFinished(*vulkanDevice);
// We can shutdown some systems in parallel since they don't depend on each other
auto[vulkan, vma, chnkMngr, gpipe] = systemTaskflow->emplace(
[&]() { cleanupVulkan(); },
[&]() { shutdownVulkanMemoryAllocator(); },
[&]() { shutdownChunkManager(); },
[&]() { shutdownGraphicsPipeline(); }
);
tf::Task saveLogFile;
if (logging)
{
systemTaskflow->emplace(
[=, &logFile=logFile, &computeTaskflow=computeTaskflow]() {
computeTaskflow->wait_for_all();
logFile.close();
}
);
}
// Task dependencies
vma.precede(vulkan);
chnkMngr.precede(vulkan);
chnkMngr.precede(vma);
gpipe.precede(vulkan);
gpipe.precede(vma);
systemTaskflow->dispatch().get();
}
}
| 34.0175 | 209 | 0.650382 | Markyparky56 |
60a17035e15fd10750cace62d2ed925eecf2bb40 | 9,270 | cpp | C++ | _studio/shared/umc/codec/jpeg_dec/src/mfx_mjpeg_task.cpp | walter-bai/oneVPL-intel-gpu | e139c5060ac5b0ab8b4be0025922688a3db9b082 | [
"MIT"
] | 17 | 2021-04-29T10:49:44.000Z | 2022-03-27T04:49:40.000Z | _studio/shared/umc/codec/jpeg_dec/src/mfx_mjpeg_task.cpp | walter-bai/oneVPL-intel-gpu | e139c5060ac5b0ab8b4be0025922688a3db9b082 | [
"MIT"
] | 55 | 2021-05-12T18:40:13.000Z | 2022-03-15T22:21:02.000Z | _studio/shared/umc/codec/jpeg_dec/src/mfx_mjpeg_task.cpp | walter-bai/oneVPL-intel-gpu | e139c5060ac5b0ab8b4be0025922688a3db9b082 | [
"MIT"
] | 54 | 2021-05-04T15:24:30.000Z | 2022-03-24T17:50:21.000Z | // Copyright (c) 2004-2019 Intel Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <mfx_mjpeg_task.h>
#include "umc_defs.h"
#if defined (MFX_ENABLE_MJPEG_VIDEO_DECODE)
#include <umc_mjpeg_mfx_decode.h>
#include <jpegbase.h>
#include <mfx_common_decode_int.h>
CJpegTaskBuffer::CJpegTaskBuffer(void)
{
bufSize = 0;
dataSize = 0;
numPieces = 0;
pBuf = NULL;
imageHeaderSize = 0;
fieldPos = 0;
numScans = 0;
timeStamp = 0;
} // CJpegTaskBuffer::CJpegTaskBuffer(void)
CJpegTaskBuffer::~CJpegTaskBuffer(void)
{
Close();
} // CJpegTaskBuffer::~CJpegTaskBuffer(void)
void CJpegTaskBuffer::Close(void)
{
if(pBuf)
{
delete[] pBuf;
pBuf = NULL;
}
bufSize = 0;
dataSize = 0;
numPieces = 0;
} // void CJpegTaskBuffer::Close(void)
mfxStatus CJpegTaskBuffer::Allocate(const size_t size)
{
// check if the existing buffer is good enough
if (pBuf)
{
if (bufSize >= size)
{
return MFX_ERR_NONE;
}
Close();
}
// allocate the new buffer
pBuf = new mfxU8[size];
bufSize = size;
return MFX_ERR_NONE;
} // mfxStatus CJpegTaskBuffer::Allocate(const size_t size)
CJpegTask::CJpegTask(void)
{
m_numPic = 0;
m_numPieces = 0;
surface_work = NULL;
surface_out = NULL;
dst = NULL;
} // CJpegTask::CJpegTask(void)
CJpegTask::~CJpegTask(void)
{
Close();
} // CJpegTask::~CJpegTask(void)
void CJpegTask::Close(void)
{
// delete all buffers allocated
for (auto& pic: m_pics)
{
pic.reset(nullptr);
}
m_numPic = 0;
m_numPieces = 0;
} // void CJpegTask::Close(void)
mfxStatus CJpegTask::Initialize(UMC::VideoDecoderParams ¶ms,
UMC::FrameAllocator *pFrameAllocator,
mfxU16 rotation,
mfxU16 chromaFormat,
mfxU16 colorFormat)
{
// close the object before initialization
Close();
{
UMC::Status umcRes;
m_pMJPEGVideoDecoder.reset(new UMC::MJPEGVideoDecoderMFX);
m_pMJPEGVideoDecoder->SetFrameAllocator(pFrameAllocator);
umcRes = m_pMJPEGVideoDecoder->Init(¶ms);
if (umcRes != UMC::UMC_OK)
{
return ConvertUMCStatusToMfx(umcRes);
}
m_pMJPEGVideoDecoder->Reset();
switch(rotation)
{
case MFX_ROTATION_0:
umcRes = m_pMJPEGVideoDecoder->SetRotation(0);
break;
case MFX_ROTATION_90:
umcRes = m_pMJPEGVideoDecoder->SetRotation(90);
break;
case MFX_ROTATION_180:
umcRes = m_pMJPEGVideoDecoder->SetRotation(180);
break;
case MFX_ROTATION_270:
umcRes = m_pMJPEGVideoDecoder->SetRotation(270);
break;
}
if (umcRes != UMC::UMC_OK)
{
return ConvertUMCStatusToMfx(umcRes);
}
umcRes = m_pMJPEGVideoDecoder->SetColorSpace(chromaFormat, colorFormat);
if (umcRes != UMC::UMC_OK)
{
return ConvertUMCStatusToMfx(umcRes);
}
}
return MFX_ERR_NONE;
} // mfxStatus CJpegTask::Initialize(const VideoDecoderParams params,
void CJpegTask::Reset(void)
{
for(mfxU32 i=0; i<m_numPic; i++)
{
m_pics[i]->pieceOffset.clear();
m_pics[i]->pieceSize.clear();
m_pics[i]->pieceRSTOffset.clear();
m_pics[i]->scanOffset.clear();
m_pics[i]->scanSize.clear();
m_pics[i]->scanTablesOffset.clear();
m_pics[i]->scanTablesSize.clear();
}
m_numPic = 0;
m_numPieces = 0;
} // void CJpegTask::Reset(void)
mfxStatus CJpegTask::AddPicture(UMC::MediaDataEx *pSrcData,
const mfxU32 fieldPos)
{
const mfxU8* pSrc = static_cast<const mfxU8*>(pSrcData->GetDataPointer());
const size_t srcSize = pSrcData->GetDataSize();
const double timeStamp = pSrcData->GetTime();
const UMC::MediaDataEx::_MediaDataEx *pAuxData = pSrcData->GetExData();
uint32_t i, numPieces, maxNumPieces, numScans, maxNumScans;
mfxStatus mfxRes;
size_t imageHeaderSize;
uint32_t marker;
// we strongly need auxilary data
if (NULL == pAuxData)
{
return MFX_ERR_NULL_PTR;
}
// allocate the buffer
mfxRes = CheckBufferSize(srcSize);
if (MFX_ERR_NONE != mfxRes)
{
return mfxRes;
}
// allocates vectors for data offsets and sizes
maxNumPieces = pAuxData->count;
m_pics[m_numPic]->pieceOffset.resize(maxNumPieces);
m_pics[m_numPic]->pieceSize.resize(maxNumPieces);
m_pics[m_numPic]->pieceRSTOffset.resize(maxNumPieces);
// allocates vectors for scans parameters
maxNumScans = MAX_SCANS_PER_FRAME;
m_pics[m_numPic]->scanOffset.resize(maxNumScans);
m_pics[m_numPic]->scanSize.resize(maxNumScans);
m_pics[m_numPic]->scanTablesOffset.resize(maxNumScans);
m_pics[m_numPic]->scanTablesSize.resize(maxNumScans);
// get the number of pieces collected. SOS piece is supposed to be
imageHeaderSize = 0;
numPieces = 0;
numScans = 0;
for (i = 0; i < pAuxData->count; i += 1)
{
size_t chunkSize;
// get chunk size
chunkSize = (i + 1 < pAuxData->count) ?
(pAuxData->offsets[i + 1] - pAuxData->offsets[i]) :
(srcSize - pAuxData->offsets[i]);
marker = pAuxData->values[i] & 0xFF;
m_pics[m_numPic]->pieceRSTOffset[numPieces] = pAuxData->values[i] >> 8;
// some data
if (JM_SOS == marker)
{
// fill the chunks with the current chunk data
m_pics[m_numPic]->pieceOffset[numPieces] = pAuxData->offsets[i];
m_pics[m_numPic]->pieceSize[numPieces] = chunkSize;
numPieces += 1;
// fill scan parameters
m_pics[m_numPic]->scanOffset[numScans] = pAuxData->offsets[i];
m_pics[m_numPic]->scanSize[numScans] = chunkSize;
numScans += 1;
if (numScans >= maxNumScans)
{
throw UMC::UMC_ERR_INVALID_STREAM;
}
}
else if ((JM_DRI == marker || JM_DQT == marker || JM_DHT == marker) && 0 != numScans)
{
if(0 == m_pics[m_numPic]->scanTablesOffset[numScans])
{
m_pics[m_numPic]->scanTablesOffset[numScans] = pAuxData->offsets[i];
m_pics[m_numPic]->scanTablesSize[numScans] += chunkSize;
}
else
{
m_pics[m_numPic]->scanTablesSize[numScans] += chunkSize;
}
}
else if ((JM_RST0 <= marker) && (JM_RST7 >= marker))
{
// fill the chunks with the current chunk data
m_pics[m_numPic]->pieceOffset[numPieces] = pAuxData->offsets[i];
m_pics[m_numPic]->pieceSize[numPieces] = chunkSize;
numPieces += 1;
}
// some header before the regular JPEG data
else if (0 == numPieces)
{
imageHeaderSize += chunkSize;
}
}
// copy the data
if(m_pics[m_numPic]->bufSize < srcSize)
return MFX_ERR_NOT_ENOUGH_BUFFER;
std::copy(pSrc, pSrc + srcSize, m_pics[m_numPic]->pBuf);
m_pics[m_numPic]->dataSize = srcSize;
m_pics[m_numPic]->imageHeaderSize = imageHeaderSize;
m_pics[m_numPic]->timeStamp = timeStamp;
m_pics[m_numPic]->numScans = numScans;
m_pics[m_numPic]->numPieces = numPieces;
m_pics[m_numPic]->fieldPos = fieldPos;
// increment the number of pictures collected
m_numPic += 1;
// increment the number of pieces collected
m_numPieces += numPieces;
return MFX_ERR_NONE;
} // mfxStatus CJpegTask::AddPicture(UMC::MediaDataEx *pSrcData,
mfxStatus CJpegTask::CheckBufferSize(const size_t srcSize)
{
// add new entry in the array
m_pics.reserve(m_numPic+1);
while (m_pics.size() <= m_numPic)
{
m_pics.emplace_back(new CJpegTaskBuffer());
}
return m_pics[m_numPic]->Allocate(srcSize);
} // mfxStatus CJpegTask::CheckBufferSize(const size_t srcSize)
#endif // MFX_ENABLE_MJPEG_VIDEO_DECODE
| 29.150943 | 93 | 0.623301 | walter-bai |
60a182784210abbf7fdf9835e1100a0ded68585a | 13,215 | cpp | C++ | src/utilities/c_datamanager.cpp | Mankio/Wakfu-Builder | d2ce635dde2da21eee3639cf3facebd07750ab78 | [
"MIT"
] | null | null | null | src/utilities/c_datamanager.cpp | Mankio/Wakfu-Builder | d2ce635dde2da21eee3639cf3facebd07750ab78 | [
"MIT"
] | null | null | null | src/utilities/c_datamanager.cpp | Mankio/Wakfu-Builder | d2ce635dde2da21eee3639cf3facebd07750ab78 | [
"MIT"
] | null | null | null | #include "c_datamanager.h"
c_datamanager::c_datamanager()
{
dbmanager = nullptr;
networkManager = new c_networkManager();
#ifdef Q_OS_MACX
imageDir = QCoreApplication::applicationDirPath() + "/../Resources";
#else
imageDir = QCoreApplication::applicationDirPath();
#endif
QString val;
QFile file;
QString version;
QJsonDocument doc;
QJsonObject jObject_config;
QJsonObject jObject_version;
QJsonObject JObject_nameList;
new_soft_version = false;
file.setFileName("config.json");
if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
file.open(QIODevice::WriteOnly | QIODevice::Text);
c_bdd_password_dialog dial;
QString password;
if (dial.exec() == QDialog::Accepted) {
password = dial.get_password();
}
val = QString("{"
"\"version\" : \"1.68.0.179615\","
"\"url_json\" : \"https://wakfu.cdn.ankama.com/gamedata/\","
"\"url_image\" : \"https://static.ankama.com/wakfu/portal/game/item/64/\","
"\"url_soft_vers\" : \"https://mankio.github.io/Wakfu-Builder/repository/\","
"\"path_json\" : \"json\","
"\"path_images\" : \"images/Items\","
"\"filelist\" : { "
"\"1\": \"items.json\","
"\"2\": \"equipmentItemTypes.json\","
"\"3\": \"itemProperties.json\","
"\"4\": \"actions.json\","
"\"5\": \"states.json\","
"\"6\": \"jobsItems.json\","
"\"7\": \"recipes.json\""
"},"
"\"password\" : \"%1\""
"}").arg(password);
file.write(val.toUtf8());
} else {
val = file.readAll();
}
file.close();
doc = QJsonDocument::fromJson(val.toUtf8());
jObject_config = doc.object();
pathJson = jObject_config.value(QString("path_json")).toString();
version_local = jObject_config.value((QString("version"))).toString();
url_json = jObject_config.value(QString("url_json")).toString();
url_image = jObject_config.value(QString("url_image")).toString();
pathImage = jObject_config.value(QString("path_images")).toString();
password = jObject_config.value(QString("password")).toString();
url_soft_vers = jObject_config.value(QString("url_soft_vers")).toString();
JObject_nameList = jObject_config.value(QString("filelist")).toObject();
for(int i = 0; i < JObject_nameList.size(); ++i) {
_filelist.push_back(JObject_nameList.value(QString("%1").arg(i+1)).toString());
}
file.setFileName("components.xml");
file.open(QIODevice::ReadOnly | QIODevice::Text);
val = file.readAll();
file.close();
QXmlStreamReader reader(val);
while(!reader.atEnd() && !reader.hasError()) {
if(reader.readNext() == QXmlStreamReader::StartElement && reader.name() == "Version") {
soft_version = reader.readElementText();
}
}
networkManager = new c_networkManager();
networkManager->downloadFile(QUrl(url_soft_vers + "version.json"),pathJson);
QObject::connect(networkManager,SIGNAL(downloadFinished(QString)),this,SLOT(slot_check_softVersion(QString)));
stop = false;
}
void c_datamanager::checkVersion() {
if (networkManager != nullptr) {
QObject::disconnect(networkManager,SIGNAL(downloadFinished(QString)),this,SLOT(trigger_download_images()));
networkManager->deleteLater();
networkManager = nullptr;
}
networkManager = new c_networkManager();
networkManager->downloadFile(QUrl(url_json + "config.json"),pathJson);
QObject::connect(networkManager,SIGNAL(downloadFinished(QString)),this,SLOT(slot_downloadVersionFinished(QString)));
}
void c_datamanager::slot_check_softVersion(QString out) {
QObject::disconnect(networkManager,SIGNAL(downloadFinished(QString)),this,SLOT(slot_check_softVersion(QString)));
QString online_soft_version;
QJsonDocument doc;
doc = QJsonDocument::fromJson(out.toUtf8());
online_soft_version = doc.object().value(QString("version")).toString();
new_soft_version = online_soft_version.compare(soft_version);
qDebug() << new_soft_version << online_soft_version << soft_version;
emit update_soft_version();
}
void c_datamanager::slot_stop() {
stop = true;
}
void c_datamanager::empty_db() {
dbmanager->empty_database();
}
void c_datamanager::updateVersion(QString newVersion) {
QFile file;
QJsonDocument doc;
QString val;
file.setFileName("config.json");
file.open(QIODevice::ReadWrite | QIODevice::Text);
val = file.readAll();
val = val.replace(version_local,newVersion);
file.resize(0);
file.write(val.toUtf8());
version_local = newVersion;
return;
}
void c_datamanager::updateFiles() {
index_fileList = 0;
trigger_download_element();
}
void c_datamanager::slot_downloadVersionFinished(QString out) {
QObject::disconnect(networkManager,SIGNAL(downloadFinished(QString)),this,SLOT(slot_downloadVersionFinished(QString)));
QString version;
QJsonDocument doc;
doc = QJsonDocument::fromJson(out.toUtf8());
version = doc.object().value(QString("version")).toString();
emit newVersion(version);
}
void c_datamanager::slot_newVersion() {
QObject::disconnect(this,SIGNAL(newVersion()),this,SLOT(slot_newVersion()));
index_fileList = 0;
trigger_download_element();
}
void c_datamanager::trigger_download_element() {
if (networkManager != nullptr) {
QObject::disconnect(networkManager,SIGNAL(downloadFinished(QString)),this,SLOT(trigger_download_element()));
networkManager->deleteLater();
networkManager = nullptr;
}
if (index_fileList < _filelist.size()) {
networkManager = new c_networkManager();
QObject::connect(networkManager,SIGNAL(downloadFinished(QString)),this,SLOT(trigger_download_element()));
networkManager->downloadFile(url_json+version_local+"/"+ _filelist.at(index_fileList++),pathJson);
emit newFile(index_fileList,_filelist.size());
} else {
emit downloadFileFinished();
qInfo() << "All files have been downloaded";
}
}
void c_datamanager::parseActions() {
QFile file;
QJsonDocument doc;
QString val;
QJsonArray JsonArray;
file.setFileName(pathJson + "/actions.json");
file.open(QIODevice::ReadOnly | QIODevice::Text);
val = file.readAll();
file.close();
doc = QJsonDocument::fromJson(val.toUtf8());
JsonArray = doc.array();
for (QJsonArray::iterator it = JsonArray.begin(); it != JsonArray.end(); ++it) {
if (stop) break;
c_action value_action(it->toObject());
dbmanager->add_action(value_action);
}
stop = false;
}
void c_datamanager::setDBManager(c_dbmanager* _dbmanager) {
dbmanager = _dbmanager;
}
void c_datamanager::parseItemproperties() {
QFile file;
QJsonDocument doc;
QString val;
QJsonArray JsonArray;
file.setFileName(pathJson + "/itemProperties.json");
file.open(QIODevice::ReadOnly | QIODevice::Text);
val = file.readAll();
file.close();
doc = QJsonDocument::fromJson(val.toUtf8());
JsonArray = doc.array();
for (QJsonArray::iterator it = JsonArray.begin(); it != JsonArray.end(); ++it) {
if (stop) break;
c_itemProperties itemProperty(it->toObject());
dbmanager->add_itemProperty(itemProperty);
}
stop = false;
}
void c_datamanager::parseEquipementItemType() {
QFile file;
QJsonDocument doc;
QString val;
QJsonArray JsonArray;
file.setFileName(pathJson + "/equipmentItemTypes.json");
file.open(QIODevice::ReadOnly | QIODevice::Text);
val = file.readAll();
file.close();
doc = QJsonDocument::fromJson(val.toUtf8());
JsonArray = doc.array();
for (QJsonArray::iterator it = JsonArray.begin(); it != JsonArray.end(); ++it) {
if (stop) break;
c_equipmentItemTypes itemType(it->toObject());
dbmanager->add_equipmentItemType(itemType);
}
stop = false;
}
void c_datamanager::parseItem() {
parseFinal();
QFile file;
QJsonDocument doc;
QString val;
QJsonArray JsonArray;
file.setFileName(pathJson + QString("/items.json"));
file.open(QIODevice::ReadOnly | QIODevice::Text);
val = file.readAll();
file.close();
doc = QJsonDocument::fromJson(val.toUtf8());
JsonArray = doc.array();
QList<int> idList = dbmanager->getItemListId();
for (QJsonArray::iterator it = JsonArray.begin(); it != JsonArray.end(); ++it) {
if (stop) break;
if (it->toObject().value("definition").toObject().value("item").toObject().contains("shardsParameters")) {
dbmanager->add_enchantement_effect(c_enchantement_effect(it->toObject()));
} else {
c_item item(it->toObject(),dbmanager);
item.setIsFinal(!(id_non_final_list.contains(item.getId()) && item.getRarity() != 5 && item.getRarity() != 7 && item.getRarity() != 4));
if (item.getId() == 24811) {
qDebug() << item.getId() << item.getIsFinal();
qDebug() << id_non_final_list.contains(item.getId()) << item.getRarity() << item.getRarity();
}
emit newItem(item.getName(),it - JsonArray.begin(), JsonArray.size());
if (!idList.contains(item.getId())) {
dbmanager->add_item(item);
} else {
//qInfo() << item.getName() << " : Already in Database";
}
}
}
stop = false;
emit updateItemFinished();
}
QString c_datamanager::getVersion() {
return version_local;
}
void c_datamanager::getImages() {
QDir directory(imageDir + "/images/items");
QStringList images = directory.entryList(QStringList() << "*.png",QDir::Files);
QList<int> images_id;
foreach (QString id, images) {
images_id.push_back(id.replace(".png","").toInt());
}
_imageList = dbmanager->getImagesList().toSet().subtract(images_id.toSet()).toList();
index_imageList = 0;
trigger_download_images("OK");
}
void c_datamanager::trigger_download_images(QString out) {
if (out.isEmpty() || stop) {
qWarning() << "Error in downloading images";
emit newImage(_imageList.size(), _imageList.size());
emit downloadImageFinished();
stop = false;
return;
}
if (networkManager != nullptr) {
QObject::disconnect(networkManager,SIGNAL(downloadFinished(QString)),this,SLOT(trigger_download_images(QString)));
networkManager->deleteLater();
networkManager = nullptr;
}
if (index_imageList < _imageList.size()) {
networkManager = new c_networkManager();
QObject::connect(networkManager,SIGNAL(downloadFinished(QString)),this,SLOT(trigger_download_images(QString)));
QString url = url_image + QString("%1.png").arg(_imageList.at(index_imageList++));
networkManager->downloadFile(url,pathImage);
emit newImage(index_imageList, _imageList.size());
} else {
qWarning() << "All files have been downloaded";
emit downloadImageFinished();
}
}
void c_datamanager::savePassword(QString _password) {
QFile file;
QJsonDocument doc;
QString val;
QJsonObject jObject_config;
file.setFileName("config.json");
file.open(QIODevice::ReadWrite | QIODevice::Text);
val = file.readAll();
doc = QJsonDocument::fromJson(val.toUtf8());
jObject_config = doc.object();
jObject_config["password"] = _password;
doc.setObject(jObject_config);
file.resize(0);
file.write(doc.toJson());
file.close();
password = _password;
return;
}
void c_datamanager::parseStates() {
QFile file;
QJsonDocument doc;
QString val;
QJsonArray JsonArray;
file.setFileName(pathJson + QString("/states.json"));
file.open(QIODevice::ReadOnly | QIODevice::Text);
val = file.readAll();
file.close();
doc = QJsonDocument::fromJson(val.toUtf8());
JsonArray = doc.array();
QString description;
for (QJsonArray::iterator it = JsonArray.begin(); it != JsonArray.end(); ++it) {
c_state state(it->toObject());
dbmanager->add_state(state);
}
}
QString c_datamanager::getPassword() {
return password;
}
void c_datamanager::parseFinal() {
QFile file;
QJsonDocument doc;
QString val;
QJsonArray JsonArray;
file.setFileName(pathJson + QString("/recipes.json"));
file.open(QIODevice::ReadOnly | QIODevice::Text);
val = file.readAll();
file.close();
doc = QJsonDocument::fromJson(val.toUtf8());
JsonArray = doc.array();
QList<int> id_list;
for (QJsonArray::iterator it = JsonArray.begin(); it != JsonArray.end(); ++it) {
int id = it->toObject().value("upgradeItemId").toInt();
if (id != 0) {
if (id == 24811) {
qDebug() << id;
}
id_list.push_back(id);
}
}
id_non_final_list = id_list;
}
bool c_datamanager::isNewSoftVersion() {
return new_soft_version;
}
| 34.685039 | 148 | 0.638138 | Mankio |
60a1869a3e87dad92df0e58863055af561ea3afa | 1,902 | cpp | C++ | src/scripts/scripts/outland/tempest_keep/the_mechanar/instance_mechanar.cpp | Subv/diamondcore | e11891587736b6308e554f71cb56e8df1a1812ad | [
"OpenSSL"
] | 1 | 2018-01-17T08:11:17.000Z | 2018-01-17T08:11:17.000Z | src/scripts/scripts/outland/tempest_keep/the_mechanar/instance_mechanar.cpp | Subv/diamondcore | e11891587736b6308e554f71cb56e8df1a1812ad | [
"OpenSSL"
] | null | null | null | src/scripts/scripts/outland/tempest_keep/the_mechanar/instance_mechanar.cpp | Subv/diamondcore | e11891587736b6308e554f71cb56e8df1a1812ad | [
"OpenSSL"
] | null | null | null | /* Copyright (C) 2006 - 2010 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* ScriptData
SDName: Instance_Mechanar
SD%Complete: 20
SDComment:
SDCategory: Mechanar
EndScriptData */
#include "precompiled.h"
#include "mechanar.h"
struct instance_mechanar : public ScriptedInstance
{
instance_mechanar(Map* pMap) : ScriptedInstance(pMap) {Initialize();};
uint32 m_auiEncounter[MAX_ENCOUNTER];
void Initialize()
{
memset(&m_auiEncounter, 0, sizeof(m_auiEncounter));
}
void SetData(uint32 uiType, uint32 uiData)
{
switch(uiType)
{
case TYPE_SEPETHREA:
m_auiEncounter[0] = uiData;
break;
}
}
uint32 GetData(uint32 uiType)
{
if (uiType == TYPE_SEPETHREA)
return m_auiEncounter[0];
return 0;
}
};
InstanceData* GetInstanceData_instance_mechanar(Map* pMap)
{
return new instance_mechanar(pMap);
}
void AddSC_instance_mechanar()
{
Script *newscript;
newscript = new Script;
newscript->Name = "instance_mechanar";
newscript->GetInstanceData = &GetInstanceData_instance_mechanar;
newscript->RegisterSelf();
}
| 27.171429 | 81 | 0.694532 | Subv |
60a2126b510cc7da18554e9c9e77c7ba7807555f | 3,202 | hpp | C++ | external/boost_1_60_0/qsboost/fusion/container/vector/detail/cpp03/vector40.hpp | wouterboomsma/quickstep | a33447562eca1350c626883f21c68125bd9f776c | [
"MIT"
] | 1 | 2019-06-27T17:54:13.000Z | 2019-06-27T17:54:13.000Z | external/boost_1_60_0/qsboost/fusion/container/vector/detail/cpp03/vector40.hpp | wouterboomsma/quickstep | a33447562eca1350c626883f21c68125bd9f776c | [
"MIT"
] | null | null | null | external/boost_1_60_0/qsboost/fusion/container/vector/detail/cpp03/vector40.hpp | wouterboomsma/quickstep | a33447562eca1350c626883f21c68125bd9f776c | [
"MIT"
] | null | null | null | /*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
Copyright (c) 2001-2011 Joel de Guzman
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)
==============================================================================*/
#if !defined(FUSION_VECTOR40_05052005_0208)
#define FUSION_VECTOR40_05052005_0208
#include <qsboost/fusion/support/config.hpp>
#include <qsboost/fusion/container/vector/detail/cpp03/vector40_fwd.hpp>
#include <qsboost/fusion/support/sequence_base.hpp>
#include <qsboost/fusion/support/is_sequence.hpp>
#include <qsboost/fusion/support/detail/access.hpp>
#include <qsboost/fusion/iterator/next.hpp>
#include <qsboost/fusion/iterator/deref.hpp>
#include <qsboost/fusion/sequence/intrinsic/begin.hpp>
#include <qsboost/fusion/container/vector/detail/at_impl.hpp>
#include <qsboost/fusion/container/vector/detail/value_at_impl.hpp>
#include <qsboost/fusion/container/vector/detail/begin_impl.hpp>
#include <qsboost/fusion/container/vector/detail/end_impl.hpp>
#include <qsboost/mpl/void.hpp>
#include <qsboost/mpl/int.hpp>
#include <qsboost/mpl/at.hpp>
#include <qsboost/mpl/bool.hpp>
#include <qsboost/mpl/vector/vector40.hpp>
#include <qsboost/type_traits/is_convertible.hpp>
#include <qsboost/utility/enable_if.hpp>
#include <qsboost/preprocessor/dec.hpp>
#include <qsboost/preprocessor/iteration/iterate.hpp>
#include <qsboost/preprocessor/repetition/enum.hpp>
#include <qsboost/preprocessor/repetition/enum_shifted.hpp>
#include <qsboost/preprocessor/repetition/enum_params.hpp>
#include <qsboost/preprocessor/repetition/enum_binary_params.hpp>
#include <qsboost/preprocessor/repetition/repeat_from_to.hpp>
#if !defined(QSBOOST_FUSION_DONT_USE_PREPROCESSED_FILES)
#include <qsboost/fusion/container/vector/detail/cpp03/preprocessed/vector40.hpp>
#else
#if defined(__WAVE__) && defined(QSBOOST_FUSION_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve: 2, line: 0, output: "preprocessed/vector40.hpp")
#endif
/*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
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)
This is an auto-generated file. Do not edit!
==============================================================================*/
#if defined(__WAVE__) && defined(QSBOOST_FUSION_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve: 1)
#endif
namespace qsboost { namespace fusion
{
struct vector_tag;
struct fusion_sequence_tag;
struct random_access_traversal_tag;
#define FUSION_HASH #
// expand vector31 to vector40
#define QSBOOST_PP_FILENAME_1 <qsboost/fusion/container/vector/detail/cpp03/vector_n.hpp>
#define QSBOOST_PP_ITERATION_LIMITS (31, 40)
#include QSBOOST_PP_ITERATE()
#undef FUSION_HASH
}}
#if defined(__WAVE__) && defined(QSBOOST_FUSION_CREATE_PREPROCESSED_FILES)
#pragma wave option(output: null)
#endif
#endif // BOOST_FUSION_DONT_USE_PREPROCESSED_FILES
#endif
| 39.04878 | 89 | 0.721736 | wouterboomsma |
60a2d28d2b4c7c10ed56c34c543a01916887fc23 | 2,008 | cpp | C++ | planning/scenario_planning/lane_driving/behavior_planning/lane_change_planner/src/state/state_base_class.cpp | betsyweilin/Pilot.Auto | 41946ba1f5b521d347581cb7bdaffe1e39a7ba33 | [
"Apache-2.0"
] | null | null | null | planning/scenario_planning/lane_driving/behavior_planning/lane_change_planner/src/state/state_base_class.cpp | betsyweilin/Pilot.Auto | 41946ba1f5b521d347581cb7bdaffe1e39a7ba33 | [
"Apache-2.0"
] | null | null | null | planning/scenario_planning/lane_driving/behavior_planning/lane_change_planner/src/state/state_base_class.cpp | betsyweilin/Pilot.Auto | 41946ba1f5b521d347581cb7bdaffe1e39a7ba33 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2020 Tier IV, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <lane_change_planner/state/state_base_class.h>
namespace lane_change_planner
{
std::ostream & operator<<(std::ostream & ostream, const State & state)
{
switch (state) {
case State::NO_STATE:
ostream << std::string("NO_STATE");
break;
case State::FOLLOWING_LANE:
ostream << std::string("FOLLOWING_LANE");
break;
case State::EXECUTING_LANE_CHANGE:
ostream << std::string("EXECUTING_LANE_CHANGE");
break;
case State::ABORTING_LANE_CHANGE:
ostream << std::string("ABORTING_LANE_CHANGE");
break;
case State::STOPPING_LANE_CHANGE:
ostream << std::string("STOPPING_LANE_CHANGE");
break;
case State::FORCING_LANE_CHANGE:
ostream << std::string("FORCING_LANE_CHANGE");
break;
case State::BLOCKED_BY_OBSTACLE:
ostream << std::string("BLOCKED_BY_OBSTACLE");
break;
default:
ostream << std::string("NO_STATE");
break;
}
return ostream;
}
StateBase::StateBase(
const Status & status, const std::shared_ptr<DataManager> & data_manager_ptr,
const std::shared_ptr<RouteHandler> & route_handler_ptr)
: status_(status), data_manager_ptr_(data_manager_ptr), route_handler_ptr_(route_handler_ptr)
{
}
Status StateBase::getStatus() const { return status_; }
DebugData StateBase::getDebugData() const { return debug_data_; }
} // namespace lane_change_planner
| 32.387097 | 93 | 0.708665 | betsyweilin |
60a80dc21d8b76024e04b52b35191ee127b8c5b6 | 7,942 | hh | C++ | sources/superlibs/owuefi/inc/ll/uefi/tables/boot_services.hh | twrl/conurbation | 0e92178fa36528acd3bbf1d1b6e417e7c1bbe659 | [
"MIT"
] | 5 | 2016-05-17T23:03:06.000Z | 2019-07-24T18:23:00.000Z | sources/superlibs/owuefi/inc/ll/uefi/tables/boot_services.hh | twrl/conurbation | 0e92178fa36528acd3bbf1d1b6e417e7c1bbe659 | [
"MIT"
] | null | null | null | sources/superlibs/owuefi/inc/ll/uefi/tables/boot_services.hh | twrl/conurbation | 0e92178fa36528acd3bbf1d1b6e417e7c1bbe659 | [
"MIT"
] | null | null | null | #pragma once
#include "ll/uefi/abi.hh"
namespace ll::UEFI::Tables {
typedef status_t(efiabi allocate_pages_f)(
allocate_type_t type, memory_type_t memoryType, uintptr_t pages, uint64_t * memory);
typedef status_t(efiabi allocate_pool_f)(memory_type_t poolType, uintptr_t size, void** buffer);
typedef status_t(efiabi calculate_crc32_f)(void* data, uintptr_t dataSize, uint32_t* crc32);
typedef status_t(efiabi close_event_f)(event_t event);
typedef status_t(efiabi close_protocol_f)(
handle_t handle, const guid_t * protocol, handle_t agentHandle, handle_t controllerHandle);
typedef void(efiabi copy_mem_f)(void* destination, void* source, uintptr_t length);
typedef status_t(efiabi create_event_f)(
uint32_t type, tpl_t notifyTpl, event_notify_f * notifyFunction, void* notifyContext, event_t* event);
typedef status_t(efiabi create_event_ex_f)(uint32_t type, tpl_t notifyTpl, event_notify_f * notifyFunction,
const void* notifyContext, const guid_t* eventGroup, event_t* event);
typedef status_t(efiabi exit_f)(
handle_t imageHandle, status_t exitStatus, uintptr_t exitDataSize, char16_t* exitData);
typedef status_t(efiabi exit_boot_services_f)(handle_t imageHandle, uintptr_t mapKey);
typedef status_t(efiabi free_pages_f)(uint64_t memory, uintptr_t pages);
typedef status_t(efiabi free_pool_t)(void* buffer);
typedef status_t(efiabi get_memory_map_f)(uintptr_t * memoryMapSize, memory_descriptor_t * memoryMap,
uintptr_t * mapKey, uintptr_t * descriptorSize, uint32_t * descriptorVersion);
typedef status_t(efiabi get_next_monotonic_count_f)(uint64_t * count);
typedef status_t(efiabi handle_protocol_f)(handle_t handle, const guid_t * protocol, void** interface);
typedef status_t(efiabi install_configuration_table_f)(const guid_t * guid, void* table);
typedef status_t(efiabi install_protocol_interface_f)(
handle_t * handle, const guid_t * protocol, interface_type_t interfaceType, void* interface);
typedef status_t(efiabi load_image_f)(bool_t bootPolicy, handle_t parentImageHandle,
Protocols::device_path_p * devicePath, void* sourcebuffer, uintptr_t sourceSize, handle_t* imageHandle);
typedef status_t(efiabi locate_device_path_f)(
const guid_t * protocol, Protocols::device_path_p * *devicePath, handle_t * device);
typedef status_t(efiabi locate_handle_f)(
locate_search_type_t searchType, const guid_t * protocol, void* searchKey, uintptr_t* bufferSize, handle_t* buffer);
typedef status_t(efiabi locate_protocol_f)(const guid_t * protocol, void* registration, void** interface);
typedef status_t(efiabi open_protocol_f)(handle_t handle, const guid_t * protocol, void** interface,
handle_t agentHandle, handle_t controllerHandle, uint32_t attributes);
typedef status_t(efiabi open_protocol_information_f)(
handle_t handle, const guid_t * protocol, open_protocol_information_entry_t * *entryBuffer, uintptr_t * entryCount);
typedef tpl_t(efiabi raise_tpl_f)(tpl_t newTpl);
typedef void(efiabi restore_tpl_f)(tpl_t oldTpl);
typedef status_t(efiabi reinstall_protocol_interface_f)(
handle_t handle, const guid_t * protocol, void* oldInterface, void* newInterface);
typedef status_t(efiabi register_protocol_notify_f)(const guid_t * protocol, event_t event, void** registration);
typedef void(efiabi set_mem_f)(void* buffer, uintptr_t size, uint8_t value);
// set_event
typedef status_t(efiabi set_timer_f)(event_t event, timer_delay_t type, uint64_t triggerTime);
typedef status_t(efiabi set_watchdog_timer_f)(
uintptr_t timeout, uint64_t watchdogCode, uintptr_t dataSize, char16_t* watchdogData);
typedef status_t(efiabi signal_event_f)(event_t event);
typedef status_t(efiabi stall_f)(uintptr_t microseconds);
typedef status_t(efiabi start_image_f)(handle_t imageHandle, uintptr_t * exitDataSize, char16_t** exitData);
typedef status_t(efiabi uninstall_protocol_interface_f)(handle_t handle, const guid_t * protocol, void* interface);
typedef status_t(efiabi wait_for_event_f)(uintptr_t numberOfEvents, event_t * event, uintptr_t * index);
typedef status_t(efiabi check_event_f)(event_t event);
typedef status_t(efiabi unload_image_f)(handle_t imageHandle);
// typedef STATUS(EFIAPI * CONNECT_CONTROLLER)(IN HANDLE ControllerHandle, IN HANDLE
// *DriverImageHandle, OPTIONAL IN Protocols::device_path_pROTOCOL *RemainingDevicePath, OPTIONAL IN
// BOOLEAN Recursive)
typedef status_t(efiabi connect_controller_f)(handle_t ControllerHandle, handle_t * driverImageHandle,
Protocols::device_path_p * remainingDevicePath, bool_t recursive);
// typedef STATUS(EFIAPI * DISCONNECT_CONTROLLER)(IN HANDLE ControllerHandle, IN
// HANDLE DriverImageHandle, OPTIONAL IN HANDLE ChildHandle OPTIONAL)
typedef status_t(efiabi disconnect_controller_f)(
handle_t ControllerHandle, handle_t driverImageHandle, handle_t ChildHandle);
// typedef STATUS(EFIAPI * PROTOCOLS_PER_HANDLE)(IN HANDLE Handle, OUT GUID
// ***ProtocolBuffer, OUT UINTN *ProtocolBufferCount)
typedef status_t(efiabi protocols_per_handle_f)(
handle_t handle, const guid_t * **protocolBuffer, uintptr_t * protocolBufferCount);
// typedef STATUS(EFIAPI * LOCATE_HANDLE_BUFFER)(IN LOCATE_SEARCH_TYPE SearchType, IN
// GUID *Protocol, OPTIONAL IN VOID *SearchKey, OPTIONAL IN OUT UINTN *NoHandles, OUT HANDLE
// **Buffer)
typedef status_t(efiabi locate_handle_buffer_f)(
locate_search_type_t searchType, const guid_t * protocol, void* searchKey, uintptr_t* noHandles, handle_t** buffer);
typedef status_t(efiabi install_multiple_protocol_interfaces_f)(handle_t * handle, ...);
typedef status_t(efiabi uninstall_multiple_protocol_interfaces_f)(handle_t * handle, ...);
struct boot_services_t: table_header_t {
raise_tpl_f* RaiseTPL;
restore_tpl_f* RestoreTPL;
allocate_pages_f* AllocatePages;
free_pages_f* FreePages;
get_memory_map_f* GetMemoryMap;
allocate_pool_f* AllocatePool;
free_pool_t* FreePool;
create_event_f* CreateEvent;
set_timer_f* SetTimer;
wait_for_event_f* WaitForEvent;
signal_event_f* SignalEvent;
close_event_f* CloseEvent;
check_event_f* CheckEvent; //?
install_protocol_interface_f* InstallProtocolInterface;
reinstall_protocol_interface_f* ReinstallProtocolInterface;
uninstall_protocol_interface_f* UninstallProtocolInterface;
handle_protocol_f* HandleProtocol;
void* _reserved;
register_protocol_notify_f* RegisterProtocolNotify;
locate_handle_f* LocateHandle;
locate_device_path_f* LocateDevicePath;
install_configuration_table_f* InstallConfigurationTable;
load_image_f* LoadImage;
start_image_f* StartImage;
exit_f* Exit;
unload_image_f* UnloadImage; //?
exit_boot_services_f* ExitBootServices;
get_next_monotonic_count_f* GetNextMonotonicCount;
stall_f* Stall;
set_watchdog_timer_f* SetWatchdogTimer;
connect_controller_f* ConnectController; //?
disconnect_controller_f* DisconnectController; //?
open_protocol_f* OpenProtocol;
close_protocol_f* CloseProtocol;
open_protocol_information_f* OpenProtocolInformation;
protocols_per_handle_f* ProtocolsPerHandle; //?
locate_handle_buffer_f* LocateHandleBuffer; //?
locate_protocol_f* LocateProtocol;
install_multiple_protocol_interfaces_f* InstallMultipleProtocolInterfaces; //?
uninstall_multiple_protocol_interfaces_f* UninstallMultipleProtocolInterfaces; //?
calculate_crc32_f* CalculateCrc32;
copy_mem_f* CopyMem;
set_mem_f* SetMem;
create_event_ex_f* CreateEventEx;
};
}
| 61.092308 | 124 | 0.758877 | twrl |
60a848083a84578a581974689a4c4b6b8857f2d0 | 1,059 | cpp | C++ | src/Tileset.cpp | Anders1232/Trab1IDJ | 64844fbe23401753176490b902ec950d03b8e3e4 | [
"Zlib"
] | null | null | null | src/Tileset.cpp | Anders1232/Trab1IDJ | 64844fbe23401753176490b902ec950d03b8e3e4 | [
"Zlib"
] | 2 | 2017-04-06T15:29:57.000Z | 2017-05-13T14:13:25.000Z | src/Tileset.cpp | Anders1232/Trab1IDJ | 64844fbe23401753176490b902ec950d03b8e3e4 | [
"Zlib"
] | 1 | 2017-04-12T17:31:49.000Z | 2017-04-12T17:31:49.000Z | #include "Tileset.h"
#include "Error.h"
#include "Game.h"
TileSet::TileSet(int tileWidth, int tileHeight, string file): tileSet(file), tileWidth(tileWidth), tileHeight(tileHeight)
{
REPORT_I_WAS_HERE;
rows= tileSet.GetHeight()/tileHeight;
columns= tileSet.GetWidth()/tileWidth;
}
void TileSet::Render(unsigned int index, float x, float y)
{
ASSERT(index < (unsigned int)rows*columns);
unsigned int desiredLine, desiredColumn;
desiredLine= index/columns;
desiredColumn= index%columns;
SDL_Rect wantedSubSprite;
wantedSubSprite.x= desiredColumn*tileWidth;
wantedSubSprite.y= desiredLine*tileHeight;
wantedSubSprite.w= tileWidth;
wantedSubSprite.h= tileHeight;
SDL_Rect destinyPosition;
destinyPosition.x=x;
destinyPosition.y=y;
destinyPosition.w= tileWidth;
destinyPosition.h= tileHeight;
SDL_RenderCopy(Game::GetInstance().GetRenderer(), tileSet.GetTexture().get(),&wantedSubSprite, &destinyPosition);
// REPORT_I_WAS_HERE;
}
int TileSet::GetTileHeight(void)
{
return tileHeight;
}
int TileSet::GetTileWidth(void)
{
return tileWidth;
}
| 25.829268 | 121 | 0.779037 | Anders1232 |
60a84fe60a1f8aa7c6acc768f42d02dc31d04148 | 6,797 | cpp | C++ | KeypointDetector.cpp | MURDriverless/depth_estimation | fe37e3e994e1bb194074fd04b37a74f875d63ce9 | [
"BSD-3-Clause"
] | 2 | 2021-12-04T03:31:37.000Z | 2022-02-06T11:34:44.000Z | KeypointDetector.cpp | MURDriverless/depth_estimation | fe37e3e994e1bb194074fd04b37a74f875d63ce9 | [
"BSD-3-Clause"
] | null | null | null | KeypointDetector.cpp | MURDriverless/depth_estimation | fe37e3e994e1bb194074fd04b37a74f875d63ce9 | [
"BSD-3-Clause"
] | null | null | null | #include "KeypointDetector.hpp"
#include <algorithm>
#include <assert.h>
#include <cmath>
#include <cublas_v2.h>
#include <cudnn.h>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <sys/stat.h>
#include <time.h>
#include <opencv2/opencv.hpp>
#include <chrono>
using namespace nvinfer1;
using namespace std;
KeypointDetector::KeypointDetector(string onnxFile, string trtFile, int input_w, int input_h, int max_batch)
: logger_(Logger::Severity::kINFO),
#ifdef KPT_PROFILE
profiler_("Layer times"),
#endif
inputW_(input_w),
inputH_(input_h),
maxBatch_(max_batch)
{
runtime_ = createInferRuntime(logger_);
assert(runtime_ != nullptr);
runtime_->setDLACore(0);
engine_ = engineFromFiles(onnxFile, trtFile, runtime_, maxBatch_, logger_, false);
context_ = engine_->createExecutionContext();
#ifdef KPT_PROFILE
context_->setProfiler(&profiler_);
#endif
assert(context_ != nullptr);
int64_t outputCount = 0;
int nbBindings = engine_->getNbBindings();
for (int i = 0; i < nbBindings; i++)
{
if (!engine_->bindingIsInput(i))
{
outputCount += volume(engine_->getBindingDimensions(i));
}
}
outputData_.reset(new float[outputCount * maxBatch_]);
inputData_.reset(new float[inputW_ * inputH_ * KEYPOINTS_CHANNEL * maxBatch_]);
CUDA_CHECK(cudaStreamCreate(&stream_));
buffers_.reset(new void*[nbBindings]);
for (int b = 0; b < nbBindings; ++b)
{
int64_t size = volume(engine_->getBindingDimensions(b));
CUDA_CHECK(cudaMalloc(&buffers_.get()[b], size * maxBatch_ * sizeof(float)));
}
}
KeypointDetector::~KeypointDetector()
{
// release the stream and the buffers
cudaStreamDestroy(stream_);
for (int b = 0; b < engine_->getNbBindings(); ++b)
{
CUDA_CHECK(cudaFree(buffers_.get()[b]));
}
// destroy the engine_
context_->destroy();
engine_->destroy();
runtime_->destroy();
}
vector<cv::Point2f> KeypointDetector::interpretOutputTensor(float *tensor, int width, int height)
{
const int size = inputW_ * inputH_ / (KEYPOINT_SCALE * KEYPOINT_SCALE);
//const float scaleX = max(width / float(inputW_ / KEYPOINT_SCALE), height / float(inputH_ / KEYPOINT_SCALE));
//const float scaleY = scaleX;
const float scaleX = width / float(inputW_ / KEYPOINT_SCALE);
const float scaleY = height / float(inputH_ / KEYPOINT_SCALE);
vector<cv::Point2f> kpt(NUM_KEYPOINTS);
for (int i = 0; i < NUM_KEYPOINTS; i++)
{
float max_elem = *std::max_element(tensor, tensor + size);
std::transform(tensor, tensor + size, tensor, [&](float x){ return std::exp(x - max_elem); });
float sum = std::accumulate(tensor, tensor + size, 0.0);
std::transform(tensor, tensor + size, tensor, std::bind2nd(std::divides<float>(), sum));
cv::Mat outImg(inputW_, inputH_, CV_32FC1);
memcpy(outImg.data, tensor, sizeof(float) * size);
cv::Mat xs(inputH_ / KEYPOINT_SCALE, inputW_ / KEYPOINT_SCALE, CV_32FC1);
cv::Mat ys(inputH_ / KEYPOINT_SCALE, inputW_ / KEYPOINT_SCALE, CV_32FC1);
for (int j = 0; j < inputW_ / KEYPOINT_SCALE; j++)
{
xs.col(j).setTo(j);
}
for (int j = 0; j < inputH_ / KEYPOINT_SCALE; j++)
{
ys.row(j).setTo(j);
}
float x = cv::sum(xs.mul(outImg))[0];
float y = cv::sum(ys.mul(outImg))[0];
kpt[i] = cv::Point2f(x * scaleX, y * scaleY);
//int largest = distance(tensor, max_element(tensor, tensor + size));
//int smallest = distance(tensor, min_element(tensor, tensor + size));
//int second = distance(tensor, max_element(tensor, tensor + size));
//kpt[i] = cv::Point2f((largest % inputW_) * scaleX, (largest / inputW_) * scaleY);//cv::Point2f((3 * (largest % (inputW_ / KEYPOINT_SCALE)) + second % (inputW_ / KEYPOINT_SCALE)) / 4. * scale, (3 * (largest / (inputW_ / KEYPOINT_SCALE)) + second / (inputW_ / KEYPOINT_SCALE)) / 4. * scale);
//cv::Mat normImg(inputW_, inputH_, CV_8UC1);
//outImg -= tensor[smallest];
//outImg *= 255 / (tensor[largest] - tensor[smallest]);
//outImg.convertTo(normImg, CV_8UC1);
//cv::imshow("kpt", normImg);
//cv::waitKey(0);
//cv::threshold(normImg, normImg, 32, 0, cv::THRESH_TOZERO);
//cv::GaussianBlur(normImg, normImg, cv::Size(5, 5), 0, 0);
//cv::Mat mask;
//cv::dilate(normImg, mask, cv::Mat());
//cv::compare(normImg, mask, mask, cv::CMP_GE);
//cv::Mat non_plateau_mask;
//cv::erode(normImg, non_plateau_mask, cv::Mat());
//cv::compare(normImg, non_plateau_mask, non_plateau_mask, cv::CMP_GT);
//cv::bitwise_and(mask, non_plateau_mask, mask);
//cv::imshow("kpt", mask);
//cv::waitKey(0);
tensor += size;
}
return kpt;
}
vector<vector<cv::Point2f>> KeypointDetector::doInference(vector<cv::Mat>& imgs)
{
int batchSize = imgs.size();
float *input = inputData_.get();
for(auto &img : imgs)
{
prepareImage(img, input, inputW_, inputH_, KEYPOINTS_CHANNEL, false, false, false);
input += inputW_ * inputH_ * KEYPOINTS_CHANNEL;
}
auto t_start = std::chrono::high_resolution_clock::now();
int nbBindings = engine_->getNbBindings();
// DMA the input to the GPU, execute the batch asynchronously, and DMA it back:
CUDA_CHECK(cudaMemcpyAsync(buffers_.get()[0], inputData_.get(), batchSize * volume(engine_->getBindingDimensions(0)) * sizeof(float), cudaMemcpyHostToDevice, stream_));
#ifdef KPT_PROFILE
context_->execute(batchSize, buffers_.get());
#else
context_->enqueue(batchSize, buffers_.get(), stream_, nullptr);
#endif
float *output = outputData_.get();
for (int b = 0; b < nbBindings; ++b)
{
if (!engine_->bindingIsInput(b))
{
int64_t size = volume(engine_->getBindingDimensions(b));
CUDA_CHECK(cudaMemcpyAsync(output, buffers_.get()[b], batchSize * size * sizeof(float), cudaMemcpyDeviceToHost, stream_));
output += maxBatch_ * size;
}
}
cudaStreamSynchronize(stream_);
#ifdef KPT_PROFILE
cout << profiler_;
#endif
auto t_end = std::chrono::high_resolution_clock::now();
auto total = std::chrono::duration<float, std::milli>(t_end - t_start).count();
std::cout << "Time taken for keypoints is " << total << " ms." << std::endl;
output = outputData_.get();
vector<vector<cv::Point2f>> results(batchSize);
for (int b = 0; b < batchSize; b++)
{
results[b] = interpretOutputTensor(output, imgs[b].cols, imgs[b].rows);
output += inputW_ * inputH_ / (KEYPOINT_SCALE * KEYPOINT_SCALE) * NUM_KEYPOINTS;
}
return results;
}
| 37.142077 | 299 | 0.638517 | MURDriverless |
60ac901eb0f98efe1d996ef34c03a6ee08b61ab5 | 4,140 | hpp | C++ | inc/mkn/kul/os/nixish/threads.os.hpp | mkn/mkn.kul | ae3d01dec3207e712aafafe6d4bff42885e081b2 | [
"BSD-3-Clause"
] | 7 | 2015-12-02T21:58:28.000Z | 2020-03-24T09:23:16.000Z | inc/mkn/kul/os/nixish/threads.os.hpp | mkn/mkn.kul | ae3d01dec3207e712aafafe6d4bff42885e081b2 | [
"BSD-3-Clause"
] | 6 | 2017-10-03T17:21:40.000Z | 2020-06-23T10:01:13.000Z | inc/mkn/kul/os/nixish/threads.os.hpp | mkn/mkn.kul | ae3d01dec3207e712aafafe6d4bff42885e081b2 | [
"BSD-3-Clause"
] | 3 | 2016-01-03T15:38:07.000Z | 2021-03-29T17:23:31.000Z | /**
Copyright (c) 2017, Philip Deegan.
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 Philip Deegan 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.
*/
// IWYU pragma: private, include "mkn/kul/threads.hpp"
#ifndef _MKN_KUL_OS_NIXISH_THREADS_OS_HPP_
#define _MKN_KUL_OS_NIXISH_THREADS_OS_HPP_
#include <pthread.h>
#include <signal.h>
#include <sys/syscall.h>
#include <unistd.h>
#if defined(__NetBSD__)
#include <lwp.h>
#endif
namespace mkn {
namespace kul {
namespace this_thread {
inline const std::string id() {
std::ostringstream os;
os << std::hex << pthread_self();
return os.str();
}
// http://stackoverflow.com/questions/4867839/how-can-i-tell-if-pthread-self-is-the-main-first-thread-in-the-process
inline bool main() {
#if defined(__FreeBSD__)
return 0;
#elif defined(__NetBSD__)
return _lwp_self();
#elif defined(__OpenBSD__)
return 0;
#elif defined(__APPLE__)
return 0;
#else
return getpid() == syscall(SYS_gettid);
#endif
}
inline void kill() { pthread_exit(0); }
} // namespace this_thread
class Mutex {
private:
pthread_mutex_t mute;
public:
Mutex() {
pthread_mutexattr_t att;
pthread_mutexattr_init(&att);
pthread_mutexattr_settype(&att, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mute, &att);
pthread_mutexattr_destroy(&att);
}
~Mutex() { pthread_mutex_destroy(&mute); }
bool tryLock() { return pthread_mutex_trylock(&mute); }
void lock() { pthread_mutex_lock(&mute); }
void unlock() { pthread_mutex_unlock(&mute); }
};
class Thread : public threading::AThread {
private:
std::function<void()> func;
pthread_t thr;
static void *threadFunction(void *th) {
((Thread *)th)->act();
return 0;
}
void act() {
try {
func();
} catch (const std::exception &e) {
ep = std::current_exception();
}
f = 1;
}
public:
Thread(const std::function<void()> &_func) : func(_func) {}
template <class T>
Thread(const T &t) : func(std::bind((void (T::*)()) & T::operator(), t)) {}
template <class T>
Thread(const std::reference_wrapper<T> &r)
: func(std::bind((void (T::*)()) & T::operator(), r)) {}
template <class T>
Thread(const std::reference_wrapper<const T> &r)
: func(std::bind((void (T::*)() const) & T::operator(), r)) {}
virtual ~Thread() {}
bool detach() { return pthread_detach(thr); }
void interrupt() KTHROW(mkn::kul::threading::InterruptionException) {
pthread_cancel(thr);
f = 1;
}
void join() {
if (!s) run();
pthread_join(thr, 0);
s = 0;
}
void run() KTHROW(mkn::kul::threading::Exception) {
if (s) KEXCEPTION("Thread running");
f = 0;
s = 1;
pthread_create(&thr, NULL, Thread::threadFunction, this);
}
};
} // namespace kul
} // namespace mkn
#endif /* _MKN_KUL_OS_NIXISH_THREADS_OS_HPP_ */
| 29.784173 | 116 | 0.710145 | mkn |
60af7555923a4219f69fc4bcb5ecee098e263f47 | 1,808 | cpp | C++ | cpp/src/solvent_lib/equiv/scramble.cpp | david-fong/sudoku-cpp | 1d8723c03f64b7829a8ebe7647cbf55e2897bfe5 | [
"MIT"
] | null | null | null | cpp/src/solvent_lib/equiv/scramble.cpp | david-fong/sudoku-cpp | 1d8723c03f64b7829a8ebe7647cbf55e2897bfe5 | [
"MIT"
] | 1 | 2022-03-05T14:40:05.000Z | 2022-03-07T09:19:57.000Z | cpp/src/solvent_lib/equiv/scramble.cpp | david-fong/sudoku-cpp | 1d8723c03f64b7829a8ebe7647cbf55e2897bfe5 | [
"MIT"
] | 1 | 2021-07-26T14:49:36.000Z | 2021-07-26T14:49:36.000Z | #include <solvent_lib/equiv/scramble.hpp>
#include <array>
#include <algorithm> // shuffle,
#include <random>
namespace solvent::lib::equiv {
std::mt19937 ScramblerRng_;
void seed_scrambler_rng(const std::uint_fast32_t seed) noexcept {
ScramblerRng_.seed(seed);
}
template<Order O>
grid_vec_t<O> scramble(const grid_vec_t<O>& input_vec) {
using ord1_t = typename size<O>::ord1_t;
using ord2_t = typename size<O>::ord2_t;
using ord4_t = typename size<O>::ord4_t;
static constexpr ord1_t O1 = O;
static constexpr ord2_t O2 = O*O;
static constexpr ord4_t O4 = O*O*O*O;
grid_mtx_t<O> input = grid_vec2mtx<O>(input_vec);
std::array<ord2_t, O2> label_map;
std::array<std::array<ord2_t, O1>, O1> row_map;
std::array<std::array<ord2_t, O1>, O1> col_map;
bool transpose;
for (ord2_t i = 0; i < O2; i++) {
label_map[i] = i;
row_map[i/O1][i%O1] = i;
col_map[i/O1][i%O1] = i;
}
std::ranges::shuffle(label_map, ScramblerRng_);
std::ranges::shuffle(row_map, ScramblerRng_);
std::ranges::shuffle(col_map, ScramblerRng_);
for (ord1_t chute = 0; chute < O1; chute++) {
std::ranges::shuffle(row_map[chute], ScramblerRng_);
std::ranges::shuffle(col_map[chute], ScramblerRng_);
}
transpose = ScramblerRng_() % 2;
grid_vec_t<O> output_vec(O4);
for (ord2_t row = 0; row < O2; row++) {
for (ord2_t col = 0; col < O2; col++) {
ord2_t mapped_row = row_map[row/O1][row%O1];
ord2_t mapped_col = col_map[col/O1][col%O1];
if (transpose) { std::swap(mapped_row, mapped_col); }
output_vec[(O2*row)+col] = label_map[input[mapped_row][mapped_col]];
}
}
return output_vec;
}
#define SOLVENT_TEMPL_TEMPL(O_) \
template grid_vec_t<O_> scramble<O_>(const grid_vec_t<O_>&);
SOLVENT_INSTANTIATE_ORDER_TEMPLATES
#undef SOLVENT_TEMPL_TEMPL
} | 30.644068 | 72 | 0.684181 | david-fong |
60b1dfd1a606d07e548f452d51a749905f5ef12e | 5,880 | hpp | C++ | PlatformIO ESP32 code/OSSM_ESP32/lib/ArduinoJson-6.x/src/ArduinoJson/Numbers/FloatTraits.hpp | ortlof/OSSM-hardware | 1cf21ce854cbe212c752726689d3c12508a3b1ee | [
"MIT"
] | 5,800 | 2015-01-05T02:36:02.000Z | 2022-03-31T04:27:26.000Z | PlatformIO ESP32 code/OSSM_ESP32/lib/ArduinoJson-6.x/src/ArduinoJson/Numbers/FloatTraits.hpp | ortlof/OSSM-hardware | 1cf21ce854cbe212c752726689d3c12508a3b1ee | [
"MIT"
] | 1,681 | 2015-01-04T00:41:40.000Z | 2022-03-31T07:30:51.000Z | PlatformIO ESP32 code/OSSM_ESP32/lib/ArduinoJson-6.x/src/ArduinoJson/Numbers/FloatTraits.hpp | ortlof/OSSM-hardware | 1cf21ce854cbe212c752726689d3c12508a3b1ee | [
"MIT"
] | 1,169 | 2015-01-04T01:32:23.000Z | 2022-03-28T13:38:00.000Z | // ArduinoJson - https://arduinojson.org
// Copyright Benoit Blanchon 2014-2021
// MIT License
#pragma once
#include <stddef.h> // for size_t
#include <stdint.h>
#include <ArduinoJson/Configuration.hpp>
#include <ArduinoJson/Polyfills/alias_cast.hpp>
#include <ArduinoJson/Polyfills/math.hpp>
#include <ArduinoJson/Polyfills/preprocessor.hpp>
#include <ArduinoJson/Polyfills/static_array.hpp>
namespace ARDUINOJSON_NAMESPACE {
template <typename T, size_t = sizeof(T)>
struct FloatTraits {};
template <typename T>
struct FloatTraits<T, 8 /*64bits*/> {
typedef uint64_t mantissa_type;
static const short mantissa_bits = 52;
static const mantissa_type mantissa_max =
(mantissa_type(1) << mantissa_bits) - 1;
typedef int16_t exponent_type;
static const exponent_type exponent_max = 308;
template <typename TExponent>
static T make_float(T m, TExponent e) {
if (e > 0) {
for (uint8_t index = 0; e != 0; index++) {
if (e & 1)
m *= positiveBinaryPowerOfTen(index);
e >>= 1;
}
} else {
e = TExponent(-e);
for (uint8_t index = 0; e != 0; index++) {
if (e & 1)
m *= negativeBinaryPowerOfTen(index);
e >>= 1;
}
}
return m;
}
static T positiveBinaryPowerOfTen(int index) {
ARDUINOJSON_DEFINE_STATIC_ARRAY( //
uint32_t, factors,
ARDUINOJSON_EXPAND18({
0x40240000, 0x00000000, // 1e1
0x40590000, 0x00000000, // 1e2
0x40C38800, 0x00000000, // 1e4
0x4197D784, 0x00000000, // 1e8
0x4341C379, 0x37E08000, // 1e16
0x4693B8B5, 0xB5056E17, // 1e32
0x4D384F03, 0xE93FF9F5, // 1e64
0x5A827748, 0xF9301D32, // 1e128
0x75154FDD, 0x7F73BF3C // 1e256
}));
return forge(
ARDUINOJSON_READ_STATIC_ARRAY(uint32_t, factors, 2 * index),
ARDUINOJSON_READ_STATIC_ARRAY(uint32_t, factors, 2 * index + 1));
}
static T negativeBinaryPowerOfTen(int index) {
ARDUINOJSON_DEFINE_STATIC_ARRAY( //
uint32_t, factors,
ARDUINOJSON_EXPAND18({
0x3FB99999, 0x9999999A, // 1e-1
0x3F847AE1, 0x47AE147B, // 1e-2
0x3F1A36E2, 0xEB1C432D, // 1e-4
0x3E45798E, 0xE2308C3A, // 1e-8
0x3C9CD2B2, 0x97D889BC, // 1e-16
0x3949F623, 0xD5A8A733, // 1e-32
0x32A50FFD, 0x44F4A73D, // 1e-64
0x255BBA08, 0xCF8C979D, // 1e-128
0x0AC80628, 0x64AC6F43 // 1e-256
}));
return forge(
ARDUINOJSON_READ_STATIC_ARRAY(uint32_t, factors, 2 * index),
ARDUINOJSON_READ_STATIC_ARRAY(uint32_t, factors, 2 * index + 1));
}
static T negativeBinaryPowerOfTenPlusOne(int index) {
ARDUINOJSON_DEFINE_STATIC_ARRAY( //
uint32_t, factors,
ARDUINOJSON_EXPAND18({
0x3FF00000, 0x00000000, // 1e0
0x3FB99999, 0x9999999A, // 1e-1
0x3F50624D, 0xD2F1A9FC, // 1e-3
0x3E7AD7F2, 0x9ABCAF48, // 1e-7
0x3CD203AF, 0x9EE75616, // 1e-15
0x398039D6, 0x65896880, // 1e-31
0x32DA53FC, 0x9631D10D, // 1e-63
0x25915445, 0x81B7DEC2, // 1e-127
0x0AFE07B2, 0x7DD78B14 // 1e-255
}));
return forge(
ARDUINOJSON_READ_STATIC_ARRAY(uint32_t, factors, 2 * index),
ARDUINOJSON_READ_STATIC_ARRAY(uint32_t, factors, 2 * index + 1));
}
static T nan() {
return forge(0x7ff80000, 0x00000000);
}
static T inf() {
return forge(0x7ff00000, 0x00000000);
}
static T highest() {
return forge(0x7FEFFFFF, 0xFFFFFFFF);
}
static T lowest() {
return forge(0xFFEFFFFF, 0xFFFFFFFF);
}
// constructs a double floating point values from its binary representation
// we use this function to workaround platforms with single precision literals
// (for example, when -fsingle-precision-constant is passed to GCC)
static T forge(uint32_t msb, uint32_t lsb) {
return alias_cast<T>((uint64_t(msb) << 32) | lsb);
}
};
template <typename T>
struct FloatTraits<T, 4 /*32bits*/> {
typedef uint32_t mantissa_type;
static const short mantissa_bits = 23;
static const mantissa_type mantissa_max =
(mantissa_type(1) << mantissa_bits) - 1;
typedef int8_t exponent_type;
static const exponent_type exponent_max = 38;
template <typename TExponent>
static T make_float(T m, TExponent e) {
if (e > 0) {
for (uint8_t index = 0; e != 0; index++) {
if (e & 1)
m *= positiveBinaryPowerOfTen(index);
e >>= 1;
}
} else {
e = -e;
for (uint8_t index = 0; e != 0; index++) {
if (e & 1)
m *= negativeBinaryPowerOfTen(index);
e >>= 1;
}
}
return m;
}
static T positiveBinaryPowerOfTen(int index) {
ARDUINOJSON_DEFINE_STATIC_ARRAY(
T, factors,
ARDUINOJSON_EXPAND6({1e1f, 1e2f, 1e4f, 1e8f, 1e16f, 1e32f}));
return ARDUINOJSON_READ_STATIC_ARRAY(T, factors, index);
}
static T negativeBinaryPowerOfTen(int index) {
ARDUINOJSON_DEFINE_STATIC_ARRAY(
T, factors,
ARDUINOJSON_EXPAND6({1e-1f, 1e-2f, 1e-4f, 1e-8f, 1e-16f, 1e-32f}));
return ARDUINOJSON_READ_STATIC_ARRAY(T, factors, index);
}
static T negativeBinaryPowerOfTenPlusOne(int index) {
ARDUINOJSON_DEFINE_STATIC_ARRAY(
T, factors,
ARDUINOJSON_EXPAND6({1e0f, 1e-1f, 1e-3f, 1e-7f, 1e-15f, 1e-31f}));
return ARDUINOJSON_READ_STATIC_ARRAY(T, factors, index);
}
static T forge(uint32_t bits) {
return alias_cast<T>(bits);
}
static T nan() {
return forge(0x7fc00000);
}
static T inf() {
return forge(0x7f800000);
}
static T highest() {
return forge(0x7f7fffff);
}
static T lowest() {
return forge(0xFf7fffff);
}
};
} // namespace ARDUINOJSON_NAMESPACE
| 29.108911 | 80 | 0.62534 | ortlof |
60b3b21c5a05123aa0304b112532d71026f3a7dd | 62,312 | cpp | C++ | bolt/lib/Rewrite/DWARFRewriter.cpp | hborla/llvm-project | 6590b7ca0bb9c01e9a362bcbc5500d41d21bd6e7 | [
"Apache-2.0"
] | null | null | null | bolt/lib/Rewrite/DWARFRewriter.cpp | hborla/llvm-project | 6590b7ca0bb9c01e9a362bcbc5500d41d21bd6e7 | [
"Apache-2.0"
] | null | null | null | bolt/lib/Rewrite/DWARFRewriter.cpp | hborla/llvm-project | 6590b7ca0bb9c01e9a362bcbc5500d41d21bd6e7 | [
"Apache-2.0"
] | null | null | null | //===- bolt/Rewrite/DWARFRewriter.cpp -------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "bolt/Rewrite/DWARFRewriter.h"
#include "bolt/Core/BinaryContext.h"
#include "bolt/Core/BinaryFunction.h"
#include "bolt/Core/DebugData.h"
#include "bolt/Core/ParallelUtilities.h"
#include "bolt/Utils/Utils.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/DWP/DWP.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
#include "llvm/MC/MCAsmBackend.h"
#include "llvm/MC/MCAsmLayout.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCDwarf.h"
#include "llvm/MC/MCObjectWriter.h"
#include "llvm/MC/MCSection.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/ThreadPool.h"
#include "llvm/Support/ToolOutputFile.h"
#include <algorithm>
#include <cstdint>
#include <string>
#include <unordered_map>
#undef DEBUG_TYPE
#define DEBUG_TYPE "bolt"
LLVM_ATTRIBUTE_UNUSED
static void printDie(const DWARFDie &DIE) {
DIDumpOptions DumpOpts;
DumpOpts.ShowForm = true;
DumpOpts.Verbose = true;
DumpOpts.ChildRecurseDepth = 0;
DumpOpts.ShowChildren = 0;
DIE.dump(dbgs(), 0, DumpOpts);
}
struct AttrInfo {
DWARFFormValue V;
uint64_t Offset;
uint32_t Size; // Size of the attribute.
};
/// Finds attributes FormValue and Offset.
///
/// \param DIE die to look up in.
/// \param Index the attribute index to extract.
/// \return an optional AttrInfo with DWARFFormValue and Offset.
static Optional<AttrInfo>
findAttributeInfo(const DWARFDie DIE,
const DWARFAbbreviationDeclaration *AbbrevDecl,
uint32_t Index) {
const DWARFUnit &U = *DIE.getDwarfUnit();
uint64_t Offset =
AbbrevDecl->getAttributeOffsetFromIndex(Index, DIE.getOffset(), U);
Optional<DWARFFormValue> Value =
AbbrevDecl->getAttributeValueFromOffset(Index, Offset, U);
if (!Value)
return None;
// AttributeSpec
const DWARFAbbreviationDeclaration::AttributeSpec *AttrVal =
AbbrevDecl->attributes().begin() + Index;
uint32_t ValSize = 0;
Optional<int64_t> ValSizeOpt = AttrVal->getByteSize(U);
if (ValSizeOpt) {
ValSize = static_cast<uint32_t>(*ValSizeOpt);
} else {
DWARFDataExtractor DebugInfoData = U.getDebugInfoExtractor();
uint64_t NewOffset = Offset;
DWARFFormValue::skipValue(Value->getForm(), DebugInfoData, &NewOffset,
U.getFormParams());
// This includes entire size of the entry, which might not be just the
// encoding part. For example for DW_AT_loc it will include expression
// location.
ValSize = NewOffset - Offset;
}
return AttrInfo{*Value, Offset, ValSize};
}
/// Finds attributes FormValue and Offset.
///
/// \param DIE die to look up in.
/// \param Attr the attribute to extract.
/// \return an optional AttrInfo with DWARFFormValue and Offset.
static Optional<AttrInfo> findAttributeInfo(const DWARFDie DIE,
dwarf::Attribute Attr) {
if (!DIE.isValid())
return None;
const DWARFAbbreviationDeclaration *AbbrevDecl =
DIE.getAbbreviationDeclarationPtr();
if (!AbbrevDecl)
return None;
Optional<uint32_t> Index = AbbrevDecl->findAttributeIndex(Attr);
if (!Index)
return None;
return findAttributeInfo(DIE, AbbrevDecl, *Index);
}
using namespace llvm;
using namespace llvm::support::endian;
using namespace object;
using namespace bolt;
namespace opts {
extern cl::OptionCategory BoltCategory;
extern cl::opt<unsigned> Verbosity;
extern cl::opt<std::string> OutputFilename;
static cl::opt<bool>
KeepARanges("keep-aranges",
cl::desc("keep or generate .debug_aranges section if .gdb_index is written"),
cl::ZeroOrMore,
cl::Hidden,
cl::cat(BoltCategory));
static cl::opt<bool>
DeterministicDebugInfo("deterministic-debuginfo",
cl::desc("disables parallel execution of tasks that may produce"
"nondeterministic debug info"),
cl::init(true),
cl::cat(BoltCategory));
static cl::opt<std::string> DwarfOutputPath(
"dwarf-output-path",
cl::desc("Path to where .dwo files or dwp file will be written out to."),
cl::init(""), cl::cat(BoltCategory));
static cl::opt<bool>
WriteDWP("write-dwp",
cl::desc("output a single dwarf package file (dwp) instead of "
"multiple non-relocatable dwarf object files (dwo)."),
cl::init(false), cl::cat(BoltCategory));
static cl::opt<bool>
DebugSkeletonCu("debug-skeleton-cu",
cl::desc("prints out offsetrs for abbrev and debu_info of "
"Skeleton CUs that get patched."),
cl::ZeroOrMore, cl::Hidden, cl::init(false),
cl::cat(BoltCategory));
} // namespace opts
/// Returns DWO Name to be used. Handles case where user specifies output DWO
/// directory, and there are duplicate names. Assumes DWO ID is unique.
static std::string
getDWOName(llvm::DWARFUnit &CU,
std::unordered_map<std::string, uint32_t> *NameToIndexMap,
std::unordered_map<uint64_t, std::string> &DWOIdToName) {
llvm::Optional<uint64_t> DWOId = CU.getDWOId();
assert(DWOId && "DWO ID not found.");
(void)DWOId;
auto NameIter = DWOIdToName.find(*DWOId);
if (NameIter != DWOIdToName.end())
return NameIter->second;
std::string DWOName = dwarf::toString(
CU.getUnitDIE().find({dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}),
"");
assert(!DWOName.empty() &&
"DW_AT_dwo_name/DW_AT_GNU_dwo_name does not exists.");
if (NameToIndexMap && !opts::DwarfOutputPath.empty()) {
auto Iter = NameToIndexMap->find(DWOName);
if (Iter == NameToIndexMap->end())
Iter = NameToIndexMap->insert({DWOName, 0}).first;
DWOName.append(std::to_string(Iter->second));
++Iter->second;
}
DWOName.append(".dwo");
DWOIdToName[*DWOId] = DWOName;
return DWOName;
}
static bool isHighPcFormEightBytes(dwarf::Form DwarfForm) {
return DwarfForm == dwarf::DW_FORM_addr || DwarfForm == dwarf::DW_FORM_data8;
}
void DWARFRewriter::updateDebugInfo() {
ErrorOr<BinarySection &> DebugInfo = BC.getUniqueSectionByName(".debug_info");
if (!DebugInfo)
return;
auto *DebugInfoPatcher =
static_cast<DebugInfoBinaryPatcher *>(DebugInfo->getPatcher());
ARangesSectionWriter = std::make_unique<DebugARangesSectionWriter>();
RangesSectionWriter = std::make_unique<DebugRangesSectionWriter>();
StrWriter = std::make_unique<DebugStrWriter>(&BC);
AbbrevWriter = std::make_unique<DebugAbbrevWriter>(*BC.DwCtx);
AddrWriter = std::make_unique<DebugAddrWriter>(&BC);
DebugLoclistWriter::setAddressWriter(AddrWriter.get());
uint64_t NumCUs = BC.DwCtx->getNumCompileUnits();
if ((opts::NoThreads || opts::DeterministicDebugInfo) &&
BC.getNumDWOCUs() == 0) {
// Use single entry for efficiency when running single-threaded
NumCUs = 1;
}
LocListWritersByCU.reserve(NumCUs);
for (size_t CUIndex = 0; CUIndex < NumCUs; ++CUIndex)
LocListWritersByCU[CUIndex] = std::make_unique<DebugLocWriter>(&BC);
// Unordered maps to handle name collision if output DWO directory is
// specified.
std::unordered_map<std::string, uint32_t> NameToIndexMap;
std::unordered_map<uint64_t, std::string> DWOIdToName;
std::mutex AccessMutex;
auto updateDWONameCompDir = [&](DWARFUnit &Unit) -> void {
const DWARFDie &DIE = Unit.getUnitDIE();
Optional<AttrInfo> AttrInfoVal =
findAttributeInfo(DIE, dwarf::DW_AT_GNU_dwo_name);
(void)AttrInfoVal;
assert(AttrInfoVal && "Skeleton CU doesn't have dwo_name.");
std::string ObjectName = "";
{
std::lock_guard<std::mutex> Lock(AccessMutex);
ObjectName = getDWOName(Unit, &NameToIndexMap, DWOIdToName);
}
uint32_t NewOffset = StrWriter->addString(ObjectName.c_str());
DebugInfoPatcher->addLE32Patch(AttrInfoVal->Offset, NewOffset,
AttrInfoVal->Size);
AttrInfoVal = findAttributeInfo(DIE, dwarf::DW_AT_comp_dir);
(void)AttrInfoVal;
assert(AttrInfoVal && "DW_AT_comp_dir is not in Skeleton CU.");
if (!opts::DwarfOutputPath.empty()) {
uint32_t NewOffset = StrWriter->addString(opts::DwarfOutputPath.c_str());
DebugInfoPatcher->addLE32Patch(AttrInfoVal->Offset, NewOffset,
AttrInfoVal->Size);
}
};
auto processUnitDIE = [&](size_t CUIndex, DWARFUnit *Unit) {
// Check if the unit is a skeleton and we need special updates for it and
// its matching split/DWO CU.
Optional<DWARFUnit *> SplitCU;
Optional<uint64_t> RangesBase;
llvm::Optional<uint64_t> DWOId = Unit->getDWOId();
if (DWOId)
SplitCU = BC.getDWOCU(*DWOId);
DebugLocWriter *DebugLocWriter = nullptr;
// Skipping CUs that failed to load.
if (SplitCU) {
updateDWONameCompDir(*Unit);
// Assuming there is unique DWOID per binary. i.e. two or more CUs don't
// have same DWO ID.
assert(LocListWritersByCU.count(*DWOId) == 0 &&
"LocList writer for DWO unit already exists.");
{
std::lock_guard<std::mutex> Lock(AccessMutex);
DebugLocWriter =
LocListWritersByCU
.insert(
{*DWOId, std::make_unique<DebugLoclistWriter>(&BC, *DWOId)})
.first->second.get();
}
DebugInfoBinaryPatcher *DwoDebugInfoPatcher =
llvm::cast<DebugInfoBinaryPatcher>(
getBinaryDWODebugInfoPatcher(*DWOId));
RangesBase = RangesSectionWriter->getSectionOffset();
DWARFContext *DWOCtx = BC.getDWOContext();
// Setting this CU offset with DWP to normalize DIE offsets to uint32_t
if (DWOCtx && !DWOCtx->getCUIndex().getRows().empty())
DwoDebugInfoPatcher->setDWPOffset((*SplitCU)->getOffset());
DwoDebugInfoPatcher->setRangeBase(*RangesBase);
DwoDebugInfoPatcher->addUnitBaseOffsetLabel((*SplitCU)->getOffset());
DebugAbbrevWriter *DWOAbbrevWriter =
createBinaryDWOAbbrevWriter((*SplitCU)->getContext(), *DWOId);
updateUnitDebugInfo(*(*SplitCU), *DwoDebugInfoPatcher, *DWOAbbrevWriter,
*DebugLocWriter);
DwoDebugInfoPatcher->clearDestinationLabels();
if (!DwoDebugInfoPatcher->getWasRangBasedUsed())
RangesBase = None;
}
{
std::lock_guard<std::mutex> Lock(AccessMutex);
DebugLocWriter = LocListWritersByCU[CUIndex].get();
}
DebugInfoPatcher->addUnitBaseOffsetLabel(Unit->getOffset());
updateUnitDebugInfo(*Unit, *DebugInfoPatcher, *AbbrevWriter,
*DebugLocWriter, RangesBase);
};
if (opts::NoThreads || opts::DeterministicDebugInfo) {
for (std::unique_ptr<DWARFUnit> &CU : BC.DwCtx->compile_units())
processUnitDIE(0, CU.get());
} else {
// Update unit debug info in parallel
ThreadPool &ThreadPool = ParallelUtilities::getThreadPool();
size_t CUIndex = 0;
for (std::unique_ptr<DWARFUnit> &CU : BC.DwCtx->compile_units()) {
ThreadPool.async(processUnitDIE, CUIndex, CU.get());
CUIndex++;
}
ThreadPool.wait();
}
DebugInfoPatcher->clearDestinationLabels();
flushPendingRanges(*DebugInfoPatcher);
finalizeDebugSections(*DebugInfoPatcher);
if (opts::WriteDWP)
writeDWP(DWOIdToName);
else
writeDWOFiles(DWOIdToName);
updateGdbIndexSection();
}
void DWARFRewriter::updateUnitDebugInfo(
DWARFUnit &Unit, DebugInfoBinaryPatcher &DebugInfoPatcher,
DebugAbbrevWriter &AbbrevWriter, DebugLocWriter &DebugLocWriter,
Optional<uint64_t> RangesBase) {
// Cache debug ranges so that the offset for identical ranges could be reused.
std::map<DebugAddressRangesVector, uint64_t> CachedRanges;
uint64_t DIEOffset = Unit.getOffset() + Unit.getHeaderSize();
uint64_t NextCUOffset = Unit.getNextUnitOffset();
DWARFDebugInfoEntry Die;
DWARFDataExtractor DebugInfoData = Unit.getDebugInfoExtractor();
uint32_t Depth = 0;
while (
DIEOffset < NextCUOffset &&
Die.extractFast(Unit, &DIEOffset, DebugInfoData, NextCUOffset, Depth)) {
if (const DWARFAbbreviationDeclaration *AbbrDecl =
Die.getAbbreviationDeclarationPtr()) {
if (AbbrDecl->hasChildren())
++Depth;
} else {
// NULL entry.
if (Depth > 0)
--Depth;
if (Depth == 0)
break;
}
DWARFDie DIE(&Unit, &Die);
switch (DIE.getTag()) {
case dwarf::DW_TAG_compile_unit: {
auto ModuleRangesOrError = DIE.getAddressRanges();
if (!ModuleRangesOrError) {
consumeError(ModuleRangesOrError.takeError());
break;
}
DWARFAddressRangesVector &ModuleRanges = *ModuleRangesOrError;
DebugAddressRangesVector OutputRanges =
BC.translateModuleAddressRanges(ModuleRanges);
const uint64_t RangesSectionOffset =
RangesSectionWriter->addRanges(OutputRanges);
if (!Unit.isDWOUnit())
ARangesSectionWriter->addCURanges(Unit.getOffset(),
std::move(OutputRanges));
updateDWARFObjectAddressRanges(DIE, RangesSectionOffset, DebugInfoPatcher,
AbbrevWriter, RangesBase);
break;
}
case dwarf::DW_TAG_subprogram: {
// Get function address either from ranges or [LowPC, HighPC) pair.
bool UsesRanges = false;
uint64_t Address;
uint64_t SectionIndex, HighPC;
if (!DIE.getLowAndHighPC(Address, HighPC, SectionIndex)) {
Expected<DWARFAddressRangesVector> RangesOrError =
DIE.getAddressRanges();
if (!RangesOrError) {
consumeError(RangesOrError.takeError());
break;
}
DWARFAddressRangesVector Ranges = *RangesOrError;
// Not a function definition.
if (Ranges.empty())
break;
Address = Ranges.front().LowPC;
UsesRanges = true;
}
// Clear cached ranges as the new function will have its own set.
CachedRanges.clear();
DebugAddressRangesVector FunctionRanges;
if (const BinaryFunction *Function =
BC.getBinaryFunctionAtAddress(Address))
FunctionRanges = Function->getOutputAddressRanges();
// Update ranges.
if (UsesRanges) {
updateDWARFObjectAddressRanges(
DIE, RangesSectionWriter->addRanges(FunctionRanges),
DebugInfoPatcher, AbbrevWriter);
} else {
// Delay conversion of [LowPC, HighPC) into DW_AT_ranges if possible.
const DWARFAbbreviationDeclaration *Abbrev =
DIE.getAbbreviationDeclarationPtr();
assert(Abbrev && "abbrev expected");
// Create a critical section.
static std::shared_timed_mutex CriticalSectionMutex;
std::unique_lock<std::shared_timed_mutex> Lock(CriticalSectionMutex);
if (FunctionRanges.size() > 1) {
convertPending(Unit, Abbrev, DebugInfoPatcher, AbbrevWriter);
// Exit critical section early.
Lock.unlock();
convertToRanges(DIE, FunctionRanges, DebugInfoPatcher);
} else if (ConvertedRangesAbbrevs.find(Abbrev) !=
ConvertedRangesAbbrevs.end()) {
// Exit critical section early.
Lock.unlock();
convertToRanges(DIE, FunctionRanges, DebugInfoPatcher);
} else {
if (FunctionRanges.empty())
FunctionRanges.emplace_back(DebugAddressRange());
addToPendingRanges(Abbrev, DIE, FunctionRanges, Unit.getDWOId());
}
}
break;
}
case dwarf::DW_TAG_lexical_block:
case dwarf::DW_TAG_inlined_subroutine:
case dwarf::DW_TAG_try_block:
case dwarf::DW_TAG_catch_block: {
uint64_t RangesSectionOffset =
RangesSectionWriter->getEmptyRangesOffset();
Expected<DWARFAddressRangesVector> RangesOrError = DIE.getAddressRanges();
const BinaryFunction *Function =
RangesOrError && !RangesOrError->empty()
? BC.getBinaryFunctionContainingAddress(
RangesOrError->front().LowPC)
: nullptr;
if (Function) {
DebugAddressRangesVector OutputRanges =
Function->translateInputToOutputRanges(*RangesOrError);
LLVM_DEBUG(if (OutputRanges.empty() != RangesOrError->empty()) {
dbgs() << "BOLT-DEBUG: problem with DIE at 0x"
<< Twine::utohexstr(DIE.getOffset()) << " in CU at 0x"
<< Twine::utohexstr(Unit.getOffset()) << '\n';
});
RangesSectionOffset = RangesSectionWriter->addRanges(
std::move(OutputRanges), CachedRanges);
} else if (!RangesOrError) {
consumeError(RangesOrError.takeError());
}
updateDWARFObjectAddressRanges(DIE, RangesSectionOffset, DebugInfoPatcher,
AbbrevWriter);
break;
}
default: {
// Handle any tag that can have DW_AT_location attribute.
DWARFFormValue Value;
uint64_t AttrOffset;
if (Optional<AttrInfo> AttrVal =
findAttributeInfo(DIE, dwarf::DW_AT_location)) {
AttrOffset = AttrVal->Offset;
Value = AttrVal->V;
if (Value.isFormClass(DWARFFormValue::FC_Constant) ||
Value.isFormClass(DWARFFormValue::FC_SectionOffset)) {
uint64_t Offset = Value.isFormClass(DWARFFormValue::FC_Constant)
? Value.getAsUnsignedConstant().getValue()
: Value.getAsSectionOffset().getValue();
DebugLocationsVector InputLL;
Optional<object::SectionedAddress> SectionAddress =
Unit.getBaseAddress();
uint64_t BaseAddress = 0;
if (SectionAddress)
BaseAddress = SectionAddress->Address;
Error E = Unit.getLocationTable().visitLocationList(
&Offset, [&](const DWARFLocationEntry &Entry) {
switch (Entry.Kind) {
default:
llvm_unreachable("Unsupported DWARFLocationEntry Kind.");
case dwarf::DW_LLE_end_of_list:
return false;
case dwarf::DW_LLE_base_address:
assert(Entry.SectionIndex == SectionedAddress::UndefSection &&
"absolute address expected");
BaseAddress = Entry.Value0;
break;
case dwarf::DW_LLE_offset_pair:
assert(
(Entry.SectionIndex == SectionedAddress::UndefSection &&
!Unit.isDWOUnit()) &&
"absolute address expected");
InputLL.emplace_back(DebugLocationEntry{
BaseAddress + Entry.Value0, BaseAddress + Entry.Value1,
Entry.Loc});
break;
case dwarf::DW_LLE_startx_length:
assert(Unit.isDWOUnit() &&
"None DWO Unit with DW_LLE_startx_length encoding.");
Optional<object::SectionedAddress> EntryAddress =
Unit.getAddrOffsetSectionItem(Entry.Value0);
assert(EntryAddress && "Address does not exist.");
InputLL.emplace_back(DebugLocationEntry{
EntryAddress->Address,
EntryAddress->Address + Entry.Value1, Entry.Loc});
break;
}
return true;
});
if (E || InputLL.empty()) {
errs() << "BOLT-WARNING: empty location list detected at 0x"
<< Twine::utohexstr(Offset) << " for DIE at 0x"
<< Twine::utohexstr(DIE.getOffset()) << " in CU at 0x"
<< Twine::utohexstr(Unit.getOffset()) << '\n';
} else {
const uint64_t Address = InputLL.front().LowPC;
if (const BinaryFunction *Function =
BC.getBinaryFunctionContainingAddress(Address)) {
DebugLocationsVector OutputLL =
Function->translateInputToOutputLocationList(InputLL);
LLVM_DEBUG(if (OutputLL.empty()) {
dbgs() << "BOLT-DEBUG: location list translated to an empty "
"one at 0x"
<< Twine::utohexstr(DIE.getOffset()) << " in CU at 0x"
<< Twine::utohexstr(Unit.getOffset()) << '\n';
});
DebugLocWriter.addList(AttrOffset, std::move(OutputLL));
}
}
} else {
assert((Value.isFormClass(DWARFFormValue::FC_Exprloc) ||
Value.isFormClass(DWARFFormValue::FC_Block)) &&
"unexpected DW_AT_location form");
if (Unit.isDWOUnit()) {
ArrayRef<uint8_t> Expr = *Value.getAsBlock();
DataExtractor Data(
StringRef((const char *)Expr.data(), Expr.size()),
Unit.getContext().isLittleEndian(), 0);
DWARFExpression LocExpr(Data, Unit.getAddressByteSize(),
Unit.getFormParams().Format);
for (auto &Expr : LocExpr) {
if (Expr.getCode() != dwarf::DW_OP_GNU_addr_index)
continue;
uint64_t Index = Expr.getRawOperand(0);
Optional<object::SectionedAddress> EntryAddress =
Unit.getAddrOffsetSectionItem(Index);
assert(EntryAddress && "Address is not found.");
assert(Index <= std::numeric_limits<uint32_t>::max() &&
"Invalid Operand Index.");
AddrWriter->addIndexAddress(EntryAddress->Address,
static_cast<uint32_t>(Index),
*Unit.getDWOId());
}
}
}
} else if (Optional<AttrInfo> AttrVal =
findAttributeInfo(DIE, dwarf::DW_AT_low_pc)) {
AttrOffset = AttrVal->Offset;
Value = AttrVal->V;
const Optional<uint64_t> Result = Value.getAsAddress();
if (Result.hasValue()) {
const uint64_t Address = Result.getValue();
uint64_t NewAddress = 0;
if (const BinaryFunction *Function =
BC.getBinaryFunctionContainingAddress(Address)) {
NewAddress = Function->translateInputToOutputAddress(Address);
LLVM_DEBUG(dbgs()
<< "BOLT-DEBUG: Fixing low_pc 0x"
<< Twine::utohexstr(Address) << " for DIE with tag "
<< DIE.getTag() << " to 0x"
<< Twine::utohexstr(NewAddress) << '\n');
}
dwarf::Form Form = Value.getForm();
assert(Form != dwarf::DW_FORM_LLVM_addrx_offset &&
"DW_FORM_LLVM_addrx_offset is not supported");
std::lock_guard<std::mutex> Lock(DebugInfoPatcherMutex);
if (Form == dwarf::DW_FORM_GNU_addr_index) {
assert(Unit.isDWOUnit() &&
"DW_FORM_GNU_addr_index in Non DWO unit.");
uint64_t Index = Value.getRawUValue();
// If there is no new address, storing old address.
// Re-using Index to make implementation easier.
// DW_FORM_GNU_addr_index is variable lenght encoding so we either
// have to create indices of same sizes, or use same index.
AddrWriter->addIndexAddress(NewAddress ? NewAddress : Address,
Index, *Unit.getDWOId());
} else {
DebugInfoPatcher.addLE64Patch(AttrOffset, NewAddress);
}
} else if (opts::Verbosity >= 1) {
errs() << "BOLT-WARNING: unexpected form value for attribute at 0x"
<< Twine::utohexstr(AttrOffset);
}
}
}
}
// Handling references.
assert(DIE.isValid() && "Invalid DIE.");
const DWARFAbbreviationDeclaration *AbbrevDecl =
DIE.getAbbreviationDeclarationPtr();
if (!AbbrevDecl)
continue;
uint32_t Index = 0;
for (const DWARFAbbreviationDeclaration::AttributeSpec &Decl :
AbbrevDecl->attributes()) {
switch (Decl.Form) {
default:
break;
case dwarf::DW_FORM_ref1:
case dwarf::DW_FORM_ref2:
case dwarf::DW_FORM_ref4:
case dwarf::DW_FORM_ref8:
case dwarf::DW_FORM_ref_udata:
case dwarf::DW_FORM_ref_addr: {
Optional<AttrInfo> AttrVal = findAttributeInfo(DIE, AbbrevDecl, Index);
uint32_t DestinationAddress =
AttrVal->V.getRawUValue() +
(Decl.Form == dwarf::DW_FORM_ref_addr ? 0 : Unit.getOffset());
DebugInfoPatcher.addReferenceToPatch(
AttrVal->Offset, DestinationAddress, AttrVal->Size, Decl.Form);
// We can have only one reference, and it can be backward one.
DebugInfoPatcher.addDestinationReferenceLabel(DestinationAddress);
break;
}
}
++Index;
}
}
if (DIEOffset > NextCUOffset)
errs() << "BOLT-WARNING: corrupt DWARF detected at 0x"
<< Twine::utohexstr(Unit.getOffset()) << '\n';
}
void DWARFRewriter::updateDWARFObjectAddressRanges(
const DWARFDie DIE, uint64_t DebugRangesOffset,
SimpleBinaryPatcher &DebugInfoPatcher, DebugAbbrevWriter &AbbrevWriter,
Optional<uint64_t> RangesBase) {
// Some objects don't have an associated DIE and cannot be updated (such as
// compiler-generated functions).
if (!DIE)
return;
const DWARFAbbreviationDeclaration *AbbreviationDecl =
DIE.getAbbreviationDeclarationPtr();
if (!AbbreviationDecl) {
if (opts::Verbosity >= 1)
errs() << "BOLT-WARNING: object's DIE doesn't have an abbreviation: "
<< "skipping update. DIE at offset 0x"
<< Twine::utohexstr(DIE.getOffset()) << '\n';
return;
}
if (RangesBase) {
// If DW_AT_GNU_ranges_base is present, update it. No further modifications
// are needed for ranges base.
Optional<AttrInfo> RangesBaseAttrInfo =
findAttributeInfo(DIE, dwarf::DW_AT_GNU_ranges_base);
if (RangesBaseAttrInfo) {
DebugInfoPatcher.addLE32Patch(RangesBaseAttrInfo->Offset,
static_cast<uint32_t>(*RangesBase),
RangesBaseAttrInfo->Size);
RangesBase = None;
}
}
if (AbbreviationDecl->findAttributeIndex(dwarf::DW_AT_ranges)) {
// Case 1: The object was already non-contiguous and had DW_AT_ranges.
// In this case we simply need to update the value of DW_AT_ranges
// and introduce DW_AT_GNU_ranges_base if required.
Optional<AttrInfo> AttrVal = findAttributeInfo(DIE, dwarf::DW_AT_ranges);
std::lock_guard<std::mutex> Lock(DebugInfoPatcherMutex);
DebugInfoPatcher.addLE32Patch(
AttrVal->Offset, DebugRangesOffset - DebugInfoPatcher.getRangeBase(),
AttrVal->Size);
if (!RangesBase)
return;
// Convert DW_AT_low_pc into DW_AT_GNU_ranges_base.
Optional<AttrInfo> LowPCAttrInfo =
findAttributeInfo(DIE, dwarf::DW_AT_low_pc);
if (!LowPCAttrInfo) {
errs() << "BOLT-ERROR: skeleton CU at 0x"
<< Twine::utohexstr(DIE.getOffset())
<< " does not have DW_AT_GNU_ranges_base or DW_AT_low_pc to"
" convert to update ranges base\n";
return;
}
AbbrevWriter.addAttributePatch(
*DIE.getDwarfUnit(), AbbreviationDecl, dwarf::DW_AT_low_pc,
dwarf::DW_AT_GNU_ranges_base, dwarf::DW_FORM_indirect);
DebugInfoPatcher.addUDataPatch(LowPCAttrInfo->Offset, dwarf::DW_FORM_udata,
1);
DebugInfoPatcher.addUDataPatch(LowPCAttrInfo->Offset + 1, *RangesBase, 7);
return;
}
// Case 2: The object has both DW_AT_low_pc and DW_AT_high_pc emitted back
// to back. Replace with new attributes and patch the DIE.
if (AbbreviationDecl->findAttributeIndex(dwarf::DW_AT_low_pc) &&
AbbreviationDecl->findAttributeIndex(dwarf::DW_AT_high_pc)) {
convertToRangesPatchAbbrev(*DIE.getDwarfUnit(), AbbreviationDecl,
AbbrevWriter, RangesBase);
convertToRangesPatchDebugInfo(DIE, DebugRangesOffset, DebugInfoPatcher,
RangesBase);
} else {
if (opts::Verbosity >= 1)
errs() << "BOLT-ERROR: cannot update ranges for DIE at offset 0x"
<< Twine::utohexstr(DIE.getOffset()) << '\n';
}
}
void DWARFRewriter::updateLineTableOffsets(const MCAsmLayout &Layout) {
ErrorOr<BinarySection &> DbgInfoSection =
BC.getUniqueSectionByName(".debug_info");
ErrorOr<BinarySection &> TypeInfoSection =
BC.getUniqueSectionByName(".debug_types");
assert(((BC.DwCtx->getNumTypeUnits() > 0 && TypeInfoSection) ||
BC.DwCtx->getNumTypeUnits() == 0) &&
"Was not able to retrieve Debug Types section.");
// We will be re-writing .debug_info so relocation mechanism doesn't work for
// Debug Info Patcher.
DebugInfoBinaryPatcher *DebugInfoPatcher = nullptr;
if (BC.DwCtx->getNumCompileUnits()) {
DbgInfoSection->registerPatcher(std::make_unique<DebugInfoBinaryPatcher>());
DebugInfoPatcher =
static_cast<DebugInfoBinaryPatcher *>(DbgInfoSection->getPatcher());
}
// There is no direct connection between CU and TU, but same offsets,
// encoded in DW_AT_stmt_list, into .debug_line get modified.
// We take advantage of that to map original CU line table offsets to new
// ones.
std::unordered_map<uint64_t, uint64_t> DebugLineOffsetMap;
auto GetStatementListValue = [](DWARFUnit *Unit) {
Optional<DWARFFormValue> StmtList =
Unit->getUnitDIE().find(dwarf::DW_AT_stmt_list);
Optional<uint64_t> Offset = dwarf::toSectionOffset(StmtList);
assert(Offset && "Was not able to retreive value of DW_AT_stmt_list.");
return *Offset;
};
const uint64_t Reloc32Type = BC.isAArch64()
? static_cast<uint64_t>(ELF::R_AARCH64_ABS32)
: static_cast<uint64_t>(ELF::R_X86_64_32);
for (const std::unique_ptr<DWARFUnit> &CU : BC.DwCtx->compile_units()) {
const unsigned CUID = CU->getOffset();
MCSymbol *Label = BC.getDwarfLineTable(CUID).getLabel();
if (!Label)
continue;
Optional<AttrInfo> AttrVal =
findAttributeInfo(CU.get()->getUnitDIE(), dwarf::DW_AT_stmt_list);
if (!AttrVal)
continue;
const uint64_t AttributeOffset = AttrVal->Offset;
const uint64_t LineTableOffset = Layout.getSymbolOffset(*Label);
DebugLineOffsetMap[GetStatementListValue(CU.get())] = LineTableOffset;
assert(DbgInfoSection && ".debug_info section must exist");
DebugInfoPatcher->addLE32Patch(AttributeOffset, LineTableOffset);
}
for (const std::unique_ptr<DWARFUnit> &TU : BC.DwCtx->types_section_units()) {
DWARFUnit *Unit = TU.get();
Optional<AttrInfo> AttrVal =
findAttributeInfo(TU.get()->getUnitDIE(), dwarf::DW_AT_stmt_list);
if (!AttrVal)
continue;
const uint64_t AttributeOffset = AttrVal->Offset;
auto Iter = DebugLineOffsetMap.find(GetStatementListValue(Unit));
assert(Iter != DebugLineOffsetMap.end() &&
"Type Unit Updated Line Number Entry does not exist.");
TypeInfoSection->addRelocation(AttributeOffset, nullptr, Reloc32Type,
Iter->second, 0, /*Pending=*/true);
}
// Set .debug_info as finalized so it won't be skipped over when
// we process sections while writing out the new binary. This ensures
// that the pending relocations will be processed and not ignored.
if (DbgInfoSection)
DbgInfoSection->setIsFinalized();
if (TypeInfoSection)
TypeInfoSection->setIsFinalized();
}
void DWARFRewriter::finalizeDebugSections(
DebugInfoBinaryPatcher &DebugInfoPatcher) {
if (StrWriter->isInitialized()) {
RewriteInstance::addToDebugSectionsToOverwrite(".debug_str");
std::unique_ptr<DebugStrBufferVector> DebugStrSectionContents =
StrWriter->finalize();
BC.registerOrUpdateNoteSection(".debug_str",
copyByteArray(*DebugStrSectionContents),
DebugStrSectionContents->size());
}
std::unique_ptr<DebugBufferVector> RangesSectionContents =
RangesSectionWriter->finalize();
BC.registerOrUpdateNoteSection(".debug_ranges",
copyByteArray(*RangesSectionContents),
RangesSectionContents->size());
std::unique_ptr<DebugBufferVector> LocationListSectionContents =
makeFinalLocListsSection(DebugInfoPatcher);
BC.registerOrUpdateNoteSection(".debug_loc",
copyByteArray(*LocationListSectionContents),
LocationListSectionContents->size());
// AddrWriter should be finalized after debug_loc since more addresses can be
// added there.
if (AddrWriter->isInitialized()) {
AddressSectionBuffer AddressSectionContents = AddrWriter->finalize();
BC.registerOrUpdateNoteSection(".debug_addr",
copyByteArray(AddressSectionContents),
AddressSectionContents.size());
for (auto &CU : BC.DwCtx->compile_units()) {
DWARFDie DIE = CU->getUnitDIE();
if (Optional<AttrInfo> AttrVal =
findAttributeInfo(DIE, dwarf::DW_AT_GNU_addr_base)) {
uint64_t Offset = AddrWriter->getOffset(*CU->getDWOId());
DebugInfoPatcher.addLE32Patch(
AttrVal->Offset, static_cast<int32_t>(Offset), AttrVal->Size);
}
}
}
std::unique_ptr<DebugBufferVector> AbbrevSectionContents =
AbbrevWriter->finalize();
BC.registerOrUpdateNoteSection(".debug_abbrev",
copyByteArray(*AbbrevSectionContents),
AbbrevSectionContents->size());
// Update abbreviation offsets for CUs/TUs if they were changed.
SimpleBinaryPatcher *DebugTypesPatcher = nullptr;
for (auto &Unit : BC.DwCtx->normal_units()) {
const uint64_t NewAbbrevOffset =
AbbrevWriter->getAbbreviationsOffsetForUnit(*Unit);
if (Unit->getAbbreviationsOffset() == NewAbbrevOffset)
continue;
// DWARFv4
// unit_length - 4 bytes
// version - 2 bytes
// So + 6 to patch debug_abbrev_offset
constexpr uint64_t AbbrevFieldOffset = 6;
if (!Unit->isTypeUnit()) {
DebugInfoPatcher.addLE32Patch(Unit->getOffset() + AbbrevFieldOffset,
static_cast<uint32_t>(NewAbbrevOffset));
continue;
}
if (!DebugTypesPatcher) {
ErrorOr<BinarySection &> DebugTypes =
BC.getUniqueSectionByName(".debug_types");
DebugTypes->registerPatcher(std::make_unique<SimpleBinaryPatcher>());
DebugTypesPatcher =
static_cast<SimpleBinaryPatcher *>(DebugTypes->getPatcher());
}
DebugTypesPatcher->addLE32Patch(Unit->getOffset() + AbbrevFieldOffset,
static_cast<uint32_t>(NewAbbrevOffset));
}
// No more creating new DebugInfoPatches.
std::unordered_map<uint32_t, uint32_t> CUMap =
DebugInfoPatcher.computeNewOffsets();
// Skip .debug_aranges if we are re-generating .gdb_index.
if (opts::KeepARanges || !BC.getGdbIndexSection()) {
SmallVector<char, 16> ARangesBuffer;
raw_svector_ostream OS(ARangesBuffer);
auto MAB = std::unique_ptr<MCAsmBackend>(
BC.TheTarget->createMCAsmBackend(*BC.STI, *BC.MRI, MCTargetOptions()));
ARangesSectionWriter->writeARangesSection(OS, CUMap);
const StringRef &ARangesContents = OS.str();
BC.registerOrUpdateNoteSection(".debug_aranges",
copyByteArray(ARangesContents),
ARangesContents.size());
}
}
// Creates all the data structures necessary for creating MCStreamer.
// They are passed by reference because they need to be kept around.
// Also creates known debug sections. These are sections handled by
// handleDebugDataPatching.
using KnownSectionsEntry = std::pair<MCSection *, DWARFSectionKind>;
namespace {
std::unique_ptr<BinaryContext>
createDwarfOnlyBC(const object::ObjectFile &File) {
return BinaryContext::createBinaryContext(
&File, false,
DWARFContext::create(File, DWARFContext::ProcessDebugRelocations::Ignore,
nullptr, "", WithColor::defaultErrorHandler,
WithColor::defaultWarningHandler));
}
StringMap<KnownSectionsEntry>
createKnownSectionsMap(const MCObjectFileInfo &MCOFI) {
StringMap<KnownSectionsEntry> KnownSectionsTemp = {
{"debug_info.dwo", {MCOFI.getDwarfInfoDWOSection(), DW_SECT_INFO}},
{"debug_types.dwo", {MCOFI.getDwarfTypesDWOSection(), DW_SECT_EXT_TYPES}},
{"debug_str_offsets.dwo",
{MCOFI.getDwarfStrOffDWOSection(), DW_SECT_STR_OFFSETS}},
{"debug_str.dwo", {MCOFI.getDwarfStrDWOSection(), DW_SECT_EXT_unknown}},
{"debug_loc.dwo", {MCOFI.getDwarfLocDWOSection(), DW_SECT_EXT_LOC}},
{"debug_abbrev.dwo", {MCOFI.getDwarfAbbrevDWOSection(), DW_SECT_ABBREV}},
{"debug_line.dwo", {MCOFI.getDwarfLineDWOSection(), DW_SECT_LINE}}};
return KnownSectionsTemp;
}
StringRef getSectionName(const SectionRef &Section) {
Expected<StringRef> SectionName = Section.getName();
assert(SectionName && "Invalid section name.");
StringRef Name = *SectionName;
Name = Name.substr(Name.find_first_not_of("._"));
return Name;
}
// Exctracts an appropriate slice if input is DWP.
// Applies patches or overwrites the section.
Optional<StringRef>
updateDebugData(std::string &Storage, const SectionRef &Section,
const StringMap<KnownSectionsEntry> &KnownSections,
MCStreamer &Streamer, DWARFRewriter &Writer,
const DWARFUnitIndex::Entry *DWOEntry, uint64_t DWOId,
std::unique_ptr<DebugBufferVector> &OutputBuffer) {
auto applyPatch = [&](DebugInfoBinaryPatcher *Patcher,
StringRef Data) -> StringRef {
Patcher->computeNewOffsets();
Storage = Patcher->patchBinary(Data);
return StringRef(Storage.c_str(), Storage.size());
};
using DWOSectionContribution =
const DWARFUnitIndex::Entry::SectionContribution;
auto getSliceData = [&](const DWARFUnitIndex::Entry *DWOEntry,
StringRef OutData, DWARFSectionKind Sec,
uint32_t &DWPOffset) -> StringRef {
if (DWOEntry) {
DWOSectionContribution *DWOContrubution = DWOEntry->getContribution(Sec);
DWPOffset = DWOContrubution->Offset;
OutData = OutData.substr(DWPOffset, DWOContrubution->Length);
}
return OutData;
};
StringRef Name = getSectionName(Section);
auto SectionIter = KnownSections.find(Name);
if (SectionIter == KnownSections.end())
return None;
Streamer.SwitchSection(SectionIter->second.first);
Expected<StringRef> Contents = Section.getContents();
assert(Contents && "Invalid contents.");
StringRef OutData = *Contents;
uint32_t DWPOffset = 0;
switch (SectionIter->second.second) {
default: {
if (!Name.equals("debug_str.dwo"))
errs() << "BOLT-WARNING: Unsupported Debug section: " << Name << "\n";
return OutData;
}
case DWARFSectionKind::DW_SECT_INFO: {
OutData = getSliceData(DWOEntry, OutData, DWARFSectionKind::DW_SECT_INFO,
DWPOffset);
DebugInfoBinaryPatcher *Patcher = llvm::cast<DebugInfoBinaryPatcher>(
Writer.getBinaryDWODebugInfoPatcher(DWOId));
return applyPatch(Patcher, OutData);
}
case DWARFSectionKind::DW_SECT_EXT_TYPES: {
return getSliceData(DWOEntry, OutData, DWARFSectionKind::DW_SECT_EXT_TYPES,
DWPOffset);
}
case DWARFSectionKind::DW_SECT_STR_OFFSETS: {
return getSliceData(DWOEntry, OutData,
DWARFSectionKind::DW_SECT_STR_OFFSETS, DWPOffset);
}
case DWARFSectionKind::DW_SECT_ABBREV: {
DebugAbbrevWriter *AbbrevWriter = Writer.getBinaryDWOAbbrevWriter(DWOId);
OutputBuffer = AbbrevWriter->finalize();
// Creating explicit StringRef here, otherwise
// with impicit conversion it will take null byte as end of
// string.
return StringRef(reinterpret_cast<const char *>(OutputBuffer->data()),
OutputBuffer->size());
}
case DWARFSectionKind::DW_SECT_EXT_LOC: {
DebugLocWriter *LocWriter = Writer.getDebugLocWriter(DWOId);
OutputBuffer = LocWriter->getBuffer();
// Creating explicit StringRef here, otherwise
// with impicit conversion it will take null byte as end of
// string.
return StringRef(reinterpret_cast<const char *>(OutputBuffer->data()),
OutputBuffer->size());
}
case DWARFSectionKind::DW_SECT_LINE: {
return getSliceData(DWOEntry, OutData, DWARFSectionKind::DW_SECT_LINE,
DWPOffset);
}
}
}
} // namespace
void DWARFRewriter::writeDWP(
std::unordered_map<uint64_t, std::string> &DWOIdToName) {
SmallString<0> OutputNameStr;
StringRef OutputName;
if (opts::DwarfOutputPath.empty()) {
OutputName =
Twine(opts::OutputFilename).concat(".dwp").toStringRef(OutputNameStr);
} else {
StringRef ExeFileName = llvm::sys::path::filename(opts::OutputFilename);
OutputName = Twine(opts::DwarfOutputPath)
.concat("/")
.concat(ExeFileName)
.concat(".dwp")
.toStringRef(OutputNameStr);
errs() << "BOLT-WARNING: dwarf-output-path is in effect and .dwp file will "
"possibly be written to another location that is not the same as "
"the executable\n";
}
std::error_code EC;
std::unique_ptr<ToolOutputFile> Out =
std::make_unique<ToolOutputFile>(OutputName, EC, sys::fs::OF_None);
const object::ObjectFile *File = BC.DwCtx->getDWARFObj().getFile();
std::unique_ptr<BinaryContext> TmpBC = createDwarfOnlyBC(*File);
std::unique_ptr<MCStreamer> Streamer = TmpBC->createStreamer(Out->os());
const MCObjectFileInfo &MCOFI = *Streamer->getContext().getObjectFileInfo();
StringMap<KnownSectionsEntry> KnownSections = createKnownSectionsMap(MCOFI);
MCSection *const StrSection = MCOFI.getDwarfStrDWOSection();
MCSection *const StrOffsetSection = MCOFI.getDwarfStrOffDWOSection();
// Data Structures for DWP book keeping
// Size of array corresponds to the number of sections supported by DWO format
// in DWARF4/5.
uint32_t ContributionOffsets[8] = {};
std::deque<SmallString<32>> UncompressedSections;
DWPStringPool Strings(*Streamer, StrSection);
MapVector<uint64_t, UnitIndexEntry> IndexEntries;
constexpr uint32_t IndexVersion = 2;
// Setup DWP code once.
DWARFContext *DWOCtx = BC.getDWOContext();
const DWARFUnitIndex *CUIndex = nullptr;
bool IsDWP = false;
if (DWOCtx) {
CUIndex = &DWOCtx->getCUIndex();
IsDWP = !CUIndex->getRows().empty();
}
for (const std::unique_ptr<DWARFUnit> &CU : BC.DwCtx->compile_units()) {
Optional<uint64_t> DWOId = CU->getDWOId();
if (!DWOId)
continue;
// Skipping CUs that we failed to load.
Optional<DWARFUnit *> DWOCU = BC.getDWOCU(*DWOId);
if (!DWOCU)
continue;
assert(CU->getVersion() == 4 && "For DWP output only DWARF4 is supported");
UnitIndexEntry CurEntry = {};
CurEntry.DWOName =
dwarf::toString(CU->getUnitDIE().find(
{dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}),
"");
const char *Name = CU->getUnitDIE().getShortName();
if (Name)
CurEntry.Name = Name;
StringRef CurStrSection;
StringRef CurStrOffsetSection;
// This maps each section contained in this file to its length.
// This information is later on used to calculate the contributions,
// i.e. offset and length, of each compile/type unit to a section.
std::vector<std::pair<DWARFSectionKind, uint32_t>> SectionLength;
const DWARFUnitIndex::Entry *DWOEntry = nullptr;
if (IsDWP)
DWOEntry = CUIndex->getFromHash(*DWOId);
bool StrSectionWrittenOut = false;
const object::ObjectFile *DWOFile =
(*DWOCU)->getContext().getDWARFObj().getFile();
for (const SectionRef &Section : DWOFile->sections()) {
std::string Storage = "";
std::unique_ptr<DebugBufferVector> OutputData;
Optional<StringRef> TOutData =
updateDebugData(Storage, Section, KnownSections, *Streamer, *this,
DWOEntry, *DWOId, OutputData);
if (!TOutData)
continue;
StringRef OutData = *TOutData;
StringRef Name = getSectionName(Section);
if (Name.equals("debug_str.dwo")) {
CurStrSection = OutData;
} else {
// Since handleDebugDataPatching returned true, we already know this is
// a known section.
auto SectionIter = KnownSections.find(Name);
if (SectionIter->second.second == DWARFSectionKind::DW_SECT_STR_OFFSETS)
CurStrOffsetSection = OutData;
else
Streamer->emitBytes(OutData);
auto Index =
getContributionIndex(SectionIter->second.second, IndexVersion);
CurEntry.Contributions[Index].Offset = ContributionOffsets[Index];
CurEntry.Contributions[Index].Length = OutData.size();
ContributionOffsets[Index] += CurEntry.Contributions[Index].Length;
}
// Strings are combined in to a new string section, and de-duplicated
// based on hash.
if (!StrSectionWrittenOut && !CurStrOffsetSection.empty() &&
!CurStrSection.empty()) {
writeStringsAndOffsets(*Streamer.get(), Strings, StrOffsetSection,
CurStrSection, CurStrOffsetSection,
CU->getVersion());
StrSectionWrittenOut = true;
}
}
CompileUnitIdentifiers CUI{*DWOId, CurEntry.Name.c_str(),
CurEntry.DWOName.c_str()};
auto P = IndexEntries.insert(std::make_pair(CUI.Signature, CurEntry));
if (!P.second) {
Error Err = buildDuplicateError(*P.first, CUI, "");
errs() << "BOLT-ERROR: " << toString(std::move(Err)) << "\n";
return;
}
}
// Lie about the type contribution for DWARF < 5. In DWARFv5 the type
// section does not exist, so no need to do anything about this.
ContributionOffsets[getContributionIndex(DW_SECT_EXT_TYPES, 2)] = 0;
writeIndex(*Streamer.get(), MCOFI.getDwarfCUIndexSection(),
ContributionOffsets, IndexEntries, IndexVersion);
Streamer->Finish();
Out->keep();
}
void DWARFRewriter::writeDWOFiles(
std::unordered_map<uint64_t, std::string> &DWOIdToName) {
// Setup DWP code once.
DWARFContext *DWOCtx = BC.getDWOContext();
const DWARFUnitIndex *CUIndex = nullptr;
bool IsDWP = false;
if (DWOCtx) {
CUIndex = &DWOCtx->getCUIndex();
IsDWP = !CUIndex->getRows().empty();
}
for (const std::unique_ptr<DWARFUnit> &CU : BC.DwCtx->compile_units()) {
Optional<uint64_t> DWOId = CU->getDWOId();
if (!DWOId)
continue;
// Skipping CUs that we failed to load.
Optional<DWARFUnit *> DWOCU = BC.getDWOCU(*DWOId);
if (!DWOCU)
continue;
std::string CompDir = opts::DwarfOutputPath.empty()
? CU->getCompilationDir()
: opts::DwarfOutputPath.c_str();
std::string ObjectName = getDWOName(*CU.get(), nullptr, DWOIdToName);
auto FullPath = CompDir.append("/").append(ObjectName);
std::error_code EC;
std::unique_ptr<ToolOutputFile> TempOut =
std::make_unique<ToolOutputFile>(FullPath, EC, sys::fs::OF_None);
const DWARFUnitIndex::Entry *DWOEntry = nullptr;
if (IsDWP)
DWOEntry = CUIndex->getFromHash(*DWOId);
const object::ObjectFile *File =
(*DWOCU)->getContext().getDWARFObj().getFile();
std::unique_ptr<BinaryContext> TmpBC = createDwarfOnlyBC(*File);
std::unique_ptr<MCStreamer> Streamer = TmpBC->createStreamer(TempOut->os());
StringMap<KnownSectionsEntry> KnownSections =
createKnownSectionsMap(*Streamer->getContext().getObjectFileInfo());
for (const SectionRef &Section : File->sections()) {
std::string Storage = "";
std::unique_ptr<DebugBufferVector> OutputData;
if (Optional<StringRef> OutData =
updateDebugData(Storage, Section, KnownSections, *Streamer, *this,
DWOEntry, *DWOId, OutputData))
Streamer->emitBytes(*OutData);
}
Streamer->Finish();
TempOut->keep();
}
}
void DWARFRewriter::updateGdbIndexSection() {
if (!BC.getGdbIndexSection())
return;
// See https://sourceware.org/gdb/onlinedocs/gdb/Index-Section-Format.html
// for .gdb_index section format.
StringRef GdbIndexContents = BC.getGdbIndexSection()->getContents();
const char *Data = GdbIndexContents.data();
// Parse the header.
const uint32_t Version = read32le(Data);
if (Version != 7 && Version != 8) {
errs() << "BOLT-ERROR: can only process .gdb_index versions 7 and 8\n";
exit(1);
}
// Some .gdb_index generators use file offsets while others use section
// offsets. Hence we can only rely on offsets relative to each other,
// and ignore their absolute values.
const uint32_t CUListOffset = read32le(Data + 4);
const uint32_t CUTypesOffset = read32le(Data + 8);
const uint32_t AddressTableOffset = read32le(Data + 12);
const uint32_t SymbolTableOffset = read32le(Data + 16);
const uint32_t ConstantPoolOffset = read32le(Data + 20);
Data += 24;
// Map CUs offsets to indices and verify existing index table.
std::map<uint32_t, uint32_t> OffsetToIndexMap;
const uint32_t CUListSize = CUTypesOffset - CUListOffset;
const unsigned NumCUs = BC.DwCtx->getNumCompileUnits();
if (CUListSize != NumCUs * 16) {
errs() << "BOLT-ERROR: .gdb_index: CU count mismatch\n";
exit(1);
}
for (unsigned Index = 0; Index < NumCUs; ++Index, Data += 16) {
const DWARFUnit *CU = BC.DwCtx->getUnitAtIndex(Index);
const uint64_t Offset = read64le(Data);
if (CU->getOffset() != Offset) {
errs() << "BOLT-ERROR: .gdb_index CU offset mismatch\n";
exit(1);
}
OffsetToIndexMap[Offset] = Index;
}
// Ignore old address table.
const uint32_t OldAddressTableSize = SymbolTableOffset - AddressTableOffset;
// Move Data to the beginning of symbol table.
Data += SymbolTableOffset - CUTypesOffset;
// Calculate the size of the new address table.
uint32_t NewAddressTableSize = 0;
for (const auto &CURangesPair : ARangesSectionWriter->getCUAddressRanges()) {
const SmallVector<DebugAddressRange, 2> &Ranges = CURangesPair.second;
NewAddressTableSize += Ranges.size() * 20;
}
// Difference between old and new table (and section) sizes.
// Could be negative.
int32_t Delta = NewAddressTableSize - OldAddressTableSize;
size_t NewGdbIndexSize = GdbIndexContents.size() + Delta;
// Free'd by ExecutableFileMemoryManager.
auto *NewGdbIndexContents = new uint8_t[NewGdbIndexSize];
uint8_t *Buffer = NewGdbIndexContents;
write32le(Buffer, Version);
write32le(Buffer + 4, CUListOffset);
write32le(Buffer + 8, CUTypesOffset);
write32le(Buffer + 12, AddressTableOffset);
write32le(Buffer + 16, SymbolTableOffset + Delta);
write32le(Buffer + 20, ConstantPoolOffset + Delta);
Buffer += 24;
// Copy over CU list and types CU list.
memcpy(Buffer, GdbIndexContents.data() + 24,
AddressTableOffset - CUListOffset);
Buffer += AddressTableOffset - CUListOffset;
// Generate new address table.
for (const std::pair<const uint64_t, DebugAddressRangesVector> &CURangesPair :
ARangesSectionWriter->getCUAddressRanges()) {
const uint32_t CUIndex = OffsetToIndexMap[CURangesPair.first];
const DebugAddressRangesVector &Ranges = CURangesPair.second;
for (const DebugAddressRange &Range : Ranges) {
write64le(Buffer, Range.LowPC);
write64le(Buffer + 8, Range.HighPC);
write32le(Buffer + 16, CUIndex);
Buffer += 20;
}
}
const size_t TrailingSize =
GdbIndexContents.data() + GdbIndexContents.size() - Data;
assert(Buffer + TrailingSize == NewGdbIndexContents + NewGdbIndexSize &&
"size calculation error");
// Copy over the rest of the original data.
memcpy(Buffer, Data, TrailingSize);
// Register the new section.
BC.registerOrUpdateNoteSection(".gdb_index", NewGdbIndexContents,
NewGdbIndexSize);
}
void DWARFRewriter::convertToRanges(DWARFDie DIE,
const DebugAddressRangesVector &Ranges,
SimpleBinaryPatcher &DebugInfoPatcher) {
uint64_t RangesSectionOffset;
if (Ranges.empty())
RangesSectionOffset = RangesSectionWriter->getEmptyRangesOffset();
else
RangesSectionOffset = RangesSectionWriter->addRanges(Ranges);
convertToRangesPatchDebugInfo(DIE, RangesSectionOffset, DebugInfoPatcher);
}
void DWARFRewriter::convertPending(const DWARFUnit &Unit,
const DWARFAbbreviationDeclaration *Abbrev,
SimpleBinaryPatcher &DebugInfoPatcher,
DebugAbbrevWriter &AbbrevWriter) {
if (ConvertedRangesAbbrevs.count(Abbrev))
return;
convertToRangesPatchAbbrev(Unit, Abbrev, AbbrevWriter);
auto I = PendingRanges.find(Abbrev);
if (I != PendingRanges.end()) {
for (std::pair<DWARFDieWrapper, DebugAddressRange> &Pair : I->second)
convertToRanges(Pair.first, {Pair.second}, DebugInfoPatcher);
PendingRanges.erase(I);
}
ConvertedRangesAbbrevs.emplace(Abbrev);
}
void DWARFRewriter::addToPendingRanges(
const DWARFAbbreviationDeclaration *Abbrev, DWARFDie DIE,
DebugAddressRangesVector &FunctionRanges, Optional<uint64_t> DWOId) {
Optional<DWARFFormValue> LowPcValue = DIE.find(dwarf::DW_AT_low_pc);
Optional<DWARFFormValue> HighPcValue = DIE.find(dwarf::DW_AT_high_pc);
if (LowPcValue &&
LowPcValue->getForm() == dwarf::Form::DW_FORM_GNU_addr_index) {
assert(DWOId && "Invalid DWO ID.");
(void)DWOId;
assert(HighPcValue && "Low PC exists, but not High PC.");
(void)HighPcValue;
uint64_t IndexL = LowPcValue->getRawUValue();
uint64_t IndexH = HighPcValue->getRawUValue();
for (auto Address : FunctionRanges) {
AddrWriter->addIndexAddress(Address.LowPC, IndexL, *DWOId);
// 2.17.2
// If the value of the DW_AT_high_pc is of class address, it is the
// relocated address of the first location past the last instruction
// associated with the entity; if it is of class constant, the value is
// an unsigned integer offset which when added to the low PC gives the
// address of the first location past the last instruction associated
// with the entity.
if (!HighPcValue->isFormClass(DWARFFormValue::FC_Constant))
AddrWriter->addIndexAddress(Address.HighPC, IndexH, *DWOId);
}
}
PendingRanges[Abbrev].emplace_back(
std::make_pair(DWARFDieWrapper(DIE), FunctionRanges.front()));
}
std::unique_ptr<DebugBufferVector>
DWARFRewriter::makeFinalLocListsSection(SimpleBinaryPatcher &DebugInfoPatcher) {
auto LocBuffer = std::make_unique<DebugBufferVector>();
auto LocStream = std::make_unique<raw_svector_ostream>(*LocBuffer);
auto Writer =
std::unique_ptr<MCObjectWriter>(BC.createObjectWriter(*LocStream));
uint64_t SectionOffset = 0;
// Add an empty list as the first entry;
const char Zeroes[16] = {0};
*LocStream << StringRef(Zeroes, 16);
SectionOffset += 2 * 8;
for (std::pair<const uint64_t, std::unique_ptr<DebugLocWriter>> &Loc :
LocListWritersByCU) {
DebugLocWriter *LocWriter = Loc.second.get();
if (auto *LocListWriter = llvm::dyn_cast<DebugLoclistWriter>(LocWriter)) {
SimpleBinaryPatcher *Patcher =
getBinaryDWODebugInfoPatcher(LocListWriter->getDWOID());
LocListWriter->finalize(0, *Patcher);
continue;
}
LocWriter->finalize(SectionOffset, DebugInfoPatcher);
std::unique_ptr<DebugBufferVector> CurrCULocationLists =
LocWriter->getBuffer();
*LocStream << *CurrCULocationLists;
SectionOffset += CurrCULocationLists->size();
}
return LocBuffer;
}
void DWARFRewriter::flushPendingRanges(SimpleBinaryPatcher &DebugInfoPatcher) {
for (std::pair<const DWARFAbbreviationDeclaration *const,
std::vector<std::pair<DWARFDieWrapper, DebugAddressRange>>>
&I : PendingRanges)
for (std::pair<DWARFDieWrapper, DebugAddressRange> &RangePair : I.second)
patchLowHigh(RangePair.first, RangePair.second, DebugInfoPatcher);
clearList(PendingRanges);
}
namespace {
void getRangeAttrData(DWARFDie DIE, Optional<AttrInfo> &LowPCVal,
Optional<AttrInfo> &HighPCVal) {
LowPCVal = findAttributeInfo(DIE, dwarf::DW_AT_low_pc);
HighPCVal = findAttributeInfo(DIE, dwarf::DW_AT_high_pc);
uint64_t LowPCOffset = LowPCVal->Offset;
uint64_t HighPCOffset = HighPCVal->Offset;
dwarf::Form LowPCForm = LowPCVal->V.getForm();
dwarf::Form HighPCForm = HighPCVal->V.getForm();
if (LowPCForm != dwarf::DW_FORM_addr &&
LowPCForm != dwarf::DW_FORM_GNU_addr_index) {
errs() << "BOLT-WARNING: unexpected low_pc form value. Cannot update DIE "
<< "at offset 0x" << Twine::utohexstr(DIE.getOffset()) << "\n";
return;
}
if (HighPCForm != dwarf::DW_FORM_addr && HighPCForm != dwarf::DW_FORM_data8 &&
HighPCForm != dwarf::DW_FORM_data4 &&
HighPCForm != dwarf::DW_FORM_data2 &&
HighPCForm != dwarf::DW_FORM_data1 &&
HighPCForm != dwarf::DW_FORM_udata) {
errs() << "BOLT-WARNING: unexpected high_pc form value. Cannot update DIE "
<< "at offset 0x" << Twine::utohexstr(DIE.getOffset()) << "\n";
return;
}
if ((LowPCOffset == -1U || (LowPCOffset + 8 != HighPCOffset)) &&
LowPCForm != dwarf::DW_FORM_GNU_addr_index) {
errs() << "BOLT-WARNING: high_pc expected immediately after low_pc. "
<< "Cannot update DIE at offset 0x"
<< Twine::utohexstr(DIE.getOffset()) << '\n';
return;
}
}
} // namespace
void DWARFRewriter::patchLowHigh(DWARFDie DIE, DebugAddressRange Range,
SimpleBinaryPatcher &DebugInfoPatcher) {
Optional<AttrInfo> LowPCVal = None;
Optional<AttrInfo> HighPCVal = None;
getRangeAttrData(DIE, LowPCVal, HighPCVal);
uint64_t LowPCOffset = LowPCVal->Offset;
uint64_t HighPCOffset = HighPCVal->Offset;
auto *TempDebugPatcher = &DebugInfoPatcher;
if (LowPCVal->V.getForm() == dwarf::DW_FORM_GNU_addr_index) {
DWARFUnit *Unit = DIE.getDwarfUnit();
assert(Unit->isDWOUnit() && "DW_FORM_GNU_addr_index not part of DWO.");
uint32_t AddressIndex =
AddrWriter->getIndexFromAddress(Range.LowPC, *Unit->getDWOId());
TempDebugPatcher = getBinaryDWODebugInfoPatcher(*Unit->getDWOId());
TempDebugPatcher->addUDataPatch(LowPCOffset, AddressIndex,
std::abs(int(HighPCOffset - LowPCOffset)));
// TODO: In DWARF5 support ULEB128 for high_pc
} else {
TempDebugPatcher->addLE64Patch(LowPCOffset, Range.LowPC);
}
if (isHighPcFormEightBytes(HighPCVal->V.getForm()))
TempDebugPatcher->addLE64Patch(HighPCOffset, Range.HighPC - Range.LowPC);
else
TempDebugPatcher->addLE32Patch(HighPCOffset, Range.HighPC - Range.LowPC,
HighPCVal->Size);
}
void DWARFRewriter::convertToRangesPatchAbbrev(
const DWARFUnit &Unit, const DWARFAbbreviationDeclaration *Abbrev,
DebugAbbrevWriter &AbbrevWriter, Optional<uint64_t> RangesBase) {
auto getAttributeForm = [&Abbrev](const dwarf::Attribute Attr) {
Optional<uint32_t> Index = Abbrev->findAttributeIndex(Attr);
assert(Index && "attribute not found");
return Abbrev->getFormByIndex(*Index);
};
dwarf::Form LowPCForm = getAttributeForm(dwarf::DW_AT_low_pc);
// DW_FORM_GNU_addr_index is already variable encoding so nothing to do
// there.
if (RangesBase) {
assert(LowPCForm != dwarf::DW_FORM_GNU_addr_index);
AbbrevWriter.addAttributePatch(Unit, Abbrev, dwarf::DW_AT_low_pc,
dwarf::DW_AT_GNU_ranges_base,
dwarf::DW_FORM_sec_offset);
}
AbbrevWriter.addAttributePatch(Unit, Abbrev, dwarf::DW_AT_high_pc,
dwarf::DW_AT_ranges,
dwarf::DW_FORM_sec_offset);
}
void DWARFRewriter::convertToRangesPatchDebugInfo(
DWARFDie DIE, uint64_t RangesSectionOffset,
SimpleBinaryPatcher &DebugInfoPatcher, Optional<uint64_t> RangesBase) {
Optional<AttrInfo> LowPCVal = None;
Optional<AttrInfo> HighPCVal = None;
getRangeAttrData(DIE, LowPCVal, HighPCVal);
uint64_t LowPCOffset = LowPCVal->Offset;
uint64_t HighPCOffset = HighPCVal->Offset;
std::lock_guard<std::mutex> Lock(DebugInfoPatcherMutex);
uint32_t BaseOffset = 0;
if (LowPCVal->V.getForm() == dwarf::DW_FORM_GNU_addr_index) {
// Use ULEB128 for the value.
DebugInfoPatcher.addUDataPatch(LowPCOffset, 0,
std::abs(int(HighPCOffset - LowPCOffset)));
// Ranges are relative to DW_AT_GNU_ranges_base.
BaseOffset = DebugInfoPatcher.getRangeBase();
} else {
// If case DW_AT_low_pc was converted into DW_AT_GNU_ranges_base
if (RangesBase)
DebugInfoPatcher.addLE32Patch(LowPCOffset, *RangesBase, 8);
else
DebugInfoPatcher.addLE64Patch(LowPCOffset, 0);
}
DebugInfoPatcher.addLE32Patch(HighPCOffset, RangesSectionOffset - BaseOffset,
HighPCVal->Size);
}
| 39.866923 | 80 | 0.656824 | hborla |
60b5274bc7478d2f77ed5e78b5246c4ab3989f6d | 10,868 | cpp | C++ | src/Microsoft.DotNet.Wpf/src/System.Printing/CPP/src/ObjectsAttributesValuesFactory.cpp | txlos/wpf | 4004b4e8c8d5c0d5e9de0f1be1fd929c3dee6fa1 | [
"MIT"
] | 5,937 | 2018-12-04T16:32:50.000Z | 2022-03-31T09:48:37.000Z | src/Microsoft.DotNet.Wpf/src/System.Printing/CPP/src/ObjectsAttributesValuesFactory.cpp | txlos/wpf | 4004b4e8c8d5c0d5e9de0f1be1fd929c3dee6fa1 | [
"MIT"
] | 4,151 | 2018-12-04T16:38:19.000Z | 2022-03-31T18:41:14.000Z | src/Microsoft.DotNet.Wpf/src/System.Printing/CPP/src/ObjectsAttributesValuesFactory.cpp | txlos/wpf | 4004b4e8c8d5c0d5e9de0f1be1fd929c3dee6fa1 | [
"MIT"
] | 1,084 | 2018-12-04T16:24:21.000Z | 2022-03-30T13:52:03.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#include "win32inc.hpp"
using namespace System;
using namespace System::IO;
using namespace System::Collections;
using namespace System::Reflection;
using namespace System::Runtime::InteropServices;
using namespace System::Xml;
using namespace System::Xml::XPath;
using namespace System::Collections::Specialized;
#ifndef __PRINTSYSTEMINTEROPINC_HPP__
#include <PrintSystemInteropInc.hpp>
#endif
#ifndef __PRINTSYSTEMINC_HPP__
#include <PrintSystemInc.hpp>
#endif
#ifndef __PRINTSYSTEMPATHRESOLVER_HPP__
#include <PrintSystemPathResolver.hpp>
#endif
using namespace System::Printing;
using namespace System::Printing::IndexedProperties;
#ifndef __OBJECTSATTRIBUTESVALUESFACTORY_HPP__
#include <ObjectsAttributesValuesFactory.hpp>
#endif
#ifndef __PRINTSYSTEMATTRIBUTEVALUEFACTORY_HPP__
#include <PrintSystemAttributeValueFactory.hpp>
#endif
#ifndef __PRINTSYSTEMOBJECTFACTORY_HPP__
#include <PrintSystemObjectFactory.hpp>
#endif
using namespace System::Printing::Activation;
ObjectsAttributesValuesFactory::
ObjectsAttributesValuesFactory(
void
):
valueDelegatesTable(nullptr),
noValueDelegatesTable(nullptr),
valueLinkedDelegatesTable(nullptr),
noValueLinkedDelegatesTable(nullptr)
{
valueDelegatesTable = gcnew Hashtable;
noValueDelegatesTable = gcnew Hashtable;
valueLinkedDelegatesTable = gcnew Hashtable;
noValueLinkedDelegatesTable = gcnew Hashtable;
}
ObjectsAttributesValuesFactory::
~ObjectsAttributesValuesFactory(
void
)
{
InternalDispose(true);
}
ObjectsAttributesValuesFactory::
!ObjectsAttributesValuesFactory(
void
)
{
InternalDispose(false);
}
void
ObjectsAttributesValuesFactory::
InternalDispose(
bool disposing
)
{
if(!this->isDisposed)
{
System::Threading::Monitor::Enter(SyncRoot);
{
__try
{
if(!this->isDisposed)
{
if(disposing)
{
isDisposed = true;
valueDelegatesTable = nullptr;
noValueDelegatesTable = nullptr;
valueLinkedDelegatesTable = nullptr;
noValueLinkedDelegatesTable = nullptr;
}
}
}
__finally
{
System::Threading::Monitor::Exit(SyncRoot);
}
}
}
}
ObjectsAttributesValuesFactory^
ObjectsAttributesValuesFactory::Value::
get(
void
)
{
if(ObjectsAttributesValuesFactory::value == nullptr)
{
System::Threading::Monitor::Enter(SyncRoot);
{
__try
{
if(ObjectsAttributesValuesFactory::value == nullptr)
{
ObjectsAttributesValuesFactory^ instanceValue = gcnew ObjectsAttributesValuesFactory();
//
// 1. Register all the managed classes that follow the frame work
// instantiation method
//
for(Int32 numOfRegisterations = 0;
numOfRegisterations < registerationDelegate->Length;
numOfRegisterations++)
{
registerationDelegate[numOfRegisterations]->DynamicInvoke();
}
//
// 2.Register creation methods for different attributes with different types
// for different objects
//
for(Int32 numOfObjectTypeDelegates = 0;
numOfObjectTypeDelegates < objectTypeDelegate->Length;
numOfObjectTypeDelegates++)
{
instanceValue->
RegisterObjectAttributeValueCreationMethod(objectTypeDelegate[numOfObjectTypeDelegates]->type,
objectTypeDelegate[numOfObjectTypeDelegates]->delegateValue);
instanceValue->
RegisterObjectAttributeNoValueCreationMethod(objectTypeDelegate[numOfObjectTypeDelegates]->type,
objectTypeDelegate[numOfObjectTypeDelegates]->delegateNoValue);
instanceValue->
RegisterObjectAttributeValueLinkedCreationMethod(objectTypeDelegate[numOfObjectTypeDelegates]->type,
objectTypeDelegate[numOfObjectTypeDelegates]->delegateValueLinked);
instanceValue->
RegisterObjectAttributeNoValueLinkedCreationMethod(objectTypeDelegate[numOfObjectTypeDelegates]->type,
objectTypeDelegate[numOfObjectTypeDelegates]->delegateNoValueLinked);
}
//
// 3.Register the attribute type creation methods
//
for(Int32 numOfAttributeValueTypeDelegate = 0;
numOfAttributeValueTypeDelegate < attributeValueTypeDelegate->Length;
numOfAttributeValueTypeDelegate++)
{
PrintPropertyFactory::Value->
RegisterValueCreationDelegate(attributeValueTypeDelegate[numOfAttributeValueTypeDelegate]->type,
attributeValueTypeDelegate[numOfAttributeValueTypeDelegate]->delegateValue);
PrintPropertyFactory::Value->
RegisterNoValueCreationDelegate(attributeValueTypeDelegate[numOfAttributeValueTypeDelegate]->type,
attributeValueTypeDelegate[numOfAttributeValueTypeDelegate]->delegateNoValue);
PrintPropertyFactory::Value->
RegisterValueLinkedCreationDelegate(attributeValueTypeDelegate[numOfAttributeValueTypeDelegate]->type,
attributeValueTypeDelegate[numOfAttributeValueTypeDelegate]->delegateValueLinked);
PrintPropertyFactory::Value->
RegisterNoValueLinkedCreationDelegate(attributeValueTypeDelegate[numOfAttributeValueTypeDelegate]->type,
attributeValueTypeDelegate[numOfAttributeValueTypeDelegate]->delegateNoValueLinked);
}
ObjectsAttributesValuesFactory::value = instanceValue;
}
}
__finally
{
System::Threading::Monitor::Exit(SyncRoot);
}
}
}
return const_cast<ObjectsAttributesValuesFactory^>(ObjectsAttributesValuesFactory::value);
}
Object^
ObjectsAttributesValuesFactory::SyncRoot::
get(
void
)
{
return const_cast<Object^>(syncRoot);
}
void
ObjectsAttributesValuesFactory::
RegisterObjectAttributeNoValueCreationMethod(
Type^ type,
PrintSystemObject::CreateWithNoValue^ delegate
)
{
try
{
noValueDelegatesTable->Add(type->FullName,
delegate);
}
catch(ArgumentException^)
{
//
// Nothing to do, this means that the item has been already
// added to the hashtable
//
}
}
void
ObjectsAttributesValuesFactory::
RegisterObjectAttributeNoValueLinkedCreationMethod(
Type^ type,
PrintSystemObject::CreateWithNoValueLinked^ delegate
)
{
try
{
noValueLinkedDelegatesTable->Add(type->FullName,
delegate);
}
catch(ArgumentException^)
{
//
// Nothing to do, this means that the item has been already
// added to the hashtable
//
}
}
void
ObjectsAttributesValuesFactory::
RegisterObjectAttributeValueCreationMethod(
Type^ type,
PrintSystemObject::CreateWithValue^ delegate
)
{
try
{
valueDelegatesTable->Add(type->FullName,
delegate);
}
catch(ArgumentException^)
{
//
// Nothing to do, this means that the item has been already
// added to the hashtable
//
}
}
void
ObjectsAttributesValuesFactory::
RegisterObjectAttributeValueLinkedCreationMethod(
Type^ type,
PrintSystemObject::CreateWithValueLinked^ delegate
)
{
try
{
valueLinkedDelegatesTable->Add(type->FullName,
delegate);
}
catch(ArgumentException^)
{
//
// Nothing to do, this means that the item has been already
// added to the hashtable
//
}
}
PrintProperty^
ObjectsAttributesValuesFactory::
Create(
Type^ type,
String^ attributeName
)
{
PrintSystemObject::CreateWithNoValue^ attributeValueDelegate =
(PrintSystemObject::CreateWithNoValue^)noValueDelegatesTable[type->FullName];
return attributeValueDelegate->Invoke(attributeName);
}
PrintProperty^
ObjectsAttributesValuesFactory::
Create(
Type^ type,
String^ attributeName,
Object^ attributeValue
)
{
PrintSystemObject::CreateWithValue^ attributeValueDelegate =
(PrintSystemObject::CreateWithValue^)valueDelegatesTable[type->FullName];
return attributeValueDelegate->Invoke(attributeName,attributeValue);
}
PrintProperty^
ObjectsAttributesValuesFactory::
Create(
Type^ type,
String^ attributeName,
MulticastDelegate^ delegate
)
{
PrintSystemObject::CreateWithNoValueLinked^ attributeValueDelegate =
(PrintSystemObject::CreateWithNoValueLinked^)noValueLinkedDelegatesTable[type->FullName];
return attributeValueDelegate->Invoke(attributeName,delegate);
}
PrintProperty^
ObjectsAttributesValuesFactory::
Create(
Type^ type,
String^ attributeName,
Object^ attributeValue,
MulticastDelegate^ delegate
)
{
PrintSystemObject::CreateWithValueLinked^ attributeValueDelegate =
(PrintSystemObject::CreateWithValueLinked^)valueLinkedDelegatesTable[type->FullName];
return attributeValueDelegate->Invoke(attributeName,attributeValue,delegate);
}
| 31.140401 | 144 | 0.602963 | txlos |
60b88c99d13aceb2c9e14268efadfe172c6f0ad9 | 3,052 | cpp | C++ | cycle_finding.cpp | elsantodel90/cses-problemset | 15550a4533ee0476e763c670134f768c85a87a4f | [
"Unlicense"
] | null | null | null | cycle_finding.cpp | elsantodel90/cses-problemset | 15550a4533ee0476e763c670134f768c85a87a4f | [
"Unlicense"
] | null | null | null | cycle_finding.cpp | elsantodel90/cses-problemset | 15550a4533ee0476e763c670134f768c85a87a4f | [
"Unlicense"
] | 1 | 2021-05-14T15:28:31.000Z | 2021-05-14T15:28:31.000Z | #include <iostream>
#include <algorithm>
#include <cassert>
#include <vector>
#include <stack>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <cstring>
using namespace std;
#define forn(i,n) for(int i=0;i<int(n);i++)
#define forsn(i,s,n) for(int i=int(s);i<int(n);i++)
#define dforn(i,n) for(int i=int(n)-1;i>=0;i--)
#define DBG(x) cerr << #x << " = " << (x) << endl
#define esta(x,c) ((c).find(x) != (c).end())
#define all(c) (c).begin(), (c).end()
typedef long long tint;
typedef pair<int,int> pint;
typedef pair<tint,tint> ptint;
const int MAXN = 2600;
struct Edge
{
int node;
tint cost;
};
tint bf[MAXN][MAXN]; // longitud, nodo
Edge bestParent[MAXN][MAXN]; // longitud, nodo
vector<Edge> parents[MAXN];
const tint INF = 1000000000000000000LL;
void printCycle(int node,int n)
{
vector<Edge> path;
forn(steps, n+1)
{
assert(node >= 0);
Edge e = bestParent[n-steps][node];
path.push_back({node, e.cost});
node = e.node;
}
assert(node == -1);
reverse(all(path));
vector<bool> visited(n, false);
stack<Edge> s;
for (Edge e : path)
{
if (visited[e.node])
{
vector<int> cycle = {e.node};
tint cycleCost = e.cost;
assert(!s.empty());
#define STACKTOP_NODE s.top().node
while (STACKTOP_NODE != e.node)
{
cycle.push_back(STACKTOP_NODE);
cycleCost += s.top().cost;
visited[STACKTOP_NODE] = false;
s.pop();
assert(!s.empty());
}
cycle.push_back(e.node);
if (cycleCost < 0)
{
dforn(i, cycle.size())
{
if (i < int(cycle.size())-1)
cout << " ";
cout << 1+cycle[i];
}
cout << "\n";
}
}
else
{
visited[e.node] = true;
s.push(e);
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n,m;
cin >> n >> m;
forn(i,m)
{
int a,b;
tint c;
cin >> a >> b >> c;
a--; b--;
parents[b].push_back({a,c});
}
forn(i,n)
{
bf[0][i] = 0;
bestParent[0][i] = {-1,0};
}
forsn(l,1,n+1)
forn(i,n)
{
bf[l][i] = INF;
bestParent[l][i] = {-1,INF};
for (Edge edge : parents[i])
{
tint newCost = bf[l-1][edge.node] + edge.cost;
if (newCost < bf[l][i])
{
bf[l][i] = newCost;
bestParent[l][i] = edge;
}
}
}
forn(i,n)
{
tint bestCost = INF;
forn(l,n)
bestCost = min(bestCost, bf[l][i]);
if (bf[n][i] < bestCost)
{
cout << "YES\n";
printCycle(i,n);
return 0;
}
}
cout << "NO\n";
return 0;
}
| 21.194444 | 58 | 0.445282 | elsantodel90 |
60b8b8951080950b3b7d455fa09e29c09b44f5cf | 6,373 | cpp | C++ | tc 160+/BatmanAndRobin.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 3 | 2015-05-25T06:24:37.000Z | 2016-09-10T07:58:00.000Z | tc 160+/BatmanAndRobin.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | null | null | null | tc 160+/BatmanAndRobin.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 5 | 2015-05-25T06:24:40.000Z | 2021-08-19T19:22:29.000Z | #include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstring>
#include <cmath>
using namespace std;
int N;
struct point {
long long x, y;
point(long long x_, long long y_): x(x_), y(y_) {}
};
point operator-(const point &a, const point &b) {
return point(a.x-b.x, a.y-b.y);
}
vector<point> P;
struct comparator {
bool operator()(int i, int j) {
if (P[i].x != P[j].x) {
return P[i].x < P[j].x;
} else {
return P[i].y < P[j].y;
}
}
};
long long cross(const point &a, const point &b) {
return a.x*b.y - a.y*b.x;
}
int sgn0(long long x) {
return x<0 ? -1 : int(x>0);
}
int ccw(const point &a, const point &b) {
return sgn0(cross(a, b));
}
int ccw(const point &c, const point &a, const point &b) {
return ccw(b-a, c-a);
}
int ccw(int k, int i, int j) {
return ccw(P[k], P[i], P[j]);
}
vector<int> combine(vector<int> A, const vector<int> &B) {
for (int i=0; i<(int)B.size(); ++i) {
A.push_back(B[i]);
}
return A;
}
vector<int> convex_hull(vector<int> A) {
if (A.size() < 3) {
return A;
}
sort(A.begin(), A.end(), comparator());
vector<int> up, down;
int p_down = 0;
int p_up = 0;
while (p_up<(int)A.size() && P[A[p_up]].x==P[A[p_down]].x) {
++p_up;
}
--p_up;
up.push_back(p_up);
down.push_back(p_down);
while (true) {
while (p_down<(int)A.size() && P[A[p_down]].x==P[A[down.back()]].x) {
++p_down;
}
if (p_down == (int)A.size()) {
break;
}
while (down.size()>1 && ccw(P[A[p_down]], P[A[down[(int)down.size()-2]]], P[A[down.back()]])<=0) {
down.pop_back();
}
down.push_back(p_down);
p_up = p_down;
while (p_up<(int)A.size() && P[A[p_up]].x==P[A[p_down]].x) {
++p_up;
}
--p_up;
while (up.size()>1 && ccw(P[A[p_up]], P[A[up[(int)up.size()-2]]], P[A[up.back()]])>=0) {
up.pop_back();
}
up.push_back(p_up);
}
if (up.back() == down.back()) {
up.pop_back();
}
reverse(up.begin(), up.end());
if (up.back() == down[0]) {
up.pop_back();
}
vector<int> ret;
for (int i=0; i<(int)down.size(); ++i) {
ret.push_back(A[down[i]]);
}
for (int i=0; i<(int)up.size(); ++i) {
ret.push_back(A[up[i]]);
}
return ret;
}
double area(const vector<int> &A) {
double ret = 0.0;
for (int i=0; i<(int)A.size(); ++i) {
int j = (i+1)%A.size();
ret += cross(P[A[j]], P[A[i]]);
}
return fabs(ret)/2.0;
}
double calc(const vector<int> &A, const vector<int> &B) {
return max(area(convex_hull(A)), area(convex_hull(B)));
}
class BatmanAndRobin {
public:
double minArea(vector <int> x, vector <int> y) {
N = x.size();
if (N == 1) {
return 0.0;
}
P.clear();
for (int i=0; i<N; ++i) {
P.push_back(point(x[i], y[i]));
}
double sol = 1e32;
for (int i=0; i<N; ++i) {
for (int j=i+1; j<N; ++j) {
vector<int> L, R, on;
for (int k=0; k<N; ++k) {
int tmp = ccw(k, i, j);
if (tmp == 0) {
on.push_back(k);
} else if (tmp == 1) {
R.push_back(k);
} else {
L.push_back(k);
}
}
sol = min(sol, calc(combine(L, on), R));
sol = min(sol, calc(L, combine(R, on)));
}
}
return sol;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arr0[] = {100,100,90,90,-100,-100,-90,-90}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {100,90,100,90,-100,-90,-100,-90}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 100.0; verify_case(0, Arg2, minArea(Arg0, Arg1)); }
void test_case_1() { int Arr0[] = {-1000,-1000,1000,1000,1000,-1000}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {-1000,1000,-1000,1000,0,0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 0.0; verify_case(1, Arg2, minArea(Arg0, Arg1)); }
void test_case_2() { int Arr0[] = {-1000,-1000,1000,1000,0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {-1000,1000,-1000,1000,0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 1000000.0; verify_case(2, Arg2, minArea(Arg0, Arg1)); }
void test_case_3() { int Arr0[] = {-904,-812,-763,-735,-692,-614,-602,-563,-435,-243,-87,-52,-28,121,126,149,157,185,315,336,390,470,528,591,673,798,815,837,853,874}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {786,10,-144,949,37,-857,-446,-969,-861,-712,5,-972,-3,-202,-845,559,-244,-542,-421,422,526,-501,-791,-899,-315,281,-275,467,743,-321}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 1067472.0; verify_case(3, Arg2, minArea(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
BatmanAndRobin ___test;
___test.run_test(-1);
}
// END CUT HERE
| 35.405556 | 519 | 0.496156 | ibudiselic |
60ba94f642d90d30195b3cb47a4bd898f2f4ff5d | 7,121 | cpp | C++ | aten/src/ATen/test/cpu_profiling_allocator_test.cpp | Gamrix/pytorch | b5b158a6c6de94dfb983b447fa33fea062358844 | [
"Intel"
] | null | null | null | aten/src/ATen/test/cpu_profiling_allocator_test.cpp | Gamrix/pytorch | b5b158a6c6de94dfb983b447fa33fea062358844 | [
"Intel"
] | null | null | null | aten/src/ATen/test/cpu_profiling_allocator_test.cpp | Gamrix/pytorch | b5b158a6c6de94dfb983b447fa33fea062358844 | [
"Intel"
] | null | null | null | #include <gtest/gtest.h>
#include <c10/core/CPUAllocator.h>
#include <c10/mobile/CPUProfilingAllocator.h>
#include <ATen/ATen.h>
#include <ATen/Context.h>
at::Tensor run_with_control_flow(
at::Tensor input,
at::Tensor conv_weight,
at::Tensor linear_weight,
bool cond,
std::vector<void*>& pointers,
bool record = false,
bool validate = false) {
if (cond) {
input = input * 2;
}
void* input_ptr = input.data_ptr();
auto conv_out = at::conv2d(input, conv_weight);
void* conv_out_ptr = input.data_ptr();
auto conv_out_flat = conv_out.view({conv_out.size(0), -1});
auto output = at::linear(conv_out_flat, linear_weight);
if (record) {
pointers.push_back(input_ptr);
pointers.push_back(conv_out_ptr);
}
if (validate) {
TORCH_CHECK(input_ptr == pointers[0]);
TORCH_CHECK(conv_out_ptr == pointers[1]);
}
return output;
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(CPUAllocationPlanTest, with_control_flow) {
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
at::Tensor a = at::rand({23, 16, 16, 16});
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
at::Tensor conv_weight = at::rand({16, 16, 3, 3});
// output shape
// 23, 16, 14, 14
// Flattened shape = 23, 3136
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
at::Tensor linear_weight = at::rand({32, 3136});
at::Tensor output, ref_output;
std::vector<void*> pointers;
auto valid_allocation_plan = [&]() {
c10::AllocationPlan plan;
{
c10::WithProfileAllocationsGuard profile_guard(&plan);
ref_output = run_with_control_flow(
a, conv_weight, linear_weight, true, pointers);
}
};
// NOLINTNEXTLINE(cppcoreguidelines-avoid-goto,hicpp-avoid-goto)
ASSERT_NO_THROW(valid_allocation_plan());
auto validate_allocation_plan =
[&](bool record_mode, bool validation_mode) -> bool {
c10::AllocationPlan plan;
{
c10::WithProfileAllocationsGuard profile_guard(&plan);
ref_output =
run_with_control_flow(a, conv_weight, linear_weight, record_mode, pointers);
}
bool success{true};
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
for (uint64_t i = 0; i < 10; ++i) {
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
bool validation_success;
{
c10::WithValidateAllocationPlanGuard
validation_guard(&plan, &validation_success);
output = run_with_control_flow(
a, conv_weight, linear_weight, validation_mode, pointers);
}
success = success && validation_success;
}
return success;
};
ASSERT_FALSE(validate_allocation_plan(false, true));
ASSERT_FALSE(validate_allocation_plan(true, false));
ASSERT_TRUE(validate_allocation_plan(true, true));
ASSERT_TRUE(validate_allocation_plan(false, false));
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(CPUAllocationPlanTest, with_profiling_alloc) {
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
at::Tensor a = at::rand({23, 16, 16, 16});
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
at::Tensor conv_weight = at::rand({16, 16, 3, 3});
// output shape
// 23, 16, 14, 14
// Flattened shape = 23, 3136
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
at::Tensor linear_weight = at::rand({32, 3136});
at::Tensor output, ref_output;
std::vector<void*> pointers;
auto valid_allocation_plan = [&]() {
c10::AllocationPlan plan;
{
c10::WithProfileAllocationsGuard profile_guard(&plan);
ref_output = run_with_control_flow(
a, conv_weight, linear_weight, false, pointers);
}
};
// NOLINTNEXTLINE(cppcoreguidelines-avoid-goto,hicpp-avoid-goto)
ASSERT_NO_THROW(valid_allocation_plan());
auto validate_allocation_plan =
[&](bool record_mode,
bool validation_mode,
bool validate_pointers) {
pointers.clear();
c10::AllocationPlan plan;
{
c10::WithProfileAllocationsGuard profile_guard(&plan);
ref_output = run_with_control_flow(
a,
conv_weight,
linear_weight,
record_mode,
pointers,
false,
false);
}
c10::CPUProfilingAllocator profiling_allocator;
{
c10::WithProfilingAllocatorGuard
profiling_allocator_guard(&profiling_allocator, &plan);
output = run_with_control_flow(
a,
conv_weight,
linear_weight,
validation_mode,
pointers,
validate_pointers,
false);
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
for (uint64_t i = 0; i < 10; ++i) {
{
c10::WithProfilingAllocatorGuard
profiling_allocator_guard(&profiling_allocator, &plan);
output = run_with_control_flow(
a,
conv_weight,
linear_weight,
validation_mode,
pointers,
false,
validate_pointers);
}
}
};
// When control flow conditions are same between profiling and evaluation
// profiling allocator should not throw.
// NOLINTNEXTLINE(cppcoreguidelines-avoid-goto,hicpp-avoid-goto)
ASSERT_NO_THROW(validate_allocation_plan(true, true, false));
ASSERT_TRUE(ref_output.equal(output));
// NOLINTNEXTLINE(cppcoreguidelines-avoid-goto,hicpp-avoid-goto)
ASSERT_NO_THROW(validate_allocation_plan(false, false, false));
ASSERT_TRUE(ref_output.equal(output));
// Furthermore profiling allocator should return the same pointers
// back for the intermediate tensors
// NOLINTNEXTLINE(cppcoreguidelines-avoid-goto,hicpp-avoid-goto)
ASSERT_NO_THROW(validate_allocation_plan(true, true, true));
ASSERT_TRUE(ref_output.equal(output));
// NOLINTNEXTLINE(cppcoreguidelines-avoid-goto,hicpp-avoid-goto)
ASSERT_NO_THROW(validate_allocation_plan(false, false, true));
ASSERT_TRUE(ref_output.equal(output));
// When control flow conditions are different between profiling and evaluation
// profiling allocator should throw.
// NOLINTNEXTLINE(cppcoreguidelines-avoid-goto,hicpp-avoid-goto)
ASSERT_THROW(validate_allocation_plan(true, false, false), c10::Error);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-goto,hicpp-avoid-goto)
ASSERT_THROW(validate_allocation_plan(false, true, false), c10::Error);
}
int main(int argc, char* argv[]) {
// Setting the priority high to make sure no other allocator gets used instead of this.
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
c10::SetCPUAllocator(c10::GetDefaultMobileCPUAllocator(), /*priority*/ 100);
// Need to disable mkldnn for this test since it allocatred memory
// via raw_allocate inteface which requires context pointer and raw
// pointer to be the same. Tis is not true for mobile allocator.
at::globalContext().setUserEnabledMkldnn(false);
::testing::InitGoogleTest(&argc, argv);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
at::manual_seed(42);
return RUN_ALL_TESTS();
}
| 35.964646 | 89 | 0.692318 | Gamrix |
60bbd477897df42027db0b4ba823bc7966e8d364 | 3,814 | hpp | C++ | src/car/smart/SmartCar.hpp | clementinejensen/smartcar_shield | b1776a1d23915ab963e385afbdef2a6851ae761c | [
"MIT"
] | null | null | null | src/car/smart/SmartCar.hpp | clementinejensen/smartcar_shield | b1776a1d23915ab963e385afbdef2a6851ae761c | [
"MIT"
] | null | null | null | src/car/smart/SmartCar.hpp | clementinejensen/smartcar_shield | b1776a1d23915ab963e385afbdef2a6851ae761c | [
"MIT"
] | 1 | 2021-11-15T14:08:15.000Z | 2021-11-15T14:08:15.000Z | /**
* \class SmartCar
* A class to programmatically represent a vehicle equipped with odometers and a heading
* sensor
*/
#pragma once
#include "../distance/DistanceCar.hpp"
#include "../heading/HeadingCar.hpp"
#ifdef SMARTCAR_BUILD_FOR_ARDUINO
#include "../../runtime/arduino_runtime/ArduinoRuntime.hpp"
extern ArduinoRuntime arduinoRuntime;
#endif
class SmartCar : public DistanceCar, public HeadingCar
{
public:
#ifdef SMARTCAR_BUILD_FOR_ARDUINO
/**
* Constructs a car equipped with a heading sensor and an odometer
* @param control The car's control
* @param headingSensor The heading sensor
* @param odometer The odometer
*
* **Example:**
* \code
* BrushedMotor leftMotor(smartcarlib::pins::v2::leftMotorPins);
* BrushedMotor rightMotor(smartcarlib::pins::v2::rightMotorPins);
* DifferentialControl control(leftMotor, rightMotor);
*
* GY50 gyroscope(37);
* DirectionlessOdometer odometer(100);
* SmartCar car(control, gyroscope, odometer);
* \endcode
*/
SmartCar(Control& control,
HeadingSensor& headingSensor,
Odometer& odometer,
Runtime& runtime = arduinoRuntime);
/**
* Constructs a car equipped with a heading sensor and two odometers
* @param control The car's control
* @param headingSensor The heading sensor
* @param odometerLeft The left odometer
* @param odometerRight The right odometer
*
* **Example:**
* \code
* BrushedMotor leftMotor(smartcarlib::pins::v2::leftMotorPins);
* BrushedMotor rightMotor(smartcarlib::pins::v2::rightMotorPins);
* DifferentialControl control(leftMotor, rightMotor);
*
* GY50 gyroscope(37);
*
* const auto pulsesPerMeter = 600;
*
* DirectionlessOdometer leftOdometer(
* smartcarlib::pins::v2::leftOdometerPin, []() { leftOdometer.update(); }, pulsesPerMeter);
* DirectionlessOdometer rightOdometer(
* smartcarlib::pins::v2::rightOdometerPin, []() { rightOdometer.update(); },
* pulsesPerMeter);
*
* SmartCar car(control, gyroscope, leftOdometer, rightOdometer);
* \endcode
*/
SmartCar(Control& control,
HeadingSensor& headingSensor,
Odometer& odometerLeft,
Odometer& odometerRight,
Runtime& runtime = arduinoRuntime);
#else
SmartCar(Control& control, HeadingSensor& headingSensor, Odometer& odometer, Runtime& runtime);
SmartCar(Control& control,
HeadingSensor& headingSensor,
Odometer& odometerLeft,
Odometer& odometerRight,
Runtime& runtime);
#endif
/**
* Adjusts the speed when cruise control is enabled and calculates the current heading.
* You must have this being executed as often as possible for highest
* accuracy of heading calculations and cruise control.
*
* **Example:**
* \code
* void loop() {
* // Update the car readings as often as possible
* car.update();
* // Other functionality
* }
* \endcode
*/
virtual void update() override;
/* Use the overriden functions from DistanceCar */
using DistanceCar::overrideMotorSpeed;
using DistanceCar::setSpeed;
};
/**
* \example SmartCar.ino
* A basic example on how to use the core functionality of the SmartCar class.
*
* \example automatedMovements.ino
* An example of how to use the SmartCar functionality in order to perform a series
* of automated movements using the vehicle's HeadingSensor and Odometer capabilities.
*
* \example rotateOnSpot.ino
* An example on how to make a SmartCar rotate on spot by using the HeadingSensor
* and the SmartCar::overrideMotorSpeed functionality.
*/
| 32.87931 | 100 | 0.665705 | clementinejensen |
60bdb366b3ff992b255d0583d8131357be42aa93 | 12,764 | cc | C++ | node_modules/nodegit/src/treebuilder.cc | hsleonis/ngMaker | 7b2d8a8969bbfdf224e344e1df959d7115ba5301 | [
"MIT"
] | 2 | 2016-08-12T06:30:45.000Z | 2016-08-17T20:18:06.000Z | node_modules/nodegit/src/treebuilder.cc | hsleonis/ngMaker | 7b2d8a8969bbfdf224e344e1df959d7115ba5301 | [
"MIT"
] | null | null | null | node_modules/nodegit/src/treebuilder.cc | hsleonis/ngMaker | 7b2d8a8969bbfdf224e344e1df959d7115ba5301 | [
"MIT"
] | null | null | null | // This is a generated file, modify: generate/templates/class_content.cc.
#include <nan.h>
#include <string.h>
#include <chrono>
#include <thread>
extern "C" {
#include <git2.h>
}
#include "../include/functions/copy.h"
#include "../include/treebuilder.h"
#include "../include/tree_entry.h"
#include "../include/oid.h"
#include "../include/repository.h"
#include "../include/tree.h"
#include <iostream>
using namespace std;
using namespace v8;
using namespace node;
GitTreebuilder::GitTreebuilder(git_treebuilder *raw, bool selfFreeing) {
this->raw = raw;
this->selfFreeing = selfFreeing;
}
GitTreebuilder::~GitTreebuilder() {
if (this->selfFreeing) {
git_treebuilder_free(this->raw);
this->raw = NULL;
}
// this will cause an error if you have a non-self-freeing object that also needs
// to save values. Since the object that will eventually free the object has no
// way of knowing to free these values.
}
void GitTreebuilder::InitializeComponent(Local<v8::Object> target) {
Nan::HandleScope scope;
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(JSNewFunction);
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->SetClassName(Nan::New("Treebuilder").ToLocalChecked());
Nan::SetPrototypeMethod(tpl, "clear", Clear);
Nan::SetPrototypeMethod(tpl, "entrycount", Entrycount);
Nan::SetPrototypeMethod(tpl, "free", Free);
Nan::SetPrototypeMethod(tpl, "get", Get);
Nan::SetPrototypeMethod(tpl, "insert", Insert);
Nan::SetMethod(tpl, "create", Create);
Nan::SetPrototypeMethod(tpl, "remove", Remove);
Nan::SetPrototypeMethod(tpl, "write", Write);
Local<Function> _constructor_template = Nan::GetFunction(tpl).ToLocalChecked();
constructor_template.Reset(_constructor_template);
Nan::Set(target, Nan::New("Treebuilder").ToLocalChecked(), _constructor_template);
}
NAN_METHOD(GitTreebuilder::JSNewFunction) {
if (info.Length() == 0 || !info[0]->IsExternal()) {
return Nan::ThrowError("A new GitTreebuilder cannot be instantiated.");
}
GitTreebuilder* object = new GitTreebuilder(static_cast<git_treebuilder *>(Local<External>::Cast(info[0])->Value()), Nan::To<bool>(info[1]).FromJust());
object->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
Local<v8::Value> GitTreebuilder::New(void *raw, bool selfFreeing) {
Nan::EscapableHandleScope scope;
Local<v8::Value> argv[2] = { Nan::New<External>((void *)raw), Nan::New(selfFreeing) };
return scope.Escape(Nan::NewInstance(Nan::New(GitTreebuilder::constructor_template), 2, argv).ToLocalChecked());
}
git_treebuilder *GitTreebuilder::GetValue() {
return this->raw;
}
git_treebuilder **GitTreebuilder::GetRefValue() {
return this->raw == NULL ? NULL : &this->raw;
}
void GitTreebuilder::ClearValue() {
this->raw = NULL;
}
/*
*/
NAN_METHOD(GitTreebuilder::Clear) {
Nan::EscapableHandleScope scope;
git_treebuilder_clear(
Nan::ObjectWrap::Unwrap<GitTreebuilder>(info.This())->GetValue()
);
return info.GetReturnValue().Set(scope.Escape(Nan::Undefined()));
}
/*
* @return Number result */
NAN_METHOD(GitTreebuilder::Entrycount) {
Nan::EscapableHandleScope scope;
unsigned int result = git_treebuilder_entrycount(
Nan::ObjectWrap::Unwrap<GitTreebuilder>(info.This())->GetValue()
);
Local<v8::Value> to;
// start convert_to_v8 block
to = Nan::New<Number>( result);
// end convert_to_v8 block
return info.GetReturnValue().Set(scope.Escape(to));
}
/*
*/
NAN_METHOD(GitTreebuilder::Free) {
Nan::EscapableHandleScope scope;
if (Nan::ObjectWrap::Unwrap<GitTreebuilder>(info.This())->GetValue() != NULL) {
git_treebuilder_free(
Nan::ObjectWrap::Unwrap<GitTreebuilder>(info.This())->GetValue()
);
Nan::ObjectWrap::Unwrap<GitTreebuilder>(info.This())->ClearValue();
}
return info.GetReturnValue().Set(scope.Escape(Nan::Undefined()));
}
/*
* @param String filename
* @return TreeEntry result */
NAN_METHOD(GitTreebuilder::Get) {
Nan::EscapableHandleScope scope;
if (info.Length() == 0 || !info[0]->IsString()) {
return Nan::ThrowError("String filename is required.");
}
// start convert_from_v8 block
const char * from_filename;
String::Utf8Value filename(info[0]->ToString());
from_filename = (const char *) strdup(*filename);
// end convert_from_v8 block
const git_tree_entry * result = git_treebuilder_get(
Nan::ObjectWrap::Unwrap<GitTreebuilder>(info.This())->GetValue()
,from_filename
);
// null checks on pointers
if (!result) {
return info.GetReturnValue().Set(scope.Escape(Nan::Undefined()));
}
Local<v8::Value> to;
// start convert_to_v8 block
if (result != NULL) {
// GitTreeEntry result
to = GitTreeEntry::New((void *)result, false);
}
else {
to = Nan::Null();
}
// end convert_to_v8 block
return info.GetReturnValue().Set(scope.Escape(to));
}
/*
* @param String filename
* @param Oid id
* @param Number filemode
* @param TreeEntry callback
*/
NAN_METHOD(GitTreebuilder::Insert) {
if (info.Length() == 0 || !info[0]->IsString()) {
return Nan::ThrowError("String filename is required.");
}
if (info.Length() == 1
|| (!info[1]->IsObject() && !info[1]->IsString())) {
return Nan::ThrowError("Oid id is required.");
}
if (info.Length() == 2 || !info[2]->IsNumber()) {
return Nan::ThrowError("Number filemode is required.");
}
if (info.Length() == 3 || !info[3]->IsFunction()) {
return Nan::ThrowError("Callback is required and must be a Function.");
}
InsertBaton* baton = new InsertBaton;
baton->error_code = GIT_OK;
baton->error = NULL;
baton->bld = Nan::ObjectWrap::Unwrap<GitTreebuilder>(info.This())->GetValue();
// start convert_from_v8 block
const char * from_filename;
String::Utf8Value filename(info[0]->ToString());
from_filename = (const char *) strdup(*filename);
// end convert_from_v8 block
baton->filename = from_filename;
// start convert_from_v8 block
const git_oid * from_id;
if (info[1]->IsString()) {
// Try and parse in a string to a git_oid
String::Utf8Value oidString(info[1]->ToString());
git_oid *oidOut = (git_oid *)malloc(sizeof(git_oid));
if (git_oid_fromstr(oidOut, (const char *) strdup(*oidString)) != GIT_OK) {
free(oidOut);
if (giterr_last()) {
return Nan::ThrowError(giterr_last()->message);
} else {
return Nan::ThrowError("Unknown Error");
}
}
from_id = oidOut;
}
else {
from_id = Nan::ObjectWrap::Unwrap<GitOid>(info[1]->ToObject())->GetValue();
}
// end convert_from_v8 block
baton->id = from_id;
baton->idNeedsFree = info[1]->IsString();
// start convert_from_v8 block
git_filemode_t from_filemode;
from_filemode = (git_filemode_t) (int) info[2]->ToNumber()->Value();
// end convert_from_v8 block
baton->filemode = from_filemode;
Nan::Callback *callback = new Nan::Callback(Local<Function>::Cast(info[3]));
InsertWorker *worker = new InsertWorker(baton, callback);
worker->SaveToPersistent("bld", info.This());
if (!info[0]->IsUndefined() && !info[0]->IsNull())
worker->SaveToPersistent("filename", info[0]->ToObject());
if (!info[1]->IsUndefined() && !info[1]->IsNull())
worker->SaveToPersistent("id", info[1]->ToObject());
if (!info[2]->IsUndefined() && !info[2]->IsNull())
worker->SaveToPersistent("filemode", info[2]->ToObject());
Nan::AsyncQueueWorker(worker);
return;
}
void GitTreebuilder::InsertWorker::Execute() {
int result = git_treebuilder_insert(
&baton->out,baton->bld,baton->filename,baton->id,baton->filemode );
baton->error_code = result;
if (result != GIT_OK && giterr_last() != NULL) {
baton->error = git_error_dup(giterr_last());
}
}
void GitTreebuilder::InsertWorker::HandleOKCallback() {
if (baton->error_code == GIT_OK) {
Local<v8::Value> to;
// start convert_to_v8 block
if (baton->out != NULL) {
// GitTreeEntry baton->out
to = GitTreeEntry::New((void *)baton->out, false);
}
else {
to = Nan::Null();
}
// end convert_to_v8 block
Local<v8::Value> result = to;
Local<v8::Value> argv[2] = {
Nan::Null(),
result
};
callback->Call(2, argv);
} else {
if (baton->error) {
Local<v8::Value> argv[1] = {
Nan::Error(baton->error->message)
};
callback->Call(1, argv);
if (baton->error->message)
free((void *)baton->error->message);
free((void *)baton->error);
} else {
callback->Call(0, NULL);
}
}
free((void *)baton->filename);
if (baton->idNeedsFree) {
baton->idNeedsFree = false;
free((void *)baton->id);
}
delete baton;
}
/*
* @param Repository repo
* @param Tree source
* @param Treebuilder callback
*/
NAN_METHOD(GitTreebuilder::Create) {
if (info.Length() == 0 || !info[0]->IsObject()) {
return Nan::ThrowError("Repository repo is required.");
}
if (info.Length() == 1 || !info[1]->IsObject()) {
return Nan::ThrowError("Tree source is required.");
}
if (info.Length() == 2 || !info[2]->IsFunction()) {
return Nan::ThrowError("Callback is required and must be a Function.");
}
CreateBaton* baton = new CreateBaton;
baton->error_code = GIT_OK;
baton->error = NULL;
// start convert_from_v8 block
git_repository * from_repo;
from_repo = Nan::ObjectWrap::Unwrap<GitRepository>(info[0]->ToObject())->GetValue();
// end convert_from_v8 block
baton->repo = from_repo;
// start convert_from_v8 block
const git_tree * from_source;
from_source = Nan::ObjectWrap::Unwrap<GitTree>(info[1]->ToObject())->GetValue();
// end convert_from_v8 block
baton->source = from_source;
Nan::Callback *callback = new Nan::Callback(Local<Function>::Cast(info[2]));
CreateWorker *worker = new CreateWorker(baton, callback);
if (!info[0]->IsUndefined() && !info[0]->IsNull())
worker->SaveToPersistent("repo", info[0]->ToObject());
if (!info[1]->IsUndefined() && !info[1]->IsNull())
worker->SaveToPersistent("source", info[1]->ToObject());
Nan::AsyncQueueWorker(worker);
return;
}
void GitTreebuilder::CreateWorker::Execute() {
int result = git_treebuilder_new(
&baton->out,baton->repo,baton->source );
baton->error_code = result;
if (result != GIT_OK && giterr_last() != NULL) {
baton->error = git_error_dup(giterr_last());
}
}
void GitTreebuilder::CreateWorker::HandleOKCallback() {
if (baton->error_code == GIT_OK) {
Local<v8::Value> to;
// start convert_to_v8 block
if (baton->out != NULL) {
// GitTreebuilder baton->out
to = GitTreebuilder::New((void *)baton->out, false);
}
else {
to = Nan::Null();
}
// end convert_to_v8 block
Local<v8::Value> result = to;
Local<v8::Value> argv[2] = {
Nan::Null(),
result
};
callback->Call(2, argv);
} else {
if (baton->error) {
Local<v8::Value> argv[1] = {
Nan::Error(baton->error->message)
};
callback->Call(1, argv);
if (baton->error->message)
free((void *)baton->error->message);
free((void *)baton->error);
} else {
callback->Call(0, NULL);
}
}
delete baton;
}
/*
* @param String filename
* @return Number result */
NAN_METHOD(GitTreebuilder::Remove) {
Nan::EscapableHandleScope scope;
if (info.Length() == 0 || !info[0]->IsString()) {
return Nan::ThrowError("String filename is required.");
}
// start convert_from_v8 block
const char * from_filename;
String::Utf8Value filename(info[0]->ToString());
from_filename = (const char *) strdup(*filename);
// end convert_from_v8 block
int result = git_treebuilder_remove(
Nan::ObjectWrap::Unwrap<GitTreebuilder>(info.This())->GetValue()
,from_filename
);
Local<v8::Value> to;
// start convert_to_v8 block
to = Nan::New<Number>( result);
// end convert_to_v8 block
return info.GetReturnValue().Set(scope.Escape(to));
}
/*
* @return Oid id */
NAN_METHOD(GitTreebuilder::Write) {
Nan::EscapableHandleScope scope;
git_oid *id = (git_oid *)malloc(sizeof(git_oid));
int result = git_treebuilder_write(
id
,Nan::ObjectWrap::Unwrap<GitTreebuilder>(info.This())->GetValue()
);
Local<v8::Value> to;
// start convert_to_v8 block
if (id != NULL) {
// GitOid id
to = GitOid::New((void *)id, false);
}
else {
to = Nan::Null();
}
// end convert_to_v8 block
return info.GetReturnValue().Set(scope.Escape(to));
}
Nan::Persistent<Function> GitTreebuilder::constructor_template;
| 26.985201 | 156 | 0.647211 | hsleonis |
60be83c4907a1e846c5502f5838ec966169f1695 | 31,033 | cpp | C++ | ui/src/virtualconsole/vcxypadproperties.cpp | markusb/qlcplus | 1aae45b8d1914114b9a7ea6174e83e51e81ab8a1 | [
"Apache-2.0"
] | 1 | 2019-02-26T14:18:52.000Z | 2019-02-26T14:18:52.000Z | ui/src/virtualconsole/vcxypadproperties.cpp | markusb/qlcplus | 1aae45b8d1914114b9a7ea6174e83e51e81ab8a1 | [
"Apache-2.0"
] | null | null | null | ui/src/virtualconsole/vcxypadproperties.cpp | markusb/qlcplus | 1aae45b8d1914114b9a7ea6174e83e51e81ab8a1 | [
"Apache-2.0"
] | null | null | null | /*
Q Light Controller
vcxypadproperties.h
Copyright (C) Stefan Krumm, Heikki Junnila
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.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <QTreeWidgetItem>
#include <QTreeWidget>
#include <QMessageBox>
#include <QHeaderView>
#include <QSettings>
#include <QDebug>
#include <QAction>
#include "qlcfixturemode.h"
#include "qlcinputchannel.h"
#include "qlcchannel.h"
#include "qlcmacros.h"
#include "vcxypadfixtureeditor.h"
#include "inputselectionwidget.h"
#include "vcxypadproperties.h"
#include "functionselection.h"
#include "fixtureselection.h"
#include "vcxypadfixture.h"
#include "vcxypadpreset.h"
#include "vcxypadarea.h"
#include "vcxypad.h"
#include "apputil.h"
#include "scene.h"
#include "doc.h"
#include "efx.h"
#define SETTINGS_GEOMETRY "vcxypad/geometry"
#define KColumnFixture 0
#define KColumnXAxis 1
#define KColumnYAxis 2
/****************************************************************************
* Initialization
****************************************************************************/
VCXYPadProperties::VCXYPadProperties(VCXYPad* xypad, Doc* doc)
: QDialog(xypad)
, m_xypad(xypad)
, m_doc(doc)
{
Q_ASSERT(doc != NULL);
Q_ASSERT(xypad != NULL);
setupUi(this);
// IDs 0-15 are reserved for XYPad base controls
m_lastAssignedID = 15;
QAction* action = new QAction(this);
action->setShortcut(QKeySequence(QKeySequence::Close));
connect(action, SIGNAL(triggered(bool)), this, SLOT(reject()));
addAction(action);
/********************************************************************
* General page
********************************************************************/
m_nameEdit->setText(m_xypad->caption());
if (m_xypad->invertedAppearance() == true)
m_YInvertedRadio->setChecked(true);
m_panInputWidget = new InputSelectionWidget(m_doc, this);
m_panInputWidget->setTitle(tr("Pan / Horizontal Axis"));
m_panInputWidget->setKeyInputVisibility(false);
m_panInputWidget->setInputSource(m_xypad->inputSource(VCXYPad::panInputSourceId));
m_panInputWidget->setWidgetPage(m_xypad->page());
m_panInputWidget->emitOddValues(true);
m_panInputWidget->show();
m_extInputLayout->addWidget(m_panInputWidget);
connect(m_panInputWidget, SIGNAL(autoDetectToggled(bool)),
this, SLOT(slotPanAutoDetectToggled(bool)));
connect(m_panInputWidget, SIGNAL(inputValueChanged(quint32,quint32)),
this, SLOT(slotPanInputValueChanged(quint32,quint32)));
m_tiltInputWidget = new InputSelectionWidget(m_doc, this);
m_tiltInputWidget->setTitle(tr("Tilt / Vertical Axis"));
m_tiltInputWidget->setKeyInputVisibility(false);
m_tiltInputWidget->setInputSource(m_xypad->inputSource(VCXYPad::tiltInputSourceId));
m_tiltInputWidget->setWidgetPage(m_xypad->page());
m_tiltInputWidget->emitOddValues(true);
m_tiltInputWidget->show();
m_extInputLayout->addWidget(m_tiltInputWidget);
connect(m_tiltInputWidget, SIGNAL(autoDetectToggled(bool)),
this, SLOT(slotTiltAutoDetectToggled(bool)));
connect(m_tiltInputWidget, SIGNAL(inputValueChanged(quint32,quint32)),
this, SLOT(slotTiltInputValueChanged(quint32,quint32)));
m_widthInputWidget = new InputSelectionWidget(m_doc, this);
m_widthInputWidget->setTitle(tr("Width"));
m_widthInputWidget->setKeyInputVisibility(false);
m_widthInputWidget->setInputSource(m_xypad->inputSource(VCXYPad::widthInputSourceId));
m_widthInputWidget->setWidgetPage(m_xypad->page());
m_widthInputWidget->show();
m_sizeInputLayout->addWidget(m_widthInputWidget);
m_heightInputWidget = new InputSelectionWidget(m_doc, this);
m_heightInputWidget->setTitle(tr("Height"));
m_heightInputWidget->setKeyInputVisibility(false);
m_heightInputWidget->setInputSource(m_xypad->inputSource(VCXYPad::heightInputSourceId));
m_heightInputWidget->setWidgetPage(m_xypad->page());
m_heightInputWidget->show();
m_sizeInputLayout->addWidget(m_heightInputWidget);
/********************************************************************
* Fixtures page
********************************************************************/
slotSelectionChanged(NULL);
fillFixturesTree();
connect(m_percentageRadio, SIGNAL(clicked(bool)),
this, SLOT(slotPercentageRadioChecked()));
connect(m_degreesRadio, SIGNAL(clicked(bool)),
this, SLOT(slotDegreesRadioChecked()));
connect(m_dmxRadio, SIGNAL(clicked(bool)),
this, SLOT(slotDMXRadioChecked()));
/********************************************************************
* Presets page
********************************************************************/
m_presetInputWidget = new InputSelectionWidget(m_doc, this);
m_presetInputWidget->setCustomFeedbackVisibility(true);
m_presetInputWidget->setWidgetPage(m_xypad->page());
m_presetInputWidget->show();
m_presetInputLayout->addWidget(m_presetInputWidget);
connect(m_presetInputWidget, SIGNAL(inputValueChanged(quint32,quint32)),
this, SLOT(slotInputValueChanged(quint32,quint32)));
connect(m_presetInputWidget, SIGNAL(keySequenceChanged(QKeySequence)),
this, SLOT(slotKeySequenceChanged(QKeySequence)));
connect(m_addPositionButton, SIGNAL(clicked(bool)),
this, SLOT(slotAddPositionClicked()));
connect(m_addEfxButton, SIGNAL(clicked(bool)),
this, SLOT(slotAddEFXClicked()));
connect(m_addSceneButton, SIGNAL(clicked(bool)),
this, SLOT(slotAddSceneClicked()));
connect(m_addFxGroupButton, SIGNAL(clicked(bool)),
this, SLOT(slotAddFixtureGroupClicked()));
connect(m_removePresetButton, SIGNAL(clicked()),
this, SLOT(slotRemovePresetClicked()));
connect(m_moveUpPresetButton, SIGNAL(clicked()),
this, SLOT(slotMoveUpPresetClicked()));
connect(m_moveDownPresetButton, SIGNAL(clicked()),
this, SLOT(slotMoveDownPresetClicked()));
connect(m_presetNameEdit, SIGNAL(textEdited(QString const&)),
this, SLOT(slotPresetNameEdited(QString const&)));
connect(m_presetsTree, SIGNAL(itemClicked(QTreeWidgetItem*,int)),
this, SLOT(slotPresetSelectionChanged()));
m_xyArea = new VCXYPadArea(this);
//m_xyArea->setFixedSize(140, 140);
m_xyArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
m_xyArea->setMode(Doc::Operate);
m_presetLayout->addWidget(m_xyArea);
connect(m_xyArea, SIGNAL(positionChanged(QPointF)),
this, SLOT(slotXYPadPositionChanged(QPointF)));
foreach(const VCXYPadPreset *preset, m_xypad->presets())
{
m_presetList.append(new VCXYPadPreset(*preset));
if (preset->m_id > m_lastAssignedID)
m_lastAssignedID = preset->m_id;
}
updatePresetsTree();
QSettings settings;
QVariant var = settings.value(SETTINGS_GEOMETRY);
if (var.isValid() == true)
restoreGeometry(var.toByteArray());
AppUtil::ensureWidgetIsVisible(this);
m_doc->masterTimer()->registerDMXSource(this);
}
VCXYPadProperties::~VCXYPadProperties()
{
QSettings settings;
settings.setValue(SETTINGS_GEOMETRY, saveGeometry());
m_doc->masterTimer()->unregisterDMXSource(this);
delete m_presetInputWidget;
}
/****************************************************************************
* Fixtures page
****************************************************************************/
void VCXYPadProperties::fillFixturesTree()
{
m_tree->clear();
QListIterator <VCXYPadFixture> it(m_xypad->fixtures());
while (it.hasNext() == true)
updateFixtureItem(new QTreeWidgetItem(m_tree), it.next());
m_tree->setCurrentItem(m_tree->topLevelItem(0));
m_tree->header()->resizeSections(QHeaderView::ResizeToContents);
}
void VCXYPadProperties::updateFixturesTree(VCXYPadFixture::DisplayMode mode)
{
for(int i = 0; i < m_tree->topLevelItemCount(); i++)
{
QTreeWidgetItem *item = m_tree->topLevelItem(i);
QVariant var(item->data(KColumnFixture, Qt::UserRole));
VCXYPadFixture fx = VCXYPadFixture(m_doc, var);
fx.setDisplayMode(mode);
updateFixtureItem(item, fx);
}
}
void VCXYPadProperties::updateFixtureItem(QTreeWidgetItem* item,
const VCXYPadFixture& fxi)
{
Q_ASSERT(item != NULL);
item->setText(KColumnFixture, fxi.name());
item->setText(KColumnXAxis, fxi.xBrief());
item->setText(KColumnYAxis, fxi.yBrief());
item->setData(KColumnFixture, Qt::UserRole, QVariant(fxi));
}
QList <VCXYPadFixture> VCXYPadProperties::selectedFixtures() const
{
QListIterator <QTreeWidgetItem*> it(m_tree->selectedItems());
QList <VCXYPadFixture> list;
/* Put all selected fixtures to a list and return it */
while (it.hasNext() == true)
list << VCXYPadFixture(m_doc, it.next()->data(KColumnFixture, Qt::UserRole));
return list;
}
QTreeWidgetItem* VCXYPadProperties::fixtureItem(const VCXYPadFixture& fxi)
{
QTreeWidgetItemIterator it(m_tree);
while (*it != NULL)
{
QVariant var((*it)->data(KColumnFixture, Qt::UserRole));
VCXYPadFixture another(m_doc, var);
if (fxi.head() == another.head())
return *it;
else
++it;
}
return NULL;
}
void VCXYPadProperties::removeFixtureItem(GroupHead const & head)
{
QTreeWidgetItemIterator it(m_tree);
while (*it != NULL)
{
QVariant var((*it)->data(KColumnFixture, Qt::UserRole));
VCXYPadFixture fxi(m_doc, var);
if (fxi.head() == head)
{
delete (*it);
break;
}
++it;
}
}
void VCXYPadProperties::slotAddClicked()
{
/* Put all fixtures already present into a list of fixtures that
will be disabled in the fixture selection dialog */
QList <GroupHead> disabled;
QTreeWidgetItemIterator twit(m_tree);
while (*twit != NULL)
{
QVariant var((*twit)->data(KColumnFixture, Qt::UserRole));
VCXYPadFixture fxi(m_doc, var);
disabled << fxi.head();
++twit;
}
/* Disable all fixtures that don't have pan OR tilt channels */
QListIterator <Fixture*> fxit(m_doc->fixtures());
while (fxit.hasNext() == true)
{
Fixture* fixture(fxit.next());
Q_ASSERT(fixture != NULL);
// If a channel with pan or tilt group exists, don't disable this fixture
if (fixture->channel(QLCChannel::Pan) == QLCChannel::invalid() &&
fixture->channel(QLCChannel::Tilt) == QLCChannel::invalid())
{
// Disable all fixtures without pan or tilt channels
disabled << fixture->id();
}
else
{
QVector <QLCFixtureHead> const& heads = fixture->fixtureMode()->heads();
for (int i = 0; i < heads.size(); ++i)
{
if (heads[i].channelNumber(QLCChannel::Pan, QLCChannel::MSB) == QLCChannel::invalid() &&
heads[i].channelNumber(QLCChannel::Tilt, QLCChannel::MSB) == QLCChannel::invalid() &&
heads[i].channelNumber(QLCChannel::Pan, QLCChannel::LSB) == QLCChannel::invalid() &&
heads[i].channelNumber(QLCChannel::Tilt, QLCChannel::LSB) == QLCChannel::invalid())
{
// Disable heads without pan or tilt channels
disabled << GroupHead(fixture->id(), i);
}
}
}
}
/* Get a list of new fixtures to add to the pad */
QTreeWidgetItem* item = NULL;
FixtureSelection fs(this, m_doc);
fs.setMultiSelection(true);
fs.setSelectionMode(FixtureSelection::Heads);
fs.setDisabledHeads(disabled);
if (fs.exec() == QDialog::Accepted)
{
QListIterator <GroupHead> it(fs.selectedHeads());
while (it.hasNext() == true)
{
VCXYPadFixture fxi(m_doc);
fxi.setHead(it.next());
item = new QTreeWidgetItem(m_tree);
updateFixtureItem(item, fxi);
}
}
if (item != NULL)
m_tree->setCurrentItem(item);
m_tree->header()->resizeSections(QHeaderView::ResizeToContents);
}
void VCXYPadProperties::slotRemoveClicked()
{
int r = QMessageBox::question(
this, tr("Remove fixtures"),
tr("Do you want to remove the selected fixtures?"),
QMessageBox::Yes, QMessageBox::No);
if (r == QMessageBox::Yes)
{
QListIterator <QTreeWidgetItem*> it(m_tree->selectedItems());
while (it.hasNext() == true)
delete it.next();
}
}
void VCXYPadProperties::slotEditClicked()
{
/* Get a list of selected fixtures */
QList <VCXYPadFixture> list(selectedFixtures());
/* Start editor */
VCXYPadFixtureEditor editor(this, list);
if (editor.exec() == QDialog::Accepted)
{
QListIterator <VCXYPadFixture> it(editor.fixtures());
while (it.hasNext() == true)
{
VCXYPadFixture fxi(it.next());
QTreeWidgetItem* item = fixtureItem(fxi);
updateFixtureItem(item, fxi);
}
m_tree->header()->resizeSections(QHeaderView::ResizeToContents);
}
}
void VCXYPadProperties::slotSelectionChanged(QTreeWidgetItem* item)
{
if (item == NULL)
{
m_removeButton->setEnabled(false);
m_editButton->setEnabled(false);
}
else
{
m_removeButton->setEnabled(true);
m_editButton->setEnabled(true);
}
}
void VCXYPadProperties::slotPercentageRadioChecked()
{
updateFixturesTree(VCXYPadFixture::Percentage);
}
void VCXYPadProperties::slotDegreesRadioChecked()
{
updateFixturesTree(VCXYPadFixture::Degrees);
}
void VCXYPadProperties::slotDMXRadioChecked()
{
updateFixturesTree(VCXYPadFixture::DMX);
}
/****************************************************************************
* Input page
****************************************************************************/
void VCXYPadProperties::slotPanAutoDetectToggled(bool toggled)
{
if (toggled == true && m_tiltInputWidget->isAutoDetecting())
m_tiltInputWidget->stopAutoDetection();
}
void VCXYPadProperties::slotPanInputValueChanged(quint32 uni, quint32 ch)
{
QSharedPointer<QLCInputSource> tmpSource = m_panInputWidget->inputSource();
if (tmpSource->universe() != uni || tmpSource->channel() != ch)
m_tiltInputWidget->setInputSource(
QSharedPointer<QLCInputSource>(new QLCInputSource(uni, ch)));
}
void VCXYPadProperties::slotTiltAutoDetectToggled(bool toggled)
{
if (toggled == true && m_panInputWidget->isAutoDetecting())
m_panInputWidget->stopAutoDetection();
}
void VCXYPadProperties::slotTiltInputValueChanged(quint32 uni, quint32 ch)
{
QSharedPointer<QLCInputSource> tmpSource = m_tiltInputWidget->inputSource();
if (tmpSource->universe() != uni || tmpSource->channel() != ch)
m_panInputWidget->setInputSource(
QSharedPointer<QLCInputSource>(new QLCInputSource(uni, ch)));
}
void VCXYPadProperties::writeDMX(MasterTimer *timer, QList<Universe *> universes)
{
Q_UNUSED(timer);
if (m_tab->currentIndex() != 2 || m_xyArea->hasPositionChanged() == false)
return;
//qDebug() << Q_FUNC_INFO;
// This call also resets the m_changed flag in m_area
QPointF pt = m_xyArea->position();
/* Scale XY coordinate values to 0.0 - 1.0 */
qreal x = SCALE(pt.x(), qreal(0), qreal(256), qreal(0), qreal(1));
qreal y = SCALE(pt.y(), qreal(0), qreal(256), qreal(0), qreal(1));
if (m_YInvertedRadio->isChecked())
y = qreal(1) - y;
QTreeWidgetItemIterator it(m_tree);
while (*it != NULL)
{
QVariant var((*it)->data(KColumnFixture, Qt::UserRole));
VCXYPadFixture fixture(m_doc, var);
fixture.arm();
fixture.writeDMX(x, y, universes);
fixture.disarm();
++it;
}
}
/********************************************************************
* Presets
********************************************************************/
void VCXYPadProperties::updatePresetsTree()
{
m_presetsTree->blockSignals(true);
m_presetsTree->clear();
for (int i = 0; i < m_presetList.count(); i++)
{
VCXYPadPreset *preset = m_presetList.at(i);
QTreeWidgetItem *item = new QTreeWidgetItem(m_presetsTree);
item->setData(0, Qt::UserRole, preset->m_id);
item->setText(0, preset->m_name);
if (preset->m_type == VCXYPadPreset::EFX)
item->setIcon(0, QIcon(":/efx.png"));
else if (preset->m_type == VCXYPadPreset::Scene)
item->setIcon(0, QIcon(":/scene.png"));
else if (preset->m_type == VCXYPadPreset::Position)
item->setIcon(0, QIcon(":/xypad.png"));
else if (preset->m_type == VCXYPadPreset::FixtureGroup)
item->setIcon(0, QIcon(":/group.png"));
}
m_presetsTree->resizeColumnToContents(0);
m_presetsTree->blockSignals(false);
}
void VCXYPadProperties::selectItemOnPresetsTree(quint8 presetId)
{
m_presetsTree->blockSignals(true);
for (int i = 0; i < m_presetsTree->topLevelItemCount(); ++i)
{
QTreeWidgetItem* treeItem = m_presetsTree->topLevelItem(i);
if (treeItem->data(0, Qt::UserRole).toUInt() == presetId)
{
treeItem->setSelected(true);
break;
}
}
m_presetsTree->blockSignals(false);
}
void VCXYPadProperties::updateTreeItem(const VCXYPadPreset &preset)
{
m_presetsTree->blockSignals(true);
for (int i = 0; i < m_presetsTree->topLevelItemCount(); ++i)
{
QTreeWidgetItem* treeItem = m_presetsTree->topLevelItem(i);
if (treeItem->data(0, Qt::UserRole).toUInt() == preset.m_id)
{
treeItem->setText(0, preset.m_name);
m_presetsTree->resizeColumnToContents(0);
m_presetsTree->blockSignals(false);
return;
}
}
Q_ASSERT(false);
}
VCXYPadPreset *VCXYPadProperties::getSelectedPreset()
{
if (m_presetsTree->selectedItems().isEmpty())
return NULL;
QTreeWidgetItem* item = m_presetsTree->selectedItems().first();
if (item != NULL)
{
quint8 presetID = item->data(0, Qt::UserRole).toUInt();
foreach(VCXYPadPreset* preset, m_presetList)
{
if (preset->m_id == presetID)
return preset;
}
}
Q_ASSERT(false);
return NULL;
}
void VCXYPadProperties::removePreset(quint8 id)
{
for(int i = 0; i < m_presetList.count(); i++)
{
if (m_presetList.at(i)->m_id == id)
{
m_presetList.removeAt(i);
return;
}
}
}
quint8 VCXYPadProperties::moveUpPreset(quint8 id)
{
for(int i = 0; i < m_presetList.count(); i++)
{
if (m_presetList.at(i)->m_id == id)
{
if(i > 0)
{
//change order on hash preset structure.
//presets are saved in hash and sort on id is used to create the preset list.
//So swapping id change order every time that preset list is created (restore, dialog open, ...).
quint8 dstPosID = m_presetList.at(i-1)->m_id;
quint8 srcPosID = m_presetList.at(i)->m_id;
m_presetList.at(i-1)->m_id = srcPosID;
m_presetList.at(i)->m_id = dstPosID;
//change order on current preset list...
m_presetList.move(i, i-1);
return dstPosID;
}
return id;
}
}
return id;
}
quint8 VCXYPadProperties::moveDownPreset(quint8 id)
{
for(int i = 0; i < m_presetList.count(); i++)
{
if (m_presetList.at(i)->m_id == id)
{
if(i < m_presetList.count() - 1)
{
//change order on hash preset structure.
//presets are saved in hash and sort on id is used to create the preset list.
//So swapping id change order every time that preset list is created (restore, dialog open, ...).
quint8 dstPosID = m_presetList.at(i+1)->m_id;
quint8 srcPosID = m_presetList.at(i)->m_id;
m_presetList.at(i+1)->m_id = srcPosID;
m_presetList.at(i)->m_id = dstPosID;
//change order on current preset list...
m_presetList.move(i, i+1);
return dstPosID;
}
return id;
}
}
return id;
}
void VCXYPadProperties::slotAddPositionClicked()
{
VCXYPadPreset *newPreset = new VCXYPadPreset(++m_lastAssignedID);
newPreset->m_type = VCXYPadPreset::Position;
newPreset->m_dmxPos = m_xyArea->position();
newPreset->m_name = QString("X:%1 - Y:%2").arg((int)newPreset->m_dmxPos.x()).arg((int)newPreset->m_dmxPos.y());
m_presetList.append(newPreset);
updatePresetsTree();
selectItemOnPresetsTree(newPreset->m_id);
}
void VCXYPadProperties::slotAddEFXClicked()
{
FunctionSelection fs(this, m_doc);
fs.setMultiSelection(false);
fs.setFilter(Function::EFXType, true);
QList <quint32> ids;
foreach (VCXYPadPreset *preset, m_presetList)
{
if (preset->m_type == VCXYPadPreset::EFX)
ids.append(preset->m_funcID);
}
if (fs.exec() == QDialog::Accepted && fs.selection().size() > 0)
{
quint32 fID = fs.selection().first();
Function *f = m_doc->function(fID);
if (f == NULL || f->type() != Function::EFXType)
return;
VCXYPadPreset *newPreset = new VCXYPadPreset(++m_lastAssignedID);
newPreset->m_type = VCXYPadPreset::EFX;
newPreset->m_funcID = fID;
newPreset->m_name = f->name();
m_presetList.append(newPreset);
updatePresetsTree();
selectItemOnPresetsTree(newPreset->m_id);
}
}
void VCXYPadProperties::slotAddSceneClicked()
{
FunctionSelection fs(this, m_doc);
fs.setMultiSelection(false);
fs.setFilter(Function::SceneType, true);
QList <quint32> ids;
foreach (VCXYPadPreset *preset, m_presetList)
{
if (preset->m_type == VCXYPadPreset::Scene)
ids.append(preset->m_funcID);
}
if (fs.exec() == QDialog::Accepted && fs.selection().size() > 0)
{
quint32 fID = fs.selection().first();
Function *f = m_doc->function(fID);
if (f == NULL || f->type() != Function::SceneType)
return;
Scene *scene = qobject_cast<Scene*>(f);
bool panTiltFound = false;
foreach(SceneValue scv, scene->values())
{
Fixture *fixture = m_doc->fixture(scv.fxi);
if (fixture == NULL)
continue;
const QLCChannel *ch = fixture->channel(scv.channel);
if (ch == NULL)
continue;
if (ch->group() == QLCChannel::Pan || ch->group() == QLCChannel::Tilt)
{
panTiltFound = true;
break;
}
}
if (panTiltFound == false)
{
QMessageBox::critical(this, tr("Error"),
tr("The selected Scene does not include any Pan or Tilt channel.\n"
"Please select one with such channels."),
QMessageBox::Close);
return;
}
VCXYPadPreset *newPreset = new VCXYPadPreset(++m_lastAssignedID);
newPreset->m_type = VCXYPadPreset::Scene;
newPreset->m_funcID = fID;
newPreset->m_name = f->name();
m_presetList.append(newPreset);
updatePresetsTree();
selectItemOnPresetsTree(newPreset->m_id);
}
}
void VCXYPadProperties::slotAddFixtureGroupClicked()
{
QList <GroupHead> enabled;
QList <GroupHead> disabled;
QTreeWidgetItemIterator it(m_tree);
while (*it != NULL)
{
QVariant var((*it)->data(KColumnFixture, Qt::UserRole));
VCXYPadFixture fxi(m_doc, var);
enabled << fxi.head();
++it;
}
foreach(Fixture *fx, m_doc->fixtures())
{
for (int i = 0; i < fx->heads(); i++)
{
GroupHead gh(fx->id(), i);
if (enabled.contains(gh) == false)
disabled << gh;
}
}
FixtureSelection fs(this, m_doc);
fs.setMultiSelection(true);
fs.setSelectionMode(FixtureSelection::Heads);
fs.setDisabledHeads(disabled);
if (fs.exec() == QDialog::Accepted)
{
QList<GroupHead> selectedGH = fs.selectedHeads();
if (selectedGH.isEmpty())
{
QMessageBox::critical(this, tr("Error"),
tr("Please select at least one fixture or head to create this type of preset !"),
QMessageBox::Close);
return;
}
VCXYPadPreset *newPreset = new VCXYPadPreset(++m_lastAssignedID);
newPreset->m_type = VCXYPadPreset::FixtureGroup;
newPreset->m_name = tr("Fixture Group");
newPreset->setFixtureGroup(selectedGH);
m_presetList.append(newPreset);
updatePresetsTree();
selectItemOnPresetsTree(newPreset->m_id);
}
}
void VCXYPadProperties::slotRemovePresetClicked()
{
if (m_presetsTree->selectedItems().isEmpty())
return;
QTreeWidgetItem *selItem = m_presetsTree->selectedItems().first();
quint8 ctlID = selItem->data(0, Qt::UserRole).toUInt();
removePreset(ctlID);
updatePresetsTree();
}
void VCXYPadProperties::slotMoveUpPresetClicked()
{
if (m_presetsTree->selectedItems().isEmpty())
return;
QTreeWidgetItem *selItem = m_presetsTree->selectedItems().first();
quint8 ctlID = selItem->data(0, Qt::UserRole).toUInt();
quint8 newID = moveUpPreset(ctlID);
updatePresetsTree();
//select item on new position. User can make multiple move up/down without need to select item everytime.
selectItemOnPresetsTree(newID);
}
void VCXYPadProperties::slotMoveDownPresetClicked()
{
if (m_presetsTree->selectedItems().isEmpty())
return;
QTreeWidgetItem *selItem = m_presetsTree->selectedItems().first();
quint8 ctlID = selItem->data(0, Qt::UserRole).toUInt();
quint8 newID =moveDownPreset(ctlID);
updatePresetsTree();
//select item on new position. User can make multiple move up/down without need to select item everytime.
selectItemOnPresetsTree(newID);
}
void VCXYPadProperties::slotPresetNameEdited(const QString &newName)
{
VCXYPadPreset* preset = getSelectedPreset();
if (preset != NULL)
{
preset->m_name = newName;
updateTreeItem(*preset);
}
}
void VCXYPadProperties::slotPresetSelectionChanged()
{
VCXYPadPreset *preset = getSelectedPreset();
if (preset != NULL)
{
m_presetNameEdit->setText(preset->m_name);
m_presetInputWidget->setInputSource(preset->m_inputSource);
m_presetInputWidget->setKeySequence(preset->m_keySequence.toString(QKeySequence::NativeText));
if (preset->m_type == VCXYPadPreset::EFX)
{
Function *f = m_doc->function(preset->functionID());
if (f == NULL || f->type() != Function::EFXType)
return;
EFX *efx = qobject_cast<EFX*>(f);
QPolygonF polygon;
efx->preview(polygon);
QVector <QPolygonF> fixturePoints;
efx->previewFixtures(fixturePoints);
m_xyArea->enableEFXPreview(true);
m_xyArea->setEnabled(false);
m_xyArea->setEFXPolygons(polygon, fixturePoints);
m_xyArea->setEFXInterval(efx->duration());
}
else if (preset->m_type == VCXYPadPreset::Position)
{
m_xyArea->enableEFXPreview(false);
m_xyArea->setEnabled(true);
m_xyArea->blockSignals(true);
m_xyArea->setPosition(preset->m_dmxPos);
m_xyArea->repaint();
m_xyArea->blockSignals(false);
}
else if (preset->m_type == VCXYPadPreset::Scene)
{
m_xyArea->enableEFXPreview(false);
m_xyArea->setEnabled(false);
}
}
}
void VCXYPadProperties::slotXYPadPositionChanged(const QPointF &pt)
{
VCXYPadPreset *preset = getSelectedPreset();
if (preset != NULL)
{
preset->m_dmxPos = pt;
if (preset->m_type == VCXYPadPreset::Position &&
preset->m_name.startsWith("X:"))
{
preset->m_name = QString("X:%1 - Y:%2").arg((int)pt.x()).arg((int)pt.y());
m_presetNameEdit->blockSignals(true);
m_presetNameEdit->setText(preset->m_name);
m_presetNameEdit->blockSignals(false);
}
updateTreeItem(*preset);
}
}
void VCXYPadProperties::slotInputValueChanged(quint32 universe, quint32 channel)
{
Q_UNUSED(universe);
Q_UNUSED(channel);
VCXYPadPreset *preset = getSelectedPreset();
if (preset != NULL)
preset->m_inputSource = m_presetInputWidget->inputSource();
}
void VCXYPadProperties::slotKeySequenceChanged(QKeySequence key)
{
VCXYPadPreset *preset = getSelectedPreset();
if (preset != NULL)
preset->m_keySequence = key;
}
/****************************************************************************
* OK/Cancel
****************************************************************************/
void VCXYPadProperties::accept()
{
m_xypad->clearFixtures();
m_xypad->setCaption(m_nameEdit->text());
m_xypad->setInputSource(m_panInputWidget->inputSource(), VCXYPad::panInputSourceId);
m_xypad->setInputSource(m_tiltInputWidget->inputSource(), VCXYPad::tiltInputSourceId);
m_xypad->setInputSource(m_widthInputWidget->inputSource(), VCXYPad::widthInputSourceId);
m_xypad->setInputSource(m_heightInputWidget->inputSource(), VCXYPad::heightInputSourceId);
if (m_YNormalRadio->isChecked())
m_xypad->setInvertedAppearance(false);
else
m_xypad->setInvertedAppearance(true);
QTreeWidgetItemIterator it(m_tree);
while (*it != NULL)
{
QVariant var((*it)->data(KColumnFixture, Qt::UserRole));
m_xypad->appendFixture(VCXYPadFixture(m_doc, var));
++it;
}
/* Controls */
m_xypad->resetPresets();
for (int i = 0; i < m_presetList.count(); i++)
m_xypad->addPreset(*m_presetList.at(i));
QDialog::accept();
}
| 32.873941 | 115 | 0.612541 | markusb |
60bfc5ec601d76cb706aa41f0032ea283e53c027 | 465 | cpp | C++ | Foundation/Source/Foundation/Network/Client.cpp | TrashCoder94/Foundation | 431e4b2b6d01fea570942dc40c93a3a08d23890f | [
"Apache-2.0"
] | null | null | null | Foundation/Source/Foundation/Network/Client.cpp | TrashCoder94/Foundation | 431e4b2b6d01fea570942dc40c93a3a08d23890f | [
"Apache-2.0"
] | null | null | null | Foundation/Source/Foundation/Network/Client.cpp | TrashCoder94/Foundation | 431e4b2b6d01fea570942dc40c93a3a08d23890f | [
"Apache-2.0"
] | null | null | null | #include "fdpch.h"
#include "Client.h"
namespace Foundation
{
void Client::PingServer()
{
Net::Message<NetMessageTypes> message;
message.m_Header.m_ID = NetMessageTypes::ServerPing;
std::chrono::system_clock::time_point timeNow = std::chrono::system_clock::now();
message << timeNow;
Send(message);
}
void Client::MessageAll()
{
Net::Message<NetMessageTypes> message;
message.m_Header.m_ID = NetMessageTypes::MessageAll;
Send(message);
}
} | 20.217391 | 83 | 0.722581 | TrashCoder94 |
60c1fe71e0b0bd89ea7e58c1a83c122df0309c28 | 1,533 | cpp | C++ | codeforces/E - Common ancestor/Time limit exceeded on test 8.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codeforces/E - Common ancestor/Time limit exceeded on test 8.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codeforces/E - Common ancestor/Time limit exceeded on test 8.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: Jul/25/2018 16:42
* solution_verdict: Time limit exceeded on test 8 language: GNU C++17
* run_time: 5000 ms memory_used: 18200 KB
* problem: https://codeforces.com/contest/49/problem/E
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int inf=1e9;
int m;
string s,s1,s2;
map<string,vector<char> >mp;
map<pair<string,string>,int>dp;
int dfs(string a,string b)
{
// cout<<a<<" "<<b<<endl;
// getchar();
if(dp[{a,b}])return dp[{a,b}];
int here=inf;
for(int i=0;i<a.size()-1;i++)
{
string tmp=a.substr(i,2);
for(auto x:mp[tmp])
here=min(here,dfs(a.substr(0,i)+x+a.substr(i+2,a.size()-i-2),b));
}
for(int i=0;i<b.size()-1;i++)
{
string tmp=b.substr(i,2);
for(auto x:mp[tmp])
here=min(here,dfs(a,b.substr(0,i)+x+b.substr(i+2,b.size()-i-2)));
}
if(a==b)
{
//cout<<a<<" "<<b<<endl;
here=min(here,(int)a.size());
}
return dp[{a,b}]=here;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cin>>s1>>s2;
cin>>m;
while(m--)
{
cin>>s;
mp[s.substr(3,2)].push_back(s[0]);
}
int tmp=dfs(s1,s2);
if(tmp==inf)tmp=-1;
cout<<tmp<<endl;
return 0;
} | 27.872727 | 111 | 0.454664 | kzvd4729 |
60c21c58f5cbcb5bd94d8466181352520f31f23e | 880 | cpp | C++ | src/BabylonCpp/src/meshes/builders/plane_builder.cpp | samdauwe/BabylonCpp | eea9f761a49bb460ff1324c20e4674ef120e94f1 | [
"Apache-2.0"
] | 277 | 2017-05-18T08:27:10.000Z | 2022-03-26T01:31:37.000Z | src/BabylonCpp/src/meshes/builders/plane_builder.cpp | samdauwe/BabylonCpp | eea9f761a49bb460ff1324c20e4674ef120e94f1 | [
"Apache-2.0"
] | 77 | 2017-09-03T15:35:02.000Z | 2022-03-28T18:47:20.000Z | src/BabylonCpp/src/meshes/builders/plane_builder.cpp | samdauwe/BabylonCpp | eea9f761a49bb460ff1324c20e4674ef120e94f1 | [
"Apache-2.0"
] | 37 | 2017-03-30T03:36:24.000Z | 2022-01-28T08:28:36.000Z | #include <babylon/meshes/builders/plane_builder.h>
#include <babylon/maths/plane.h>
#include <babylon/meshes/builders/mesh_builder_options.h>
#include <babylon/meshes/mesh.h>
#include <babylon/meshes/vertex_data.h>
namespace BABYLON {
MeshPtr PlaneBuilder::CreatePlane(const std::string& name, PlaneOptions& options, Scene* scene)
{
const auto plane = Mesh::New(name, scene);
options.sideOrientation = Mesh::_GetDefaultSideOrientation(options.sideOrientation);
plane->_originalBuilderSideOrientation = *options.sideOrientation;
const auto vertexData = VertexData::CreatePlane(options);
vertexData->applyToMesh(*plane, options.updatable);
if (options.sourcePlane) {
plane->translate(options.sourcePlane->normal, -options.sourcePlane->d);
plane->setDirection(options.sourcePlane->normal.scale(-1.f));
}
return plane;
}
} // end of namespace BABYLON
| 29.333333 | 95 | 0.765909 | samdauwe |
60c5118dece542eb91ad4cffc642909347765509 | 1,982 | hpp | C++ | configuration/configurator/schemas/SchemaSequence.hpp | miguelvazq/HPCC-Platform | 22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5 | [
"Apache-2.0"
] | null | null | null | configuration/configurator/schemas/SchemaSequence.hpp | miguelvazq/HPCC-Platform | 22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5 | [
"Apache-2.0"
] | 1 | 2018-03-01T18:15:12.000Z | 2018-03-01T18:15:12.000Z | configuration/configurator/schemas/SchemaSequence.hpp | miguelvazq/HPCC-Platform | 22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5 | [
"Apache-2.0"
] | null | null | null | /*##############################################################################
HPCC SYSTEMS software Copyright (C) 2015 HPCC Systems®.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
############################################################################## */
#ifndef _SCHEMA_SEQUENCE_HPP_
#define _SCHEMA_SEQUENCE_HPP_
#include "SchemaCommon.hpp"
namespace CONFIGURATOR
{
class CArrayOfElementArrays;
class CSequence : public CXSDNode
{
public:
CSequence(CXSDNodeBase* pParentNode = NULL, CArrayOfElementArrays* pArrayOfElemArrays = NULL) : CXSDNode::CXSDNode(pParentNode, XSD_SEQUENCE), m_pArrayOfElementArrays(pArrayOfElemArrays)
{
}
virtual ~CSequence()
{
}
virtual const CXSDNodeBase* getNodeByTypeAndNameDescending(NODE_TYPES eNodeType, const char *pName) const;
virtual void dump(::std::ostream& cout, unsigned int offset = 0) const;
virtual void getDocumentation(::StringBuffer &strDoc) const;
virtual void getJSON(::StringBuffer &strJSON, unsigned int offset = 0, int idx = -1) const;
virtual void populateEnvXPath(::StringBuffer strXPath, unsigned int index = 1);
virtual void loadXMLFromEnvXml(const ::IPropertyTree *pEnvTree);
bool hasChildElements() const;
static CSequence* load(CXSDNodeBase* pRootNode, const ::IPropertyTree *pSchemaRoot, const char* xpath = NULL);
protected:
CArrayOfElementArrays *m_pArrayOfElementArrays;
private:
};
}
#endif // _SCHEMA_SEQUENCE_HPP_
| 34.77193 | 190 | 0.690716 | miguelvazq |
60c958d4f1abc35b180894df61d59b512106813a | 173 | cpp | C++ | src/Main.cpp | MatheusRich/IDJ | a25f4484d65a032b1f440c8237a1bd5dd2295266 | [
"MIT"
] | null | null | null | src/Main.cpp | MatheusRich/IDJ | a25f4484d65a032b1f440c8237a1bd5dd2295266 | [
"MIT"
] | null | null | null | src/Main.cpp | MatheusRich/IDJ | a25f4484d65a032b1f440c8237a1bd5dd2295266 | [
"MIT"
] | 1 | 2021-08-28T15:12:11.000Z | 2021-08-28T15:12:11.000Z | #include "Game.h"
#include "TitleState.h"
int main(int argc, char **argv) {
Game& game = Game::GetInstance();
game.Push(new TitleState());
game.Run();
return 0;
}
| 15.727273 | 35 | 0.635838 | MatheusRich |
60ca43871e717756ba0c703b730103affc1331a8 | 40,020 | cc | C++ | test/extensions/filters/http/lua/lua_integration_test.cc | akonradi/envoy | ea105235bd914e0df985f9e945e021bb6288d435 | [
"Apache-2.0"
] | 1 | 2021-04-16T18:57:56.000Z | 2021-04-16T18:57:56.000Z | test/extensions/filters/http/lua/lua_integration_test.cc | akonradi/envoy | ea105235bd914e0df985f9e945e021bb6288d435 | [
"Apache-2.0"
] | 104 | 2021-10-03T11:09:20.000Z | 2022-01-05T00:21:59.000Z | test/extensions/filters/http/lua/lua_integration_test.cc | akonradi/envoy | ea105235bd914e0df985f9e945e021bb6288d435 | [
"Apache-2.0"
] | 2 | 2021-01-21T14:46:11.000Z | 2021-01-22T03:14:08.000Z | #include "envoy/config/bootstrap/v3/bootstrap.pb.h"
#include "envoy/extensions/filters/network/http_connection_manager/v3/http_connection_manager.pb.h"
#include "extensions/filters/http/well_known_names.h"
#include "test/integration/http_integration.h"
#include "test/test_common/utility.h"
#include "gtest/gtest.h"
using Envoy::Http::HeaderValueOf;
namespace Envoy {
namespace {
class LuaIntegrationTest : public testing::TestWithParam<Network::Address::IpVersion>,
public HttpIntegrationTest {
public:
LuaIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam()) {}
void createUpstreams() override {
HttpIntegrationTest::createUpstreams();
addFakeUpstream(FakeHttpConnection::Type::HTTP1);
addFakeUpstream(FakeHttpConnection::Type::HTTP1);
// Create the xDS upstream.
addFakeUpstream(FakeHttpConnection::Type::HTTP2);
}
void initializeFilter(const std::string& filter_config, const std::string& domain = "*") {
config_helper_.addFilter(filter_config);
// Create static clusters.
createClusters();
config_helper_.addConfigModifier(
[domain](
envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager&
hcm) {
hcm.mutable_route_config()
->mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_match()
->set_prefix("/test/long/url");
hcm.mutable_route_config()->mutable_virtual_hosts(0)->set_domains(0, domain);
auto* new_route = hcm.mutable_route_config()->mutable_virtual_hosts(0)->add_routes();
new_route->mutable_match()->set_prefix("/alt/route");
new_route->mutable_route()->set_cluster("alt_cluster");
const std::string key = Extensions::HttpFilters::HttpFilterNames::get().Lua;
const std::string yaml =
R"EOF(
foo.bar:
foo: bar
baz: bat
keyset:
foo: MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAp0cSZtAdFgMI1zQJwG8ujTXFMcRY0+SA6fMZGEfQYuxcz/e8UelJ1fLDVAwYmk7KHoYzpizy0JIxAcJ+OAE+cd6a6RpwSEm/9/vizlv0vWZv2XMRAqUxk/5amlpQZE/4sRg/qJdkZZjKrSKjf5VEUQg2NytExYyYWG+3FEYpzYyUeVktmW0y/205XAuEQuxaoe+AUVKeoON1iDzvxywE42C0749XYGUFicqBSRj2eO7jm4hNWvgTapYwpswM3hV9yOAPOVQGKNXzNbLDbFTHyLw3OKayGs/4FUBa+ijlGD9VDawZq88RRaf5ztmH22gOSiKcrHXe40fsnrzh/D27uwIDAQAB
)EOF";
ProtobufWkt::Struct value;
TestUtility::loadFromYaml(yaml, value);
// Sets the route's metadata.
hcm.mutable_route_config()
->mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_metadata()
->mutable_filter_metadata()
->insert(Protobuf::MapPair<std::string, ProtobufWkt::Struct>(key, value));
});
initialize();
}
void initializeWithYaml(const std::string& filter_config, const std::string& route_config) {
config_helper_.addFilter(filter_config);
createClusters();
config_helper_.addConfigModifier(
[route_config](
envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager&
hcm) {
TestUtility::loadFromYaml(route_config, *hcm.mutable_route_config(), true);
});
initialize();
}
void createClusters() {
config_helper_.addConfigModifier([](envoy::config::bootstrap::v3::Bootstrap& bootstrap) {
auto* lua_cluster = bootstrap.mutable_static_resources()->add_clusters();
lua_cluster->MergeFrom(bootstrap.static_resources().clusters()[0]);
lua_cluster->set_name("lua_cluster");
auto* alt_cluster = bootstrap.mutable_static_resources()->add_clusters();
alt_cluster->MergeFrom(bootstrap.static_resources().clusters()[0]);
alt_cluster->set_name("alt_cluster");
auto* xds_cluster = bootstrap.mutable_static_resources()->add_clusters();
xds_cluster->MergeFrom(bootstrap.static_resources().clusters()[0]);
xds_cluster->set_name("xds_cluster");
xds_cluster->mutable_http2_protocol_options();
});
}
void initializeWithRds(const std::string& filter_config, const std::string& route_config_name,
const std::string& initial_route_config) {
config_helper_.addFilter(filter_config);
// Create static clusters.
createClusters();
// Set RDS config source.
config_helper_.addConfigModifier(
[route_config_name](
envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager&
hcm) {
hcm.mutable_rds()->set_route_config_name(route_config_name);
hcm.mutable_rds()->mutable_config_source()->set_resource_api_version(
envoy::config::core::v3::ApiVersion::V3);
envoy::config::core::v3::ApiConfigSource* rds_api_config_source =
hcm.mutable_rds()->mutable_config_source()->mutable_api_config_source();
rds_api_config_source->set_api_type(envoy::config::core::v3::ApiConfigSource::GRPC);
envoy::config::core::v3::GrpcService* grpc_service =
rds_api_config_source->add_grpc_services();
grpc_service->mutable_envoy_grpc()->set_cluster_name("xds_cluster");
});
on_server_init_function_ = [&]() {
AssertionResult result =
fake_upstreams_[3]->waitForHttpConnection(*dispatcher_, xds_connection_);
RELEASE_ASSERT(result, result.message());
result = xds_connection_->waitForNewStream(*dispatcher_, xds_stream_);
RELEASE_ASSERT(result, result.message());
xds_stream_->startGrpcStream();
EXPECT_TRUE(compareSotwDiscoveryRequest(Config::TypeUrl::get().RouteConfiguration, "",
{route_config_name}, true));
sendSotwDiscoveryResponse<envoy::config::route::v3::RouteConfiguration>(
Config::TypeUrl::get().RouteConfiguration,
{TestUtility::parseYaml<envoy::config::route::v3::RouteConfiguration>(
initial_route_config)},
"1");
};
initialize();
registerTestServerPorts({"http"});
}
void testRewriteResponse(const std::string& code) {
initializeFilter(code);
codec_client_ = makeHttpConnection(makeClientConnection(lookupPort("http")));
Http::TestRequestHeaderMapImpl request_headers{{":method", "POST"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"},
{"x-forwarded-for", "10.0.0.1"}};
auto encoder_decoder = codec_client_->startRequest(request_headers);
Http::StreamEncoder& encoder = encoder_decoder.first;
auto response = std::move(encoder_decoder.second);
Buffer::OwnedImpl request_data("done");
encoder.encodeData(request_data, true);
waitForNextUpstreamRequest();
Http::TestResponseHeaderMapImpl response_headers{{":status", "200"}, {"foo", "bar"}};
upstream_request_->encodeHeaders(response_headers, false);
Buffer::OwnedImpl response_data1("good");
upstream_request_->encodeData(response_data1, false);
Buffer::OwnedImpl response_data2("bye");
upstream_request_->encodeData(response_data2, true);
response->waitForEndStream();
EXPECT_EQ("2", response->headers()
.get(Http::LowerCaseString("content-length"))[0]
->value()
.getStringView());
EXPECT_EQ("ok", response->body());
cleanup();
}
void cleanup() {
codec_client_->close();
if (fake_lua_connection_ != nullptr) {
AssertionResult result = fake_lua_connection_->close();
RELEASE_ASSERT(result, result.message());
result = fake_lua_connection_->waitForDisconnect();
RELEASE_ASSERT(result, result.message());
}
if (fake_upstream_connection_ != nullptr) {
AssertionResult result = fake_upstream_connection_->close();
RELEASE_ASSERT(result, result.message());
result = fake_upstream_connection_->waitForDisconnect();
RELEASE_ASSERT(result, result.message());
}
if (xds_connection_ != nullptr) {
AssertionResult result = xds_connection_->close();
RELEASE_ASSERT(result, result.message());
result = xds_connection_->waitForDisconnect();
RELEASE_ASSERT(result, result.message());
xds_connection_ = nullptr;
}
}
FakeHttpConnectionPtr fake_lua_connection_;
FakeStreamPtr lua_request_;
};
INSTANTIATE_TEST_SUITE_P(IpVersions, LuaIntegrationTest,
testing::ValuesIn(TestEnvironment::getIpVersionsForTest()),
TestUtility::ipTestParamsToString);
// Regression test for pulling route info during early local replies using the Lua filter
// metadata() API. Covers both the upgrade required and no authority cases.
TEST_P(LuaIntegrationTest, CallMetadataDuringLocalReply) {
const std::string FILTER_AND_CODE =
R"EOF(
name: lua
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua
inline_code: |
function envoy_on_response(response_handle)
local metadata = response_handle:metadata():get("foo.bar")
if metadata == nil then
end
end
)EOF";
initializeFilter(FILTER_AND_CODE, "foo");
std::string response;
sendRawHttpAndWaitForResponse(lookupPort("http"), "GET / HTTP/1.0\r\n\r\n", &response, true);
EXPECT_TRUE(response.find("HTTP/1.1 426 Upgrade Required\r\n") == 0);
response = "";
sendRawHttpAndWaitForResponse(lookupPort("http"), "GET / HTTP/1.1\r\n\r\n", &response, true);
EXPECT_TRUE(response.find("HTTP/1.1 400 Bad Request\r\n") == 0);
}
// Basic request and response.
TEST_P(LuaIntegrationTest, RequestAndResponse) {
const std::string FILTER_AND_CODE =
R"EOF(
name: lua
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua
inline_code: |
function envoy_on_request(request_handle)
request_handle:logTrace("log test")
request_handle:logDebug("log test")
request_handle:logInfo("log test")
request_handle:logWarn("log test")
request_handle:logErr("log test")
request_handle:logCritical("log test")
local metadata = request_handle:metadata():get("foo.bar")
local body_length = request_handle:body():length()
request_handle:streamInfo():dynamicMetadata():set("envoy.lb", "foo", "bar")
local dynamic_metadata_value = request_handle:streamInfo():dynamicMetadata():get("envoy.lb")["foo"]
request_handle:headers():add("request_body_size", body_length)
request_handle:headers():add("request_metadata_foo", metadata["foo"])
request_handle:headers():add("request_metadata_baz", metadata["baz"])
if request_handle:connection():ssl() == nil then
request_handle:headers():add("request_secure", "false")
else
request_handle:headers():add("request_secure", "true")
end
request_handle:headers():add("request_protocol", request_handle:streamInfo():protocol())
request_handle:headers():add("request_dynamic_metadata_value", dynamic_metadata_value)
request_handle:headers():add("request_downstream_local_address_value",
request_handle:streamInfo():downstreamLocalAddress())
request_handle:headers():add("request_downstream_directremote_address_value",
request_handle:streamInfo():downstreamDirectRemoteAddress())
end
function envoy_on_response(response_handle)
local metadata = response_handle:metadata():get("foo.bar")
local body_length = response_handle:body():length()
response_handle:headers():add("response_metadata_foo", metadata["foo"])
response_handle:headers():add("response_metadata_baz", metadata["baz"])
response_handle:headers():add("response_body_size", body_length)
response_handle:headers():add("request_protocol", response_handle:streamInfo():protocol())
response_handle:headers():remove("foo")
end
)EOF";
initializeFilter(FILTER_AND_CODE);
codec_client_ = makeHttpConnection(makeClientConnection(lookupPort("http")));
Http::TestRequestHeaderMapImpl request_headers{{":method", "POST"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"},
{"x-forwarded-for", "10.0.0.1"}};
auto encoder_decoder = codec_client_->startRequest(request_headers);
Http::StreamEncoder& encoder = encoder_decoder.first;
auto response = std::move(encoder_decoder.second);
Buffer::OwnedImpl request_data1("hello");
encoder.encodeData(request_data1, false);
Buffer::OwnedImpl request_data2("world");
encoder.encodeData(request_data2, true);
waitForNextUpstreamRequest();
EXPECT_EQ("10", upstream_request_->headers()
.get(Http::LowerCaseString("request_body_size"))[0]
->value()
.getStringView());
EXPECT_EQ("bar", upstream_request_->headers()
.get(Http::LowerCaseString("request_metadata_foo"))[0]
->value()
.getStringView());
EXPECT_EQ("bat", upstream_request_->headers()
.get(Http::LowerCaseString("request_metadata_baz"))[0]
->value()
.getStringView());
EXPECT_EQ("false", upstream_request_->headers()
.get(Http::LowerCaseString("request_secure"))[0]
->value()
.getStringView());
EXPECT_EQ("HTTP/1.1", upstream_request_->headers()
.get(Http::LowerCaseString("request_protocol"))[0]
->value()
.getStringView());
EXPECT_EQ("bar", upstream_request_->headers()
.get(Http::LowerCaseString("request_dynamic_metadata_value"))[0]
->value()
.getStringView());
EXPECT_TRUE(
absl::StrContains(upstream_request_->headers()
.get(Http::LowerCaseString("request_downstream_local_address_value"))[0]
->value()
.getStringView(),
GetParam() == Network::Address::IpVersion::v4 ? "127.0.0.1:" : "[::1]:"));
EXPECT_TRUE(absl::StrContains(
upstream_request_->headers()
.get(Http::LowerCaseString("request_downstream_directremote_address_value"))[0]
->value()
.getStringView(),
GetParam() == Network::Address::IpVersion::v4 ? "127.0.0.1:" : "[::1]:"));
Http::TestResponseHeaderMapImpl response_headers{{":status", "200"}, {"foo", "bar"}};
upstream_request_->encodeHeaders(response_headers, false);
Buffer::OwnedImpl response_data1("good");
upstream_request_->encodeData(response_data1, false);
Buffer::OwnedImpl response_data2("bye");
upstream_request_->encodeData(response_data2, true);
response->waitForEndStream();
EXPECT_EQ("7", response->headers()
.get(Http::LowerCaseString("response_body_size"))[0]
->value()
.getStringView());
EXPECT_EQ("bar", response->headers()
.get(Http::LowerCaseString("response_metadata_foo"))[0]
->value()
.getStringView());
EXPECT_EQ("bat", response->headers()
.get(Http::LowerCaseString("response_metadata_baz"))[0]
->value()
.getStringView());
EXPECT_EQ("HTTP/1.1", response->headers()
.get(Http::LowerCaseString("request_protocol"))[0]
->value()
.getStringView());
EXPECT_TRUE(response->headers().get(Http::LowerCaseString("foo")).empty());
cleanup();
}
// Upstream call followed by continuation.
TEST_P(LuaIntegrationTest, UpstreamHttpCall) {
const std::string FILTER_AND_CODE =
R"EOF(
name: lua
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua
inline_code: |
function envoy_on_request(request_handle)
local headers, body = request_handle:httpCall(
"lua_cluster",
{
[":method"] = "POST",
[":path"] = "/",
[":authority"] = "lua_cluster"
},
"hello world",
5000)
request_handle:headers():add("upstream_foo", headers["foo"])
request_handle:headers():add("upstream_body_size", #body)
end
)EOF";
initializeFilter(FILTER_AND_CODE);
codec_client_ = makeHttpConnection(makeClientConnection(lookupPort("http")));
Http::TestRequestHeaderMapImpl request_headers{{":method", "GET"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"},
{"x-forwarded-for", "10.0.0.1"}};
auto response = codec_client_->makeHeaderOnlyRequest(request_headers);
ASSERT_TRUE(fake_upstreams_[1]->waitForHttpConnection(*dispatcher_, fake_lua_connection_));
ASSERT_TRUE(fake_lua_connection_->waitForNewStream(*dispatcher_, lua_request_));
ASSERT_TRUE(lua_request_->waitForEndStream(*dispatcher_));
Http::TestResponseHeaderMapImpl response_headers{{":status", "200"}, {"foo", "bar"}};
lua_request_->encodeHeaders(response_headers, false);
Buffer::OwnedImpl response_data1("good");
lua_request_->encodeData(response_data1, true);
waitForNextUpstreamRequest();
EXPECT_EQ("bar", upstream_request_->headers()
.get(Http::LowerCaseString("upstream_foo"))[0]
->value()
.getStringView());
EXPECT_EQ("4", upstream_request_->headers()
.get(Http::LowerCaseString("upstream_body_size"))[0]
->value()
.getStringView());
upstream_request_->encodeHeaders(default_response_headers_, true);
response->waitForEndStream();
cleanup();
}
// Upstream call followed by immediate response.
TEST_P(LuaIntegrationTest, UpstreamCallAndRespond) {
const std::string FILTER_AND_CODE =
R"EOF(
name: lua
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua
inline_code: |
function envoy_on_request(request_handle)
local headers, body = request_handle:httpCall(
"lua_cluster",
{
[":method"] = "POST",
[":path"] = "/",
[":authority"] = "lua_cluster"
},
"hello world",
5000)
request_handle:respond(
{[":status"] = "403",
["upstream_foo"] = headers["foo"]},
"nope")
end
)EOF";
initializeFilter(FILTER_AND_CODE);
codec_client_ = makeHttpConnection(makeClientConnection(lookupPort("http")));
Http::TestRequestHeaderMapImpl request_headers{{":method", "GET"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"},
{"x-forwarded-for", "10.0.0.1"}};
auto response = codec_client_->makeHeaderOnlyRequest(request_headers);
ASSERT_TRUE(fake_upstreams_[1]->waitForHttpConnection(*dispatcher_, fake_lua_connection_));
ASSERT_TRUE(fake_lua_connection_->waitForNewStream(*dispatcher_, lua_request_));
ASSERT_TRUE(lua_request_->waitForEndStream(*dispatcher_));
Http::TestResponseHeaderMapImpl response_headers{{":status", "200"}, {"foo", "bar"}};
lua_request_->encodeHeaders(response_headers, true);
response->waitForEndStream();
cleanup();
EXPECT_TRUE(response->complete());
EXPECT_EQ("403", response->headers().getStatusValue());
EXPECT_EQ("nope", response->body());
}
// Upstream fire and forget asynchronous call.
TEST_P(LuaIntegrationTest, UpstreamAsyncHttpCall) {
const std::string FILTER_AND_CODE =
R"EOF(
name: envoy.filters.http.lua
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua
inline_code: |
function envoy_on_request(request_handle)
local headers, body = request_handle:httpCall(
"lua_cluster",
{
[":method"] = "POST",
[":path"] = "/",
[":authority"] = "lua_cluster"
},
"hello world",
5000,
true)
end
)EOF";
initializeFilter(FILTER_AND_CODE);
codec_client_ = makeHttpConnection(makeClientConnection(lookupPort("http")));
Http::TestRequestHeaderMapImpl request_headers{{":method", "GET"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"},
{"x-forwarded-for", "10.0.0.1"}};
auto response = codec_client_->makeHeaderOnlyRequest(request_headers);
ASSERT_TRUE(fake_upstreams_[1]->waitForHttpConnection(*dispatcher_, fake_lua_connection_));
ASSERT_TRUE(fake_lua_connection_->waitForNewStream(*dispatcher_, lua_request_));
ASSERT_TRUE(lua_request_->waitForEndStream(*dispatcher_));
// Sanity checking that we sent the expected data.
EXPECT_THAT(lua_request_->headers(), HeaderValueOf(Http::Headers::get().Method, "POST"));
EXPECT_THAT(lua_request_->headers(), HeaderValueOf(Http::Headers::get().Path, "/"));
waitForNextUpstreamRequest();
upstream_request_->encodeHeaders(default_response_headers_, true);
response->waitForEndStream();
cleanup();
EXPECT_TRUE(response->complete());
EXPECT_EQ("200", response->headers().getStatusValue());
}
// Filter alters headers and changes route.
TEST_P(LuaIntegrationTest, ChangeRoute) {
const std::string FILTER_AND_CODE =
R"EOF(
name: lua
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua
inline_code: |
function envoy_on_request(request_handle)
request_handle:headers():remove(":path")
request_handle:headers():add(":path", "/alt/route")
end
)EOF";
initializeFilter(FILTER_AND_CODE);
codec_client_ = makeHttpConnection(makeClientConnection(lookupPort("http")));
Http::TestRequestHeaderMapImpl request_headers{{":method", "GET"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"},
{"x-forwarded-for", "10.0.0.1"}};
auto response = codec_client_->makeHeaderOnlyRequest(request_headers);
waitForNextUpstreamRequest(2);
upstream_request_->encodeHeaders(default_response_headers_, true);
response->waitForEndStream();
cleanup();
EXPECT_TRUE(response->complete());
EXPECT_EQ("200", response->headers().getStatusValue());
}
// Should survive from 30 calls when calling streamInfo():dynamicMetadata(). This is a regression
// test for #4305.
TEST_P(LuaIntegrationTest, SurviveMultipleCalls) {
const std::string FILTER_AND_CODE =
R"EOF(
name: lua
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua
inline_code: |
function envoy_on_request(request_handle)
request_handle:streamInfo():dynamicMetadata()
end
)EOF";
initializeFilter(FILTER_AND_CODE);
codec_client_ = makeHttpConnection(makeClientConnection(lookupPort("http")));
Http::TestRequestHeaderMapImpl request_headers{{":method", "GET"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"},
{"x-forwarded-for", "10.0.0.1"}};
for (uint32_t i = 0; i < 30; ++i) {
auto response = codec_client_->makeHeaderOnlyRequest(request_headers);
waitForNextUpstreamRequest();
upstream_request_->encodeHeaders(default_response_headers_, true);
response->waitForEndStream();
EXPECT_TRUE(response->complete());
EXPECT_EQ("200", response->headers().getStatusValue());
}
cleanup();
}
// Basic test for verifying signature.
TEST_P(LuaIntegrationTest, SignatureVerification) {
const std::string FILTER_AND_CODE =
R"EOF(
name: lua
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua
inline_code: |
function string.fromhex(str)
return (str:gsub('..', function (cc)
return string.char(tonumber(cc, 16))
end))
end
-- decoding
function dec(data)
local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
data = string.gsub(data, '[^'..b..'=]', '')
return (data:gsub('.', function(x)
if (x == '=') then return '' end
local r,f='',(b:find(x)-1)
for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end
return r;
end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x)
if (#x ~= 8) then return '' end
local c=0
for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end
return string.char(c)
end))
end
function envoy_on_request(request_handle)
local metadata = request_handle:metadata():get("keyset")
local keyder = metadata[request_handle:headers():get("keyid")]
local rawkeyder = dec(keyder)
local pubkey = request_handle:importPublicKey(rawkeyder, string.len(rawkeyder)):get()
if pubkey == nil then
request_handle:logErr("log test")
request_handle:headers():add("signature_verification", "rejected")
return
end
local hash = request_handle:headers():get("hash")
local sig = request_handle:headers():get("signature")
local rawsig = sig:fromhex()
local data = request_handle:headers():get("message")
local ok, error = request_handle:verifySignature(hash, pubkey, rawsig, string.len(rawsig), data, string.len(data))
if ok then
request_handle:headers():add("signature_verification", "approved")
else
request_handle:logErr(error)
request_handle:headers():add("signature_verification", "rejected")
end
request_handle:headers():add("verification", "done")
end
)EOF";
initializeFilter(FILTER_AND_CODE);
auto signature =
"345ac3a167558f4f387a81c2d64234d901a7ceaa544db779d2f797b0ea4ef851b740905a63e2f4d5af42cee093a2"
"9c7155db9a63d3d483e0ef948f5ac51ce4e10a3a6606fd93ef68ee47b30c37491103039459122f78e1c7ea71a1a5"
"ea24bb6519bca02c8c9915fe8be24927c91812a13db72dbcb500103a79e8f67ff8cb9e2a631974e0668ab3977bf5"
"70a91b67d1b6bcd5dce84055f21427d64f4256a042ab1dc8e925d53a769f6681a873f5859693a7728fcbe95beace"
"1563b5ffbcd7c93b898aeba31421dafbfadeea50229c49fd6c445449314460f3d19150bd29a91333beaced557ed6"
"295234f7c14fa46303b7e977d2c89ba8a39a46a35f33eb07a332";
codec_client_ = makeHttpConnection(makeClientConnection(lookupPort("http")));
Http::TestRequestHeaderMapImpl request_headers{
{":method", "POST"}, {":path", "/test/long/url"}, {":scheme", "https"},
{":authority", "host"}, {"x-forwarded-for", "10.0.0.1"}, {"message", "hello"},
{"keyid", "foo"}, {"signature", signature}, {"hash", "sha256"}};
auto response = codec_client_->makeHeaderOnlyRequest(request_headers);
waitForNextUpstreamRequest();
EXPECT_EQ("approved", upstream_request_->headers()
.get(Http::LowerCaseString("signature_verification"))[0]
->value()
.getStringView());
EXPECT_EQ("done", upstream_request_->headers()
.get(Http::LowerCaseString("verification"))[0]
->value()
.getStringView());
upstream_request_->encodeHeaders(default_response_headers_, true);
response->waitForEndStream();
EXPECT_TRUE(response->complete());
EXPECT_EQ("200", response->headers().getStatusValue());
cleanup();
}
const std::string FILTER_AND_CODE =
R"EOF(
name: lua
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua
inline_code: |
function envoy_on_request(request_handle)
request_handle:headers():add("code", "code_from_global")
end
source_codes:
hello.lua:
inline_string: |
function envoy_on_request(request_handle)
request_handle:headers():add("code", "code_from_hello")
end
byebye.lua:
inline_string: |
function envoy_on_request(request_handle)
request_handle:headers():add("code", "code_from_byebye")
end
)EOF";
const std::string INITIAL_ROUTE_CONFIG =
R"EOF(
name: basic_lua_routes
virtual_hosts:
- name: rds_vhost_1
domains: ["lua.per.route"]
routes:
- match:
prefix: "/lua/per/route/default"
route:
cluster: lua_cluster
- match:
prefix: "/lua/per/route/disabled"
route:
cluster: lua_cluster
typed_per_filter_config:
envoy.filters.http.lua:
"@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.LuaPerRoute
disabled: true
- match:
prefix: "/lua/per/route/hello"
route:
cluster: lua_cluster
typed_per_filter_config:
envoy.filters.http.lua:
"@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.LuaPerRoute
name: hello.lua
- match:
prefix: "/lua/per/route/byebye"
route:
cluster: lua_cluster
typed_per_filter_config:
envoy.filters.http.lua:
"@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.LuaPerRoute
name: byebye.lua
- match:
prefix: "/lua/per/route/inline"
route:
cluster: lua_cluster
typed_per_filter_config:
envoy.filters.http.lua:
"@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.LuaPerRoute
source_code:
inline_string: |
function envoy_on_request(request_handle)
request_handle:headers():add("code", "inline_code_from_inline")
end
- match:
prefix: "/lua/per/route/nocode"
route:
cluster: lua_cluster
typed_per_filter_config:
envoy.filters.http.lua:
"@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.LuaPerRoute
name: nocode.lua
)EOF";
const std::string UPDATE_ROUTE_CONFIG =
R"EOF(
name: basic_lua_routes
virtual_hosts:
- name: rds_vhost_1
domains: ["lua.per.route"]
routes:
- match:
prefix: "/lua/per/route/hello"
route:
cluster: lua_cluster
typed_per_filter_config:
envoy.filters.http.lua:
"@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.LuaPerRoute
source_code:
inline_string: |
function envoy_on_request(request_handle)
request_handle:headers():add("code", "inline_code_from_hello")
end
- match:
prefix: "/lua/per/route/inline"
route:
cluster: lua_cluster
typed_per_filter_config:
envoy.filters.http.lua:
"@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.LuaPerRoute
source_code:
inline_string: |
function envoy_on_request(request_handle)
request_handle:headers():add("code", "new_inline_code_from_inline")
end
)EOF";
// Test whether LuaPerRoute works properly. Since this test is mainly for configuration, the Lua
// script can be very simple.
TEST_P(LuaIntegrationTest, BasicTestOfLuaPerRoute) {
initializeWithYaml(FILTER_AND_CODE, INITIAL_ROUTE_CONFIG);
codec_client_ = makeHttpConnection(lookupPort("http"));
auto check_request = [this](Http::TestRequestHeaderMapImpl request_headers,
std::string expected_value) {
auto response = codec_client_->makeHeaderOnlyRequest(request_headers);
waitForNextUpstreamRequest(1);
auto entry = upstream_request_->headers().get(Http::LowerCaseString("code"));
if (!expected_value.empty()) {
EXPECT_EQ(expected_value, entry[0]->value().getStringView());
} else {
EXPECT_TRUE(entry.empty());
}
upstream_request_->encodeHeaders(default_response_headers_, true);
response->waitForEndStream();
EXPECT_TRUE(response->complete());
EXPECT_EQ("200", response->headers().getStatusValue());
};
// Lua code defined in 'inline_code' will be executed by default.
Http::TestRequestHeaderMapImpl default_headers{{":method", "GET"},
{":path", "/lua/per/route/default"},
{":scheme", "http"},
{":authority", "lua.per.route"},
{"x-forwarded-for", "10.0.0.1"}};
check_request(default_headers, "code_from_global");
// Test whether LuaPerRoute can disable the Lua filter.
Http::TestRequestHeaderMapImpl disabled_headers{{":method", "GET"},
{":path", "/lua/per/route/disabled"},
{":scheme", "http"},
{":authority", "lua.per.route"},
{"x-forwarded-for", "10.0.0.1"}};
check_request(disabled_headers, "");
// Test whether LuaPerRoute can correctly reference Lua code defined in filter config.
Http::TestRequestHeaderMapImpl hello_headers{{":method", "GET"},
{":path", "/lua/per/route/hello"},
{":scheme", "http"},
{":authority", "lua.per.route"},
{"x-forwarded-for", "10.0.0.1"}};
check_request(hello_headers, "code_from_hello");
Http::TestRequestHeaderMapImpl byebye_headers{{":method", "GET"},
{":path", "/lua/per/route/byebye"},
{":scheme", "http"},
{":authority", "lua.per.route"},
{"x-forwarded-for", "10.0.0.1"}};
check_request(byebye_headers, "code_from_byebye");
// Test whether LuaPerRoute can directly provide inline Lua code.
Http::TestRequestHeaderMapImpl inline_headers{{":method", "GET"},
{":path", "/lua/per/route/inline"},
{":scheme", "http"},
{":authority", "lua.per.route"},
{"x-forwarded-for", "10.0.0.1"}};
check_request(inline_headers, "inline_code_from_inline");
// When the name referenced by LuaPerRoute does not exist, Lua filter does nothing.
Http::TestRequestHeaderMapImpl nocode_headers{{":method", "GET"},
{":path", "/lua/per/route/nocode"},
{":scheme", "http"},
{":authority", "lua.per.route"},
{"x-forwarded-for", "10.0.0.1"}};
check_request(nocode_headers, "");
cleanup();
}
// Test whether Rds can correctly deliver LuaPerRoute configuration.
TEST_P(LuaIntegrationTest, RdsTestOfLuaPerRoute) {
// When the route configuration is updated dynamically via RDS and the configuration contains an
// inline Lua code, Envoy may call lua_open in multiple threads to create new lua_State objects.
// During lua_State creation, 'LuaJIT' uses some static local variables shared by multiple threads
// to aid memory allocation. Although 'LuaJIT' itself guarantees that there is no thread safety
// issue here, the use of these static local variables by multiple threads will cause a TSAN alarm.
#if defined(__has_feature) && __has_feature(thread_sanitizer)
ENVOY_LOG_MISC(critical, "LuaIntegrationTest::RdsTestOfLuaPerRoute not supported by this "
"compiler configuration");
#else
initializeWithRds(FILTER_AND_CODE, "basic_lua_routes", INITIAL_ROUTE_CONFIG);
codec_client_ = makeHttpConnection(lookupPort("http"));
auto check_request = [this](Http::TestRequestHeaderMapImpl request_headers,
std::string expected_value) {
auto response = codec_client_->makeHeaderOnlyRequest(request_headers);
waitForNextUpstreamRequest(1);
auto entry = upstream_request_->headers().get(Http::LowerCaseString("code"));
if (!expected_value.empty()) {
EXPECT_EQ(expected_value, entry[0]->value().getStringView());
} else {
EXPECT_TRUE(entry.empty());
}
upstream_request_->encodeHeaders(default_response_headers_, true);
response->waitForEndStream();
EXPECT_TRUE(response->complete());
EXPECT_EQ("200", response->headers().getStatusValue());
};
Http::TestRequestHeaderMapImpl hello_headers{{":method", "GET"},
{":path", "/lua/per/route/hello"},
{":scheme", "http"},
{":authority", "lua.per.route"},
{"x-forwarded-for", "10.0.0.1"}};
check_request(hello_headers, "code_from_hello");
Http::TestRequestHeaderMapImpl inline_headers{{":method", "GET"},
{":path", "/lua/per/route/inline"},
{":scheme", "http"},
{":authority", "lua.per.route"},
{"x-forwarded-for", "10.0.0.1"}};
check_request(inline_headers, "inline_code_from_inline");
// Update route config by RDS. Test whether RDS can work normally.
sendSotwDiscoveryResponse<envoy::config::route::v3::RouteConfiguration>(
Config::TypeUrl::get().RouteConfiguration,
{TestUtility::parseYaml<envoy::config::route::v3::RouteConfiguration>(UPDATE_ROUTE_CONFIG)},
"2");
test_server_->waitForCounterGe("http.config_test.rds.basic_lua_routes.update_success", 2);
check_request(hello_headers, "inline_code_from_hello");
check_request(inline_headers, "new_inline_code_from_inline");
cleanup();
#endif
}
// Rewrite response buffer.
TEST_P(LuaIntegrationTest, RewriteResponseBuffer) {
const std::string FILTER_AND_CODE =
R"EOF(
name: lua
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua
inline_code: |
function envoy_on_response(response_handle)
local content_length = response_handle:body():setBytes("ok")
response_handle:logTrace(content_length)
response_handle:headers():replace("content-length", content_length)
end
)EOF";
testRewriteResponse(FILTER_AND_CODE);
}
// Rewrite chunked response body.
TEST_P(LuaIntegrationTest, RewriteChunkedBody) {
const std::string FILTER_AND_CODE =
R"EOF(
name: lua
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua
inline_code: |
function envoy_on_response(response_handle)
response_handle:headers():replace("content-length", 2)
local last
for chunk in response_handle:bodyChunks() do
chunk:setBytes("")
last = chunk
end
last:setBytes("ok")
end
)EOF";
testRewriteResponse(FILTER_AND_CODE);
}
} // namespace
} // namespace Envoy
| 40.1002 | 411 | 0.627086 | akonradi |
60ccdc14d780d83535a4880145662945cda09eab | 619 | cpp | C++ | PhantomEngine/PhantomOS.cpp | DexianZhao/PhantomGameEngine | cf8e341d21e3973856d9f23ad0b1af9db831bac7 | [
"MIT"
] | 4 | 2019-11-08T00:15:13.000Z | 2021-03-26T13:34:50.000Z | src/PhantomEngine/PhantomOS.cpp | DexianZhao/PhantomEngineV2 | cc3bf02ca1d442713d471ca8835ca026bb32e841 | [
"MIT"
] | 4 | 2021-03-13T10:26:09.000Z | 2021-03-13T10:45:35.000Z | src/PhantomEngine/PhantomOS.cpp | DexianZhao/PhantomEngineV2 | cc3bf02ca1d442713d471ca8835ca026bb32e841 | [
"MIT"
] | 3 | 2020-06-01T01:53:05.000Z | 2021-03-21T03:51:33.000Z | //////////////////////////////////////////////////////////////////////////////////////////////////////
/*
幻影游戏引擎, 2009-2016, Phantom Game Engine, http://www.aixspace.com
Design Writer : 赵德贤 Dexian Zhao
Email: yuzhou_995@hotmail.com
Copyright 2009-2016 Zhao Dexian
-------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------
*/
//////////////////////////////////////////////////////////////////////////////////////////////////////
#include "PhantomOS.h"
namespace Phantom{
};
| 32.578947 | 103 | 0.256866 | DexianZhao |
f5a25fa8db11e9829c74742edd836fe39270b63a | 16 | cpp | C++ | chapter-7/7.33.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | chapter-7/7.33.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | chapter-7/7.33.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | // See Screen.h
| 8 | 15 | 0.625 | zero4drift |
f5a3333a166f95e3b10b8b1279385189a338d2a7 | 925 | cpp | C++ | kernel/arch/x86_64/device/graphic.cpp | aiuno/WingOS | 9a81927c1dc38062617245d7adb1d8b9419950bb | [
"BSD-2-Clause"
] | 549 | 2020-08-19T12:03:58.000Z | 2022-03-31T18:04:39.000Z | kernel/arch/x86_64/device/graphic.cpp | aiuno/WingOS | 9a81927c1dc38062617245d7adb1d8b9419950bb | [
"BSD-2-Clause"
] | 8 | 2020-08-29T18:05:13.000Z | 2021-02-01T23:15:27.000Z | kernel/arch/x86_64/device/graphic.cpp | aiuno/WingOS | 9a81927c1dc38062617245d7adb1d8b9419950bb | [
"BSD-2-Clause"
] | 32 | 2021-02-15T17:19:00.000Z | 2022-02-08T18:41:10.000Z | #include "graphic.h"
#include <logging.h>
#include <mem/virtual.h>
#include <physical.h>
basic_framebuffer_graphic_device::basic_framebuffer_graphic_device(size_t width, size_t height, uintptr_t physical_addr, framebuff_bpp bpp)
{
if (bpp == BPP_32_BIT)
{
log("framebuffer_graphic_device", LOG_INFO, "loading basic framebuffer device, with width: {} height: {} at addr {}", width, height, physical_addr);
_width = width;
_height = height;
_addr = reinterpret_cast<void *>(get_mem_addr(physical_addr));
for (size_t i = 0; i < (width * height * sizeof(uint32_t)) + 4096; i += 4096)
{
map_page(physical_addr + i, get_mem_addr(physical_addr + i), true, true);
}
}
else
{
log("framebuffer_graphic_device", LOG_WARNING, "basic_framebuffer_graphic_device don't support 24bit pixel for the moment");
// unsupported rn
}
}
| 34.259259 | 156 | 0.662703 | aiuno |
f5a3cb01647bebe38a5025cd4d11aeb90b012dda | 1,268 | hh | C++ | SearchTrees/old_version/binarysearchtree.hh | heikkilv/BST-Test | 3a946394683c350acfc52d5ad6e5422447d00af8 | [
"MIT"
] | null | null | null | SearchTrees/old_version/binarysearchtree.hh | heikkilv/BST-Test | 3a946394683c350acfc52d5ad6e5422447d00af8 | [
"MIT"
] | null | null | null | SearchTrees/old_version/binarysearchtree.hh | heikkilv/BST-Test | 3a946394683c350acfc52d5ad6e5422447d00af8 | [
"MIT"
] | null | null | null | // Standard binary search tree implementation
//
// Implementation is based on T.H. Cormen, C.E. Leiserson, R.L. Rivest, C. Stein,
// Introduction to algorithms, 3rd ed. MIT Press, Cambridge, MA, 2009, Chapter 12
//
// Ville Heikkilä
#ifndef BINARYSEARCHTREE_HH
#define BINARYSEARCHTREE_HH
struct TreeNode
{
int key_;
TreeNode* parent_;
TreeNode* left_;
TreeNode* right_;
TreeNode(int key) :
key_{ key },
parent_{ nullptr },
left_{ nullptr },
right_{ nullptr } {}
};
class BinarySearchTree
{
public:
BinarySearchTree();
~BinarySearchTree();
int nodes() const;
int height() const;
int height(TreeNode* node) const;
void clear();
TreeNode* maximum() const;
TreeNode* maximum(TreeNode* node) const;
TreeNode* minimum() const;
TreeNode* minimum(TreeNode* node) const;
TreeNode* successor(TreeNode* node) const;
TreeNode* predecessor(TreeNode* node) const;
bool isInTree(TreeNode* node) const;
TreeNode* search(int key) const;
void insertNode(TreeNode* node);
void deleteNode(TreeNode* node);
void print() const;
private:
TreeNode* root_;
int nodes_;
void transplant(TreeNode* u, TreeNode* v);
};
#endif // BINARYSEARCHTREE_HH
| 20.786885 | 81 | 0.663249 | heikkilv |
f5a4e0f2dfdf0e310f68adf713bb34a0030df10f | 10,555 | cc | C++ | caffe2/operators/segment_reduction_op.cc | Hosseinabady/caffe2_fpga | d7a31107332d9288a672e8dadda7774cffb78561 | [
"MIT"
] | null | null | null | caffe2/operators/segment_reduction_op.cc | Hosseinabady/caffe2_fpga | d7a31107332d9288a672e8dadda7774cffb78561 | [
"MIT"
] | null | null | null | caffe2/operators/segment_reduction_op.cc | Hosseinabady/caffe2_fpga | d7a31107332d9288a672e8dadda7774cffb78561 | [
"MIT"
] | null | null | null | #include "caffe2/operators/segment_reduction_op.h"
namespace caffe2 {
// registering 4 input gradient with main output
OPERATOR_SCHEMA(SparseLengthsIndicesInGradientWeightedSumWithMainInputGradient)
.NumInputs(5)
.NumOutputs(2);
REGISTER_CPU_OPERATOR(
SparseLengthsIndicesInGradientWeightedSumWithMainInputGradient,
AbstractLengthsWithMainInputGradientOp<
float,
int,
CPUContext,
WeightedSumReducerDef::template ReducerGradient<float, CPUContext>,
true /*SparseFused*/,
true /*GradientNeedIndices*/>);
// registering 4 input version
OPERATOR_SCHEMA(SparseLengthsIndicesInGradientWeightedSumGradient)
.NumInputs(4)
.NumOutputs(1);
REGISTER_CPU_OPERATOR(
SparseLengthsIndicesInGradientWeightedSumGradient,
AbstractLengthsGradientOp<
float,
int,
CPUContext,
WeightedSumReducerDef::template ReducerGradient<float, CPUContext>,
true /*GradientNeedIndices*/>);
// registering 3 input version
OPERATOR_SCHEMA(SparseLengthsIndicesInGradientSumGradient)
.NumInputs(3)
.NumOutputs(1);
REGISTER_CPU_OPERATOR(
SparseLengthsIndicesInGradientSumGradient,
AbstractLengthsGradientOp<
float,
int,
CPUContext,
SumReducerDef::template ReducerGradient<float, CPUContext>,
true /*GradientNeedIndices*/>);
OPERATOR_SCHEMA(LengthsIndicesInGradientSumGradient).NumInputs(3).NumOutputs(1);
REGISTER_CPU_OPERATOR(
LengthsIndicesInGradientSumGradient,
AbstractLengthsGradientOp<
float,
int,
CPUContext,
SumReducerDef::template ReducerGradient<float, CPUContext>,
true /*GradientNeedIndices*/>);
namespace {
template <typename Def>
string FormatDoc() {
string doc = Def::doc;
ReplaceAll(doc, "{op}", Def::OpDef::name);
ReplaceAll(doc, "{op_doc}", Def::OpDef::doc);
return doc;
}
// Helper macro when the main op is defined elsewhere, and we only need to
// define the schema, and the gradient op.
#define REGISTER_SEGMENT_DEF_SCHEMA_GRADIENT_ONLY(...) \
OPERATOR_SCHEMA_STR( \
string(__VA_ARGS__::basename) + (__VA_ARGS__::OpDef::name)) \
.NumInputs(__VA_ARGS__::ForwardOp::kNumInputs) \
.NumOutputs(1) \
.SetDoc(FormatDoc<__VA_ARGS__>()) \
.Output(0, "OUTPUT", "Aggregated tensor") \
.FillUsing(__VA_ARGS__::PopulateSchema); \
REGISTER_CPU_OPERATOR_STR( \
string(__VA_ARGS__::basename) + (__VA_ARGS__::OpDef::name) + "Gradient", \
__VA_ARGS__::BackwardOp); \
OPERATOR_SCHEMA_STR( \
string(__VA_ARGS__::basename) + (__VA_ARGS__::OpDef::name) + "Gradient") \
.NumInputs(__VA_ARGS__::BackwardOp::kNumInputs) \
.NumOutputs(1); \
REGISTER_GRADIENT_STR( \
string(__VA_ARGS__::basename) + (__VA_ARGS__::OpDef::name), \
__VA_ARGS__::GetGradient)
#define REGISTER_SEGMENT_DEF(...) \
REGISTER_CPU_OPERATOR_STR( \
string(__VA_ARGS__::basename) + (__VA_ARGS__::OpDef::name), \
__VA_ARGS__::ForwardOp); \
REGISTER_SEGMENT_DEF_SCHEMA_GRADIENT_ONLY(__VA_ARGS__)
REGISTER_SEGMENT_DEF(
AbstractSortedSegmentRangeDef<float, int, CPUContext, SumRangeReducerDef>);
REGISTER_SEGMENT_DEF(AbstractSortedSegmentRangeDef<
float,
int,
CPUContext,
LogSumExpRangeReducerDef>);
REGISTER_SEGMENT_DEF(AbstractSortedSegmentRangeDef<
float,
int,
CPUContext,
LogMeanExpRangeReducerDef>);
REGISTER_SEGMENT_DEF(
AbstractSortedSegmentRangeDef<float, int, CPUContext, MeanRangeReducerDef>);
REGISTER_SEGMENT_DEF(
AbstractSortedSegmentRangeDef<float, int, CPUContext, MaxRangeReducerDef>);
#define REGISTER_REDUCER_WITH_OPS(reducer_def) \
REGISTER_SEGMENT_DEF( \
AbstractReduceFrontDef<float, CPUContext, reducer_def>); \
REGISTER_SEGMENT_DEF( \
AbstractSortedSegmentDef<float, int, CPUContext, reducer_def>); \
REGISTER_SEGMENT_DEF( \
AbstractSparseSortedSegmentDef<float, int, CPUContext, reducer_def>); \
REGISTER_SEGMENT_DEF( \
AbstractUnsortedSegmentDef<float, int, CPUContext, reducer_def>); \
REGISTER_SEGMENT_DEF( \
AbstractSparseUnsortedSegmentDef<float, int, CPUContext, reducer_def>)
#define REGISTER_REDUCER_WITH_LENGTH_OPS(reducer_def, GradientNeedIndices) \
REGISTER_SEGMENT_DEF(AbstractLengthsDef< \
float, \
int, \
CPUContext, \
reducer_def, \
GradientNeedIndices>)
#define REGISTER_REDUCER_WITH_ALL_OPS(reducer_def) \
REGISTER_REDUCER_WITH_OPS(reducer_def) \
REGISTER_REDUCER_WITH_LENGTH_OPS(reducer_def, false)
REGISTER_REDUCER_WITH_OPS(SumReducerDef);
REGISTER_REDUCER_WITH_LENGTH_OPS(SumReducerDef, true);
REGISTER_REDUCER_WITH_ALL_OPS(WeightedSumReducerDef);
REGISTER_REDUCER_WITH_ALL_OPS(MeanReducerDef);
// SparseLengths[Sum,WeightedSum,Mean] are now implemented separately,
// so we only rely to the historical implementation for the backward + schema.
REGISTER_SEGMENT_DEF_SCHEMA_GRADIENT_ONLY(AbstractSparseLengthsDef<
float,
int,
CPUContext,
SumReducerDef,
true /*GradientNeedIndices*/>)
REGISTER_SEGMENT_DEF_SCHEMA_GRADIENT_ONLY(AbstractSparseLengthsDef<
float,
int,
CPUContext,
WeightedSumReducerDef,
true /*GradientNeedIndices*/>)
REGISTER_SEGMENT_DEF_SCHEMA_GRADIENT_ONLY(
AbstractSparseLengthsDef<float, int, CPUContext, MeanReducerDef>)
REGISTER_SEGMENT_DEF(AbstractReduceBackDef<float, CPUContext, SumReducerDef>);
REGISTER_SEGMENT_DEF(AbstractReduceBackDef<float, CPUContext, MeanReducerDef>);
// Auxiliary output gradients are currently implemented only for Lengths version
#define REGISTER_GRADIENT_WITH_MAIN_INPUT(...) \
REGISTER_CPU_OPERATOR_STR( \
string(__VA_ARGS__::basename) + (__VA_ARGS__::OpDef::name) + \
"WithMainInputGradient", \
__VA_ARGS__::WithMainInputBackwardOp); \
OPERATOR_SCHEMA_STR( \
string(__VA_ARGS__::basename) + (__VA_ARGS__::OpDef::name) + \
"WithMainInputGradient") \
.NumInputs(__VA_ARGS__::WithMainInputBackwardOp::kNumInputs) \
.NumOutputs(1, INT_MAX)
REGISTER_GRADIENT_WITH_MAIN_INPUT(
AbstractLengthsDef<float, int, CPUContext, WeightedSumReducerDef>);
REGISTER_GRADIENT_WITH_MAIN_INPUT(
AbstractSparseLengthsDef<float, int, CPUContext, WeightedSumReducerDef>);
#define REGISTER_GRADIENT_WITH_MAIN_INPUT_AND_FORWARD_OUTPUT(...) \
REGISTER_CPU_OPERATOR_STR( \
string(__VA_ARGS__::basename) + (__VA_ARGS__::OpDef::name) + \
"WithMainInputAndForwardOutputGradient", \
__VA_ARGS__::WithMainInputAndForwardOutputBackwardOp); \
OPERATOR_SCHEMA_STR( \
string(__VA_ARGS__::basename) + (__VA_ARGS__::OpDef::name) + \
"WithMainInputAndForwardOutputGradient") \
.NumInputs( \
__VA_ARGS__::WithMainInputAndForwardOutputBackwardOp::kNumInputs) \
.NumOutputs(1, INT_MAX)
#define REGISTER_SEGMENT_DEF_MAIN_INPUT_AND_FORWARD_OUTPUT_GRADIENT(...) \
OPERATOR_SCHEMA_STR( \
string(__VA_ARGS__::basename) + (__VA_ARGS__::OpDef::name)) \
.NumInputs(__VA_ARGS__::ForwardOp::kNumInputs) \
.NumOutputs(1) \
.SetDoc(FormatDoc<__VA_ARGS__>()) \
.Output(0, "OUTPUT", "Aggregated tensor") \
.FillUsing(__VA_ARGS__::PopulateSchema); \
REGISTER_GRADIENT_WITH_MAIN_INPUT_AND_FORWARD_OUTPUT(__VA_ARGS__); \
REGISTER_GRADIENT_STR( \
string(__VA_ARGS__::basename) + (__VA_ARGS__::OpDef::name), \
__VA_ARGS__::GetGradient)
// This implements and registers a length op with a gradient which requires
// the main input as well as the output of the forward output.
#define REGISTER_LENGTHS_OPS_MAIN_INPUT_AND_FORWARD_OUTPUT_GRADIENT(...) \
REGISTER_CPU_OPERATOR_STR( \
string(__VA_ARGS__::basename) + (__VA_ARGS__::OpDef::name), \
__VA_ARGS__::ForwardOp); \
REGISTER_SEGMENT_DEF_MAIN_INPUT_AND_FORWARD_OUTPUT_GRADIENT(__VA_ARGS__)
REGISTER_LENGTHS_OPS_MAIN_INPUT_AND_FORWARD_OUTPUT_GRADIENT(
AbstractLengthsDef<float, int, CPUContext, MaxReducerDef>);
}
}
| 50.023697 | 80 | 0.564472 | Hosseinabady |
f5a59eba6ac336b9c73b2365ae199beb3c45f9cc | 3,459 | hpp | C++ | src/cosma/interval.hpp | rohany/COSMA | c16e14f8e4251a08765c0bf83386b2aef16d566b | [
"BSD-3-Clause"
] | 123 | 2019-05-10T07:45:16.000Z | 2022-03-10T17:23:05.000Z | src/cosma/interval.hpp | rohany/COSMA | c16e14f8e4251a08765c0bf83386b2aef16d566b | [
"BSD-3-Clause"
] | 79 | 2019-08-15T09:35:14.000Z | 2022-03-28T09:25:51.000Z | src/cosma/interval.hpp | rohany/COSMA | c16e14f8e4251a08765c0bf83386b2aef16d566b | [
"BSD-3-Clause"
] | 20 | 2019-05-08T21:48:12.000Z | 2022-01-26T15:03:12.000Z | #pragma once
#include <iostream>
#include <vector>
namespace cosma {
// interval of consecutive numbers
class Interval {
public:
int start_;
int end_;
Interval();
Interval(int start, int end);
int first() const;
int last() const;
std::size_t length();
bool empty();
bool only_one();
// divides the interval into intervals of equal length.
// if the interval is not divisible by divisor, then
// last interval might not be of the same size as others.
std::vector<Interval> divide_by(int divisor);
int subinterval_index(int divisor, int elem);
int subinterval_offset(int divisor, int elem);
std::pair<int, int> locate_in_subinterval(int divisor, int elem);
int locate_in_interval(int divisor, int subint_index, int subint_offset);
// returns the interval containing elem
Interval subinterval_containing(int divisor, int elem);
// returns the box_index-th interval
Interval subinterval(int divisor, int box_index);
// returns the largest subinterval when divided by divisor
int largest_subinterval_length(int divisor);
// returns the smallest subinterval when divided by divisor
int smallest_subinterval_length(int divisor);
bool contains(int num);
bool contains(Interval other);
bool before(Interval &other) const;
bool operator==(const Interval &other) const;
friend std::ostream &operator<<(std::ostream &os, const Interval &inter);
};
class Interval2D {
public:
Interval rows;
Interval cols;
Interval2D();
Interval2D(Interval row, Interval col);
Interval2D(int row_start, int row_end, int col_start, int col_end);
// splits the current Interval2D into divisor many submatrices by splitting
// only the columns interval and returns the size of the submatrix indexed
// with index
std::size_t split_by(int divisor, int index);
std::size_t size();
bool contains(int row, int col);
bool contains(Interval2D other);
bool before(Interval2D &other) const;
int local_index(int row, int col);
std::pair<int, int> global_index(int local_index);
Interval2D submatrix(int divisor, int index);
bool operator==(const Interval2D &other) const;
friend std::ostream &operator<<(std::ostream &os, const Interval2D &inter);
};
} // namespace cosma
template <class T>
inline void hash_combine(std::size_t &s, const T &v) {
std::hash<T> h;
s ^= h(v) + 0x9e3779b9 + (s << 6) + (s >> 2);
}
// add hash function specialization for these struct-s
// so that we can use this class as a key of the unordered_map
namespace std {
template <>
struct hash<cosma::Interval> {
std::size_t operator()(const cosma::Interval &k) const {
using std::hash;
// Compute individual hash values for first,
// second and third and combine them using XOR
// and bit shifting:
size_t result = 0;
hash_combine(result, k.start_);
hash_combine(result, k.end_);
return result;
}
};
template <>
struct hash<cosma::Interval2D> {
std::size_t operator()(const cosma::Interval2D &k) const {
using std::hash;
// Compute individual hash values for first,
// second and third and combine them using XOR
// and bit shifting:
size_t result = 0;
hash_combine(result, k.rows);
hash_combine(result, k.cols);
return result;
}
};
} // namespace std
| 28.352459 | 79 | 0.674472 | rohany |
f5a67185960047058055d3eeabb4b73ddedcb2e2 | 334 | cpp | C++ | 160121-c03.13.02-q03_illegal_variables/q03_illegal_variables.cpp | R4mzy/ppp2-cpp-stroustrup | a7eb816e136f146c282ec8682f8b48440064481f | [
"MIT"
] | 3 | 2015-10-28T18:37:09.000Z | 2020-03-23T04:38:51.000Z | 160121-c03.13.02-q03_illegal_variables/q03_illegal_variables.cpp | R4mzy/ppp2-cpp-stroustrup | a7eb816e136f146c282ec8682f8b48440064481f | [
"MIT"
] | 6 | 2015-10-19T16:11:50.000Z | 2015-11-03T12:24:26.000Z | 160121-c03.13.02-q03_illegal_variables/q03_illegal_variables.cpp | R4mzy/ppp2-cpp-stroustrup | a7eb816e136f146c282ec8682f8b48440064481f | [
"MIT"
] | null | null | null | #include "../res-files/std_lib_facilities.h"
// testing illegal and stupid-but-legal variable names to see the behaviour of the compiler
int main() {
string _underscore = "what does";
int ALLCAP = 1919;
double if = 4.2;
char one char = 'a';
string #tag = "hashy";
int and!123 = 123;
double 2digi = 2.1;
char string = 's';
}
| 22.266667 | 91 | 0.673653 | R4mzy |
f5a9755539de3ab898c1ce9f9a2ad2858869a7a6 | 55,168 | cxx | C++ | Applications/BreastDensityFromMRIsGivenMaskAndImage/niftkBreastDensityFromMRIsGivenMaskAndImage.cxx | NifTK/NifTK | 2358b333c89ff1bba1c232eecbbcdc8003305dfe | [
"BSD-3-Clause"
] | 13 | 2018-07-28T13:36:38.000Z | 2021-11-01T19:17:39.000Z | Applications/BreastDensityFromMRIsGivenMaskAndImage/niftkBreastDensityFromMRIsGivenMaskAndImage.cxx | NifTK/NifTK | 2358b333c89ff1bba1c232eecbbcdc8003305dfe | [
"BSD-3-Clause"
] | null | null | null | Applications/BreastDensityFromMRIsGivenMaskAndImage/niftkBreastDensityFromMRIsGivenMaskAndImage.cxx | NifTK/NifTK | 2358b333c89ff1bba1c232eecbbcdc8003305dfe | [
"BSD-3-Clause"
] | 10 | 2018-08-20T07:06:00.000Z | 2021-07-07T07:55:27.000Z | /*=============================================================================
NifTK: A software platform for medical image computing.
Copyright (c) University College London (UCL). All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See LICENSE.txt in the top level directory for details.
=============================================================================*/
/*!
* \file niftkBreastDensityFromMRIs.cxx
* \page niftkBreastDensityFromMRIs
* \section niftkBreastDensityFromMRIsSummary niftkBreastDensityFromMRIs
*
* Compute breast density for directories of DICOM MR images
*
*/
#include <string>
#include <vector>
#include <sstream>
#include <fstream>
#include <iostream>
#include <iterator>
#include <QProcess>
#include <QString>
#include <QDebug>
#include <boost/filesystem/path.hpp>
#include <boost/iostreams/tee.hpp>
#include <boost/iostreams/stream.hpp>
#include <niftkFileHelper.h>
#include <niftkConversionUtils.h>
#include <niftkCSVRow.h>
#include <niftkEnvironmentHelper.h>
#include <itkCommandLineHelper.h>
#include <itkImage.h>
#include <itkImageFileReader.h>
#include <itkImageSeriesReader.h>
#include <itkImageFileWriter.h>
#include <itkNifTKImageIOFactory.h>
#include <itkWriteImage.h>
#include <itkReadImage.h>
#include <itkConversionUtils.h>
#include <itkImageRegionIterator.h>
#include <itkImageRegionIteratorWithIndex.h>
#include <itkInvertIntensityBetweenMaxAndMinImageFilter.h>
#include <itkMaskImageFilter.h>
#include <itkCastImageFilter.h>
#include <itkOrientImageFilter.h>
#include <itkSampleImageFilter.h>
#include <itkBinaryShapeBasedSuperSamplingFilter.h>
#include <itkIsImageBinary.h>
#include <itkRescaleIntensityImageFilter.h>
//#define LINK_TO_SEG_EM
#ifdef LINK_TO_SEG_EM
#include <_seg_EM.h>
#endif
#include <niftkBreastDensityFromMRIsGivenMaskAndImageCLP.h>
#define SegPrecisionTYPE float
namespace fs = boost::filesystem;
namespace bio = boost::iostreams;
using bio::tee_device;
using bio::stream;
typedef itk::MetaDataDictionary DictionaryType;
typedef itk::MetaDataObject< std::string > MetaDataStringType;
typedef float PixelType;
const unsigned int Dimension = 3;
typedef itk::Image< PixelType, Dimension > ImageType;
typedef itk::Image< PixelType, 4 > ImageType4D;
// -------------------------------------------------------------------------
// CreateFilename()
// -------------------------------------------------------------------------
std::string CreateFilename( std::string fileOne,
std::string fileTwo,
std::string description,
std::string suffix )
{
std::string fileOneWithoutSuffix;
niftk::ExtractImageFileSuffix( fileOne, fileOneWithoutSuffix );
std::string fileTwoWithoutSuffix;
niftk::ExtractImageFileSuffix( fileTwo, fileTwoWithoutSuffix );
return fileOneWithoutSuffix + "_" + description + "_" + fileTwoWithoutSuffix + suffix;
};
// -------------------------------------------------------------------------
// PrintOrientationInfo()
// -------------------------------------------------------------------------
void PrintOrientationInfo( ImageType::Pointer image )
{
itk::SpatialOrientationAdapter adaptor;
ImageType::DirectionType direction;
for (unsigned int i = 0; i < Dimension; i++)
{
for (unsigned int j = 0; j < Dimension; j++)
{
direction[i][j] = image->GetDirection()[i][j];
}
}
std::cout << "Image direction: " << std::endl
<< direction;
std::cout << "ITK orientation: "
<< itk::ConvertSpatialOrientationToString(adaptor.FromDirectionCosines(direction))
<< std::endl;
}
// -------------------------------------------------------------------------
// GetOrientation()
// -------------------------------------------------------------------------
itk::SpatialOrientation::ValidCoordinateOrientationFlags GetOrientation( ImageType::Pointer image )
{
ImageType::DirectionType direction;
itk::SpatialOrientationAdapter adaptor;
for (unsigned int i = 0; i < Dimension; i++)
{
for (unsigned int j = 0; j < Dimension; j++)
{
direction[i][j] = image->GetDirection()[i][j];
}
}
return adaptor.FromDirectionCosines(direction);
}
// -------------------------------------------------------------------------
// ReorientateImage()
// -------------------------------------------------------------------------
ImageType::Pointer ReorientateImage( ImageType::Pointer image,
itk::SpatialOrientation::ValidCoordinateOrientationFlags desiredOrientation )
{
std::cout << std::endl << "Input image:" << std::endl;
//image->Print( std::cout );
PrintOrientationInfo( image );
std::cout << "Desired orientation: " << itk::ConvertSpatialOrientationToString( desiredOrientation )
<< std::endl;
typedef itk::OrientImageFilter<ImageType,ImageType> OrientImageFilterType;
OrientImageFilterType::Pointer orienter = OrientImageFilterType::New();
orienter->UseImageDirectionOn();
orienter->SetDesiredCoordinateOrientation( desiredOrientation );
orienter->SetInput( image );
orienter->Update();
typedef OrientImageFilterType::FlipAxesArrayType FlipAxesArrayType;
typedef OrientImageFilterType::PermuteOrderArrayType PermuteOrderArrayType;
FlipAxesArrayType flipAxes = orienter->GetFlipAxes();
PermuteOrderArrayType permuteAxes = orienter->GetPermuteOrder();
std::cout << std::endl
<< "Permute Axes: " << permuteAxes << std::endl
<< "Flip Axes: " << flipAxes << std::endl;
ImageType::Pointer reorientatedImage = orienter->GetOutput();
//reorientatedImage->DisconnectPipeline();
std::cout << std::endl << "Output image:" << std::endl;
//reorientatedImage->Print( std::cout );
PrintOrientationInfo( reorientatedImage );
return reorientatedImage;
};
// -------------------------------------------------------------------------
// ReorientateImage()
// -------------------------------------------------------------------------
ImageType::Pointer ReorientateImage( ImageType::Pointer image, ImageType::Pointer reference )
{
itk::SpatialOrientation::ValidCoordinateOrientationFlags desiredOrientation;
std::cout << std::endl << "Reference image:" << std::endl;
//reference->Print( std::cout );
PrintOrientationInfo( reference );
desiredOrientation = GetOrientation( reference );
return ReorientateImage( image, desiredOrientation );
}
// -------------------------------------------------------------------------
// class InputParameters
// -------------------------------------------------------------------------
class InputParameters
{
public:
bool flgVerbose;
bool flgDebug;
bool flgCompression;
bool flgOverwrite;
bool flgFatIsBright;
std::string dirInput;
std::string dirOutput;
std::string fileLog;
std::string fileOutputCSV;
std::string fileMaskPattern;
std::string fileImagePattern;
std::string dirMask;
std::string dirImage;
std::string dirSubData;
std::string dirPrefix;
std::string progSegEM;
QStringList argsSegEM;
std::ofstream *foutLog;
std::ofstream *foutOutputCSV;
std::ostream *newCout;
typedef tee_device<std::ostream, std::ofstream> TeeDevice;
typedef stream<TeeDevice> TeeStream;
TeeDevice *teeDevice;
TeeStream *teeStream;
InputParameters( TCLAP::CmdLine &commandLine,
bool verbose,
bool compression,
bool debug,
bool overwrite,
bool fatIsBright,
std::string subDirMask,
std::string fileMask,
std::string subDirImage,
std::string fileImage,
std::string subDirData,
std::string prefix,
std::string dInput,
std::string logfile,
std::string csvfile,
std::string segEM,
QStringList aSegEM ) {
std::stringstream message;
flgVerbose = verbose;
flgDebug = debug;
flgCompression = compression;
flgOverwrite = overwrite;
flgFatIsBright = fatIsBright;
dirMask = subDirMask;
fileMaskPattern = fileMask;
dirImage = subDirImage;
fileImagePattern = fileImage;
dirSubData = subDirData;
dirPrefix = prefix;
dirInput = dInput;
fileLog = logfile;
fileOutputCSV = csvfile;
progSegEM = segEM;
argsSegEM = aSegEM;
if ( fileLog.length() > 0 )
{
foutLog = new std::ofstream( fileLog.c_str() );
if ((! *foutLog) || foutLog->bad()) {
message << "Could not open file: " << fileLog << std::endl;
PrintErrorAndExit( message );
}
newCout = new std::ostream( std::cout.rdbuf() );
teeDevice = new TeeDevice( *newCout, *foutLog);
teeStream = new TeeStream( *teeDevice );
std::cout.rdbuf( teeStream->rdbuf() );
std::cerr.rdbuf( teeStream->rdbuf() );
}
else
{
foutLog = 0;
newCout = 0;
teeDevice = 0;
teeStream = 0;
}
if ( fileOutputCSV.length() > 0 )
{
foutOutputCSV = new std::ofstream( fileOutputCSV.c_str() );
if ((! *foutOutputCSV) || foutOutputCSV->bad()) {
message << "Could not open file: " << fileOutputCSV << std::endl;
PrintErrorAndExit( message );
}
}
else
{
foutOutputCSV = 0;
}
if ( dirInput.length() == 0 )
{
commandLine.getOutput()->usage( commandLine );
message << "The input directory must be specified" << std::endl;
PrintErrorAndExit( message );
}
}
~InputParameters() {
#if 0
if ( teeStream )
{
teeStream->flush();
teeStream->close();
delete teeStream;
}
if ( teeDevice )
{
delete teeDevice;
}
if ( foutLog )
{
foutLog->close();
delete foutLog;
}
if ( foutOutputCSV )
{
foutOutputCSV->close();
delete foutOutputCSV;
}
if ( newCout )
{
delete newCout;
}
#endif
}
void Print(void) {
std::stringstream message;
message << std::endl
<< "Examining directory: " << dirInput << std::endl
<< std::endl
<< std::boolalpha
<< "Verbose output?: " << flgVerbose << std::endl
<< "Compress images?: " << flgCompression << std::endl
<< "Debugging output?: " << flgDebug << std::endl
<< "Overwrite previous results?: " << flgOverwrite << std::endl
<< "Fat is bright?: " << flgFatIsBright << std::endl
<< std::noboolalpha
<< std::endl
<< "Input mask sub-directory: " << dirMask << std::endl
<< "Input mask file name pattern: " << fileMaskPattern << std::endl
<< "Input image sub-directory: " << dirImage << std::endl
<< "Input image file name pattern: " << fileMaskPattern << std::endl
<< "Output data sub-directory: " << dirSubData << std::endl
<< "Study directory prefix: " << dirPrefix << std::endl
<< std::endl
<< "Output log file: " << fileLog << std::endl
<< "Output csv file: " << fileOutputCSV << std::endl
<< std::endl
<< "Segmentation executable: "
<< progSegEM << " " << argsSegEM.join(" ").toStdString() << std::endl
<< std::endl;
PrintMessage( message );
}
void PrintMessage( std::stringstream &message ) {
std::cout << message.str();
message.str( "" );
if ( teeStream )
{
teeStream->flush();
}
}
void PrintError( std::stringstream &message ) {
std::cerr << "ERROR: " << message.str();
message.str( "" );
if ( teeStream )
{
teeStream->flush();
}
}
void PrintErrorAndExit( std::stringstream &message ) {
PrintError( message );
exit( EXIT_FAILURE );
}
void PrintWarning( std::stringstream &message ) {
std::cerr << "WARNING: " << message.str();
message.str( "" );
if ( teeStream )
{
teeStream->flush();
}
}
bool ReadImageFromFile( std::string fileInput,
std::string description, ImageType::Pointer &image ) {
std::stringstream message;
if ( fileInput.find( ".nii" ) == std::string::npos )
{
return false;
}
if ( itk::ReadImageFromFile< ImageType >( fileInput, image ) )
{
message << std::endl << "Read " << description << " from file: " << fileInput << std::endl;
PrintMessage( message );
}
else if ( itk::ReadImageFromFile< ImageType >( fileInput + ".gz", image ) )
{
message << std::endl << "Read " << description << " from file: " << fileInput << std::endl;
PrintMessage( message );
}
else
{
return false;
}
itk::SpatialOrientation::ValidCoordinateOrientationFlags orientation;
orientation = GetOrientation( image );
if ( orientation != itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RAI )
{
image = ReorientateImage( image, itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RAI );
}
return true;
}
bool ReadImageFromFile( std::string dirInput, std::string filename,
std::string description, ImageType::Pointer &image ) {
std::string fileInput = niftk::ConcatenatePath( dirInput, filename );
return ReadImageFromFile( fileInput, description, image );
}
void WriteImageToFile( std::string filename,
std::string description, ImageType::Pointer image,
bool flgConcatenatePath=true ) {
std::stringstream message;
std::string fileOutput;
if ( flgConcatenatePath )
{
fileOutput = niftk::ConcatenatePath( dirOutput, filename );
}
else
{
fileOutput = filename;
}
message << std::endl << "Writing " << description << " to file: "
<< fileOutput << std::endl;
PrintMessage( message );
if ( itk::IsImageBinary< ImageType >( image ) )
{
typedef unsigned char OutputPixelType;
typedef itk::Image< OutputPixelType, ImageType::ImageDimension> OutputImageType;
typedef itk::RescaleIntensityImageFilter< ImageType, OutputImageType > CastFilterType;
CastFilterType::Pointer caster = CastFilterType::New();
caster->SetInput( image );
caster->SetOutputMinimum( 0 );
caster->SetOutputMaximum( 255 );
caster->Update();
OutputImageType::Pointer imOut = caster->GetOutput();
itk::WriteImageToFile< OutputImageType >( fileOutput, imOut );
}
else
{
itk::WriteImageToFile< ImageType >( fileOutput, image );
}
}
void DeleteFile( std::string filename ) {
std::stringstream message;
std::string filePath = niftk::ConcatenatePath( dirOutput, filename );
if ( ! niftk::FileIsRegular( filePath ) )
{
return;
}
if ( niftk::FileDelete( filePath ) )
{
message << std::endl << "Deleted file: " << filePath << std::endl;
PrintMessage( message );
}
else
{
message << std::endl << "Failed to delete file: " << filePath << std::endl;
PrintWarning( message );
}
}
};
// -------------------------------------------------------------------------
// SplitStringIntoCommandAndArguments()
// -------------------------------------------------------------------------
std::string SplitStringIntoCommandAndArguments( std::string inString,
QStringList &arguments )
{
std::string command;
std::stringstream ssString( inString );
std::istream_iterator< std::string > itStringStream( ssString );
std::istream_iterator< std::string > itEnd;
command = *itStringStream;
itStringStream++;
for (; itStringStream != itEnd; itStringStream++)
{
arguments << (*itStringStream).c_str();
}
return command;
};
// -------------------------------------------------------------------------
// ResampleImageToIsotropicVoxels()
// -------------------------------------------------------------------------
bool ResampleImageToIsotropicVoxels( ImageType::Pointer &image, InputParameters &args )
{
std::stringstream message;
double factor[Dimension];
ImageType::SpacingType spacing = image->GetSpacing();
// Calculate the minimum spacing
double minSpacing = std::numeric_limits<double>::max();
for (unsigned int j = 0; j < ImageType::ImageDimension; j++)
{
if ( spacing[j] < minSpacing )
{
minSpacing = spacing[j];
}
}
// Calculate the subsampling factors
bool flgSamplingRequired = false;
for (unsigned int j = 0; j < ImageType::ImageDimension; j++)
{
factor[j] = minSpacing/spacing[j];
if ( factor[j] < 0.8 )
{
flgSamplingRequired = true;
}
}
// Run the sampling filter
if ( itk::IsImageBinary< ImageType >(image) )
{
typedef itk::BinaryShapeBasedSuperSamplingFilter< ImageType, ImageType > SampleImageFilterType;
SampleImageFilterType::Pointer sampler = SampleImageFilterType::New();
sampler->SetIsotropicVoxels( true );
sampler->SetInput( image );
sampler->VerboseOn();
message << "Computing sampled binary image" << std::endl;
args.PrintMessage( message );
sampler->Update();
ImageType::Pointer sampledImage = sampler->GetOutput();
sampledImage->DisconnectPipeline();
image = sampledImage;
}
else
{
typedef itk::SampleImageFilter< ImageType, ImageType > SampleImageFilterType;
SampleImageFilterType::Pointer sampler = SampleImageFilterType::New();
sampler->SetIsotropicVoxels( true );
sampler->SetInterpolationType( itk::NEAREST );
sampler->SetInput( image );
sampler->VerboseOn();
message << "Computing sampled image" << std::endl;
args.PrintMessage( message );
sampler->Update();
ImageType::Pointer sampledImage = sampler->GetOutput();
sampledImage->DisconnectPipeline();
image = sampledImage;
}
return true;
};
// -------------------------------------------------------------------------
// NaiveParenchymaSegmentation()
// -------------------------------------------------------------------------
void NaiveParenchymaSegmentation( InputParameters &args,
ImageType::Pointer &imSegmentedBreastMask,
ImageType::Pointer &image,
bool flgFatIsBright,
float &nLeftVoxels,
float &nRightVoxels,
float &totalDensity,
float &leftDensity,
float &rightDensity,
std::string fileOutputParenchyma )
{
float minFraction = 0.02;
std::stringstream message;
ImageType::Pointer imParenchyma = 0;
typedef itk::ImageDuplicator< ImageType > DuplicatorType;
DuplicatorType::Pointer duplicator = DuplicatorType::New();
duplicator->SetInputImage( image );
duplicator->Update();
imParenchyma = duplicator->GetOutput();
imParenchyma->DisconnectPipeline();
imParenchyma->FillBuffer( 0. );
nLeftVoxels = 0;
nRightVoxels = 0;
totalDensity = 0.;
leftDensity = 0.;
rightDensity = 0.;
float meanOfHighProbIntensities = 0.;
float meanOfLowProbIntensities = 0.;
float nHighProbIntensities = 0.;
float nLowProbIntensities = 0.;
itk::ImageRegionIteratorWithIndex< ImageType >
itMask( imSegmentedBreastMask, imSegmentedBreastMask->GetLargestPossibleRegion() );
itk::ImageRegionIterator< ImageType >
itSegmentation( imParenchyma, imParenchyma->GetLargestPossibleRegion() );
itk::ImageRegionConstIterator< ImageType >
itImage( image, image->GetLargestPossibleRegion() );
// Compute the range of intensities inside the mask
float minIntensity = std::numeric_limits< float >::max();
float maxIntensity = -std::numeric_limits< float >::max();
for ( itMask.GoToBegin(), itImage.GoToBegin();
! itMask.IsAtEnd();
++itMask, ++itImage )
{
if ( itMask.Get() )
{
if ( itImage.Get() > maxIntensity )
{
maxIntensity = itImage.Get();
}
if ( itImage.Get() < minIntensity )
{
minIntensity = itImage.Get();
}
}
}
message << std::endl
<< "Range of " << " is from: "
<< minIntensity << " to: " << maxIntensity << std::endl;
args.PrintMessage( message );
// Compute 1st and 99th percentiles of the image from the image histogram
unsigned int nBins = static_cast<unsigned int>( maxIntensity - minIntensity + 0.5 ) + 1;
itk::Array< float > histogram( nBins );
histogram.Fill( 0 );
float nPixels = 0;
float flIntensity;
for ( itImage.GoToBegin(), itMask.GoToBegin();
! itImage.IsAtEnd();
++itImage, ++itMask )
{
if ( itMask.Get() )
{
flIntensity = itImage.Get() - minIntensity;
if ( flIntensity < 0. )
{
flIntensity = 0.;
}
if ( flIntensity > static_cast<float>( nBins - 1 ) )
{
flIntensity = static_cast<float>( nBins - 1 );
}
nPixels++;
histogram[ static_cast<unsigned int>( flIntensity ) ] += 1.;
}
}
float sumProbability = 0.;
unsigned int intensity;
float pLowerBound = 0.;
float pUpperBound = 0.;
bool flgLowerBoundFound = false;
bool flgUpperBoundFound = false;
for ( intensity=0; intensity<nBins; intensity++ )
{
histogram[ intensity ] /= nPixels;
sumProbability += histogram[ intensity ];
if ( ( ! flgLowerBoundFound ) && ( sumProbability >= minFraction ) )
{
pLowerBound = intensity;
flgLowerBoundFound = true;
}
if ( ( ! flgUpperBoundFound ) && ( sumProbability >= (1. - minFraction) ) )
{
pUpperBound = intensity;
flgUpperBoundFound = true;
}
if ( args.flgDebug )
{
std::cout << std::setw( 18 ) << intensity << " "
<< std::setw( 18 ) << histogram[ intensity ] << " "
<< std::setw( 18 ) << sumProbability << std::endl;
}
}
message << std::endl
<< "Density lower bound: " << pLowerBound
<< " ( " << minFraction*100. << "% )" << std::endl
<< " upper bound: " << pUpperBound
<< " ( " << (1. - minFraction)*100. << "% )" << std::endl;
args.PrintMessage( message );
// Compute the density
ImageType::SpacingType spacing = imParenchyma->GetSpacing();
float voxelVolume = spacing[0]*spacing[1]*spacing[2];
ImageType::RegionType region;
region = imSegmentedBreastMask->GetLargestPossibleRegion();
ImageType::SizeType lateralSize;
lateralSize = region.GetSize();
lateralSize[0] = lateralSize[0]/2;
ImageType::IndexType idx;
for ( itMask.GoToBegin(), itSegmentation.GoToBegin(), itImage.GoToBegin();
! itMask.IsAtEnd();
++itMask, ++itSegmentation, ++itImage )
{
if ( itMask.Get() )
{
idx = itMask.GetIndex();
flIntensity = ( itImage.Get() - pLowerBound )/( pUpperBound - pLowerBound );
if ( flIntensity < 0. )
{
itSegmentation.Set( 0. );
}
else if ( flIntensity > 1. )
{
itSegmentation.Set( 1. );
}
else
{
itSegmentation.Set( flIntensity );
}
//std::cout << idx << " " << itImage.Get() << " -> " << flIntensity << std::endl;
// Left breast
if ( idx[0] < (int) lateralSize[0] )
{
nLeftVoxels++;
leftDensity += flIntensity;
}
// Right breast
else
{
nRightVoxels++;
rightDensity += flIntensity;
}
// Both breasts
totalDensity += flIntensity;
// Ensure we have the polarity correct by calculating the
// mean intensities of each class
if ( flIntensity > 0.5 )
{
meanOfHighProbIntensities += itImage.Get();
nHighProbIntensities++;
}
else
{
meanOfLowProbIntensities += itImage.Get();
nLowProbIntensities++;
}
}
}
leftDensity /= nLeftVoxels;
rightDensity /= nRightVoxels;
totalDensity /= ( nLeftVoxels + nRightVoxels);
// Calculate the mean intensities of each class
if ( nHighProbIntensities > 0. )
{
meanOfHighProbIntensities /= nHighProbIntensities;
}
if ( nLowProbIntensities > 0. )
{
meanOfLowProbIntensities /= nLowProbIntensities;
}
message << std::endl
<< "Mean intensity of high probability class = " << meanOfHighProbIntensities
<< " ( " << nHighProbIntensities << " voxels )" << std::endl
<< "Mean intensity of low probability class = " << meanOfLowProbIntensities
<< " ( " << nLowProbIntensities << " voxels )" << std::endl;
args.PrintMessage( message );
// Fat should be high intensity in the T2 image so if the dense
// region (high prob) has a high intensity then it is probably fat
// and we need to invert the density, whereas the opposite is true
// for the fat-saturated T1w VIBE image.
if ( ( flgFatIsBright && ( meanOfHighProbIntensities > meanOfLowProbIntensities ) ) ||
( ( ! flgFatIsBright ) && ( meanOfHighProbIntensities < meanOfLowProbIntensities ) ) )
{
message << "Inverting the density estimation" << std::endl;
args.PrintWarning( message );
leftDensity = 1. - leftDensity;
rightDensity = 1. - rightDensity;
totalDensity = 1. - totalDensity;
typedef itk::InvertIntensityBetweenMaxAndMinImageFilter< ImageType > InvertFilterType;
InvertFilterType::Pointer invertFilter = InvertFilterType::New();
invertFilter->SetInput( imParenchyma );
typedef itk::MaskImageFilter< ImageType, ImageType > MaskFilterType;
MaskFilterType::Pointer maskFilter = MaskFilterType::New();
maskFilter->SetInput( invertFilter->GetOutput() );
maskFilter->SetMaskImage( imSegmentedBreastMask );
maskFilter->Update();
ImageType::Pointer imInverted = maskFilter->GetOutput();
imInverted->DisconnectPipeline();
imParenchyma = imInverted;
}
std::string fileOut = niftk::ModifyImageFileSuffix( fileOutputParenchyma,
std::string( "_Naive.nii" ) );
if ( args.flgCompression ) fileOut.append( ".gz" );
args.WriteImageToFile( fileOut,
std::string( "naive parenchyma image"), imParenchyma );
float leftBreastVolume = nLeftVoxels*voxelVolume;
float rightBreastVolume = nRightVoxels*voxelVolume;
message << "Naive - Number of left breast voxels: " << nLeftVoxels << std::endl
<< "Naive - Volume of left breast: " << leftBreastVolume << " mm^3" << std::endl
<< "Naive - Density of left breast (fraction of glandular tissue): " << leftDensity
<< std::endl << std::endl
<< "Naive - Number of right breast voxels: " << nRightVoxels << std::endl
<< "Naive - Volume of right breast: " << rightBreastVolume << " mm^3" << std::endl
<< "Naive - Density of right breast (fraction of glandular tissue): " << rightDensity
<< std::endl << std::endl
<< "Naive - Total number of breast voxels: "
<< nLeftVoxels + nRightVoxels << std::endl
<< "Naive - Total volume of both breasts: "
<< leftBreastVolume + rightBreastVolume << " mm^3" << std::endl
<< "Naive - Combined density of both breasts (fraction of glandular tissue): "
<< totalDensity << std::endl << std::endl;
args.PrintMessage( message );
};
// -------------------------------------------------------------------------
// main()
// -------------------------------------------------------------------------
int main( int argc, char *argv[] )
{
itk::NifTKImageIOFactory::Initialize();
bool flgVeryFirstRow = true;
float progress = 0.;
float iDirectory = 0.;
float nDirectories;
std::stringstream message;
fs::path pathExecutable( argv[0] );
fs::path dirExecutables = pathExecutable.parent_path();
// Validate command line args
// ~~~~~~~~~~~~~~~~~~~~~~~~~~
PARSE_ARGS;
// Extract any arguments from the input commands
QStringList argsSegEM;
std::string progSegEM = SplitStringIntoCommandAndArguments( comSegEM, argsSegEM );
InputParameters args( commandLine,
flgVerbose,
flgCompression,
flgDebug,
flgOverwrite,
flgFatIsBright,
dirMask,
fileMaskPattern,
dirImage,
fileImagePattern,
dirSubData,
dirPrefix,
dirInput,
fileLog,
fileOutputCSV,
progSegEM,
argsSegEM );
// Can we find the seg_EM executable or verify the path?
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if ( ! niftk::FileIsRegular( args.progSegEM ) )
{
std::string fileSearchSegEM = niftk::ConcatenatePath( dirExecutables.string(),
args.progSegEM );
if ( niftk::FileIsRegular( fileSearchSegEM ) )
{
args.progSegEM = fileSearchSegEM;
}
}
args.Print();
std::cout << std::endl << "<filter-progress>" << std::endl
<< 0. << std::endl
<< "</filter-progress>" << std::endl << std::endl;
// Get the list of files in the directory
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
std::string dirFullPath;
std::string dirBaseName;
std::string dirMaskFullPath;
std::string dirImageFullPath;
std::vector< std::string > directoryNames;
std::vector< std::string >::iterator iterDirectoryNames;
std::vector< std::string > fileMaskNames;
std::vector< std::string >::iterator iterFileMaskNames;
std::vector< std::string > fileImageNames;
std::vector< std::string >::iterator iterFileImageNames;
directoryNames = niftk::GetDirectoriesInDirectory( args.dirInput );
nDirectories = directoryNames.size();
for ( iterDirectoryNames = directoryNames.begin();
iterDirectoryNames < directoryNames.end();
++iterDirectoryNames, iDirectory += 1. )
{
dirFullPath = *iterDirectoryNames;
dirBaseName = niftk::Basename( dirFullPath );
if ( ! (dirBaseName.compare( 0, args.dirPrefix.length(), args.dirPrefix ) == 0) )
{
message << std::endl << "Skipping directory: " << dirFullPath << std::endl;
args.PrintMessage( message );
continue;
}
message << std::endl << "Directory: " << dirFullPath << std::endl;
args.PrintMessage( message );
// The mask directory
if ( args.dirMask.length() > 0 )
{
dirMaskFullPath = niftk::ConcatenatePath( dirFullPath, args.dirMask );
}
else
{
dirMaskFullPath = dirFullPath;
}
// The image directory
if ( args.dirImage.length() > 0 )
{
dirImageFullPath = niftk::ConcatenatePath( dirFullPath, args.dirImage );
}
else
{
dirImageFullPath = dirFullPath;
}
// The output directory
if ( dirSubData.length() > 0 )
{
args.dirOutput = niftk::ConcatenatePath( dirFullPath, args.dirSubData );
}
else
{
args.dirOutput = dirFullPath;
}
if ( ! niftk::DirectoryExists( args.dirOutput ) )
{
niftk::CreateDirAndParents( args.dirOutput );
message << "Creating output directory: " << args.dirOutput << std::endl;
args.PrintMessage( message );
}
// For each mask image
// ~~~~~~~~~~~~~~~~~~~
fileMaskNames = niftk::GetFilesInDirectory( dirMaskFullPath );
float iMask = 0.;
float nMasks = fileMaskNames.size();
for ( iterFileMaskNames = fileMaskNames.begin();
iterFileMaskNames < fileMaskNames.end();
++iterFileMaskNames, iMask += 1. )
{
std::string fileMaskFullPath = *iterFileMaskNames;
std::string fileMaskBasename = niftk::Basename( fileMaskFullPath );
if ( fileMaskBasename.find( args.fileMaskPattern ) == std::string::npos )
{
if ( args.flgDebug )
{
message << std::endl << "Skipping non-mask file: " << fileMaskBasename
<< std::endl;
args.PrintMessage( message );
}
continue;
}
// Read the mask image
ImageType::Pointer imMask = 0;
if ( ! args.ReadImageFromFile( fileMaskFullPath,
std::string( "mask image" ),
imMask ) )
{
if ( args.flgDebug )
{
message << std::endl << "Cannot read mask: " << fileMaskFullPath << std::endl << std::endl;
args.PrintMessage( message );
}
continue;
}
if ( ResampleImageToIsotropicVoxels( imMask, args ) )
{
fileMaskBasename = niftk::ModifyImageFileSuffix( fileMaskBasename,
std::string( "_Isotropic.nii" ) );
fileMaskFullPath = niftk::ConcatenatePath( args.dirOutput, fileMaskBasename );
if ( flgCompression )
{
fileMaskFullPath.append( ".gz" );
}
args.WriteImageToFile( fileMaskFullPath,
std::string( "isotropic mask image" ),
imMask, false );
}
// For each image
// ~~~~~~~~~~~~~~
fileImageNames = niftk::GetFilesInDirectory( dirImageFullPath );
float iImage = 0.;
float nImages = fileImageNames.size();
for ( iterFileImageNames = fileImageNames.begin();
iterFileImageNames < fileImageNames.end();
++iterFileImageNames, iImage += 1. )
{
std::string fileImageFullPath = *iterFileImageNames;
std::string fileImageBasename = niftk::Basename( fileImageFullPath );
if ( fileImageBasename.find( args.fileImagePattern ) == std::string::npos )
{
if ( args.flgDebug )
{
message << std::endl << "Skipping non-image file: " << fileImageBasename
<< std::endl;
args.PrintMessage( message );
}
continue;
}
// Read the image
ImageType::Pointer imInput = 0;
if ( ! args.ReadImageFromFile( fileImageFullPath,
std::string( "input image" ),
imInput ) )
{
if ( args.flgDebug )
{
message << std::endl << "Cannot read image: " << fileImageFullPath
<< std::endl;
args.PrintMessage( message );
}
continue;
}
if ( ResampleImageToIsotropicVoxels( imInput, args ) )
{
fileImageBasename = niftk::ModifyImageFileSuffix( fileImageBasename,
std::string( "_Isotropic.nii" ) );
fileImageFullPath = niftk::ConcatenatePath( args.dirOutput, fileImageBasename );
if ( flgCompression )
{
fileImageFullPath.append( ".gz" );
}
args.WriteImageToFile( fileImageFullPath,
std::string( "isotropic image" ),
imInput, false );
}
try
{
// If the CSV file has already been generated then read it
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
std::string fileDensityMeasurements = CreateFilename( fileImageBasename,
fileMaskBasename,
std::string( "WithMask" ),
std::string( ".csv" ) );
std::string fileInputDensityMeasurements
= niftk::ConcatenatePath( args.dirOutput, fileDensityMeasurements );
if ( ! args.flgOverwrite )
{
if ( niftk::FileIsRegular( fileInputDensityMeasurements ) )
{
std::ifstream fin( fileInputDensityMeasurements.c_str() );
if ((! fin) || fin.bad())
{
message << "ERROR: Could not open file: " << fileDensityMeasurements << std::endl;
args.PrintError( message );
continue;
}
message << std::endl << "Reading CSV file: " << fileInputDensityMeasurements << std::endl;
args.PrintMessage( message );
niftk::CSVRow csvRow;
bool flgFirstRowOfThisFile = true;
while( fin >> csvRow )
{
message << "" << csvRow << std::endl;
args.PrintMessage( message );
if ( flgFirstRowOfThisFile )
{
if ( flgVeryFirstRow ) // Include the title row?
{
*args.foutOutputCSV << csvRow << std::endl;
flgVeryFirstRow = false;
}
flgFirstRowOfThisFile = false;
}
else
{
*args.foutOutputCSV << csvRow << std::endl;
}
}
continue;
}
else
{
message << "Density measurements: " << fileInputDensityMeasurements
<< " not found" << std::endl;
args.PrintMessage( message );
}
}
progress = ( iDirectory + ( iMask + ( iImage + 0.3 )/nImages )/nMasks )/nDirectories;
std::cout << std::endl << "<filter-progress>" << std::endl
<< progress << std::endl
<< "</filter-progress>" << std::endl << std::endl;
// Segment the parenchyma
// ~~~~~~~~~~~~~~~~~~~~~~
ImageType::Pointer imParenchyma = 0;
std::string fileOutputParenchyma = CreateFilename( fileImageBasename,
fileMaskBasename,
std::string( "WithMask" ),
std::string( "_Parenchyma.nii" ) );
if ( args.flgOverwrite ||
( ! args.ReadImageFromFile( args.dirOutput,
fileOutputParenchyma,
"breast parenchyma", imParenchyma ) ) )
{
// QProcess call to seg_EM
QStringList argumentsNiftySeg = args.argsSegEM;
argumentsNiftySeg
<< "-in" << fileImageFullPath.c_str()
<< "-mask" << fileMaskFullPath.c_str()
<< "-out" << niftk::ConcatenatePath( args.dirOutput, fileOutputParenchyma ).c_str();
message << std::endl << "Executing parenchyma segmentation (QProcess): "
<< std::endl << " " << args.progSegEM;
for(int i=0;i<argumentsNiftySeg.size();i++)
{
message << " " << argumentsNiftySeg[i].toStdString();
}
message << std::endl << std::endl;
args.PrintMessage( message );
QProcess callSegEM;
QString outSegEM;
callSegEM.setProcessChannelMode( QProcess::MergedChannels );
callSegEM.start( args.progSegEM.c_str(), argumentsNiftySeg );
bool flgFinished = callSegEM.waitForFinished( 3600000 ); // Wait one hour
outSegEM = callSegEM.readAllStandardOutput();
message << "" << outSegEM.toStdString();
if ( ! flgFinished )
{
message << "ERROR: Could not execute: " << args.progSegEM << " ( "
<< callSegEM.errorString().toStdString() << " )" << std::endl;
args.PrintMessage( message );
continue;
}
args.PrintMessage( message );
callSegEM.close();
args.ReadImageFromFile( args.dirOutput,
fileOutputParenchyma,
"breast parenchyma", imParenchyma );
}
progress = ( iDirectory + ( iMask + ( iImage + 0.6 )/nImages )/nMasks )/nDirectories;
std::cout << std::endl << "<filter-progress>" << std::endl
<< progress << std::endl
<< "</filter-progress>" << std::endl << std::endl;
// Compute the breast density
// ~~~~~~~~~~~~~~~~~~~~~~~~~~
if ( imParenchyma && imMask )
{
float nLeftVoxels = 0;
float nRightVoxels = 0;
float totalDensity = 0.;
float leftDensity = 0.;
float rightDensity = 0.;
float meanOfHighProbIntensities = 0.;
float meanOfLowProbIntensities = 0.;
float nHighProbIntensities = 0.;
float nLowProbIntensities = 0.;
itk::ImageRegionIteratorWithIndex< ImageType >
maskIterator( imMask, imMask->GetLargestPossibleRegion() );
itk::ImageRegionConstIterator< ImageType >
segmIterator( imParenchyma, imParenchyma->GetLargestPossibleRegion() );
itk::ImageRegionConstIterator< ImageType >
imIterator( imInput, imInput->GetLargestPossibleRegion() );
ImageType::SpacingType spacing = imParenchyma->GetSpacing();
float voxelVolume = spacing[0]*spacing[1]*spacing[2];
ImageType::RegionType region;
region = imMask->GetLargestPossibleRegion();
ImageType::SizeType lateralSize;
lateralSize = region.GetSize();
lateralSize[0] = lateralSize[0]/2;
ImageType::IndexType idx;
for ( maskIterator.GoToBegin(), segmIterator.GoToBegin(), imIterator.GoToBegin();
! maskIterator.IsAtEnd();
++maskIterator, ++segmIterator, ++imIterator )
{
if ( maskIterator.Get() )
{
idx = maskIterator.GetIndex();
// Left breast
if ( idx[0] < (int) lateralSize[0] )
{
nLeftVoxels++;
leftDensity += segmIterator.Get();
}
// Right breast
else
{
nRightVoxels++;
rightDensity += segmIterator.Get();
}
// Both breasts
totalDensity += segmIterator.Get();
// Ensure we have the polarity correct by calculating the
// mean intensities of each class
if ( segmIterator.Get() > 0.5 )
{
meanOfHighProbIntensities += imIterator.Get();
nHighProbIntensities++;
}
else
{
meanOfLowProbIntensities += imIterator.Get();
nLowProbIntensities++;
}
}
}
leftDensity /= nLeftVoxels;
rightDensity /= nRightVoxels;
totalDensity /= ( nLeftVoxels + nRightVoxels);
// Calculate the mean intensities of each class
if ( nHighProbIntensities > 0. )
{
meanOfHighProbIntensities /= nHighProbIntensities;
}
if ( nLowProbIntensities > 0. )
{
meanOfLowProbIntensities /= nLowProbIntensities;
}
message << std::endl
<< "Mean intensity of high probability class = " << meanOfHighProbIntensities
<< " ( " << nHighProbIntensities << " voxels )" << std::endl
<< "Mean intensity of low probability class = " << meanOfLowProbIntensities
<< " ( " << nLowProbIntensities << " voxels )" << std::endl;
args.PrintMessage( message );
// Fat should be high intensity in the T2 image so if the
// dense region (high prob) has a high intensity then it is
// probably fat and we need to invert the density
if ( ( args.flgFatIsBright && ( meanOfHighProbIntensities > meanOfLowProbIntensities ) ) ||
( ( ! args.flgFatIsBright ) && ( meanOfHighProbIntensities < meanOfLowProbIntensities ) ) )
{
message << std::endl << "Inverting the density estimation" << std::endl;
args.PrintWarning( message );
leftDensity = 1. - leftDensity;
rightDensity = 1. - rightDensity;
totalDensity = 1. - totalDensity;
itk::ImageRegionIterator< ImageType >
imIterator( imParenchyma, imParenchyma->GetLargestPossibleRegion() );
itk::ImageRegionConstIterator< ImageType >
maskIterator( imMask, imMask->GetLargestPossibleRegion() );
for ( maskIterator.GoToBegin(), imIterator.GoToBegin();
! maskIterator.IsAtEnd();
++maskIterator, ++imIterator )
{
if ( maskIterator.Get() )
{
imIterator.Set( 1. - imIterator.Get() );
}
}
args.WriteImageToFile( fileOutputParenchyma,
std::string( "inverted parenchyma image" ),
imParenchyma );
}
float leftBreastVolume = nLeftVoxels*voxelVolume;
float rightBreastVolume = nRightVoxels*voxelVolume;
message << "Number of left breast voxels: " << nLeftVoxels << std::endl
<< "Volume of left breast: " << leftBreastVolume << " mm^3" << std::endl
<< "Density of left breast (fraction of glandular tissue): " << leftDensity
<< std::endl << std::endl
<< "Number of right breast voxels: " << nRightVoxels << std::endl
<< "Volume of right breast: " << rightBreastVolume << " mm^3" << std::endl
<< "Density of right breast (fraction of glandular tissue): " << rightDensity
<< std::endl << std::endl
<< "Total number of breast voxels: "
<< nLeftVoxels + nRightVoxels << std::endl
<< "Total volume of both breasts: "
<< leftBreastVolume + rightBreastVolume << " mm^3" << std::endl
<< "Combined density of both breasts (fraction of glandular tissue): "
<< totalDensity << std::endl << std::endl;
args.PrintMessage( message );
// Compute a naive value of the breast density
float nLeftVoxelsNaive;
float nRightVoxelsNaive;
float totalDensityNaive;
float leftDensityNaive;
float rightDensityNaive;
NaiveParenchymaSegmentation( args,
imMask, imInput,
flgFatIsBright,
nLeftVoxelsNaive, nRightVoxelsNaive,
totalDensityNaive, leftDensityNaive, rightDensityNaive,
fileOutputParenchyma );
if ( fileDensityMeasurements.length() != 0 )
{
std::string fileOutputDensityMeasurements
= niftk::ConcatenatePath( args.dirOutput, fileDensityMeasurements );
std::ofstream fout( fileOutputDensityMeasurements.c_str() );
fout.precision(16);
if ((! fout) || fout.bad())
{
message << "ERROR: Could not open file: " << fileDensityMeasurements << std::endl;
args.PrintError( message );
continue;
}
fout << "Study ID, "
<< "Image, "
<< "Mask, "
<< "Number of left breast voxels, "
<< "Volume of left breast (mm^3), "
<< "Density of left breast (fraction of glandular tissue), "
<< "Number of right breast voxels, "
<< "Volume of right breast (mm^3), "
<< "Density of right breast (fraction of glandular tissue), "
<< "Total number of breast voxels, "
<< "Total volume of both breasts (mm^3), "
<< "Combined density of both breasts (fraction of glandular tissue), "
<< "Naive density of left breast (fraction of glandular tissue), "
<< "Naive density of right breast (fraction of glandular tissue), "
<< "Naive combined density of both breasts (fraction of glandular tissue)"
<< std::endl;
fout << dirBaseName << ", "
<< fileImageBasename << ", "
<< fileMaskBasename << ", "
<< nLeftVoxels << ", "
<< leftBreastVolume << ", "
<< leftDensity << ", "
<< nRightVoxels << ", "
<< rightBreastVolume << ", "
<< rightDensity << ", "
<< nLeftVoxels + nRightVoxels << ", "
<< leftBreastVolume + rightBreastVolume << ", "
<< totalDensity << ", "
<< leftDensityNaive << ", "
<< rightDensityNaive << ", "
<< totalDensityNaive
<< std::endl;
fout.close();
message << "Density measurements written to file: "
<< fileOutputDensityMeasurements << std::endl << std::endl;
args.PrintMessage( message );
}
// Write the data to the main collated csv file
if ( args.foutOutputCSV )
{
if ( flgVeryFirstRow ) // Include the title row?
{
*args.foutOutputCSV << "Study ID, "
<< "Image, "
<< "Mask, "
<< "Number of left breast voxels, "
<< "Volume of left breast (mm^3), "
<< "Density of left breast (fraction of glandular tissue), "
<< "Number of right breast voxels, "
<< "Volume of right breast (mm^3), "
<< "Density of right breast (fraction of glandular tissue), "
<< "Total number of breast voxels, "
<< "Total volume of both breasts (mm^3), "
<< "Combined density of both breasts (fraction of glandular tissue), "
<< "Naive density of left breast (fraction of glandular tissue), "
<< "Naive density of right breast (fraction of glandular tissue), "
<< "Naive combined density of both breasts (fraction of glandular tissue)"
<< std::endl;
flgVeryFirstRow = false;
}
*args.foutOutputCSV << dirBaseName << ", "
<< fileImageBasename << ", "
<< fileMaskBasename << ", "
<< nLeftVoxels << ", "
<< leftBreastVolume << ", "
<< leftDensity << ", "
<< nRightVoxels << ", "
<< rightBreastVolume << ", "
<< rightDensity << ", "
<< nLeftVoxels + nRightVoxels << ", "
<< leftBreastVolume + rightBreastVolume << ", "
<< totalDensity << ", "
<< leftDensityNaive << ", "
<< rightDensityNaive << ", "
<< totalDensityNaive
<< std::endl;
}
else
{
message << "Collated csv data file: " << fileOutputCSV
<< " is not open, data will not be written." << std::endl;
args.PrintWarning( message );
}
}
progress = ( iDirectory + ( iMask + ( iImage + 0.9 )/nImages )/nMasks )/nDirectories;
std::cout << std::endl << "<filter-progress>" << std::endl
<< progress << std::endl
<< "</filter-progress>" << std::endl << std::endl;
}
catch (itk::ExceptionObject &ex)
{
message << ex << std::endl;
args.PrintError( message );
continue;
}
progress = ( iDirectory + ( iMask + iImage/nImages )/nMasks )/nDirectories;
std::cout << std::endl << "<filter-progress>" << std::endl
<< progress << std::endl
<< "</filter-progress>" << std::endl << std::endl;
}
}
}
progress = iDirectory/nDirectories;
std::cout << std::endl << "<filter-progress>" << std::endl
<< progress << std::endl
<< "</filter-progress>" << std::endl << std::endl;
return EXIT_SUCCESS;
}
| 30.820112 | 114 | 0.522876 | NifTK |
f5ac708371da614765a39b7cc53f0d62720b480d | 1,568 | cpp | C++ | Source/Zebaniya/Private/ClimbAnimInstance.cpp | StanimirMitev/Zebaniya | c9e381ceba124e6063e4c3d6292bfa1842d952a4 | [
"MIT"
] | null | null | null | Source/Zebaniya/Private/ClimbAnimInstance.cpp | StanimirMitev/Zebaniya | c9e381ceba124e6063e4c3d6292bfa1842d952a4 | [
"MIT"
] | 1 | 2020-02-01T21:44:57.000Z | 2020-02-01T21:44:57.000Z | Source/Zebaniya/Private/ClimbAnimInstance.cpp | StanimirMitev/Zebaniya | c9e381ceba124e6063e4c3d6292bfa1842d952a4 | [
"MIT"
] | 4 | 2020-01-11T16:20:03.000Z | 2020-01-25T18:59:07.000Z | // Fill out your copyright notice in the Description page of Project Settings.
#include "ClimbAnimInstance.h"
#include "ClimbingComponent.h"
bool UClimbAnimInstance::GetCanGrabLedge() const
{
return bCanGrabLedge;
}
void UClimbAnimInstance::SetIsClimbingUP(const bool bIsClimbing)
{
bIsClimbingUp = bIsClimbing;
}
bool UClimbAnimInstance::GetIsClimbingUP() const
{
return bIsClimbingUp;
}
void UClimbAnimInstance::SetCanGrabLedge(bool bCanGrab)
{
bCanGrabLedge = bCanGrab;
}
void UClimbAnimInstance::GrabLedge(const bool bCanLedgeGrap)
{
SetCanGrabLedge(bCanLedgeGrap);
}
void UClimbAnimInstance::ClimbUp_Implementation()
{
SetIsClimbingUP(true);
}
void UClimbAnimInstance::FinishClimbing()
{
UClimbingComponent* Climb = Cast<UClimbingComponent>(TryGetPawnOwner()->GetComponentByClass(UClimbingComponent::StaticClass()));
bIsClimbingUp = false;
bCanGrabLedge = false;
Climb->FinishClimbUP();
}
void UClimbAnimInstance::SetIsMovingLeft(const bool bIsLeft)
{
bIsMovingLeft = bIsLeft;
}
bool UClimbAnimInstance::GetIsMovingLeft() const
{
return bIsMovingLeft;
}
void UClimbAnimInstance::SetIsMovingRight(const bool bIsRight)
{
bIsMovingRight = bIsRight;
}
bool UClimbAnimInstance::GetIsMovingRight() const
{
return bIsMovingRight;
}
void UClimbAnimInstance::ClimbRight_Implementation()
{
SetIsMovingRight(true);
SetIsMovingLeft(false);
}
void UClimbAnimInstance::ClimbLeft_Implementation()
{
SetIsMovingLeft(true);
SetIsMovingRight(false);
}
void UClimbAnimInstance::FinishMoving()
{
SetIsMovingLeft(false);
SetIsMovingRight(false);
} | 19.358025 | 129 | 0.797194 | StanimirMitev |
f5ae1691367ae8239064edca9a7f843be153632d | 301 | hpp | C++ | textbook-example-mbed-queue-memoryPool/basicIOCmd.hpp | betaghIEEE/stm32-mbed-tutorials | fe4f4c37e8e58f4e1e5707231fd5de8759cfe02b | [
"Apache-2.0"
] | null | null | null | textbook-example-mbed-queue-memoryPool/basicIOCmd.hpp | betaghIEEE/stm32-mbed-tutorials | fe4f4c37e8e58f4e1e5707231fd5de8759cfe02b | [
"Apache-2.0"
] | null | null | null | textbook-example-mbed-queue-memoryPool/basicIOCmd.hpp | betaghIEEE/stm32-mbed-tutorials | fe4f4c37e8e58f4e1e5707231fd5de8759cfe02b | [
"Apache-2.0"
] | null | null | null |
#include "mbed.h"
extern void clrscr();
extern void homescr();
extern void gotoscr(int line, int column);
extern void printFloat ( float t);
extern void wait (float delay);
extern void wait_seconds (int seconds);
extern void wait_milliseconds (int ms);
extern void printVoltage(float t); | 13.086957 | 42 | 0.730897 | betaghIEEE |
f5b0e3f6890052a5805ed773a55cee5cd4c65869 | 5,232 | hpp | C++ | extrema.hpp | tailsu/Boost.Extrema | ab76cbb303072c9fb62902794ac544033c2d08cf | [
"BSL-1.0"
] | null | null | null | extrema.hpp | tailsu/Boost.Extrema | ab76cbb303072c9fb62902794ac544033c2d08cf | [
"BSL-1.0"
] | null | null | null | extrema.hpp | tailsu/Boost.Extrema | ab76cbb303072c9fb62902794ac544033c2d08cf | [
"BSL-1.0"
] | null | null | null | #pragma once
#ifndef BOOST_EXTREMA_MAX_ARITY
# define BOOST_EXTREMA_MAX_ARITY 10
#endif
#ifdef BOOST_EXTREMA_INTEGRATE_WITH_STD
# if defined(BOOST_EXTREMA_MIN_NAME) || defined(BOOST_EXTREMA_MAX_NAME) || defined(BOOST_EXTREMA_NAMESPACE)
# error When integrating with the std namespace, don't define a custom namespace or custom names for the min and max functions.
# endif
# define BOOST_EXTREMA_MAX_NAME max
# define BOOST_EXTREMA_MIN_NAME min
# define BOOST_EXTREMA_NAMESPACE std
#else
# ifndef BOOST_EXTREMA_MIN_NAME
# define BOOST_EXTREMA_MIN_NAME minimum
# endif
# ifndef BOOST_EXTREMA_MAX_NAME
# define BOOST_EXTREMA_MAX_NAME maximum
# endif
# ifndef BOOST_EXTREMA_NAMESPACE
# define BOOST_EXTREMA_NAMESPACE boost
# endif
#endif
#include <boost/preprocessor/arithmetic/inc.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/identity.hpp>
#include <boost/preprocessor/punctuation/paren.hpp>
#include <boost/preprocessor/repetition/enum_binary_params.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/preprocessor/repetition/repeat_from_to.hpp>
#include <boost/preprocessor/seq/elem.hpp>
#include <boost/mpl/and.hpp>
#include <boost/mpl/if.hpp>
#include <boost/type_traits/is_arithmetic.hpp>
#include <boost/type_traits/integral_constant.hpp>
#include <boost/type_traits/is_void.hpp>
#include "comparison_type.hpp"
#ifdef BOOST_EXTREMA_INTEGRATE_WITH_STD
# include <boost/mpl/not.hpp>
# include <boost/type_traits/is_same.hpp>
# include <boost/utility/enable_if.hpp>
#endif
namespace BOOST_EXTREMA_NAMESPACE {
#ifdef BOOST_EXTREMA_INTEGRATE_WITH_STD
# define BOOST_EXTREMA_RETURN_TYPE_OF_BINARY_OVERLOAD(function_name) \
typename boost::lazy_enable_if<boost::mpl::not_<boost::is_same<A, B>> \
, boost::BOOST_PP_CAT(function_name, _return_type)<A, B>>::type
#else
# define BOOST_EXTREMA_RETURN_TYPE_OF_BINARY_OVERLOAD(function_name) \
typename boost::BOOST_PP_CAT(function_name, _return_type)<A, B>::type
#endif
#define BOOST_EXTREMA_BASE_FUNCTION_IMPL(function_name, op, semantic, cast_type, caster) \
template <typename A, typename B> \
BOOST_EXTREMA_RETURN_TYPE_OF_BINARY_OVERLOAD(semantic) \
BOOST_PP_CAT(function_name, _impl)(const A& a, const B& b, boost::cast_type /*dont_cast_comparends*/) \
{ \
typedef typename boost::comparison_type<A, B>::type C; \
typedef BOOST_EXTREMA_RETURN_TYPE_OF_BINARY_OVERLOAD(semantic) R; \
if (caster(a) op caster(b)) \
return (R)a; \
else return (R)b; \
}
#define BOOST_EXTREMA_CASTER(x) C(x)
#define BOOST_EXTREMA_BASE_FUNCTION(function_name, op, semantic) \
BOOST_EXTREMA_BASE_FUNCTION_IMPL(function_name, op, semantic, false_type, C) \
BOOST_EXTREMA_BASE_FUNCTION_IMPL(function_name, op, semantic, true_type, ) \
template <typename A, typename B> \
BOOST_EXTREMA_RETURN_TYPE_OF_BINARY_OVERLOAD(semantic) \
function_name(const A& a, const B& b) \
{ \
typedef typename boost::comparison_type<A, B>::type C; \
return BOOST_PP_CAT(function_name, _impl)(a, b, boost::is_void<C>()); \
}
BOOST_EXTREMA_BASE_FUNCTION(BOOST_EXTREMA_MIN_NAME, <, min)
BOOST_EXTREMA_BASE_FUNCTION(BOOST_EXTREMA_MAX_NAME, >, max)
#ifndef BOOST_EXTREMA_NO_OVERLOADS_OF_GREATER_ARITY
#define BOOST_EXTREMA_FUNCTION_CALL_PREFIX(z, n, data) data(BOOST_PP_CAT(t, n),
#define BOOST_EXTREMA_FUNCTION_CALL_SUFFIX(z, n, data) BOOST_PP_RPAREN()
#define BOOST_EXTREMA_COMPOUND_RESULT_PREFIX(z, n, data) typename boost::BOOST_PP_CAT(data, _return_type)<BOOST_PP_CAT(T, n),
#define BOOST_EXTREMA_COMPOUND_RESULT_SUFFIX(z, n, data) >::type
#define BOOST_EXTREMA_PREFIX_AND_SUFFIX(n, data, prefix, middle, suffix) \
BOOST_PP_REPEAT(n, prefix, data) \
middle \
BOOST_PP_REPEAT(n, suffix, data)
#define BOOST_EXTREMA_FUNCTION_TEMPLATE(z, n, data) \
template <BOOST_PP_ENUM_PARAMS(BOOST_PP_INC(n), typename T)> \
BOOST_EXTREMA_PREFIX_AND_SUFFIX(n, BOOST_PP_SEQ_ELEM(1, data), BOOST_EXTREMA_COMPOUND_RESULT_PREFIX, BOOST_PP_CAT(T, n), BOOST_EXTREMA_COMPOUND_RESULT_SUFFIX) \
BOOST_PP_SEQ_ELEM(0, data)(BOOST_PP_ENUM_BINARY_PARAMS(BOOST_PP_INC(n), T, t)) \
{ \
return BOOST_EXTREMA_PREFIX_AND_SUFFIX(n, BOOST_PP_SEQ_ELEM(0, data), BOOST_EXTREMA_FUNCTION_CALL_PREFIX, BOOST_PP_CAT(t, n), BOOST_EXTREMA_FUNCTION_CALL_SUFFIX); \
}
#define BOOST_EXTREMA_FUNCTION_TEMPLATE_DEC_N(z, n, data) BOOST_EXTREMA_FUNCTION_TEMPLATE(z, BOOST_PP_DEC(n), data)
BOOST_PP_REPEAT_FROM_TO(3, BOOST_PP_INC(BOOST_EXTREMA_MAX_ARITY), BOOST_EXTREMA_FUNCTION_TEMPLATE_DEC_N, (BOOST_EXTREMA_MIN_NAME)(min))
BOOST_PP_REPEAT_FROM_TO(3, BOOST_PP_INC(BOOST_EXTREMA_MAX_ARITY), BOOST_EXTREMA_FUNCTION_TEMPLATE_DEC_N, (BOOST_EXTREMA_MAX_NAME)(max))
#undef BOOST_EXTREMA_RETURN_TYPE_OF_BINARY_OVERLOAD
#undef BOOST_EXTREMA_BASE_FUNCTION_IMPL
#undef BOOST_EXTREMA_BASE_FUNCTION
#undef BOOST_EXTREMA_FUNCTION_CALL_PREFIX
#undef BOOST_EXTREMA_FUNCTION_CALL_SUFFIX
#undef BOOST_EXTREMA_TYPE_PROMOTION_PREFIX
#undef BOOST_EXTREMA_TYPE_PROMOTION_SUFFIX
#undef BOOST_EXTREMA_PREFIX_AND_SUFFIX
#undef BOOST_EXTREMA_FUNCTION_TEMPLATE
#undef BOOST_EXTREMA_FUNCTION_TEMPLATE_DEC_N
#endif
}
| 40.55814 | 166 | 0.797783 | tailsu |
f5b85a1181c18a14b3ea81aab0a8e394427965a7 | 1,152 | cpp | C++ | ZhenTiBan/test.cpp | drt4243566/leetcode_learn | ef51f215079556895eec2252d84965cd1c3a7bf4 | [
"MIT"
] | null | null | null | ZhenTiBan/test.cpp | drt4243566/leetcode_learn | ef51f215079556895eec2252d84965cd1c3a7bf4 | [
"MIT"
] | null | null | null | ZhenTiBan/test.cpp | drt4243566/leetcode_learn | ef51f215079556895eec2252d84965cd1c3a7bf4 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
int judge(vector<int>& A,vector<int>& B){
int res=0;
int sumA1=0,sumA2=0,sumB1=0,sumB2=0;
for(int i=0;i<3;i++){
sumA1 += A[i];
}
for(int i=3;i<6;i++){
sumA2 += A[i];
}
for(int i=0;i<3;i++){
sumB1 += B[i];
}
for(int i=3;i<6;i++){
sumB2 += B[i];
}
for(int i=0;i<3;i++){
for(int j=3;j<6;j++){
for(int k=0;k<3;k++){
for(int m=3;m<6;m++){
int count=0;
if((sumA1-A[i])<(sumB1-B[k])) count++;
if((sumA2-A[j])<(sumB2-B[m])) count++;
if((A[i]+A[j])<(B[k]+B[m])) count++;
if(count>=2) res++;
}
}
}
}
return res;
}
int main(){
int T=0;
cin >> T;
int ans=0;
while(T--){
vector<int> A(6,0);
vector<int> B(6,0);
for(int i=0;i<6;i++){
cin >> A[i];
}
for(int i=0;i<6;i++){
cin >> B[i];
}
ans = judge(A,B);
cout << ans <<endl;
}
return 0;
} | 21.735849 | 58 | 0.366319 | drt4243566 |
f5b9229de258cfd4557c16616773363a422d34fc | 2,608 | hpp | C++ | src/Token/Token.hpp | RainingComputers/ShnooTalk | 714f6648363a99e011e329ed1a3f800e6fe65f39 | [
"MIT"
] | 6 | 2021-07-17T16:02:07.000Z | 2022-02-05T16:33:51.000Z | src/Token/Token.hpp | RainingComputers/ShnooTalk | 714f6648363a99e011e329ed1a3f800e6fe65f39 | [
"MIT"
] | 1 | 2021-07-16T07:14:31.000Z | 2021-07-16T07:22:10.000Z | src/Token/Token.hpp | RainingComputers/ShnooTalk | 714f6648363a99e011e329ed1a3f800e6fe65f39 | [
"MIT"
] | 2 | 2021-07-16T02:54:27.000Z | 2022-03-29T20:51:57.000Z | #ifndef TOKEN_TOKEN
#define TOKEN_TOKEN
#include <string>
namespace token
{
enum TokenType
{
NONE,
SPACE,
FUNCTION,
EXTERN_FUNCTION,
IDENTIFIER,
LPAREN,
RPAREN,
STRUCT,
ENUM,
DEF,
BEGIN,
END,
COLON,
DOUBLE_COLON,
COMMA,
DOT,
VAR,
CONST,
STR_LITERAL,
CHAR_LITERAL,
INT_LITERAL,
HEX_LITERAL,
BIN_LITERAL,
FLOAT_LITERAL,
IF,
ELSEIF,
ELSE,
WHILE,
DO,
FOR,
LOOP,
BREAK,
CONTINUE,
RETURN,
VOID,
EQUAL,
PLUS_EQUAL,
MINUS_EQUAL,
DIVIDE_EQUAL,
MULTIPLY_EQUAL,
OR_EQUAL,
AND_EQUAL,
XOR_EQUAL,
NOT,
CONDN_NOT,
CAST,
PTR_CAST,
ARRAY_PTR_CAST,
OPEN_SQUARE,
CLOSE_SQUARE,
OPEN_BRACE,
CLOSE_BRACE,
EMPTY_SUBSCRIPT,
RIGHT_ARROW,
LEFT_ARROW,
PLUS,
MINUS,
BITWISE_OR,
BITWISE_XOR,
RIGHT_SHIFT,
LEFT_SHIFT,
CONDN_OR,
GREATER_THAN,
LESS_THAN,
GREATER_THAN_EQUAL,
LESS_THAN_EQUAL,
CONDN_EQUAL,
CONDN_NOT_EQUAL,
MULTIPLY,
DIVIDE,
MOD,
BITWISE_AND,
CONDN_AND,
USE,
AS,
FROM,
MUTABLE,
SEMICOLON,
END_OF_LINE,
END_OF_FILE,
INVALID,
SIZEOF,
TYPEOF,
PRINT,
PRINTLN,
INPUT
};
}
class Token
{
std::string string;
std::string unescapedString;
token::TokenType type;
unsigned int column;
unsigned int line;
std::string file;
void initializeUnescapedString();
public:
int getPrecedence() const;
bool isBitwiseOperator() const;
bool isConditionalOperator() const;
bool isIntLiteral() const;
bool isEqualOrLeftArrow() const;
long toInt() const;
double toFloat() const;
std::string toString() const;
std::string toFunctionNameString() const;
std::string toUnescapedString() const;
token::TokenType getType() const;
std::string getLineColString() const;
int getLineNo() const;
int getColumn() const;
std::string getFileName() const;
Token(std::string fileName = "",
std::string tokenString = "",
token::TokenType tokenType = token::NONE,
unsigned int column = 0,
unsigned int linenumber = 0);
};
#endif | 19.036496 | 51 | 0.529141 | RainingComputers |
f5b9ce1254d9810af3e9fdcb616dfede69325e70 | 1,506 | cc | C++ | graph/bellman-ford.cc | deyuan/coding-practice | 82bdf719397507601e582ab6d5693e4e50e96a3a | [
"MIT"
] | null | null | null | graph/bellman-ford.cc | deyuan/coding-practice | 82bdf719397507601e582ab6d5693e4e50e96a3a | [
"MIT"
] | null | null | null | graph/bellman-ford.cc | deyuan/coding-practice | 82bdf719397507601e582ab6d5693e4e50e96a3a | [
"MIT"
] | null | null | null | // Bellman-Ford: Single source negative weight shortest path
// Copyright (c) 2021 Deyuan Guo <guodeyuan@gmail.com>. All rights reserved.
#include <iostream>
#include <vector>
#include <queue>
#include "graph_util.h"
void BellmanFord(int n,
const std::vector<std::vector<int>> &adj,
const std::vector<std::vector<int>> &cost,
int start,
std::vector<int> &dist,
std::vector<int> &prev) {
prev.clear();
prev.resize(n);
dist.clear();
dist.resize(n, INT_MAX);
dist[start] = 0;
for (int i = 0; i < n - 1; i++) {
bool updated = false;
for (int v = 0; v < n; v++) {
if (dist[v] == INT_MAX) {
continue;
}
for (int j = 0; j < adj[v].size(); j++) {
int u = adj[v][j];
int c = cost[v][j];
if (dist[u] > dist[v] + c) {
dist[u] = dist[v] + c;
prev[u] = v;
updated = true;
}
}
}
if (!updated) {
break;
}
}
}
int main() {
// read in graph
int n = 0;
std::vector<std::vector<int>> edges;
ReadWeightedEdgeListFromStdIn(n, edges);
std::vector<std::vector<int>> adj(n);
std::vector<std::vector<int>> cost(n);
DirectedEdgeListToAdjAndCostList(edges, adj, cost);
// test Bellman Ford
std::vector<int> dist;
std::vector<int> prev;
BellmanFord(n, adj, cost, 0, dist, prev);
std::cout << "Bellman-Ford shortest path from 0" << std::endl;
for (int i = 0; i < n; i++) {
std::cout << "0 -> " << i << ": dist = " << dist[i] << std::endl;
}
}
| 24.290323 | 76 | 0.547145 | deyuan |
f5bec97352b2d4f6290577626225cae06dbd6ebf | 7,159 | tcc | C++ | cxxblas/auxiliary/cuda.tcc | ccecka/FLENS | b6cd7e630d490fde5432c6e9fc357089861bdffd | [
"BSD-3-Clause"
] | 3 | 2015-04-10T18:09:12.000Z | 2018-03-27T23:43:32.000Z | cxxblas/auxiliary/cuda.tcc | ccecka/FLENS | b6cd7e630d490fde5432c6e9fc357089861bdffd | [
"BSD-3-Clause"
] | null | null | null | cxxblas/auxiliary/cuda.tcc | ccecka/FLENS | b6cd7e630d490fde5432c6e9fc357089861bdffd | [
"BSD-3-Clause"
] | 4 | 2015-09-06T20:24:35.000Z | 2021-07-31T07:50:55.000Z | #ifndef CXXBLAS_AUXILIARY_CUDA_TCC
#define CXXBLAS_AUXILIARY_CUDA_TCC 1
#if defined(HAVE_CUBLAS) || defined(HAVE_CUSOLVER)
// XXX
#include <utility>
#include <sstream>
#include <iomanip>
namespace cxxblas {
void
CudaEnv::release()
{
// destroy streams_
for (auto& s : streams_)
checkStatus(cudaStreamDestroy(s));
streams_.clear();
// destroy events_
for (auto& e : events_)
checkStatus(cudaEventDestroy(e));
events_.clear();
}
void
CudaEnv::destroyStream(int streamID)
{
if (streamID < int(streams_.size())) {
checkStatus(cudaStreamDestroy(streams_[streamID]));
streams_[streamID] = cudaStream_t(); // XXX: Needed?
}
}
cudaStream_t &
CudaEnv::getStream(int streamID)
{
// Expand the stream map
while (streamID >= int(streams_.size()))
streams_.push_back(cudaStream_t());
// Create new stream if not inited
if (streams_[streamID] == cudaStream_t())
checkStatus(cudaStreamCreate(&streams_[streamID]));
return streams_[streamID];
}
void
CudaEnv::syncStream(int streamID)
{
checkStatus(cudaStreamSynchronize(streams_[streamID]));
}
void
CudaEnv::eventRecord(int eventID, int streamID)
{
// Expand the event map
while (eventID >= int(events_.size()))
events_.push_back(cudaEvent_t());
// Create new event if not inited
if (events_.at(eventID) == cudaEvent_t())
checkStatus(cudaEventCreate(&events_.at(eventID)));
// Create Event
checkStatus(cudaEventRecord(events_[eventID], getStream(streamID)));
}
void
CudaEnv::eventSynchronize(int eventID)
{
checkStatus(cudaEventSynchronize(events_[eventID]));
}
std::string
CudaEnv::getInfo()
{
std::stringstream sstream;
// Number of CUDA devices
int devCount;
cudaGetDeviceCount(&devCount);
// Iterate through devices
for (int i = 0; i < devCount; ++i)
{
// Get device properties
cudaDeviceProp devProp;
cudaGetDeviceProperties(&devProp, i);
sstream << "CUDA Device " << devProp.name << std::endl;
sstream << "==============================================" << std::endl;
sstream << "Major revision number: " << std::setw(15) << devProp.major << std::endl;
sstream << "Minor revision number: " << std::setw(15) << devProp.minor << std::endl;
sstream << "Number of multiprocessors: " << std::setw(15) << devProp.multiProcessorCount << std::endl;
sstream << "Clock rate: " << std::setw(11) << devProp.clockRate / (1024.f*1024.f) << " GHz" << std::endl;
sstream << "Total global memory: " << std::setw(9) << devProp.totalGlobalMem / (1024*1024) << " MByte" << std::endl;
sstream << "Total constant memory: " << std::setw(9) << devProp.totalConstMem / (1024) << " KByte"<< std::endl;
sstream << "Maximum memory: " << std::setw(9) << devProp.memPitch / (1024*1024) << " MByte"<< std::endl;
sstream << "Total shared memory per block: " << std::setw(9) << devProp.sharedMemPerBlock / (1024) << " KByte" << std::endl;
sstream << "Total registers per block: " << std::setw(15) << devProp.regsPerBlock << std::endl;
sstream << "Warp size: " << std::setw(15) << devProp.warpSize << std::endl;
sstream << "Maximum threads per block: " << std::setw(15) << devProp.maxThreadsPerBlock << std::endl;
for (int j = 0; j < 3; ++j) {
sstream << "Maximum dimension of block " << j << ": " << std::setw(15) << devProp.maxThreadsDim[j] << std::endl;
}
for (int j = 0; j < 3; ++j) {
sstream << "Maximum dimension of grid " << j << ": " << std::setw(15) << devProp.maxGridSize[j] << std::endl;
}
sstream << "Texture alignment: " << std::setw(15) << devProp.textureAlignment << std::endl;
sstream << "Concurrent copy and execution: " << std::setw(15) << std::boolalpha << (devProp.deviceOverlap>0) << std::endl;
sstream << "Concurrent kernel execution: " << std::setw(15) << std::boolalpha << (devProp.concurrentKernels>0) << std::endl;
sstream << "Kernel execution timeout: " << std::setw(15) << std::boolalpha << (devProp.kernelExecTimeoutEnabled>0) << std::endl;
sstream << "ECC support enabled: " << std::setw(15) << std::boolalpha << (devProp.ECCEnabled>0) << std::endl;
}
return sstream.str();
}
void
checkStatus(cudaError_t status)
{
if(status==cudaSuccess)
return;
std::cerr << cudaGetErrorString(status) << std::endl;
}
void
destroyStream(int streamID)
{
CudaEnv::destroyStream(streamID);
}
template <typename... Args>
void
destroyStream(int streamID, Args... args)
{
destroyStream(streamID);
destroyStream(args...);
}
void
syncStream(int streamID)
{
CudaEnv::syncStream(streamID);
}
template <typename... Args>
void
syncStream(int streamID, Args... args)
{
syncStream(streamID);
syncStream(args...);
}
#ifdef HAVE_CUBLAS
void
checkStatus(cublasStatus_t status)
{
if (status==CUBLAS_STATUS_SUCCESS) {
return;
}
if (status==CUBLAS_STATUS_NOT_INITIALIZED) {
std::cerr << "CUBLAS: Library was not initialized!" << std::endl;
} else if (status==CUBLAS_STATUS_INVALID_VALUE) {
std::cerr << "CUBLAS: Parameter had illegal value!" << std::endl;
} else if (status==CUBLAS_STATUS_MAPPING_ERROR) {
std::cerr << "CUBLAS: Error accessing GPU memory!" << std::endl;
} else if (status==CUBLAS_STATUS_ALLOC_FAILED) {
std::cerr << "CUBLAS: allocation failed!" << std::endl;
} else if (status==CUBLAS_STATUS_ARCH_MISMATCH) {
std::cerr << "CUBLAS: Device does not support double precision!" << std::endl;
} else if (status==CUBLAS_STATUS_EXECUTION_FAILED) {
std::cerr << "CUBLAS: Failed to launch function on the GPU" << std::endl;
} else if (status==CUBLAS_STATUS_INTERNAL_ERROR) {
std::cerr << "CUBLAS: An internal operation failed" << std::endl;
} else {
std::cerr << "CUBLAS: Unkown error" << std::endl;
}
ASSERT(status==CUBLAS_STATUS_SUCCESS); // false
}
void
CublasEnv::init()
{
checkStatus(cublasCreate(&handle_));
}
void
CublasEnv::release()
{
checkStatus(cublasDestroy(handle_));
CudaEnv::release(); // XXX race
}
cublasHandle_t &
CublasEnv::handle()
{
// TODO: Safety checks? Error msgs?
return handle_;
}
cudaStream_t
CublasEnv::stream()
{
cudaStream_t s;
cublasGetStream(handle_, &s);
return s;
}
int
CublasEnv::streamID()
{
return streamID_;
}
void
CublasEnv::setStream(int streamID)
{
streamID_ = streamID;
checkStatus(cublasSetStream(handle_, CudaEnv::getStream(streamID_)));
}
void
CublasEnv::enableSyncCopy()
{
syncCopyEnabled_ = true;
}
void
CublasEnv::disableSyncCopy()
{
syncCopyEnabled_ = false;
}
bool
CublasEnv::isSyncCopyEnabled()
{
return syncCopyEnabled_;
}
void
CublasEnv::syncCopy()
{
if (syncCopyEnabled_ && streamID_ >= 0)
CudaEnv::syncStream(streamID_);
}
#endif // HAVE_CUBLAS
} // end namespace flens
#endif // WITH_CUDA
#endif
| 27.748062 | 141 | 0.624529 | ccecka |
f5c173023c50360153f092964e435317cfd0f114 | 8,387 | cpp | C++ | Server Lib/Projeto IOCP/Client/client.cpp | eantoniobr/SuperSS-Dev | f57c094f164cc90c2694df33ba394304cd0e7846 | [
"MIT"
] | null | null | null | Server Lib/Projeto IOCP/Client/client.cpp | eantoniobr/SuperSS-Dev | f57c094f164cc90c2694df33ba394304cd0e7846 | [
"MIT"
] | null | null | null | Server Lib/Projeto IOCP/Client/client.cpp | eantoniobr/SuperSS-Dev | f57c094f164cc90c2694df33ba394304cd0e7846 | [
"MIT"
] | 1 | 2021-11-03T00:21:07.000Z | 2021-11-03T00:21:07.000Z | // Arquivo client.cpp
// Criado em 19/12/2017 por Acrisio
// Implementação da classe client
// Tem que ter o pack aqui se não da erro na hora da allocação do HEAP
#if defined(_WIN32)
#pragma pack(1)
#endif
#include <WinSock2.h>
#include "client.h"
#include "../SOCKET/socket.h"
#include "../UTIL/exception.h"
#include "../UTIL/message_pool.h"
#include "../UTIL/hex_util.h"
#include "../TIMER/timer.h"
#include "../PACKET/packet_func.h"
#include <DbgHelp.h>
#define CHECK_SESSION_BEGIN(method) if (!_session.getState()) \
throw exception("[client::" + std::string((method)) +"][Error] player nao esta connectado.", STDA_MAKE_ERROR(STDA_ERROR_TYPE::CLIENT, 1, 0)); \
using namespace stdA;
client::client(session_manager& _session_manager) : m_session_manager(_session_manager), threadpl_client(16, 16), m_state(UNINITIALIZED) {
size_t i = 0;
try {
InterlockedExchange(&m_continue_monitor, 1);
InterlockedExchange(&m_continue_send_msg, 1);
// Send Message to Lobby
//m_threads.push_back(new thread(TT_SEND_MSG_TO_LOBBY, client::_send_msg_lobby, this));
// Monitor Thread
m_thread_monitor = new thread(TT_MONITOR, client::_monitor, (LPVOID)this, THREAD_PRIORITY_NORMAL);
m_state = INITIALIZED;
}catch (exception& e) {
_smp::message_pool::getInstance().push(new message("[client::client][Error] client inicializado com error: " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
m_state = FAILURE;
}
};
client::~client() {
if (m_thread_monitor != nullptr)
delete m_thread_monitor;
m_state = UNINITIALIZED;
};
DWORD client::_monitor(LPVOID lpParameter) {
BEGIN_THREAD_SETUP(client)
pTP->monitor();
END_THREAD_SETUP("_monitor()");
};
DWORD client::_send_msg_lobby(LPVOID lpParameter) {
BEGIN_THREAD_SETUP(client)
pTP->send_msg_lobby();
END_THREAD_SETUP("_send_msg_lobby()");
};
DWORD client::monitor() {
try {
_smp::message_pool::getInstance().push(new message("monitor iniciado com sucesso!"));
while (InterlockedCompareExchange(&m_continue_monitor, 1, 1)) {
try {
if (m_thread_console != nullptr && !m_thread_console->isLive())
m_thread_console->init_thread();
for (size_t i = 0; i < m_threads.size(); i++)
if (m_threads[i] != nullptr && !m_threads[i]->isLive())
m_threads[i]->init_thread();
checkClienteOnline();
Sleep(1000); // 1 second para próxima verificação
}catch (exception& e) {
if (STDA_SOURCE_ERROR_DECODE(e.getCodeError()) != STDA_ERROR_TYPE::THREAD)
throw;
}
}
}catch (exception& e) {
_smp::message_pool::getInstance().push(new message(e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
}catch (...) {
std::cout << "monitor() -> Exception (...) c++ nao tratada ou uma excessao de C(nullptr e etc)\n";
}
_smp::message_pool::getInstance().push(new message("Saindo de monitor()..."));
return 0u;
};
inline void client::dispach_packet_same_thread(session& _session, packet *_packet) {
CHECK_SESSION_BEGIN("dispach_packet_same_thread");
//ParamWorkerC pw = { *this, m_iocp_io, m_job_pool, m_session_pool, (cliente*)_packet->getSession()->m_client, _packet };
func_arr::func_arr_ex *func = nullptr;
try {
func = packet_func_base::funcs.getPacketCall(_packet->getTipo());
}catch (exception& e) {
if (STDA_SOURCE_ERROR_DECODE(e.getCodeError()) == STDA_ERROR_TYPE::FUNC_ARR/*Packet_func Erro, Warning e etc*/) {
_smp::message_pool::getInstance().push(new message(e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
_smp::message_pool::getInstance().push(new message("size packet: " + std::to_string(_packet->getSize()) + "\n" + hex_util::BufferToHexString(_packet->getBuffer(), _packet->getSize()), CL_FILE_LOG_AND_CONSOLE));
// Trata o erro aqui
// e desloga a session que enviou pacote errado
/// colocar de novo ------> m_pe->_session_pool.deleteSession(_packet->getSession());
// se for muito grave relança ele para terminar a thread
}else
throw;
}
//pw.p = _packet;
ParamDispatch _pd = { *(player*)&_session, _packet };
if (func != nullptr && func->execCmd(&_pd) != 0)
_smp::message_pool::getInstance().push(new message("Erro ao tratar o pacote. ID: " + std::to_string(_pd._packet->getTipo()) + "(0x" + hex_util::ltoaToHex(_pd._packet->getTipo()) + "). threadpool::dispach_packet_same_thread()", CL_FILE_LOG_AND_CONSOLE));
};
inline void client::dispach_packet_sv_same_thread(session& _session, packet *_packet) {
CHECK_SESSION_BEGIN("dispach_packet_sv_same_thread");
//ParamWorkerC pw = { *this, m_iocp_io, m_job_pool, m_session_pool, (cliente*)_packet->getSession()->m_client, _packet };
func_arr::func_arr_ex *func = nullptr;
try {
func = packet_func_base::funcs_sv.getPacketCall(_packet->getTipo());
}catch (exception& e) {
if (STDA_SOURCE_ERROR_DECODE(e.getCodeError()) == STDA_ERROR_TYPE::FUNC_ARR/*Packet_func Erro, Warning e etc*/) {
_smp::message_pool::getInstance().push(new message(e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
//_smp::message_pool.push(new message("size packet: " + std::to_string(_pd._packet->getSize()) + "\n" + hex_util::BufferToHexString(_pd._packet->getBuffer(), _pd._packet->getSize()), CL_FILE_LOG_AND_CONSOLE));
// Trata o erro aqui
// e desloga a session que enviou pacote errado
/// colocar de novo ------> m_pe->_session_pool.deleteSession(_packet->getSession());
// se for muito grave relança ele para terminar a thread
}else
throw;
}
//pw.p = _packet;
ParamDispatch _pd = { *(player*)&_session, _packet };
if (func != nullptr && func->execCmd(&_pd) != 0)
_smp::message_pool::getInstance().push(new message("Erro ao tratar o pacote. ID: " + std::to_string(_pd._packet->getTipo()) + "(0x" + hex_util::ltoaToHex(_pd._packet->getTipo()) + "). threadpool::dispach_packet_sv_same_thread()", CL_FILE_LOG_AND_CONSOLE));
};
void client::waitAllThreadFinish(DWORD dwMilleseconds) {
// Monitor Thread
InterlockedDecrement(&m_continue_monitor);
InterlockedDecrement(&m_continue_send_msg);
if (m_thread_monitor != nullptr)
m_thread_monitor->waitThreadFinish(dwMilleseconds);
for (size_t i = 0; i < m_threads.size(); i++) {
switch (m_threads[i]->getTipo()) {
case TT_WORKER_IO:
for (auto io = 0u; io < (sizeof(m_iocp_io) / sizeof(iocp)); ++io)
m_iocp_io[io].postStatus((ULONG_PTR)nullptr, 0, nullptr);
break;
case TT_WORKER_IO_SEND:
for (auto io = 0u; io < (sizeof(m_iocp_io_send) / sizeof(iocp)); ++io)
m_iocp_io_send[io].postStatus((ULONG_PTR)nullptr, 0, nullptr);
break;
case TT_WORKER_IO_RECV:
for (auto io = 0u; io < (sizeof(m_iocp_io_recv) / sizeof(iocp)); ++io)
m_iocp_io_recv[io].postStatus((ULONG_PTR)nullptr, 0, nullptr);
break;
case TT_WORKER_LOGICAL:
//for (auto io = 0u; io < (sizeof(m_iocp_logical) / sizeof(iocp)); ++io)
m_iocp_logical.postStatus((ULONG_PTR)nullptr, 0, nullptr); // Esse tinha Index[io], era um array de 16 iocp
break;
case TT_WORKER_SEND:
//for (auto io = 0u; io < (sizeof(m_iocp_send) / sizeof(iocp)); ++io)
m_iocp_send.postStatus((ULONG_PTR)nullptr, 0, nullptr); // Esse tinha Index[io], era um array de 16 iocp
break;
case TT_JOB:
m_job_pool.push(nullptr); // Sai do job
break;
case TT_CONSOLE:
_smp::message_pool::getInstance().push(nullptr); // Sai do console
break;
case TT_MONITOR:
InterlockedDecrement(&m_continue_monitor);
break;
}
}
for (size_t i = 0; i < m_threads.size(); i++)
if (m_threads[i] != nullptr)
m_threads[i]->waitThreadFinish(dwMilleseconds);
_smp::message_pool::getInstance().push(nullptr); // Sai console;
if (m_thread_console != nullptr)
m_thread_console->waitThreadFinish(dwMilleseconds);
};
void client::start() {
if (m_state != FAILURE) {
try {
commandScan();
_smp::message_pool::getInstance().push(new message("Saindo..."));
waitAllThreadFinish(INFINITE);
}catch (exception& e) {
_smp::message_pool::getInstance().push(new message(e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
}catch (std::exception& e) {
_smp::message_pool::getInstance().push(new message(e.what(), CL_FILE_LOG_AND_CONSOLE));
}catch (...) {
_smp::message_pool::getInstance().push(new message("Error desconhecido. client::start()", CL_FILE_LOG_AND_CONSOLE));
}
}else {
_smp::message_pool::getInstance().push(new message("Cliente inicializado com falha.", CL_FILE_LOG_AND_CONSOLE));
waitAllThreadFinish(INFINITE);
}
};
| 34.80083 | 258 | 0.707285 | eantoniobr |
f5c82977e67aace78c370a2fa7cb04e091ee4f42 | 14,947 | cpp | C++ | src/flow.cpp | MarkGillespie/SurfaceSchroedingerSmoke | 6a1fbce7b52147283017964d81111d6d2aad1581 | [
"MIT"
] | 2 | 2021-11-19T06:56:21.000Z | 2021-12-25T13:22:14.000Z | src/flow.cpp | MarkGillespie/SurfaceSchroedingerSmoke | 6a1fbce7b52147283017964d81111d6d2aad1581 | [
"MIT"
] | null | null | null | src/flow.cpp | MarkGillespie/SurfaceSchroedingerSmoke | 6a1fbce7b52147283017964d81111d6d2aad1581 | [
"MIT"
] | 1 | 2021-11-19T06:57:00.000Z | 2021-11-19T06:57:00.000Z | #include "flow.h"
// Convert from a vertex-based vector field to face-based by averaging together
// the vectors on all of a face's vertices
FaceData<Vector2> toFaces(ManifoldSurfaceMesh& mesh,
VertexPositionGeometry& geo,
const VertexData<Vector2>& field) {
FaceData<Vector2> faceField(mesh, Vector2{0, 0});
geo.requireHalfedgeVectorsInVertex();
geo.requireHalfedgeVectorsInFace();
const HalfedgeData<Vector2>& hV = geo.halfedgeVectorsInVertex;
const HalfedgeData<Vector2>& hF = geo.halfedgeVectorsInFace;
for (Face f : mesh.faces()) {
double D = f.degree();
for (Halfedge he : f.adjacentHalfedges()) {
Vector2 v = field[he.vertex()];
faceField[f] += v / hV[he] * hF[he] / D;
}
}
return faceField;
}
SparseMatrix<double> computeAdvectionMatrix(ManifoldSurfaceMesh& mesh,
VertexPositionGeometry& geo,
const FaceData<Vector2>& velocity) {
std::vector<Eigen::Triplet<double>> T;
VertexData<size_t> vIdx = mesh.getVertexIndices();
geo.requireFaceAreas();
const FaceData<double>& area = geo.faceAreas;
geo.requireHalfedgeVectorsInFace();
const HalfedgeData<Vector2>& hF = geo.halfedgeVectorsInFace;
Vector2 J{0, 1};
for (Vertex v : mesh.vertices()) {
double vArea = 0;
for (Face f : v.adjacentFaces()) vArea += area[f];
size_t iV = vIdx[v];
for (Halfedge he : v.outgoingHalfedges()) {
size_t iW = vIdx[he.next().vertex()];
Face f = he.face();
Vector2 grad = (J * hF[he.next()]).normalize();
double entry = dot(grad, velocity[f]) * area[f] / vArea;
T.emplace_back(iV, iW, entry);
}
}
size_t n = mesh.nVertices();
SparseMatrix<double> M(n, n);
M.setFromTriplets(std::begin(T), std::end(T));
return M;
}
// Advect with face-based velocity field
VertexData<double> advect(ManifoldSurfaceMesh& mesh,
VertexPositionGeometry& geo,
const FaceData<Vector2>& velocity,
const VertexData<double>& field, double t) {
Vector<double> fieldVec = field.toVector();
size_t n = mesh.nVertices();
SparseMatrix<double> I(n, n);
I.setIdentity();
SparseMatrix<double> advectionMatrix =
computeAdvectionMatrix(mesh, geo, velocity);
SparseMatrix<double> evolution =
I + t * advectionMatrix +
t * t / 2. * advectionMatrix * advectionMatrix;
Vector<double> newFieldVec = evolution * fieldVec;
// newFieldVec *= fieldVec.norm() / newFieldVec.norm();
return VertexData<double>(mesh, newFieldVec);
}
// Advect with vertex-based velocity field
VertexData<double> advect(ManifoldSurfaceMesh& mesh,
VertexPositionGeometry& geo,
const VertexData<Vector2>& velocity,
const VertexData<double>& field, double t) {
FaceData<Vector2> faceVelocity = toFaces(mesh, geo, velocity);
return advect(mesh, geo, faceVelocity, field, t);
}
// Advect with vertex-based velocity field
VertexData<double> advectSemiLagrangian(ManifoldSurfaceMesh& mesh,
VertexPositionGeometry& geo,
const VertexData<Vector2>& velocity,
const VertexData<double>& field,
double t) {
VertexData<double> advectedField(mesh);
for (Vertex v : mesh.vertices()) {
TraceGeodesicResult path =
traceGeodesic(geo, SurfacePoint(v), -t * velocity[v]);
advectedField[v] = path.endPoint.interpolate(field);
}
return advectedField;
}
SparseMatrix<std::complex<double>> connectionD0(ManifoldSurfaceMesh& mesh,
VertexPositionGeometry& geo) {
std::vector<Eigen::Triplet<std::complex<double>>> T;
geo.requireTransportVectorsAlongHalfedge();
HalfedgeData<Vector2> hedgeRot = geo.transportVectorsAlongHalfedge;
VertexData<size_t> vIdx = mesh.getVertexIndices();
EdgeData<size_t> eIdx = mesh.getEdgeIndices();
std::complex<double> i(0, 1);
for (Edge e : mesh.edges()) {
Vertex v = e.halfedge().vertex();
Vertex w = e.halfedge().next().vertex();
std::complex<double> rot =
static_cast<std::complex<double>>(hedgeRot[e.halfedge()]);
std::complex<double> halfRot = std::sqrt(rot);
T.emplace_back(eIdx[e], vIdx[w], halfRot);
T.emplace_back(eIdx[e], vIdx[w], -std::conj(halfRot));
}
SparseMatrix<std::complex<double>> d0(mesh.nEdges(), mesh.nVertices());
d0.setFromTriplets(std::begin(T), std::end(T));
return d0;
}
SchroedingerSolver::SchroedingerSolver(ManifoldSurfaceMesh& mesh_,
VertexPositionGeometry& geo_, double dt,
double hbar_)
: mesh(mesh_), geo(geo_), hbar(hbar_) {
geo.requireCotanLaplacian();
geo.requireVertexConnectionLaplacian();
geo.requireVertexLumpedMassMatrix();
SparseMatrix<double> L = geo.cotanLaplacian;
M = geo.vertexLumpedMassMatrix.cast<std::complex<double>>();
/*
SparseMatrix<std::complex<double>> Lconn = geo.vertexConnectionLaplacian;
SparseMatrix<std::complex<double>> d0conn = connectionD0(mesh, geo);
geo.requireDECOperators();
SparseMatrix<double> DEC_L = geo.d0.transpose() * geo.hodge1 * geo.d0;
for (size_t iV = 0; iV < mesh.nVertices(); ++iV) {
Vector<std::complex<double>> vecI =
Vector<std::complex<double>>::Zero(mesh.nVertices());
vecI(iV) = 1;
Vector<std::complex<double>> DECLV =
d0conn.transpose() * geo.hodge1 * d0conn * vecI;
Vector<std::complex<double>> LV = Lconn * vecI;
if ((DECLV - LV).norm() > 1e-8) {
std::cerr << "DEC laplacian and cotan laplacian disgree?"
<< std::endl;
exit(1);
}
Vector<double> vecI = Vector<double>::Zero(mesh.nVertices());
vecI(iV) = 1;
Vector<double> DECLV = DEC_L * vecI;
Vector<double> LV = L * vecI;
if ((DECLV - LV).norm() > 1e-8) {
std::cerr << "DEC laplacian and cotan laplacian disgree?"
<< std::endl;
exit(1);
}
}
*/
std::complex<double> i(0, 1);
SparseMatrix<std::complex<double>> evolution0 =
M.cast<std::complex<double>>() - i * hbar * dt / 4. * L;
SparseMatrix<std::complex<double>> evolution1 =
M.cast<std::complex<double>>() + i * hbar * dt / 4. * L;
evolutionSolver0 = std::unique_ptr<SquareSolver<std::complex<double>>>(
new SquareSolver<std::complex<double>>(evolution0));
evolutionSolver1 = std::unique_ptr<SquareSolver<std::complex<double>>>(
new SquareSolver<std::complex<double>>(evolution1));
Lsolver = std::unique_ptr<PositiveDefiniteSolver<double>>(
new PositiveDefiniteSolver<double>(L));
}
Wavefunction SchroedingerSolver::schroedingerAdvect(const Wavefunction& psi) {
Vector<std::complex<double>> psi0 = psi[0].toVector();
Vector<std::complex<double>> psi1 = psi[1].toVector();
Vector<std::complex<double>> newPsi0 = evolutionSolver0->solve(M * psi0);
Vector<std::complex<double>> newPsi1 = evolutionSolver1->solve(M * psi1);
return Wavefunction{VertexData<std::complex<double>>(mesh, newPsi0),
VertexData<std::complex<double>>(mesh, newPsi1)};
}
void SchroedingerSolver::normalize(Wavefunction& psi) {
for (Vertex v : mesh.vertices()) {
// Apparently std::norm(std::complex) computes the *squared* norm
double vNorm = sqrt(std::norm(psi[0][v]) + std::norm(psi[1][v]));
psi[0][v] /= vNorm;
psi[1][v] /= vNorm;
}
}
VertexData<double>
SchroedingerSolver::computePressure(const EdgeData<double>& velocity) {
geo.requireDECOperators();
Vector<double> delV = geo.d0.transpose() * geo.hodge1 * velocity.toVector();
Vector<double> pressureVec = Lsolver->solve(delV);
Vector<double> updatedVelocity = velocity.toVector() - geo.d0 * pressureVec;
Vector<double> updatedDivergence =
geo.d0.transpose() * geo.hodge1 * updatedVelocity;
for (size_t iV = 0; iV < mesh.nVertices(); ++iV) {
if (abs(updatedDivergence(iV)) > 1e-8) {
std::cerr << "Pressure projection failed (inside)" << std::endl;
exit(1);
}
}
return VertexData<double>(mesh, pressureVec);
}
Wavefunction SchroedingerSolver::pressureProject(Wavefunction psi) {
EdgeData<double> velocityField = getVelocityField(psi);
VertexData<double> pressure = computePressure(velocityField);
Wavefunction oldPsi = psi;
std::complex<double> i(0, 1);
for (Vertex v : mesh.vertices()) {
psi[0][v] *= exp(-i * pressure[v] / hbar);
psi[1][v] *= exp(-i * pressure[v] / hbar);
}
/*
EdgeData<double> updatedVelocityField = getVelocityField(psi);
geo.requireDECOperators();
Vector<double> edgeUpdate =
updatedVelocityField.toVector() - velocityField.toVector();
Vector<double> gradP = geo.d0 * pressure.toVector();
EdgeData<size_t> eIdx = mesh.getEdgeIndices();
for (Edge e : mesh.edges()) {
size_t iE = eIdx[e];
Vertex v = e.halfedge().vertex();
Vertex w = e.halfedge().next().vertex();
if (abs(edgeUpdate(iE) + gradP(iE)) > 1e-8) {
std::cerr << "Error: gradP = " << gradP(iE)
<< " but edge update was " << edgeUpdate(iE)
<< "\t| new velocity: " << updatedVelocityField[e]
<< ", old velocity: " << velocityField[e]
<< "\t| err / hbar = "
<< (edgeUpdate(iE) + gradP(iE)) / hbar << std::endl;
// exit(1);
}
}
Vector<double> divergence =
geo.d0.transpose() * geo.hodge1 * updatedVelocityField.toVector();
for (size_t iV = 0; iV < mesh.nVertices(); ++iV) {
if (abs(divergence(iV)) > 1e-8) {
std::cerr << "Pressure projection failed" << std::endl;
exit(1);
}
}
*/
return psi;
}
// v@s;
// @s.x = 2*(@psi1re*@psi2re - @psi1im*@psi2im);
// @s.y = 2*(@psi1re*@psi2im + @psi2re*@psi1im);
// @s.z = pow(@psi1re,2)+pow(@psi1im,2)
// -pow(@psi2re,2)-pow(@psi2im,2);
VertexData<Vector3> SchroedingerSolver::computeSpin(Wavefunction psi) {
VertexData<Vector3> spins(mesh);
for (Vertex v : mesh.vertices()) {
std::complex<double> prod = psi[0][v] * psi[1][v];
spins[v] = Vector3{2 * std::real(prod), 2 * std::imag(prod),
std::norm(psi[0][v]) - std::norm(psi[1][v])};
spins[v] = spins[v] / 2. + Vector3{0.5, 0.5, 0.5};
}
return spins;
}
std::vector<Wavefunction>
SchroedingerSolver::schroedingerFlow(const Wavefunction& psi, size_t steps) {
std::vector<Wavefunction> frames{psi};
for (size_t iS = 0; iS < steps; ++iS) {
const Wavefunction oldPsi = frames[frames.size() - 1];
Wavefunction psiTmp = schroedingerAdvect(oldPsi);
normalize(psiTmp);
frames.push_back(pressureProject(psiTmp));
}
return frames;
}
std::vector<EdgeData<double>>
SchroedingerSolver::schroedingerFlowVelocities(const Wavefunction& psi,
size_t steps) {
std::vector<EdgeData<double>> velocities;
for (Wavefunction psi_t : schroedingerFlow(psi, steps)) {
velocities.push_back(getVelocityField(psi_t));
}
return velocities;
}
EdgeData<double> SchroedingerSolver::getVelocityField(const Wavefunction& psi) {
EdgeData<double> velocity(mesh, 0);
geo.requireTransportVectorsAlongHalfedge();
HalfedgeData<Vector2> hedgeRot = geo.transportVectorsAlongHalfedge;
std::complex<double> i(0, 1);
for (Edge e : mesh.edges()) {
Vertex v = e.halfedge().vertex();
Vertex w = e.halfedge().next().vertex();
// std::complex<double> rot =
// static_cast<std::complex<double>>(hedgeRot[e.halfedge()]);
// std::complex<double> psi_v_0 = rot * psi[0][v];
// std::complex<double> psi_v_1 = rot * psi[1][v];
std::complex<double> psi_v_0 = psi[0][v];
std::complex<double> psi_v_1 = psi[1][v];
// std::complex<double> psi_v_0 = rot * psi[0][v];
// std::complex<double> psi_v_1 = rot * psi[1][v];
std::complex<double> psi_w_0 = psi[0][w];
std::complex<double> psi_w_1 = psi[1][w];
std::complex<double> psi_v_bar_psi_w =
std::conj(psi_v_0) * psi_w_0 + std::conj(psi_v_1) * psi_w_1;
velocity[e] = hbar * std::arg(psi_v_bar_psi_w);
// double a = std::real(psi_v_bar_psi_w);
// double b = std::imag(psi_v_bar_psi_w);
// velocity[e] = hbar * atan2(b, a);
// std::complex<double> psi_avg_0 = (psi_v_0 + psi_w_0) / 2.;
// std::complex<double> psi_avg_1 = (psi_v_1 + psi_w_1) / 2.;
// double r0_sq = std::norm(psi_avg_0);
// double r1_sq = std::norm(psi_avg_1);
// double q = r0_sq + r1_sq;
// std::complex<double> dpsi_0 = psi_w_0 / psi_v_0;
// std::complex<double> dpsi_1 = psi_w_0 / psi_v_0;
// velocity[e] =
// hbar * (r0_sq * std::arg(dpsi_0) + r1_sq * std::arg(dpsi_1)) / q;
// velocity[e] = hbar / q *
// std::real(-std::conj(psi_avg_0) * i * dpsi_0 -
// std::conj(psi_avg_1) * i * dpsi_1);
// velocity[e] = hbar * std::arg(std::conj(psi_v_0) * psi_w_0 +
// std::conj(psi_v_1) * psi_w_1);
}
return velocity;
}
FaceData<Vector2> SchroedingerSolver::reconstructFaceVectors(
const EdgeData<double>& velocityField) {
geo.requireHalfedgeVectorsInFace();
const HalfedgeData<Vector2>& faceVec = geo.halfedgeVectorsInFace;
auto hedgeVelocity = [&](Halfedge he) {
double sign = (he.edge().halfedge() == he) ? 1 : -1;
return sign * velocityField[he.edge()];
};
FaceData<Vector2> faceVectors(mesh);
for (Face f : mesh.faces()) {
Vector2 v0 = faceVec[f.halfedge()];
Vector2 v1 = faceVec[f.halfedge().next()];
double a0 = hedgeVelocity(f.halfedge());
double a1 = hedgeVelocity(f.halfedge().next());
double det = v0.x * v1.y - v0.y * v1.x;
double w0 = (v1.y * a0 - v0.y * a1) / det;
double w1 = (-v1.x * a0 + v0.x * a1) / det;
faceVectors[f] = {w0, w1};
}
return faceVectors;
}
| 35.758373 | 80 | 0.583662 | MarkGillespie |
f5cd92492a3e5ece5cc8305256600a3a28812c79 | 4,220 | cpp | C++ | generator/generated_components/T.cpp | AlevtinaGlonina/MCSSim | d668115949e6eb49b6e1e21c011e48e05a59445f | [
"BSD-3-Clause"
] | null | null | null | generator/generated_components/T.cpp | AlevtinaGlonina/MCSSim | d668115949e6eb49b6e1e21c011e48e05a59445f | [
"BSD-3-Clause"
] | null | null | null | generator/generated_components/T.cpp | AlevtinaGlonina/MCSSim | d668115949e6eb49b6e1e21c011e48e05a59445f | [
"BSD-3-Clause"
] | null | null | null | #include "T.h"
using namespace std;
namespace T {
T::T(string _name, Network *n, int p, bool __t, TaskData* _data, Var* _abs_deadline, Var* _is_ready, Var* _prio, vector <Var*> &_is_data_ready
, Channel* _exec, Channel* _preempt, Channel* _ready, Channel* _finished, Channel* _send, Channel* _receive
): Automaton(n, _name, p, __t), data(_data), abs_deadline(_abs_deadline), is_ready(_is_ready), prio(_prio), is_data_ready(_is_data_ready), exec(_exec), preempt(_preempt), ready(_ready), finished(_finished), send(_send), receive(_receive), exec_timer(n, "T_exec_timer"), local_timer(n, "T_local_timer")
{
Dormant* dormant = new Dormant (n, "Dormant", false, false, this);
addLocation(dormant);
Ready* ready = new Ready (n, "Ready", false, false, this);
addLocation(ready);
SendReadySig* sendreadysig = new SendReadySig (n, "SendReadySig", false, true, this);
addLocation(sendreadysig);
Finished* finished = new Finished (n, "Finished", false, true, this);
addLocation(finished);
Exec* exec = new Exec (n, "Exec", false, false, this);
addLocation(exec);
WaitingForData* waitingfordata = new WaitingForData (n, "WaitingForData", false, false, this);
addLocation(waitingfordata);
WaitingForNewPeriod* waitingfornewperiod = new WaitingForNewPeriod (n, "WaitingForNewPeriod", false, false, this);
addLocation(waitingfornewperiod);
Start* start = new Start (n, "Start", true, true, this);
addLocation(start);
Send* send = new Send (n, "Send", false, true, this);
addLocation(send);
Start_Dormant_0 *start_dormant_0 = new Start_Dormant_0 (n, dormant, this);
start->addTransition(start_dormant_0);
WaitingForData_WaitingForData_1 *waitingfordata_waitingfordata_1 = new WaitingForData_WaitingForData_1 (n, waitingfordata, this);
waitingfordata->addTransition(waitingfordata_waitingfordata_1);
Dormant_Dormant_2 *dormant_dormant_2 = new Dormant_Dormant_2 (n, dormant, this);
dormant->addTransition(dormant_dormant_2);
WaitingForNewPeriod_Dormant_3 *waitingfornewperiod_dormant_3 = new WaitingForNewPeriod_Dormant_3 (n, dormant, this);
waitingfornewperiod->addTransition(waitingfornewperiod_dormant_3);
Exec_Finished_4 *exec_finished_4 = new Exec_Finished_4 (n, finished, this);
exec->addTransition(exec_finished_4);
Send_Finished_5 *send_finished_5 = new Send_Finished_5 (n, finished, this);
send->addTransition(send_finished_5);
Exec_Send_6 *exec_send_6 = new Exec_Send_6 (n, send, this);
exec->addTransition(exec_send_6);
WaitingForData_WaitingForNewPeriod_7 *waitingfordata_waitingfornewperiod_7 = new WaitingForData_WaitingForNewPeriod_7 (n, waitingfornewperiod, this);
waitingfordata->addTransition(waitingfordata_waitingfornewperiod_7);
Ready_WaitingForNewPeriod_8 *ready_waitingfornewperiod_8 = new Ready_WaitingForNewPeriod_8 (n, waitingfornewperiod, this);
ready->addTransition(ready_waitingfornewperiod_8);
WaitingForData_SendReadySig_9 *waitingfordata_sendreadysig_9 = new WaitingForData_SendReadySig_9 (n, sendreadysig, this);
waitingfordata->addTransition(waitingfordata_sendreadysig_9);
WaitingForData_WaitingForData_10 *waitingfordata_waitingfordata_10 = new WaitingForData_WaitingForData_10 (n, waitingfordata, this);
waitingfordata->addTransition(waitingfordata_waitingfordata_10);
Dormant_WaitingForData_11 *dormant_waitingfordata_11 = new Dormant_WaitingForData_11 (n, waitingfordata, this);
dormant->addTransition(dormant_waitingfordata_11);
Finished_WaitingForNewPeriod_12 *finished_waitingfornewperiod_12 = new Finished_WaitingForNewPeriod_12 (n, waitingfornewperiod, this);
finished->addTransition(finished_waitingfornewperiod_12);
Exec_Ready_13 *exec_ready_13 = new Exec_Ready_13 (n, ready, this);
exec->addTransition(exec_ready_13);
Ready_Exec_14 *ready_exec_14 = new Ready_Exec_14 (n, exec, this);
ready->addTransition(ready_exec_14);
SendReadySig_Ready_15 *sendreadysig_ready_15 = new SendReadySig_Ready_15 (n, ready, this);
sendreadysig->addTransition(sendreadysig_ready_15);
Dormant_SendReadySig_16 *dormant_sendreadysig_16 = new Dormant_SendReadySig_16 (n, sendreadysig, this);
dormant->addTransition(dormant_sendreadysig_16);
automaton = this;
automaton->timers.push_back(&exec_timer);
automaton->timers.push_back(&local_timer);
}
}
| 55.526316 | 301 | 0.804502 | AlevtinaGlonina |
f5cff69e63a8a8eb91d33211f4c33b049af3b9c1 | 3,803 | cc | C++ | tensorflow/core/kernels/tridiagonal_matmul_op_gpu.cu.cc | yanyang729/tensorflow | 112433f1c968ff721caf70e7846f5719a9e6053a | [
"Apache-2.0"
] | 1 | 2019-07-11T22:06:41.000Z | 2019-07-11T22:06:41.000Z | tensorflow/core/kernels/tridiagonal_matmul_op_gpu.cu.cc | yanyang729/tensorflow | 112433f1c968ff721caf70e7846f5719a9e6053a | [
"Apache-2.0"
] | 8 | 2019-07-08T10:09:18.000Z | 2019-09-26T20:55:43.000Z | tensorflow/core/kernels/tridiagonal_matmul_op_gpu.cu.cc | yanyang729/tensorflow | 112433f1c968ff721caf70e7846f5719a9e6053a | [
"Apache-2.0"
] | 1 | 2021-06-02T04:11:53.000Z | 2021-06-02T04:11:53.000Z | /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// See docs in ../ops/linalg_ops.cc.
#ifdef GOOGLE_CUDA
#define EIGEN_USE_GPU
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/kernels/cuda_solvers.h"
#include "tensorflow/core/kernels/cuda_sparse.h"
#include "tensorflow/core/kernels/linalg_ops_common.h"
#include "tensorflow/core/kernels/transpose_functor.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/util/gpu_device_functions.h"
#include "tensorflow/core/util/gpu_kernel_helper.h"
#include "tensorflow/core/util/gpu_launch_config.h"
namespace tensorflow {
template <typename Scalar>
__global__ void TridiagonalMatMulKernel(int batch_size, int m, int n,
const Scalar* superdiag,
const Scalar* maindiag,
const Scalar* subdiag,
const Scalar* rhs, Scalar* product) {
for (int i : CudaGridRangeX(batch_size * m * n)) {
int row_id = i / n;
Scalar result = maindiag[row_id] * rhs[i];
if (row_id % m != 0) {
result = result + subdiag[row_id] * rhs[i - n];
}
if ((row_id + 1) % m != 0) {
result = result + superdiag[row_id] * rhs[i + n];
}
product[i] = result;
}
}
template <typename Scalar>
class TridiagonalMatMulOpGpu : public OpKernel {
public:
explicit TridiagonalMatMulOpGpu(OpKernelConstruction* context)
: OpKernel(context) {}
void Compute(OpKernelContext* context) final {
const Tensor& superdiag = context->input(0);
const Tensor& maindiag = context->input(1);
const Tensor& subdiag = context->input(2);
const Tensor& rhs = context->input(3);
const int ndims = rhs.dims();
int64 batch_size = 1;
for (int i = 0; i < ndims - 2; i++) {
batch_size *= rhs.dim_size(i);
}
const int m = rhs.dim_size(ndims - 2);
const int n = rhs.dim_size(ndims - 1);
// Allocate output.
Tensor* output;
OP_REQUIRES_OK(context, context->allocate_output(0, rhs.shape(), &output));
const Eigen::GpuDevice& device = context->eigen_device<Eigen::GpuDevice>();
CudaLaunchConfig cfg = GetGpuLaunchConfig(1, device);
TF_CHECK_OK(GpuLaunchKernel(
TridiagonalMatMulKernel<Scalar>, cfg.block_count, cfg.thread_per_block,
0, device.stream(), batch_size, m, n, superdiag.flat<Scalar>().data(),
maindiag.flat<Scalar>().data(), subdiag.flat<Scalar>().data(),
rhs.flat<Scalar>().data(), output->flat<Scalar>().data()));
}
};
REGISTER_LINALG_OP_GPU("TridiagonalMatMul", (TridiagonalMatMulOpGpu<float>),
float);
REGISTER_LINALG_OP_GPU("TridiagonalMatMul", (TridiagonalMatMulOpGpu<double>),
double);
REGISTER_LINALG_OP_GPU("TridiagonalMatMul", (TridiagonalMatMulOpGpu<complex64>),
complex64);
REGISTER_LINALG_OP_GPU("TridiagonalMatMul",
(TridiagonalMatMulOpGpu<complex128>), complex128);
} // namespace tensorflow
#endif // GOOGLE_CUDA
| 38.03 | 80 | 0.661583 | yanyang729 |
f5d20ed875fd2c94625baa7fbdf1578e597810f5 | 699 | hpp | C++ | src/libv/utility/concat.hpp | cpplibv/libv | 293e382f459f0acbc540de8ef6283782b38d2e63 | [
"Zlib"
] | 2 | 2018-04-11T03:07:03.000Z | 2019-03-29T15:24:12.000Z | src/libv/utility/concat.hpp | cpplibv/libv | 293e382f459f0acbc540de8ef6283782b38d2e63 | [
"Zlib"
] | null | null | null | src/libv/utility/concat.hpp | cpplibv/libv | 293e382f459f0acbc540de8ef6283782b38d2e63 | [
"Zlib"
] | 1 | 2021-06-13T06:39:06.000Z | 2021-06-13T06:39:06.000Z | // Project: libv.utility, File: src/libv/utility/concat.hpp, Author: Császár Mátyás [Vader]
#pragma once
// std
#include <string>
#include <sstream>
namespace libv {
// -------------------------------------------------------------------------------------------------
template <typename... Args>
[[nodiscard]] inline std::string concat(Args&&... args) noexcept {
// TODO P4: libv.utility: Improve implementation to a real str cat, ostringstream performance is unacceptable
std::ostringstream ss;
(ss << ... << std::forward<Args>(args));
return std::move(ss).str();
}
// -------------------------------------------------------------------------------------------------
} // namespace libv
| 27.96 | 110 | 0.494993 | cpplibv |
f5dd720d92992008aee6348942e1665ee40186cb | 1,746 | hpp | C++ | AlphaZeroPytorch/include/ai/playGame.hpp | JulianWww/AlphaZero | 8eb754659793305eba7b9e636eeab37d9ccd45f7 | [
"MIT"
] | 1 | 2021-12-05T13:26:17.000Z | 2021-12-05T13:26:17.000Z | AlphaZeroPytorch/include/ai/playGame.hpp | JulianWww/AlphaZero | 8eb754659793305eba7b9e636eeab37d9ccd45f7 | [
"MIT"
] | null | null | null | AlphaZeroPytorch/include/ai/playGame.hpp | JulianWww/AlphaZero | 8eb754659793305eba7b9e636eeab37d9ccd45f7 | [
"MIT"
] | null | null | null | #pragma once
#include <ai/agent.hpp>
#include <ai/memory.hpp>
namespace AlphaZero {
namespace ai {
struct gameOutput
{
std::unordered_map<Agent*, int> map;
std::mutex ex;
gameOutput(Agent*, Agent*);
void updateValue(Agent*);
};
void train(int);
void playGames(gameOutput* output, Agent* agent1, Agent* agent2, Memory* memory, int probMoves, int Epochs, char RunId[], int goesFist = 0, bool log = false);
std::unordered_map<Agent*, int> playGames_inThreads(Game::Game* game, Agent* agent1, Agent* agend2, Memory* memory, int probMoves, int Epochs, int Threads, char RunId[], int goesFirst = 0, bool log = false);
}
namespace test {
void playGame(std::shared_ptr<Game::Game> game, std::shared_ptr<ai::Agent> player1, std::shared_ptr<ai::Agent>player2, int goesFirst=0);
}
}
inline std::unordered_map<AlphaZero::ai::Agent*, int> AlphaZero::ai::playGames_inThreads(Game::Game* game, Agent* agent1, Agent* agent2, Memory* memory, int probMoves, int Epochs, int Threads, char RunId[], int goesFirst, bool log)
{
gameOutput output(agent1, agent2);
std::vector<std::thread> workers;
for (size_t idx = 0; idx < Threads; idx++)
{
bool doLog = (log && (idx == 0));
workers.push_back(std::thread(playGames, &output, agent1, agent2, memory, probMoves, Epochs, RunId, goesFirst, doLog));
}
for (auto& worker : workers)
{
worker.join();
}
return output.map;
}
inline void AlphaZero::ai::gameOutput::updateValue(Agent* idx)
{
this->ex.lock();
this->map[idx] = this->map[idx] + 1;
this->ex.unlock();
}
inline AlphaZero::ai::gameOutput::gameOutput(Agent* agent1, Agent* agent2)
{
this->map.insert({ agent1, 0 });
this->map.insert({ agent2, 0 });
} | 30.631579 | 232 | 0.668385 | JulianWww |
f5e14cc5702a14ed0a0bfb55bbaae3f13babb1a5 | 26,977 | cpp | C++ | RSDKv4/Scene3D.cpp | 0xR00KIE/Decomp-for-S1F | c8ffedd211f25bb46803f9d637baf1b1fc635db0 | [
"Unlicense"
] | 2 | 2022-01-15T05:05:39.000Z | 2022-03-19T07:36:31.000Z | RSDKv4/Scene3D.cpp | LittlePlanetCD/Decomp-for-S1F | c8ffedd211f25bb46803f9d637baf1b1fc635db0 | [
"Unlicense"
] | null | null | null | RSDKv4/Scene3D.cpp | LittlePlanetCD/Decomp-for-S1F | c8ffedd211f25bb46803f9d637baf1b1fc635db0 | [
"Unlicense"
] | null | null | null | #include "RetroEngine.hpp"
int vertexCount = 0;
int faceCount = 0;
Matrix matFinal = Matrix();
Matrix matWorld = Matrix();
Matrix matView = Matrix();
Matrix matTemp = Matrix();
Face faceBuffer[FACEBUFFER_SIZE];
Vertex vertexBuffer[VERTEXBUFFER_SIZE];
Vertex vertexBufferT[VERTEXBUFFER_SIZE];
DrawListEntry3D drawList3D[FACEBUFFER_SIZE];
int projectionX = 136;
int projectionY = 160;
int fogColour = 0;
int fogStrength = 0;
int faceLineStart[SCREEN_YSIZE];
int faceLineEnd[SCREEN_YSIZE];
int faceLineStartU[SCREEN_YSIZE];
int faceLineEndU[SCREEN_YSIZE];
int faceLineStartV[SCREEN_YSIZE];
int faceLineEndV[SCREEN_YSIZE];
void setIdentityMatrix(Matrix *matrix)
{
matrix->values[0][0] = 0x100;
matrix->values[0][1] = 0;
matrix->values[0][2] = 0;
matrix->values[0][3] = 0;
matrix->values[1][0] = 0;
matrix->values[1][1] = 0x100;
matrix->values[1][2] = 0;
matrix->values[1][3] = 0;
matrix->values[2][0] = 0;
matrix->values[2][1] = 0;
matrix->values[2][2] = 0x100;
matrix->values[2][3] = 0;
matrix->values[3][0] = 0;
matrix->values[3][0] = 0;
matrix->values[3][2] = 0;
matrix->values[3][3] = 0x100;
}
void matrixMultiply(Matrix *matrixA, Matrix *matrixB)
{
int output[16];
for (int i = 0; i < 0x10; ++i) {
uint rowA = i / 4;
uint rowB = i % 4;
output[i] =
(matrixA->values[rowA][3] * matrixB->values[3][rowB] >> 8) +
(matrixA->values[rowA][2] * matrixB->values[2][rowB] >> 8) +
(matrixA->values[rowA][1] * matrixB->values[1][rowB] >> 8) +
(matrixA->values[rowA][0] * matrixB->values[0][rowB] >> 8);
}
for (int i = 0; i < 0x10; ++i) matrixA->values[i / 4][i % 4] = output[i];
}
void matrixTranslateXYZ(Matrix *matrix, int XPos, int YPos, int ZPos)
{
matrix->values[0][0] = 0x100;
matrix->values[0][1] = 0;
matrix->values[0][2] = 0;
matrix->values[0][3] = 0;
matrix->values[1][0] = 0;
matrix->values[1][1] = 0x100;
matrix->values[1][2] = 0;
matrix->values[1][3] = 0;
matrix->values[2][0] = 0;
matrix->values[2][1] = 0;
matrix->values[2][2] = 0x100;
matrix->values[2][3] = 0;
matrix->values[3][0] = XPos;
matrix->values[3][1] = YPos;
matrix->values[3][2] = ZPos;
matrix->values[3][3] = 0x100;
}
void matrixScaleXYZ(Matrix *matrix, int scaleX, int scaleY, int scaleZ)
{
matrix->values[0][0] = scaleX;
matrix->values[0][1] = 0;
matrix->values[0][2] = 0;
matrix->values[0][3] = 0;
matrix->values[1][0] = 0;
matrix->values[1][1] = scaleY;
matrix->values[1][2] = 0;
matrix->values[1][3] = 0;
matrix->values[2][0] = 0;
matrix->values[2][1] = 0;
matrix->values[2][2] = scaleZ;
matrix->values[2][3] = 0;
matrix->values[3][0] = 0;
matrix->values[3][1] = 0;
matrix->values[3][2] = 0;
matrix->values[3][3] = 0x100;
}
void matrixRotateX(Matrix *matrix, int rotationX)
{
int sine = sinVal512[rotationX & 0x1FF] >> 1;
int cosine = cosVal512[rotationX & 0x1FF] >> 1;
matrix->values[0][0] = 0x100;
matrix->values[0][1] = 0;
matrix->values[0][2] = 0;
matrix->values[0][3] = 0;
matrix->values[1][0] = 0;
matrix->values[1][1] = cosine;
matrix->values[1][2] = sine;
matrix->values[1][3] = 0;
matrix->values[2][0] = 0;
matrix->values[2][1] = -sine;
matrix->values[2][2] = cosine;
matrix->values[2][3] = 0;
matrix->values[3][0] = 0;
matrix->values[3][1] = 0;
matrix->values[3][2] = 0;
matrix->values[3][3] = 0x100;
}
void matrixRotateY(Matrix *matrix, int rotationY)
{
int sine = sinVal512[rotationY & 0x1FF] >> 1;
int cosine = cosVal512[rotationY & 0x1FF] >> 1;
matrix->values[0][0] = cosine;
matrix->values[0][1] = 0;
matrix->values[0][2] = sine;
matrix->values[0][3] = 0;
matrix->values[1][0] = 0;
matrix->values[1][1] = 0x100;
matrix->values[1][2] = 0;
matrix->values[1][3] = 0;
matrix->values[2][0] = -sine;
matrix->values[2][1] = 0;
matrix->values[2][2] = cosine;
matrix->values[2][3] = 0;
matrix->values[3][0] = 0;
matrix->values[3][1] = 0;
matrix->values[3][2] = 0;
matrix->values[3][3] = 0x100;
}
void matrixRotateZ(Matrix *matrix, int rotationZ)
{
int sine = sinVal512[rotationZ & 0x1FF] >> 1;
int cosine = cosVal512[rotationZ & 0x1FF] >> 1;
matrix->values[0][0] = cosine;
matrix->values[0][1] = 0;
matrix->values[0][2] = sine;
matrix->values[0][3] = 0;
matrix->values[1][0] = 0;
matrix->values[1][1] = 0x100;
matrix->values[1][2] = 0;
matrix->values[1][3] = 0;
matrix->values[2][0] = -sine;
matrix->values[2][1] = 0;
matrix->values[2][2] = cosine;
matrix->values[2][3] = 0;
matrix->values[3][0] = 0;
matrix->values[3][1] = 0;
matrix->values[3][2] = 0;
matrix->values[3][3] = 0x100;
}
void matrixRotateXYZ(Matrix *matrix, short rotationX, short rotationY, short rotationZ)
{
int sinX = sinVal512[rotationX & 0x1FF] >> 1;
int cosX = cosVal512[rotationX & 0x1FF] >> 1;
int sinY = sinVal512[rotationY & 0x1FF] >> 1;
int cosY = cosVal512[rotationY & 0x1FF] >> 1;
int sinZ = sinVal512[rotationZ & 0x1FF] >> 1;
int cosZ = cosVal512[rotationZ & 0x1FF] >> 1;
matrix->values[0][0] = (cosZ * cosY >> 8) + (sinZ * (sinY * sinX >> 8) >> 8);
matrix->values[0][1] = (sinZ * cosY >> 8) - (cosZ * (sinY * sinX >> 8) >> 8);
matrix->values[0][2] = sinY * cosX >> 8;
matrix->values[0][3] = 0;
matrix->values[1][0] = sinZ * -cosX >> 8;
matrix->values[1][1] = cosZ * cosX >> 8;
matrix->values[1][2] = sinX;
matrix->values[1][3] = 0;
matrix->values[2][0] = (sinZ * (cosY * sinX >> 8) >> 8) - (cosZ * sinY >> 8);
matrix->values[2][1] = (sinZ * -sinY >> 8) - (cosZ * (cosY * sinX >> 8) >> 8);
matrix->values[2][2] = cosY * cosX >> 8;
matrix->values[2][3] = 0;
matrix->values[3][0] = 0;
matrix->values[3][1] = 0;
matrix->values[3][2] = 0;
matrix->values[3][3] = 0x100;
}
void matrixInverse(Matrix *matrix)
{
double inv[16], det;
double m[16];
for (int y = 0; y < 4; ++y) {
for (int x = 0; x < 4; ++x) {
m[(y << 2) + x] = matrix->values[y][x] / 256.0;
}
}
inv[0] = m[5] * m[10] * m[15] - m[5] * m[11] * m[14] - m[9] * m[6] * m[15] + m[9] * m[7] * m[14] + m[13] * m[6] * m[11] - m[13] * m[7] * m[10];
inv[4] = -m[4] * m[10] * m[15] + m[4] * m[11] * m[14] + m[8] * m[6] * m[15] - m[8] * m[7] * m[14] - m[12] * m[6] * m[11] + m[12] * m[7] * m[10];
inv[8] = m[4] * m[9] * m[15] - m[4] * m[11] * m[13] - m[8] * m[5] * m[15] + m[8] * m[7] * m[13] + m[12] * m[5] * m[11] - m[12] * m[7] * m[9];
inv[12] = -m[4] * m[9] * m[14] + m[4] * m[10] * m[13] + m[8] * m[5] * m[14] - m[8] * m[6] * m[13] - m[12] * m[5] * m[10] + m[12] * m[6] * m[9];
inv[1] = -m[1] * m[10] * m[15] + m[1] * m[11] * m[14] + m[9] * m[2] * m[15] - m[9] * m[3] * m[14] - m[13] * m[2] * m[11] + m[13] * m[3] * m[10];
inv[5] = m[0] * m[10] * m[15] - m[0] * m[11] * m[14] - m[8] * m[2] * m[15] + m[8] * m[3] * m[14] + m[12] * m[2] * m[11] - m[12] * m[3] * m[10];
inv[9] = -m[0] * m[9] * m[15] + m[0] * m[11] * m[13] + m[8] * m[1] * m[15] - m[8] * m[3] * m[13] - m[12] * m[1] * m[11] + m[12] * m[3] * m[9];
inv[13] = m[0] * m[9] * m[14] - m[0] * m[10] * m[13] - m[8] * m[1] * m[14] + m[8] * m[2] * m[13] + m[12] * m[1] * m[10] - m[12] * m[2] * m[9];
inv[2] = m[1] * m[6] * m[15] - m[1] * m[7] * m[14] - m[5] * m[2] * m[15] + m[5] * m[3] * m[14] + m[13] * m[2] * m[7] - m[13] * m[3] * m[6];
inv[6] = -m[0] * m[6] * m[15] + m[0] * m[7] * m[14] + m[4] * m[2] * m[15] - m[4] * m[3] * m[14] - m[12] * m[2] * m[7] + m[12] * m[3] * m[6];
inv[10] = m[0] * m[5] * m[15] - m[0] * m[7] * m[13] - m[4] * m[1] * m[15] + m[4] * m[3] * m[13] + m[12] * m[1] * m[7] - m[12] * m[3] * m[5];
inv[14] = -m[0] * m[5] * m[14] + m[0] * m[6] * m[13] + m[4] * m[1] * m[14] - m[4] * m[2] * m[13] - m[12] * m[1] * m[6] + m[12] * m[2] * m[5];
inv[3] = -m[1] * m[6] * m[11] + m[1] * m[7] * m[10] + m[5] * m[2] * m[11] - m[5] * m[3] * m[10] - m[9] * m[2] * m[7] + m[9] * m[3] * m[6];
inv[7] = m[0] * m[6] * m[11] - m[0] * m[7] * m[10] - m[4] * m[2] * m[11] + m[4] * m[3] * m[10] + m[8] * m[2] * m[7] - m[8] * m[3] * m[6];
inv[11] = -m[0] * m[5] * m[11] + m[0] * m[7] * m[9] + m[4] * m[1] * m[11] - m[4] * m[3] * m[9] - m[8] * m[1] * m[7] + m[8] * m[3] * m[5];
inv[15] = m[0] * m[5] * m[10] - m[0] * m[6] * m[9] - m[4] * m[1] * m[10] + m[4] * m[2] * m[9] + m[8] * m[1] * m[6] - m[8] * m[2] * m[5];
det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12];
if (det == 0)
return;
det = 1.0 / det;
for (int i = 0; i < 0x10; ++i) inv[i] = (int)((inv[i] * det) * 256);
for (int i = 0; i < 0x10; ++i) matrix->values[i / 4][i % 4] = inv[i];
}
void transformVertexBuffer()
{
matFinal.values[0][0] = matWorld.values[0][0];
matFinal.values[0][1] = matWorld.values[0][1];
matFinal.values[0][2] = matWorld.values[0][2];
matFinal.values[0][3] = matWorld.values[0][3];
matFinal.values[1][0] = matWorld.values[1][0];
matFinal.values[1][1] = matWorld.values[1][1];
matFinal.values[1][2] = matWorld.values[1][2];
matFinal.values[1][3] = matWorld.values[1][3];
matFinal.values[2][0] = matWorld.values[2][0];
matFinal.values[2][1] = matWorld.values[2][1];
matFinal.values[2][2] = matWorld.values[2][2];
matFinal.values[2][3] = matWorld.values[2][3];
matFinal.values[3][0] = matWorld.values[3][0];
matFinal.values[3][1] = matWorld.values[3][1];
matFinal.values[3][2] = matWorld.values[3][2];
matFinal.values[3][3] = matWorld.values[3][3];
matrixMultiply(&matFinal, &matView);
for (int v = 0; v < vertexCount; ++v) {
int vx = vertexBuffer[v].x;
int vy = vertexBuffer[v].y;
int vz = vertexBuffer[v].z;
vertexBufferT[v].x = (vx * matFinal.values[0][0] >> 8) + (vy * matFinal.values[1][0] >> 8) + (vz * matFinal.values[2][0] >> 8) + matFinal.values[3][0];
vertexBufferT[v].y = (vx * matFinal.values[0][1] >> 8) + (vy * matFinal.values[1][1] >> 8) + (vz * matFinal.values[2][1] >> 8) + matFinal.values[3][1];
vertexBufferT[v].z = (vx * matFinal.values[0][2] >> 8) + (vy * matFinal.values[1][2] >> 8) + (vz * matFinal.values[2][2] >> 8) + matFinal.values[3][2];
}
}
void transformVertices(Matrix *matrix, int startIndex, int endIndex)
{
for (int v = startIndex; v < endIndex; ++v) {
int vx = vertexBuffer[v].x;
int vy = vertexBuffer[v].y;
int vz = vertexBuffer[v].z;
Vertex *vert = &vertexBuffer[v];
vert->x = (vx * matrix->values[0][0] >> 8) + (vy * matrix->values[1][0] >> 8) + (vz * matrix->values[2][0] >> 8) + matrix->values[3][0];
vert->y = (vx * matrix->values[0][1] >> 8) + (vy * matrix->values[1][1] >> 8) + (vz * matrix->values[2][1] >> 8) + matrix->values[3][1];
vert->z = (vx * matrix->values[0][2] >> 8) + (vy * matrix->values[1][2] >> 8) + (vz * matrix->values[2][2] >> 8) + matrix->values[3][2];
}
}
void sort3DDrawList()
{
for (int i = 0; i < faceCount; ++i) {
drawList3D[i].depth = (vertexBufferT[faceBuffer[i].d].z + vertexBufferT[faceBuffer[i].c].z + vertexBufferT[faceBuffer[i].b].z
+ vertexBufferT[faceBuffer[i].a].z)
>> 2;
drawList3D[i].faceID = i;
}
for (int i = 0; i < faceCount; ++i) {
for (int j = faceCount - 1; j > i; --j) {
if (drawList3D[j].depth > drawList3D[j - 1].depth) {
int faceID = drawList3D[j].faceID;
int depth = drawList3D[j].depth;
drawList3D[j].faceID = drawList3D[j - 1].faceID;
drawList3D[j].depth = drawList3D[j - 1].depth;
drawList3D[j - 1].faceID = faceID;
drawList3D[j - 1].depth = depth;
}
}
}
}
void draw3DScene(int spriteSheetID)
{
Vertex quad[4];
for (int i = 0; i < faceCount; ++i) {
Face *face = &faceBuffer[drawList3D[i].faceID];
memset(quad, 0, 4 * sizeof(Vertex));
switch (face->flag) {
default: break;
case FACE_FLAG_TEXTURED_3D:
if (vertexBufferT[face->a].z > 0 && vertexBufferT[face->b].z > 0 && vertexBufferT[face->c].z > 0 && vertexBufferT[face->d].z > 0) {
quad[0].x = SCREEN_CENTERX + projectionX * vertexBufferT[face->a].x / vertexBufferT[face->a].z;
quad[0].y = SCREEN_CENTERY - projectionY * vertexBufferT[face->a].y / vertexBufferT[face->a].z;
quad[1].x = SCREEN_CENTERX + projectionX * vertexBufferT[face->b].x / vertexBufferT[face->b].z;
quad[1].y = SCREEN_CENTERY - projectionY * vertexBufferT[face->b].y / vertexBufferT[face->b].z;
quad[2].x = SCREEN_CENTERX + projectionX * vertexBufferT[face->c].x / vertexBufferT[face->c].z;
quad[2].y = SCREEN_CENTERY - projectionY * vertexBufferT[face->c].y / vertexBufferT[face->c].z;
quad[3].x = SCREEN_CENTERX + projectionX * vertexBufferT[face->d].x / vertexBufferT[face->d].z;
quad[3].y = SCREEN_CENTERY - projectionY * vertexBufferT[face->d].y / vertexBufferT[face->d].z;
quad[0].u = vertexBuffer[face->a].u;
quad[0].v = vertexBuffer[face->a].v;
quad[1].u = vertexBuffer[face->b].u;
quad[1].v = vertexBuffer[face->b].v;
quad[2].u = vertexBuffer[face->c].u;
quad[2].v = vertexBuffer[face->c].v;
quad[3].u = vertexBuffer[face->d].u;
quad[3].v = vertexBuffer[face->d].v;
DrawTexturedFace(quad, spriteSheetID);
}
break;
case FACE_FLAG_TEXTURED_2D:
if (vertexBufferT[face->a].z >= 0 && vertexBufferT[face->b].z >= 0 && vertexBufferT[face->c].z >= 0
&& vertexBufferT[face->d].z >= 0) {
quad[0].x = vertexBufferT[face->a].x;
quad[0].y = vertexBufferT[face->a].y;
quad[1].x = vertexBufferT[face->b].x;
quad[1].y = vertexBufferT[face->b].y;
quad[2].x = vertexBufferT[face->c].x;
quad[2].y = vertexBufferT[face->c].y;
quad[3].x = vertexBufferT[face->d].x;
quad[3].y = vertexBufferT[face->d].y;
quad[0].u = vertexBuffer[face->a].u;
quad[0].v = vertexBuffer[face->a].v;
quad[1].u = vertexBuffer[face->b].u;
quad[1].v = vertexBuffer[face->b].v;
quad[2].u = vertexBuffer[face->c].u;
quad[2].v = vertexBuffer[face->c].v;
quad[3].u = vertexBuffer[face->d].u;
quad[3].v = vertexBuffer[face->d].v;
DrawTexturedFace(quad, spriteSheetID);
}
break;
case FACE_FLAG_COLOURED_3D:
if (vertexBufferT[face->a].z > 0 && vertexBufferT[face->b].z > 0 && vertexBufferT[face->c].z > 0 && vertexBufferT[face->d].z > 0) {
quad[0].x = SCREEN_CENTERX + projectionX * vertexBufferT[face->a].x / vertexBufferT[face->a].z;
quad[0].y = SCREEN_CENTERY - projectionY * vertexBufferT[face->a].y / vertexBufferT[face->a].z;
quad[1].x = SCREEN_CENTERX + projectionX * vertexBufferT[face->b].x / vertexBufferT[face->b].z;
quad[1].y = SCREEN_CENTERY - projectionY * vertexBufferT[face->b].y / vertexBufferT[face->b].z;
quad[2].x = SCREEN_CENTERX + projectionX * vertexBufferT[face->c].x / vertexBufferT[face->c].z;
quad[2].y = SCREEN_CENTERY - projectionY * vertexBufferT[face->c].y / vertexBufferT[face->c].z;
quad[3].x = SCREEN_CENTERX + projectionX * vertexBufferT[face->d].x / vertexBufferT[face->d].z;
quad[3].y = SCREEN_CENTERY - projectionY * vertexBufferT[face->d].y / vertexBufferT[face->d].z;
DrawFace(quad, face->colour);
}
break;
case FACE_FLAG_COLOURED_2D:
if (vertexBufferT[face->a].z >= 0 && vertexBufferT[face->b].z >= 0 && vertexBufferT[face->c].z >= 0
&& vertexBufferT[face->d].z >= 0) {
quad[0].x = vertexBufferT[face->a].x;
quad[0].y = vertexBufferT[face->a].y;
quad[1].x = vertexBufferT[face->b].x;
quad[1].y = vertexBufferT[face->b].y;
quad[2].x = vertexBufferT[face->c].x;
quad[2].y = vertexBufferT[face->c].y;
quad[3].x = vertexBufferT[face->d].x;
quad[3].y = vertexBufferT[face->d].y;
DrawFace(quad, face->colour);
}
break;
case FACE_FLAG_FADED:
if (vertexBufferT[face->a].z > 0 && vertexBufferT[face->b].z > 0 && vertexBufferT[face->c].z > 0 && vertexBufferT[face->d].z > 0) {
quad[0].x = SCREEN_CENTERX + projectionX * vertexBufferT[face->a].x / vertexBufferT[face->a].z;
quad[0].y = SCREEN_CENTERY - projectionY * vertexBufferT[face->a].y / vertexBufferT[face->a].z;
quad[1].x = SCREEN_CENTERX + projectionX * vertexBufferT[face->b].x / vertexBufferT[face->b].z;
quad[1].y = SCREEN_CENTERY - projectionY * vertexBufferT[face->b].y / vertexBufferT[face->b].z;
quad[2].x = SCREEN_CENTERX + projectionX * vertexBufferT[face->c].x / vertexBufferT[face->c].z;
quad[2].y = SCREEN_CENTERY - projectionY * vertexBufferT[face->c].y / vertexBufferT[face->c].z;
quad[3].x = SCREEN_CENTERX + projectionX * vertexBufferT[face->d].x / vertexBufferT[face->d].z;
quad[3].y = SCREEN_CENTERY - projectionY * vertexBufferT[face->d].y / vertexBufferT[face->d].z;
int fogStr = 0;
if ((drawList3D[i].depth - 0x8000) >> 8 >= 0)
fogStr = (drawList3D[i].depth - 0x8000) >> 8;
if (fogStr > fogStrength)
fogStr = fogStrength;
DrawFadedFace(quad, face->colour, fogColour, 0xFF - fogStr);
}
break;
case FACE_FLAG_TEXTURED_C:
if (vertexBufferT[face->a].z > 0) {
quad[0].x = SCREEN_CENTERX + projectionX * (vertexBufferT[face->a].x - vertexBuffer[face->b].u) / vertexBufferT[face->a].z;
quad[0].y = SCREEN_CENTERY - projectionY * (vertexBufferT[face->a].y + vertexBuffer[face->b].v) / vertexBufferT[face->a].z;
quad[1].x = SCREEN_CENTERX + projectionX * (vertexBufferT[face->a].x + vertexBuffer[face->b].u) / vertexBufferT[face->a].z;
quad[1].y = SCREEN_CENTERY - projectionY * (vertexBufferT[face->a].y + vertexBuffer[face->b].v) / vertexBufferT[face->a].z;
quad[2].x = SCREEN_CENTERX + projectionX * (vertexBufferT[face->a].x - vertexBuffer[face->b].u) / vertexBufferT[face->a].z;
quad[2].y = SCREEN_CENTERY - projectionY * (vertexBufferT[face->a].y - vertexBuffer[face->b].v) / vertexBufferT[face->a].z;
quad[3].x = SCREEN_CENTERX + projectionX * (vertexBufferT[face->a].x + vertexBuffer[face->b].u) / vertexBufferT[face->a].z;
quad[3].y = SCREEN_CENTERY - projectionY * (vertexBufferT[face->a].y - vertexBuffer[face->b].v) / vertexBufferT[face->a].z;
quad[0].u = vertexBuffer[face->a].u - vertexBuffer[face->c].u;
quad[0].v = vertexBuffer[face->a].v - vertexBuffer[face->c].v;
quad[1].u = vertexBuffer[face->c].u + vertexBuffer[face->a].u;
quad[1].v = vertexBuffer[face->a].v - vertexBuffer[face->c].v;
quad[2].u = vertexBuffer[face->a].u - vertexBuffer[face->c].u;
quad[2].v = vertexBuffer[face->a].v + vertexBuffer[face->c].v;
quad[3].u = vertexBuffer[face->c].u + vertexBuffer[face->a].u;
quad[3].v = vertexBuffer[face->a].v + vertexBuffer[face->c].v;
DrawTexturedFace(quad, face->colour);
}
break;
case FACE_FLAG_TEXTURED_D:
if (vertexBufferT[face->a].z > 0) {
quad[0].x = SCREEN_CENTERX + projectionX * (vertexBufferT[face->a].x - vertexBuffer[face->b].u) / vertexBufferT[face->a].z;
quad[0].y = SCREEN_CENTERY - projectionY * (vertexBufferT[face->a].y + vertexBuffer[face->b].v) / vertexBufferT[face->a].z;
quad[1].x = SCREEN_CENTERX + projectionX * (vertexBufferT[face->a].x + vertexBuffer[face->b].u) / vertexBufferT[face->a].z;
quad[1].y = SCREEN_CENTERY - projectionY * (vertexBufferT[face->a].y + vertexBuffer[face->b].v) / vertexBufferT[face->a].z;
quad[2].x = SCREEN_CENTERX + projectionX * (vertexBufferT[face->a].x - vertexBuffer[face->b].u) / vertexBufferT[face->a].z;
quad[2].y = SCREEN_CENTERY - projectionY * (vertexBufferT[face->a].y - vertexBuffer[face->b].v) / vertexBufferT[face->a].z;
quad[3].x = SCREEN_CENTERX + projectionX * (vertexBufferT[face->a].x + vertexBuffer[face->b].u) / vertexBufferT[face->a].z;
quad[3].y = SCREEN_CENTERY - projectionY * (vertexBufferT[face->a].y - vertexBuffer[face->b].v) / vertexBufferT[face->a].z;
quad[0].u = vertexBuffer[face->a].u - vertexBuffer[face->c].u;
quad[0].v = vertexBuffer[face->a].v - vertexBuffer[face->c].v;
quad[1].u = vertexBuffer[face->c].u + vertexBuffer[face->a].u;
quad[1].v = vertexBuffer[face->a].v - vertexBuffer[face->c].v;
quad[2].u = vertexBuffer[face->a].u - vertexBuffer[face->c].u;
quad[2].v = vertexBuffer[face->a].v + vertexBuffer[face->c].v;
quad[3].u = vertexBuffer[face->c].u + vertexBuffer[face->a].u;
quad[3].v = vertexBuffer[face->a].v + vertexBuffer[face->c].v;
DrawTexturedFaceBlended(quad, face->colour);
}
break;
case FACE_FLAG_3DSPRITE:
if (vertexBufferT[face->a].z > 0) {
int xpos = SCREEN_CENTERX + projectionX * vertexBufferT[face->a].x / vertexBufferT[face->a].z;
int ypos = SCREEN_CENTERY - projectionY * vertexBufferT[face->a].y / vertexBufferT[face->a].z;
ObjectScript *scriptInfo = &objectScriptList[vertexBuffer[face->a].u];
SpriteFrame *frame = &scriptFrames[scriptInfo->frameListOffset + vertexBuffer[face->b].u];
switch (vertexBuffer[face->a].v) {
case FX_SCALE:
DrawSpriteScaled(vertexBuffer[face->b].v, xpos, ypos, -frame->pivotX, -frame->pivotY, vertexBuffer[face->c].u,
vertexBuffer[face->c].u, frame->width, frame->height, frame->sprX, frame->sprY,
scriptInfo->spriteSheetID);
break;
case FX_ROTATE:
DrawSpriteRotated(vertexBuffer[face->b].v, xpos, ypos, -frame->pivotX, -frame->pivotY, frame->sprX, frame->sprY,
frame->width, frame->height, vertexBuffer[face->c].v, scriptInfo->spriteSheetID);
break;
case FX_ROTOZOOM:
DrawSpriteRotozoom(vertexBuffer[face->b].v, xpos, ypos, -frame->pivotX, -frame->pivotY, frame->sprX, frame->sprY,
frame->width, frame->height, vertexBuffer[face->c].v, vertexBuffer[face->c].u,
scriptInfo->spriteSheetID);
break;
}
}
break;
}
}
}
void processScanEdge(Vertex *vertA, Vertex *vertB)
{
int bottom, top;
if (vertA->y == vertB->y)
return;
if (vertA->y >= vertB->y) {
top = vertB->y;
bottom = vertA->y + 1;
}
else {
top = vertA->y;
bottom = vertB->y + 1;
}
if (top > SCREEN_YSIZE - 1 || bottom < 0)
return;
if (bottom > SCREEN_YSIZE)
bottom = SCREEN_YSIZE;
int fullX = vertA->x << 16;
int deltaX = ((vertB->x - vertA->x) << 16) / (vertB->y - vertA->y);
if (top < 0) {
fullX -= top * deltaX;
top = 0;
}
for (int i = top; i < bottom; ++i) {
int trueX = fullX >> 16;
if (trueX < faceLineStart[i])
faceLineStart[i] = trueX;
if (trueX > faceLineEnd[i])
faceLineEnd[i] = trueX;
fullX += deltaX;
}
}
void processScanEdgeUV(Vertex *vertA, Vertex *vertB)
{
int bottom, top;
if (vertA->y == vertB->y)
return;
if (vertA->y >= vertB->y) {
top = vertB->y;
bottom = vertA->y + 1;
}
else {
top = vertA->y;
bottom = vertB->y + 1;
}
if (top > SCREEN_YSIZE - 1 || bottom < 0)
return;
if (bottom > SCREEN_YSIZE)
bottom = SCREEN_YSIZE;
int fullX = vertA->x << 16;
int fullU = vertA->u << 16;
int fullV = vertA->v << 16;
int deltaX = ((vertB->x - vertA->x) << 16) / (vertB->y - vertA->y);
int deltaU = 0;
if (vertA->u != vertB->u)
deltaU = ((vertB->u - vertA->u) << 16) / (vertB->y - vertA->y);
int deltaV = 0;
if (vertA->v != vertB->v) {
deltaV = ((vertB->v - vertA->v) << 16) / (vertB->y - vertA->y);
}
if (top < 0) {
fullX -= top * deltaX;
fullU -= top * deltaU;
fullV -= top * deltaV;
top = 0;
}
for (int i = top; i < bottom; ++i) {
int trueX = fullX >> 16;
if (trueX < faceLineStart[i]) {
faceLineStart[i] = trueX;
faceLineStartU[i] = fullU;
faceLineStartV[i] = fullV;
}
if (trueX > faceLineEnd[i]) {
faceLineEnd[i] = trueX;
faceLineEndU[i] = fullU;
faceLineEndV[i] = fullV;
}
fullX += deltaX;
fullU += deltaU;
fullV += deltaV;
}
}
| 47.32807 | 159 | 0.506357 | 0xR00KIE |
f5e1cbce5c3d007f32975bb9b4f8833b3732997d | 766 | cpp | C++ | src/States/Gamestate.cpp | PyroFlareX/CraftGame | aee39f0406da9bc92ed3850f753c60d173af2c97 | [
"MIT"
] | 3 | 2021-02-06T00:15:28.000Z | 2021-02-23T19:04:59.000Z | src/States/Gamestate.cpp | PyroFlareX/CraftGame | aee39f0406da9bc92ed3850f753c60d173af2c97 | [
"MIT"
] | null | null | null | src/States/Gamestate.cpp | PyroFlareX/CraftGame | aee39f0406da9bc92ed3850f753c60d173af2c97 | [
"MIT"
] | null | null | null | #include "Gamestate.h"
GameState::GameState(Application& app) : Basestate(app)
{
app.getCam().follow(m_player);
m_world.setPlayerCam(&app.getCam());
vn::Transform t;
vn::GameObject gobj(t);
m_gameObjects.push_back(gobj);
}
GameState::~GameState()
{
m_world.isRunning = false;
}
bool GameState::input()
{
vInput = Input::getInput();
m_player.getInput(vInput, false);
return false;
}
void GameState::update(float dt)
{
m_player.update(dt);
m_world.update(dt);
for (auto& obj : m_gameObjects)
{
obj.update();
}
}
void GameState::lateUpdate(Camera* cam)
{
}
void GameState::render(Renderer* renderer)
{
m_world.renderWorld(*renderer);
for (auto& obj : m_gameObjects)
{
obj.getCurrentTransform();
renderer->drawObject(obj);
}
}
| 13.438596 | 55 | 0.690601 | PyroFlareX |
f5e2b839a8077a9e3271d6a1ce7fd4decee169a9 | 5,438 | hpp | C++ | openstudiocore/src/model/FanConstantVolume_Impl.hpp | ORNL-BTRIC/OpenStudio | 878f94bebf6f025445d1373e8b2304ececac16d8 | [
"blessing"
] | null | null | null | openstudiocore/src/model/FanConstantVolume_Impl.hpp | ORNL-BTRIC/OpenStudio | 878f94bebf6f025445d1373e8b2304ececac16d8 | [
"blessing"
] | null | null | null | openstudiocore/src/model/FanConstantVolume_Impl.hpp | ORNL-BTRIC/OpenStudio | 878f94bebf6f025445d1373e8b2304ececac16d8 | [
"blessing"
] | null | null | null | /**********************************************************************
* Copyright (c) 2008-2014, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#ifndef MODEL_FANCONSTANTVOLUME_IMPL_HPP
#define MODEL_FANCONSTANTVOLUME_IMPL_HPP
#include <model/StraightComponent_Impl.hpp>
namespace openstudio {
namespace model {
class Schedule;
namespace detail {
class MODEL_API FanConstantVolume_Impl : public StraightComponent_Impl {
Q_OBJECT;
Q_PROPERTY(double fanEfficiency READ fanEfficiency WRITE setFanEfficiency);
Q_PROPERTY(double pressureRise READ pressureRise WRITE setPressureRise);
Q_PROPERTY(boost::optional<double> maximumFlowRate READ maximumFlowRate WRITE setMaximumFlowRate);
Q_PROPERTY(double motorEfficiency READ motorEfficiency WRITE setMotorEfficiency);
Q_PROPERTY(double motorInAirstreamFraction READ motorInAirstreamFraction WRITE setMotorInAirstreamFraction);
Q_PROPERTY(std::string endUseSubcategory READ endUseSubcategory WRITE setEndUseSubcategory);
Q_PROPERTY( boost::optional<openstudio::model::ModelObject> availabilitySchedule
READ availabilityScheduleAsModelObject
WRITE setAvailibiltyScheduleAsModelObject);
public:
/** @name Constructors and Destructors */
//@{
// constructor
FanConstantVolume_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle);
// construct from workspace
FanConstantVolume_Impl(const openstudio::detail::WorkspaceObject_Impl& other,
Model_Impl* model,
bool keepHandle);
// copy constructor
FanConstantVolume_Impl(const FanConstantVolume_Impl& other,
Model_Impl* model,
bool keepHandle);
// virtual destructor
virtual ~FanConstantVolume_Impl();
//@}
/** @name Virtual Methods */
//@{
virtual std::vector<openstudio::IdfObject> remove();
virtual ModelObject clone(Model model) const;
// Get all output variable names that could be associated with this object.
virtual const std::vector<std::string>& outputVariableNames() const;
virtual IddObjectType iddObjectType() const;
virtual std::vector<ScheduleTypeKey> getScheduleTypeKeys(const Schedule& schedule) const;
virtual unsigned inletPort();
virtual unsigned outletPort();
virtual bool addToNode(Node & node);
//@}
/** @name Getters and Setters */
//@{
Schedule availabilitySchedule() const;
bool setAvailabilitySchedule(Schedule& s);
// Get FanEfficiency
double fanEfficiency();
// Set fanEfficiency
void setFanEfficiency(double val);
// Get PressureRise
double pressureRise();
// Set PressureRise
void setPressureRise(double val);
// Get MotorEfficiency
double motorEfficiency();
// Set MotorEfficiency
void setMotorEfficiency(double val);
// Get MotorInAirstreamFraction
double motorInAirstreamFraction();
// Set MotorInAirstreamFraction
void setMotorInAirstreamFraction(double val);
// Get EndUseSubcategory
std::string endUseSubcategory();
// Set EndUseSubcategory
void setEndUseSubcategory(std::string val);
boost::optional<double> maximumFlowRate() const;
OSOptionalQuantity getMaximumFlowRate(bool returnIP=false) const;
bool isMaximumFlowRateAutosized() const;
bool setMaximumFlowRate(boost::optional<double> maximumFlowRate);
bool setMaximumFlowRate(const OSOptionalQuantity& maximumFlowRate);
void resetMaximumFlowRate();
void autosizeMaximumFlowRate();
//@}
private:
REGISTER_LOGGER("openstudio.model.FanConstantVolume");
// Optional getters for use by methods like children() so can remove() if the constructor fails.
// There are other ways for the public versions of these getters to fail--perhaps all required
// objects should be returned as boost::optionals
boost::optional<Schedule> optionalAvailabilitySchedule() const;
boost::optional<ModelObject> availabilityScheduleAsModelObject() const;
bool setAvailibiltyScheduleAsModelObject(const boost::optional<ModelObject>& modelObject);
virtual boost::optional<HVACComponent> containingHVACComponent() const;
virtual boost::optional<ZoneHVACComponent> containingZoneHVACComponent() const;
};
} // detail
} // model
} // openstudio
#endif // MODEL_FANCONSTANTVOLUME_IMPL_HPP
| 33.567901 | 113 | 0.691247 | ORNL-BTRIC |
f5e470541dfdb7a5b2216bea978afdfdd1a6dd40 | 3,849 | cpp | C++ | Firmware/Marlin/src/HAL/shared/I2cEeprom.cpp | PavelTajdus/Anet-A8-PLUS-Dual-Color-Rebuild | 76ce07b6c8f52962c1251d40beb6de26301409ef | [
"MIT"
] | 1 | 2019-10-22T11:04:05.000Z | 2019-10-22T11:04:05.000Z | Firmware/Marlin/src/HAL/shared/I2cEeprom.cpp | PavelTajdus/Anet-A8-PLUS-Dual-Color-Rebuild | 76ce07b6c8f52962c1251d40beb6de26301409ef | [
"MIT"
] | null | null | null | Firmware/Marlin/src/HAL/shared/I2cEeprom.cpp | PavelTajdus/Anet-A8-PLUS-Dual-Color-Rebuild | 76ce07b6c8f52962c1251d40beb6de26301409ef | [
"MIT"
] | 2 | 2019-07-22T20:31:15.000Z | 2021-08-01T00:15:38.000Z | /**
* Marlin 3D Printer Firmware
* Copyright (c) 2019 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
* Description: functions for I2C connected external EEPROM.
* Not platform dependent.
*/
#include "../../inc/MarlinConfig.h"
#if ENABLED(I2C_EEPROM)
#include "../HAL.h"
#include <Wire.h>
// ------------------------
// Private Variables
// ------------------------
static uint8_t eeprom_device_address = 0x50;
// ------------------------
// Public functions
// ------------------------
static void eeprom_init(void) {
static bool eeprom_initialized = false;
if (!eeprom_initialized) {
Wire.begin();
eeprom_initialized = true;
}
}
void eeprom_write_byte(uint8_t *pos, unsigned char value) {
unsigned eeprom_address = (unsigned) pos;
eeprom_init();
Wire.beginTransmission(I2C_ADDRESS(eeprom_device_address));
Wire.write((int)(eeprom_address >> 8)); // MSB
Wire.write((int)(eeprom_address & 0xFF)); // LSB
Wire.write(value);
Wire.endTransmission();
// wait for write cycle to complete
// this could be done more efficiently with "acknowledge polling"
delay(5);
}
// WARNING: address is a page address, 6-bit end will wrap around
// also, data can be maximum of about 30 bytes, because the Wire library has a buffer of 32 bytes
void eeprom_update_block(const void *pos, void* eeprom_address, size_t n) {
eeprom_init();
Wire.beginTransmission(I2C_ADDRESS(eeprom_device_address));
Wire.write((int)((unsigned)eeprom_address >> 8)); // MSB
Wire.write((int)((unsigned)eeprom_address & 0xFF)); // LSB
Wire.endTransmission();
uint8_t *ptr = (uint8_t*)pos;
uint8_t flag = 0;
Wire.requestFrom(eeprom_device_address, (byte)n);
for (byte c = 0; c < n && Wire.available(); c++)
flag |= Wire.read() ^ ptr[c];
if (flag) {
Wire.beginTransmission(I2C_ADDRESS(eeprom_device_address));
Wire.write((int)((unsigned)eeprom_address >> 8)); // MSB
Wire.write((int)((unsigned)eeprom_address & 0xFF)); // LSB
Wire.write((uint8_t*)pos, n);
Wire.endTransmission();
// wait for write cycle to complete
// this could be done more efficiently with "acknowledge polling"
delay(5);
}
}
uint8_t eeprom_read_byte(uint8_t *pos) {
unsigned eeprom_address = (unsigned)pos;
eeprom_init();
Wire.beginTransmission(I2C_ADDRESS(eeprom_device_address));
Wire.write((int)(eeprom_address >> 8)); // MSB
Wire.write((int)(eeprom_address & 0xFF)); // LSB
Wire.endTransmission();
Wire.requestFrom(eeprom_device_address, (byte)1);
return Wire.available() ? Wire.read() : 0xFF;
}
// Don't read more than 30..32 bytes at a time!
void eeprom_read_block(void* pos, const void* eeprom_address, size_t n) {
eeprom_init();
Wire.beginTransmission(I2C_ADDRESS(eeprom_device_address));
Wire.write((int)((unsigned)eeprom_address >> 8)); // MSB
Wire.write((int)((unsigned)eeprom_address & 0xFF)); // LSB
Wire.endTransmission();
Wire.requestFrom(eeprom_device_address, (byte)n);
for (byte c = 0; c < n; c++ )
if (Wire.available()) *((uint8_t*)pos + c) = Wire.read();
}
#endif // I2C_EEPROM
| 30.792 | 97 | 0.683554 | PavelTajdus |
f5e4e110abac78e28c10ed77c7c9d583be5de714 | 5,827 | cpp | C++ | Modules/QtWidgets/src/QmitkDataStorageComboBoxWithSelectNone.cpp | samsmu/MITK | c93dce6dc38d8f4c961de4440e4dd113b9841c8c | [
"BSD-3-Clause"
] | 5 | 2015-02-05T10:58:41.000Z | 2019-04-17T15:04:07.000Z | Modules/QtWidgets/src/QmitkDataStorageComboBoxWithSelectNone.cpp | kometa-dev/MITK | 984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d | [
"BSD-3-Clause"
] | 141 | 2015-03-03T06:52:01.000Z | 2020-12-10T07:28:14.000Z | Modules/QtWidgets/src/QmitkDataStorageComboBoxWithSelectNone.cpp | kometa-dev/MITK | 984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d | [
"BSD-3-Clause"
] | 4 | 2015-02-19T06:48:13.000Z | 2020-06-19T16:20:25.000Z | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) University College London (UCL).
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkDataStorageComboBoxWithSelectNone.h"
#include <QDebug>
const QString QmitkDataStorageComboBoxWithSelectNone::ZERO_ENTRY_STRING = "please select";
//-----------------------------------------------------------------------------
QmitkDataStorageComboBoxWithSelectNone::QmitkDataStorageComboBoxWithSelectNone(
QWidget* parent,
bool autoSelectNewNodes )
: QmitkDataStorageComboBox(parent, autoSelectNewNodes)
, m_CurrentPath("")
{
}
//-----------------------------------------------------------------------------
QmitkDataStorageComboBoxWithSelectNone::QmitkDataStorageComboBoxWithSelectNone(
mitk::DataStorage* dataStorage,
const mitk::NodePredicateBase* predicate,
QWidget* parent, bool autoSelectNewNodes )
: QmitkDataStorageComboBox(dataStorage, predicate, parent, autoSelectNewNodes)
{
}
//-----------------------------------------------------------------------------
QmitkDataStorageComboBoxWithSelectNone::~QmitkDataStorageComboBoxWithSelectNone()
{
}
//-----------------------------------------------------------------------------
int QmitkDataStorageComboBoxWithSelectNone::Find( const mitk::DataNode* dataNode ) const
{
int index = QmitkDataStorageComboBox::Find(dataNode);
if (index != -1)
{
index += 1;
}
return index;
}
//-----------------------------------------------------------------------------
mitk::DataNode::Pointer QmitkDataStorageComboBoxWithSelectNone::GetNode( int index ) const
{
mitk::DataNode::Pointer result = nullptr;
if (this->HasIndex(index))
{
if (index != 0)
{
result = m_Nodes.at(index - 1);
}
}
return result;
}
//-----------------------------------------------------------------------------
mitk::DataNode::Pointer QmitkDataStorageComboBoxWithSelectNone::GetSelectedNode() const
{
return this->GetNode(this->currentIndex());
}
//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::SetSelectedNode(const mitk::DataNode::Pointer& node)
{
int currentIndex = -1;
for (int i = 0; i < static_cast<int>(m_Nodes.size()); i++)
{
if (m_Nodes[i] == node.GetPointer())
{
currentIndex = i;
break;
}
}
if (currentIndex == -1)
{
// didn't find it, so set the value to 0.
currentIndex = 0;
}
else
{
currentIndex += 1; // because the combo box contains "please select" at position zero.
}
this->setCurrentIndex(currentIndex);
}
//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::RemoveNode( int index )
{
if(index > 0 && this->HasIndex(index))
{
// remove itk::Event observer
mitk::DataNode* dataNode = m_Nodes.at(index - 1);
// get name property first
mitk::BaseProperty* nameProperty = dataNode->GetProperty("name");
// if prop exists remove modified listener
if(nameProperty)
{
nameProperty->RemoveObserver(m_NodesModifiedObserverTags[index-1]);
// remove name property map
m_PropertyToNode.erase(dataNode);
}
// then remove delete listener on the node itself
dataNode->RemoveObserver(m_NodesDeleteObserverTags[index-1]);
// remove observer tags from lists
m_NodesModifiedObserverTags.erase(m_NodesModifiedObserverTags.begin()+index-1);
m_NodesDeleteObserverTags.erase(m_NodesDeleteObserverTags.begin()+index-1);
// remove node name from combobox
this->removeItem(index);
// remove node from node vector
m_Nodes.erase(m_Nodes.begin()+index-1);
}
}
//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::SetNode(int index, const mitk::DataNode* dataNode)
{
if(index > 0 && this->HasIndex(index))
{
// if node identical, we only update the name in the QComboBoxItem
if( dataNode == this->m_Nodes.at(index-1 ) )
{
this->setItemText(index, GetDisplayedNodeName(dataNode));
}
else
QmitkDataStorageComboBox::InsertNode(index - 1, dataNode);
}
}
//-----------------------------------------------------------------------------
bool QmitkDataStorageComboBoxWithSelectNone::HasIndex(unsigned int index) const
{
return (m_Nodes.size() > 0 && index <= m_Nodes.size());
}
//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::InsertNode(int index, const mitk::DataNode* dataNode)
{
if (index != 0)
{
QmitkDataStorageComboBox::InsertNode(index - 1, dataNode);
}
}
//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::Reset()
{
QmitkDataStorageComboBox::Reset();
this->insertItem(0, ZERO_ENTRY_STRING);
}
//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::SetZeroEntryText(const QString& zeroEntryString)
{
this->setItemText(0, zeroEntryString);
}
//-----------------------------------------------------------------------------
QString QmitkDataStorageComboBoxWithSelectNone::currentValue() const
{
return m_CurrentPath;
}
//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::setCurrentValue(const QString& path)
{
m_CurrentPath = path;
}
| 28.704433 | 98 | 0.563755 | samsmu |
f5e5fd09b7ba9e62476b0c3b6054c00c0cbcc769 | 1,394 | cpp | C++ | tools/gfx/d3d12/descriptor-heap-d3d12.cpp | apanteleev/slang | 11da2fb2051894b3cc873748cfc8f47588d8af93 | [
"MIT"
] | null | null | null | tools/gfx/d3d12/descriptor-heap-d3d12.cpp | apanteleev/slang | 11da2fb2051894b3cc873748cfc8f47588d8af93 | [
"MIT"
] | null | null | null | tools/gfx/d3d12/descriptor-heap-d3d12.cpp | apanteleev/slang | 11da2fb2051894b3cc873748cfc8f47588d8af93 | [
"MIT"
] | null | null | null |
#include "descriptor-heap-d3d12.h"
namespace gfx {
using namespace Slang;
D3D12DescriptorHeap::D3D12DescriptorHeap():
m_totalSize(0),
m_currentIndex(0),
m_descriptorSize(0)
{
}
Result D3D12DescriptorHeap::init(ID3D12Device* device, int size, D3D12_DESCRIPTOR_HEAP_TYPE type, D3D12_DESCRIPTOR_HEAP_FLAGS flags)
{
m_device = device;
D3D12_DESCRIPTOR_HEAP_DESC srvHeapDesc = {};
srvHeapDesc.NumDescriptors = size;
srvHeapDesc.Flags = flags;
srvHeapDesc.Type = type;
SLANG_RETURN_ON_FAIL(device->CreateDescriptorHeap(&srvHeapDesc, IID_PPV_ARGS(m_heap.writeRef())));
m_descriptorSize = device->GetDescriptorHandleIncrementSize(type);
m_totalSize = size;
m_heapFlags = flags;
return SLANG_OK;
}
Result D3D12DescriptorHeap::init(ID3D12Device* device, const D3D12_CPU_DESCRIPTOR_HANDLE* handles, int numHandles, D3D12_DESCRIPTOR_HEAP_TYPE type, D3D12_DESCRIPTOR_HEAP_FLAGS flags)
{
SLANG_RETURN_ON_FAIL(init(device, numHandles, type, flags));
D3D12_CPU_DESCRIPTOR_HANDLE dst = m_heap->GetCPUDescriptorHandleForHeapStart();
// Copy them all
for (int i = 0; i < numHandles; i++, dst.ptr += m_descriptorSize)
{
D3D12_CPU_DESCRIPTOR_HANDLE src = handles[i];
if (src.ptr != 0)
{
device->CopyDescriptorsSimple(1, dst, src, type);
}
}
return SLANG_OK;
}
} // namespace gfx
| 27.333333 | 182 | 0.721664 | apanteleev |
f5ea3cf8a5b7cf87ebc0f230d353528bf0872a35 | 881 | cpp | C++ | src/main/cpp/commands/TransferSecondBall.cpp | ParadigmShift1259/FRC_Robot_2022 | 646bab32b4749fde32b0c68a5ab2bfbf704ac4a5 | [
"BSD-3-Clause",
"MIT"
] | null | null | null | src/main/cpp/commands/TransferSecondBall.cpp | ParadigmShift1259/FRC_Robot_2022 | 646bab32b4749fde32b0c68a5ab2bfbf704ac4a5 | [
"BSD-3-Clause",
"MIT"
] | null | null | null | src/main/cpp/commands/TransferSecondBall.cpp | ParadigmShift1259/FRC_Robot_2022 | 646bab32b4749fde32b0c68a5ab2bfbf704ac4a5 | [
"BSD-3-Clause",
"MIT"
] | null | null | null | #include "commands/TransferSecondBall.h"
#include "Constants.h"
using namespace IntakeConstants;
using namespace TransferConstants;
TransferSecondBall::TransferSecondBall(TransferSubsystem& transfer, IntakeSubsystem& intake, double speed)
: m_transfer(transfer)
, m_intake(intake)
, m_speed(speed)
, m_photoeyeCount(0)
{
AddRequirements({&transfer, &intake});
}
void TransferSecondBall::Initialize()
{
m_timer.Start();
m_photoeyeCount = 0;
}
void TransferSecondBall::Execute()
{
m_transfer.SetTransfer(kSpeedFiring);
m_intake.Set(kIngestHigh);
}
bool TransferSecondBall::IsFinished() {
if (m_transfer.GetTransferPhotoeye()) {
m_photoeyeCount++;
}
return m_transfer.GetTransferPhotoeye();
}
void TransferSecondBall::End(bool interrupted)
{
m_transfer.SetTransfer(0);
m_intake.Set(0);
} | 22.025 | 107 | 0.708286 | ParadigmShift1259 |
f5eabd94847d0f4f1a944222a62223fe4442fff8 | 900 | cpp | C++ | Upsolving/URI/2749.cpp | rodrigoAMF7/Notebook---Maratonas | 06b38197a042bfbd27b20f707493e0a19fda7234 | [
"MIT"
] | 4 | 2019-01-25T21:22:55.000Z | 2019-03-20T18:04:01.000Z | Upsolving/URI/2749.cpp | rodrigoAMF/competitive-programming-notebook | 06b38197a042bfbd27b20f707493e0a19fda7234 | [
"MIT"
] | null | null | null | Upsolving/URI/2749.cpp | rodrigoAMF/competitive-programming-notebook | 06b38197a042bfbd27b20f707493e0a19fda7234 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
// Nome de Tipos
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
// Valores
#define INF 0x3F3F3F3F
#define LINF 0x3F3F3F3F3F3F3F3FLL
#define DINF (double)1e+30
#define EPS (double)1e-9
#define RAD(x) (double)(x*PI)/180.0
#define PCT(x,y) (double)x*100.0/y
// Atalhos
#define F first
#define S second
#define PB push_back
#define MP make_pair
#define forn(i, n) for ( int i = 0; i < (n); ++i )
using namespace std;
int main(){
forn(i, 39){
printf("-");
}
cout << endl;
forn(j, 5){
forn(i, 39){
if(i == 0 || i == 38)
printf("|");
else if(i == 1 && j==0){
printf("x = 35");
i+=5;
}else if(i == 16 && j==2){
printf("x = 35");
i+=5;
}else if(i == 32 && j==4){
printf("x = 35");
i+=5;
}else
printf(" ");
}
cout << endl;
}
forn(i, 39){
printf("-");
}
cout << endl;
return 0;
} | 15.789474 | 50 | 0.555556 | rodrigoAMF7 |
f5f1ffeb030613fd3ecc74b907d7c963775b3244 | 11,700 | cpp | C++ | thirdparty/ULib/src/ulib/internal/common.cpp | liftchampion/nativejson-benchmark | 6d575ffa4359a5c4230f74b07d994602a8016fb5 | [
"MIT"
] | null | null | null | thirdparty/ULib/src/ulib/internal/common.cpp | liftchampion/nativejson-benchmark | 6d575ffa4359a5c4230f74b07d994602a8016fb5 | [
"MIT"
] | null | null | null | thirdparty/ULib/src/ulib/internal/common.cpp | liftchampion/nativejson-benchmark | 6d575ffa4359a5c4230f74b07d994602a8016fb5 | [
"MIT"
] | null | null | null | // ============================================================================
//
// = LIBRARY
// ULib - c++ library
//
// = FILENAME
// common.cpp
//
// = AUTHOR
// Stefano Casazza
//
// ============================================================================
/*
* _oo0oo_
* o8888888o
* 88" . "88
* (| -_- |)
* 0\ = /0
* ___/`---'\___
* .' \\| |// '.
* / \\||| : |||// \
* / _||||| -:- |||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' |_/ |
* \ .-\__ '-' ___/-. /
* ___'. .' /--.--\ `. .'___
* ."" '< `.___\_<|>_/___.' >' "".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `_. \_ __\ /__ _/ .-` / /
* =====`-.____`.___ \_____/___.-`___.-'=====
* `=---='
*
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
#include <ulib/file.h>
#include <ulib/json/value.h>
#include <ulib/application.h>
#include <ulib/utility/interrupt.h>
#ifndef HAVE_POLL_H
# include <ulib/notifier.h>
# include <ulib/event/event_time.h>
#endif
#ifdef U_STDCPP_ENABLE
# if defined(HAVE_CXX14) && GCC_VERSION_NUM > 60100 && defined(HAVE_ARCH64)
# include "./itoa.h"
# endif
#else
U_EXPORT bool __cxa_guard_acquire() { return 1; }
U_EXPORT bool __cxa_guard_release() { return 1; }
U_EXPORT void* operator new( size_t n) { return malloc(n); }
U_EXPORT void* operator new[](size_t n) { return malloc(n); }
U_EXPORT void operator delete( void* p) { free(p); }
U_EXPORT void operator delete[](void* p) { free(p); }
# ifdef __MINGW32__
U_EXPORT void operator delete( void* p, unsigned int) { free(p); }
U_EXPORT void operator delete[](void* p, unsigned int) { free(p); }
# else
U_EXPORT void operator delete( void* p, long unsigned int) { free(p); }
U_EXPORT void operator delete[](void* p, long unsigned int) { free(p); }
# endif
#endif
const double u_pow10[309] = { // 1e-0...1e308: 309 * 8 bytes = 2472 bytes
1,
1e+1, 1e+2, 1e+3, 1e+4, 1e+5, 1e+6, 1e+7, 1e+8, 1e+9, 1e+10, 1e+11, 1e+12, 1e+13, 1e+14, 1e+15, 1e+16, 1e+17, 1e+18, 1e+19, 1e+20,
1e+21, 1e+22, 1e+23, 1e+24, 1e+25, 1e+26, 1e+27, 1e+28, 1e+29, 1e+30, 1e+31, 1e+32, 1e+33, 1e+34, 1e+35, 1e+36, 1e+37, 1e+38, 1e+39, 1e+40,
1e+41, 1e+42, 1e+43, 1e+44, 1e+45, 1e+46, 1e+47, 1e+48, 1e+49, 1e+50, 1e+51, 1e+52, 1e+53, 1e+54, 1e+55, 1e+56, 1e+57, 1e+58, 1e+59, 1e+60,
1e+61, 1e+62, 1e+63, 1e+64, 1e+65, 1e+66, 1e+67, 1e+68, 1e+69, 1e+70, 1e+71, 1e+72, 1e+73, 1e+74, 1e+75, 1e+76, 1e+77, 1e+78, 1e+79, 1e+80,
1e+81, 1e+82, 1e+83, 1e+84, 1e+85, 1e+86, 1e+87, 1e+88, 1e+89, 1e+90, 1e+91, 1e+92, 1e+93, 1e+94, 1e+95, 1e+96, 1e+97, 1e+98, 1e+99, 1e+100,
1e+101,1e+102,1e+103,1e+104,1e+105,1e+106,1e+107,1e+108,1e+109,1e+110,1e+111,1e+112,1e+113,1e+114,1e+115,1e+116,1e+117,1e+118,1e+119,1e+120,
1e+121,1e+122,1e+123,1e+124,1e+125,1e+126,1e+127,1e+128,1e+129,1e+130,1e+131,1e+132,1e+133,1e+134,1e+135,1e+136,1e+137,1e+138,1e+139,1e+140,
1e+141,1e+142,1e+143,1e+144,1e+145,1e+146,1e+147,1e+148,1e+149,1e+150,1e+151,1e+152,1e+153,1e+154,1e+155,1e+156,1e+157,1e+158,1e+159,1e+160,
1e+161,1e+162,1e+163,1e+164,1e+165,1e+166,1e+167,1e+168,1e+169,1e+170,1e+171,1e+172,1e+173,1e+174,1e+175,1e+176,1e+177,1e+178,1e+179,1e+180,
1e+181,1e+182,1e+183,1e+184,1e+185,1e+186,1e+187,1e+188,1e+189,1e+190,1e+191,1e+192,1e+193,1e+194,1e+195,1e+196,1e+197,1e+198,1e+199,1e+200,
1e+201,1e+202,1e+203,1e+204,1e+205,1e+206,1e+207,1e+208,1e+209,1e+210,1e+211,1e+212,1e+213,1e+214,1e+215,1e+216,1e+217,1e+218,1e+219,1e+220,
1e+221,1e+222,1e+223,1e+224,1e+225,1e+226,1e+227,1e+228,1e+229,1e+230,1e+231,1e+232,1e+233,1e+234,1e+235,1e+236,1e+237,1e+238,1e+239,1e+240,
1e+241,1e+242,1e+243,1e+244,1e+245,1e+246,1e+247,1e+248,1e+249,1e+250,1e+251,1e+252,1e+253,1e+254,1e+255,1e+256,1e+257,1e+258,1e+259,1e+260,
1e+261,1e+262,1e+263,1e+264,1e+265,1e+266,1e+267,1e+268,1e+269,1e+270,1e+271,1e+272,1e+273,1e+274,1e+275,1e+276,1e+277,1e+278,1e+279,1e+280,
1e+281,1e+282,1e+283,1e+284,1e+285,1e+286,1e+287,1e+288,1e+289,1e+290,1e+291,1e+292,1e+293,1e+294,1e+295,1e+296,1e+297,1e+298,1e+299,1e+300,
1e+301,1e+302,1e+303,1e+304,1e+305,1e+306,1e+307,1e+308
};
#if defined(USE_LIBSSL) && OPENSSL_VERSION_NUMBER < 0x10100000L
# include <openssl/ssl.h>
# include <openssl/rand.h>
# include <openssl/conf.h>
#endif
#ifndef HAVE_OLD_IOSTREAM
# include "./dtoa.h"
#endif
static struct ustringrep u_empty_string_rep_storage = {
# ifdef DEBUG
(void*)U_CHECK_MEMORY_SENTINEL, /* memory_error (_this) */
# endif
# if defined(U_SUBSTR_INC_REF) || defined(DEBUG)
0, /* parent - substring increment reference of source string */
# ifdef DEBUG
0, /* child - substring capture event 'DEAD OF SOURCE STRING WITH CHILD ALIVE'... */
# endif
# endif
0, /* _length */
0, /* _capacity */
0, /* references */
"" /* str - NB: we need an address (see c_str() or isNullTerminated()) and must be null terminated... */
};
static struct ustring u_empty_string_storage = { &u_empty_string_rep_storage };
uustring ULib::uustringnull = { &u_empty_string_storage };
uustringrep ULib::uustringrepnull = { &u_empty_string_rep_storage };
void ULib::init(const char* mempool, char** argv)
{
u_init_ulib(argv);
U_TRACE(1, "ULib::init(%S,%p)", mempool, argv)
// conversion number => string
#ifndef HAVE_OLD_IOSTREAM
u_dbl2str = dtoa_rapidjson;
#endif
#ifdef DEBUG
char buffer[32];
UMemoryPool::obj_class = "";
UMemoryPool::func_call = __PRETTY_FUNCTION__;
U_INTERNAL_ASSERT_EQUALS(u_dbl2str(1234567890, buffer)-buffer, 12)
U_INTERNAL_ASSERT_EQUALS(memcmp(buffer, "1234567890.0", 12), 0)
U_INTERNAL_ASSERT_EQUALS(u_num2str64(1234567890, buffer)-buffer, 10)
U_INTERNAL_ASSERT_EQUALS(memcmp(buffer, "1234567890", 10), 0)
#endif
#if defined(HAVE_CXX14) && GCC_VERSION_NUM > 60100 && defined(HAVE_ARCH64)
u_num2str32 = itoa_fwd;
u_num2str64 = itoa_fwd;
U_INTERNAL_ASSERT_EQUALS(u_num2str64(1234567890, buffer)-buffer, 10)
U_INTERNAL_DUMP("buffer = %.10S", buffer)
U_INTERNAL_ASSERT_EQUALS(memcmp(buffer, "1234567890", 10), 0)
#endif
// setting from u_init_ulib(char** argv)
U_INTERNAL_DUMP("u_progname(%u) = %.*S u_cwd(%u) = %.*S", u_progname_len, u_progname_len, u_progname, u_cwd_len, u_cwd_len, u_cwd)
// allocation from memory pool
#if defined(ENABLE_MEMPOOL) // check if we want some preallocation for memory pool
const char* ptr = (mempool ? (UValue::jsonParseFlags = 2, mempool) : U_SYSCALL(getenv, "%S", "UMEMPOOL")); // start from 1... (Ex: 768,768,0,1536,2085,0,0,0,121)
// coverity[tainted_scalar]
if ( ptr &&
u__isdigit(*ptr))
{
UMemoryPool::allocateMemoryBlocks(ptr);
}
U_INTERNAL_ASSERT_EQUALS(U_BUFFER_SIZE, U_MAX_SIZE_PREALLOCATE * 2)
ptr = (char*) UMemoryPool::pop(U_SIZE_TO_STACK_INDEX(U_MAX_SIZE_PREALLOCATE));
u_buffer = (char*) UMemoryPool::pop(U_SIZE_TO_STACK_INDEX(U_MAX_SIZE_PREALLOCATE));
if (ptr < u_buffer) u_buffer = (char*)ptr;
u_err_buffer = (char*) UMemoryPool::pop(U_SIZE_TO_STACK_INDEX(256));
U_INTERNAL_DUMP("ptr = %p u_buffer = %p diff = %ld", ptr, u_buffer, ptr - u_buffer)
# ifdef DEBUG
UMemoryError::pbuffer = (char*) UMemoryPool::pop(U_SIZE_TO_STACK_INDEX(U_MAX_SIZE_PREALLOCATE));
# endif
#else
u_buffer = (char*) U_SYSCALL(malloc, "%u", U_BUFFER_SIZE);
u_err_buffer = (char*) U_SYSCALL(malloc, "%u", 256);
# ifdef DEBUG
UMemoryError::pbuffer = (char*) U_SYSCALL(malloc, "%u", U_MAX_SIZE_PREALLOCATE);
# endif
#endif
UString::ptrbuf =
UString::appbuf = (char*)UMemoryPool::pop(U_SIZE_TO_STACK_INDEX(1024));
UFile::cwd_save = (char*)UMemoryPool::pop(U_SIZE_TO_STACK_INDEX(1024));
#if defined(DEBUG) && defined(U_STDCPP_ENABLE)
# ifdef DEBUG
UMemoryPool::obj_class = UMemoryPool::func_call = 0;
# endif
UObjectIO::init((char*)UMemoryPool::pop(U_SIZE_TO_STACK_INDEX(U_MAX_SIZE_PREALLOCATE)), U_MAX_SIZE_PREALLOCATE);
#endif
UInterrupt::init();
#ifdef _MSWINDOWS_
WSADATA wsaData;
WORD version_requested = MAKEWORD(2, 2); // version_high, version_low
int err = U_SYSCALL(WSAStartup, "%d.%p", version_requested, &wsaData);
// Confirm that the WinSock DLL supports 2.2. Note that if the DLL supports versions greater than 2.2 in addition to 2.2,
// it will still return 2.2 in wVersion since that is the version we requested
if (err ||
LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 2)
{
WSACleanup();
// Tell the user that we could not find a usable WinSock DLL
U_ERROR("Couldn't find useable Winsock DLL. Must be at least 2.2");
}
# ifdef HAVE_ATEXIT
(void) U_SYSCALL(atexit, "%p", (vPF)&WSACleanup);
# endif
#endif
#if defined(SOLARIS) && (defined(SPARC) || defined(sparc)) && !defined(HAVE_ARCH64)
asm("ta 6"); // make this if there are pointer misalligned (because pointers must be always a multiple of 4 (when running 32 bit applications))
#endif
#if defined(DEBUG) && defined(__GNUC__) && defined(U_ENABLE_ALIGNMENT_CHECKING)
# ifdef __i386__
__asm__("pushf\norl $0x40000,(%esp)\npopf"); // Enable Alignment Checking on x86
# elif defined(__x86_64__)
__asm__("pushf\norl $0x40000,(%rsp)\npopf"); // Enable Alignment Checking on x86_64
# endif
#endif
U_INTERNAL_ASSERT_EQUALS(sizeof(UStringRep), sizeof(ustringrep))
#if defined(U_STATIC_ONLY)
if (UStringRep::string_rep_null == 0)
{
UString::string_null = uustringnull.p2;
UStringRep::string_rep_null = uustringrepnull.p2;
}
#endif
UString::str_allocate(0);
U_INTERNAL_DUMP("u_is_tty = %b UStringRep::string_rep_null = %p UString::string_null = %p", u_is_tty, UStringRep::string_rep_null, UString::string_null)
U_INTERNAL_DUMP("sizeof(off_t) = %u SIZEOF_OFF_T = %u", sizeof(off_t), SIZEOF_OFF_T)
/**
* NB: there are to many exceptions...
*
* #if defined(_LARGEFILE_SOURCE) && !defined(_MSWINDOWS_)
* U_INTERNAL_ASSERT_EQUALS(sizeof(off_t), SIZEOF_OFF_T)
* #endif
*/
#if defined(USE_LIBSSL) && OPENSSL_VERSION_NUMBER < 0x10100000L
// A typical TLS/SSL application will start with the library initialization,
// will provide readable error messages and will seed the PRNG (Pseudo Random Number Generator).
// The environment variable OPENSSL_CONFIG can be set to specify the location of the configuration file
U_SYSCALL_VOID_NO_PARAM(SSL_load_error_strings);
U_SYSCALL_VOID_NO_PARAM(SSL_library_init);
# ifdef HAVE_OPENSSL_97
U_SYSCALL_VOID(OPENSSL_config, "%S", 0);
# endif
U_SYSCALL_VOID_NO_PARAM(OpenSSL_add_all_ciphers);
U_SYSCALL_VOID_NO_PARAM(OpenSSL_add_all_digests);
// OpenSSL makes sure that the PRNG state is unique for each thread. On systems that provide "/dev/urandom",
// the randomness device is used to seed the PRNG transparently. However, on all other systems, the application
// is responsible for seeding the PRNG by calling RAND_add()
# ifdef _MSWINDOWS_
U_SYSCALL_VOID(srand, "%ld", u_seed_hash);
while (RAND_status() == 0) // Seed PRNG only if needed
{
// PRNG may need lots of seed data
int tmp = U_SYSCALL_NO_PARAM(rand);
RAND_seed(&tmp, sizeof(int));
}
# endif
#endif
#ifndef HAVE_POLL_H
U_INTERNAL_ASSERT_EQUALS(UNotifier::time_obj, 0)
U_NEW_ULIB_OBJECT(UEventTime, UNotifier::time_obj, UEventTime);
#endif
}
void ULib::end()
{
#if defined(U_STDCPP_ENABLE) && defined(DEBUG)
UApplication::printMemUsage();
#endif
}
| 37.620579 | 164 | 0.643333 | liftchampion |
f5f3da30f6701fa41545d5a87b6fa0c97c38daee | 2,980 | cpp | C++ | Eudora71/DirectoryServices/Ph/src/component.cpp | dusong7/eudora-win | 850a6619e6b0d5abc770bca8eb5f3b9001b7ccd2 | [
"BSD-3-Clause-Clear"
] | 10 | 2018-05-23T10:43:48.000Z | 2021-12-02T17:59:48.000Z | Eudora71/DirectoryServices/Ph/src/component.cpp | ivanagui2/hermesmail-code | 34387722d5364163c71b577fc508b567de56c5f6 | [
"BSD-3-Clause-Clear"
] | 1 | 2019-03-19T03:56:36.000Z | 2021-05-26T18:36:03.000Z | Eudora71/DirectoryServices/Ph/src/component.cpp | ivanagui2/hermesmail-code | 34387722d5364163c71b577fc508b567de56c5f6 | [
"BSD-3-Clause-Clear"
] | 11 | 2018-05-23T10:43:53.000Z | 2021-12-27T15:42:58.000Z | /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
File: component.cpp
Description: Implementation of components in PH directory services DLL
Date: 7/22/97
Version: 1.0
Module: PH.DLL (PH protocol directory service object)
Notice: Copyright 1997 Qualcomm Inc. All Rights Reserved.
Copyright (c) 2016, Computer History Museum
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to
the limitations in the disclaimer below) 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 Computer History Museum nor the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. 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.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Revisions:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
#pragma warning(disable : 4514)
#include <afx.h>
#include <objbase.h>
#include "DebugNewHelpers.h"
#include "factory.h"
#include "component.h"
#include "finger.h"
#include "ph.h"
////////////////////////////////////////////////////////////////////////////
// Creation Data
IUnknown * CreatePH()
{
CPHProtocol *pProto = DEBUG_NEW_NOTHROW CPHProtocol;
return(pProto);
}
IUnknown * CreateFinger()
{
CFingerProtocol *pProto = DEBUG_NEW_NOTHROW CFingerProtocol;
return(pProto);
}
CFactoryData g_FactoryDataArray[] =
{
{ &CLSID_DsProtocolPH, CreatePH, "Qualcomm PH Protocol", NULL, NULL, NULL },
{ &CLSID_DsProtocolFinger, CreateFinger, "Qualcomm Finger Protocol", NULL, NULL, NULL }
};
int g_cFactoryDataEntries = sizeof(g_FactoryDataArray) / sizeof(CFactoryData);
| 42.571429 | 129 | 0.687919 | dusong7 |
f5f42f01e49ec16b542694355642a44bc717fdd0 | 7,663 | cc | C++ | vector/mmap_raw_vector.cc | matadorhong/gamma | 90bd56485278171a7a528bc0485df87f26a3e442 | [
"Apache-2.0"
] | null | null | null | vector/mmap_raw_vector.cc | matadorhong/gamma | 90bd56485278171a7a528bc0485df87f26a3e442 | [
"Apache-2.0"
] | null | null | null | vector/mmap_raw_vector.cc | matadorhong/gamma | 90bd56485278171a7a528bc0485df87f26a3e442 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2019 The Gamma Authors.
*
* This source code is licensed under the Apache License, Version 2.0 license
* found in the LICENSE file in the root directory of this source tree.
*/
#include "mmap_raw_vector.h"
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <exception>
#include "error_code.h"
#include "log.h"
#include "utils.h"
using namespace std;
namespace tig_gamma {
MmapRawVector::MmapRawVector(VectorMetaInfo *meta_info, const string &root_path,
const StoreParams &store_params,
const char *docids_bitmap)
: RawVector(meta_info, root_path, docids_bitmap, store_params),
AsyncFlusher(meta_info->Name()) {
flush_batch_size_ = 1000;
data_size_ = meta_info_->DataSize();
vector_byte_size_ = data_size_ * meta_info->Dimension();
flush_write_retry_ = 10;
buffer_chunk_num_ = kDefaultBufferChunkNum;
fet_fd_ = -1;
max_size_ = store_params.segment_size_;
max_buffer_size_ = 0;
}
MmapRawVector::~MmapRawVector() {
CHECK_DELETE(vector_buffer_queue_);
CHECK_DELETE(vector_file_mapper_);
CHECK_DELETE_ARRAY(flush_batch_vectors_);
if (fet_fd_ != -1) {
fsync(fet_fd_);
close(fet_fd_);
}
}
int MmapRawVector::InitStore() {
int dimension = meta_info_->Dimension();
std::string &name = meta_info_->Name();
std::string vec_dir = root_path_ + "/" + name;
if (utils::make_dir(vec_dir.c_str())) {
LOG(ERROR) << "mkdir error, path=" << vec_dir;
return IO_ERR;
}
fet_file_path_ = vec_dir + "/vector.dat";
fet_fd_ = open(fet_file_path_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 00664);
if (fet_fd_ == -1) {
LOG(ERROR) << "open file error:" << strerror(errno);
return IO_ERR;
}
max_buffer_size_ =
(int)(this->store_params_->cache_size_ / this->vector_byte_size_);
int remainder = max_buffer_size_ % buffer_chunk_num_;
if (remainder > 0) {
max_buffer_size_ += buffer_chunk_num_ - remainder;
}
vector_buffer_queue_ = new VectorBufferQueue(max_buffer_size_, dimension,
buffer_chunk_num_, data_size_);
vector_file_mapper_ = new VectorFileMapper(fet_file_path_, 1000 * 1000 * 10,
dimension, data_size_);
int ret = vector_buffer_queue_->Init();
if (ret) {
LOG(ERROR) << "init vector buffer queue error, ret=" << ret;
return ret;
}
total_mem_bytes_ += vector_buffer_queue_->GetTotalMemBytes();
flush_batch_vectors_ =
new uint8_t[(uint64_t)flush_batch_size_ * vector_byte_size_];
total_mem_bytes_ += (uint64_t)flush_batch_size_ * vector_byte_size_;
ret = vector_file_mapper_->Init();
if (ret) {
LOG(ERROR) << "vector file mapper map error";
return ret;
}
LOG(INFO) << "Init success! vector byte size=" << vector_byte_size_
<< ", flush batch size=" << flush_batch_size_
<< ", dimension=" << dimension << ", ntotal=" << meta_info_->Size()
<< ", init max_size=" << max_size_;
return 0;
}
int MmapRawVector::FlushOnce() {
int psize = vector_buffer_queue_->GetPopSize();
int count = 0;
while (count < psize) {
int num =
psize - count > flush_batch_size_ ? flush_batch_size_ : psize - count;
vector_buffer_queue_->Pop(flush_batch_vectors_, vector_byte_size_, num, -1);
ssize_t write_size = (ssize_t)num * vector_byte_size_;
ssize_t ret = utils::write_n(fet_fd_, (char *)flush_batch_vectors_,
write_size, flush_write_retry_);
if (ret != write_size) {
LOG(ERROR) << "write_n error:" << strerror(errno) << ", num=" << num;
// TODO: truncate and seek file, or write the success number to file
return -2;
}
count += num;
}
return psize;
}
int MmapRawVector::DumpVectors(int dump_vid, int n) {
int dump_end = dump_vid + n;
while (nflushed_ < dump_end) {
LOG(INFO) << "raw vector=" << meta_info_->Name()
<< ", dump waiting! dump_end=" << dump_end
<< ", nflushed=" << nflushed_;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
return SUCC;
}
int MmapRawVector::LoadVectors(int vec_num) {
int dimension = meta_info_->Dimension();
StopFlushingIfNeed(this);
long file_size = utils::get_file_size(fet_file_path_.c_str());
if (file_size % vector_byte_size_ != 0) {
LOG(ERROR) << "file_size % vector_byte_size_ != 0, path=" << fet_file_path_;
return FORMAT_ERR;
}
long disk_vector_num = file_size / vector_byte_size_;
LOG(INFO) << "disk_vector_num=" << disk_vector_num << ", vec_num=" << vec_num;
assert(disk_vector_num >= vec_num);
if (disk_vector_num > vec_num) {
// release file
if (fet_fd_ != -1) {
close(fet_fd_);
}
if (vector_file_mapper_) {
delete vector_file_mapper_;
}
long trunc_size = (long)vec_num * vector_byte_size_;
if (truncate(fet_file_path_.c_str(), trunc_size)) {
LOG(ERROR) << "truncate feature file=" << fet_file_path_ << " to "
<< trunc_size << ", error:" << strerror(errno);
return IO_ERR;
}
fet_fd_ =
open(fet_file_path_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 00664);
if (fet_fd_ == -1) {
LOG(ERROR) << "open file error:" << strerror(errno);
return -1;
}
vector_file_mapper_ = new VectorFileMapper(fet_file_path_, 1000 * 1000 * 10,
dimension, data_size_);
if (vector_file_mapper_->Init()) {
LOG(ERROR) << "vector file mapper map error";
return INTERNAL_ERR;
}
disk_vector_num = vec_num;
}
nflushed_ = disk_vector_num;
last_nflushed_ = nflushed_;
LOG(INFO) << "load vectors success, nflushed=" << nflushed_;
StartFlushingIfNeed(this);
return SUCC;
}
void FreeFileMapper(VectorFileMapper *file_mapper) { delete file_mapper; }
int MmapRawVector::Extend() {
VectorFileMapper *old_file_mapper = vector_file_mapper_;
VectorFileMapper *new_mapper =
new VectorFileMapper(fet_file_path_, max_size_ * 2,
meta_info_->Dimension(), meta_info_->DataSize());
if (new_mapper->Init()) {
LOG(ERROR) << "extend file mapper, init error, max size=" << max_size_ * 2;
return INTERNAL_ERR;
}
vector_file_mapper_ = new_mapper;
max_size_ *= 2;
LOG(INFO) << "extend file mapper sucess, max_size=" << max_size_;
// delay free old mapper
std::function<void(VectorFileMapper *)> func_free =
std::bind(&FreeFileMapper, std::placeholders::_1);
utils::AsyncWait(1000, func_free, old_file_mapper);
return SUCC;
}
int MmapRawVector::AddToStore(uint8_t *v, int len) {
if ((long)meta_info_->Size() >= max_size_ && Extend()) {
LOG(ERROR) << "extend error";
return INTERNAL_ERR;
}
return vector_buffer_queue_->Push(v, len, -1);
}
int MmapRawVector::GetVectorHeader(int start, int n, ScopeVectors &vecs,
std::vector<int> &lens) {
if (start + n > (int)meta_info_->Size()) return PARAM_ERR;
Until(start + n);
vecs.Add(
vector_file_mapper_->GetVectors() + (uint64_t)start * vector_byte_size_,
false);
lens.push_back(n);
return SUCC;
}
int MmapRawVector::UpdateToStore(int vid, uint8_t *v, int len) {
LOG(ERROR) << "MMap doesn't support update!";
return -1;
};
int MmapRawVector::GetVector(long vid, const uint8_t *&vec,
bool &deletable) const {
if (vid >= (long)meta_info_->Size() || vid < 0) return -1;
Until((int)vid + 1);
vec = vector_file_mapper_->GetVector(vid);
deletable = false;
return SUCC;
}
} // namespace tig_gamma
| 31.929167 | 80 | 0.648441 | matadorhong |
f5fa36a906fb85aa475cab193237dc66a955f346 | 27,293 | cpp | C++ | src/transport/PASESession.cpp | hakieyin/connectedhomeip | 0b19aa2330fb5ca7ccfb6d2a53a6f49accf131bd | [
"Apache-2.0"
] | 1 | 2021-07-12T18:41:08.000Z | 2021-07-12T18:41:08.000Z | src/transport/PASESession.cpp | hakieyin/connectedhomeip | 0b19aa2330fb5ca7ccfb6d2a53a6f49accf131bd | [
"Apache-2.0"
] | 2 | 2022-03-25T10:07:16.000Z | 2022-03-28T07:17:39.000Z | src/transport/PASESession.cpp | hakieyin/connectedhomeip | 0b19aa2330fb5ca7ccfb6d2a53a6f49accf131bd | [
"Apache-2.0"
] | 2 | 2022-03-18T10:37:29.000Z | 2022-03-24T10:35:16.000Z | /*
*
* Copyright (c) 2020-2021 Project CHIP Authors
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* This file implements the CHIP SPAKE2P Session object that provides
* APIs for constructing spake2p messages and establishing encryption
* keys.
*
* The protocol for handling pA, pB, cB and cA is defined in SPAKE2
* Plus specifications.
* (https://www.ietf.org/id/draft-bar-cfrg-spake2plus-01.html)
*
*/
#include <transport/PASESession.h>
#include <inttypes.h>
#include <string.h>
#include <core/CHIPEncoding.h>
#include <core/CHIPSafeCasts.h>
#include <protocols/Protocols.h>
#include <setup_payload/SetupPayload.h>
#include <support/BufferWriter.h>
#include <support/CHIPMem.h>
#include <support/CodeUtils.h>
#include <support/ReturnMacros.h>
#include <support/SafeInt.h>
#include <transport/SecureSessionMgr.h>
namespace chip {
using namespace Crypto;
const char * kSpake2pContext = "CHIP PAKE V1 Commissioning";
const char * kSpake2pI2RSessionInfo = "Commissioning I2R Key";
const char * kSpake2pR2ISessionInfo = "Commissioning R2I Key";
static constexpr uint32_t kSpake2p_Iteration_Count = 100;
static const char * kSpake2pKeyExchangeSalt = "SPAKE2P Key Salt";
PASESession::PASESession() {}
PASESession::~PASESession()
{
// Let's clear out any security state stored in the object, before destroying it.
Clear();
}
void PASESession::Clear()
{
// This function zeroes out and resets the memory used by the object.
// It's done so that no security related information will be leaked.
memset(&mPoint[0], 0, sizeof(mPoint));
memset(&mPASEVerifier[0][0], 0, sizeof(mPASEVerifier));
memset(&mKe[0], 0, sizeof(mKe));
mNextExpectedMsg = Protocols::SecureChannel::MsgType::PASE_Spake2pError;
// Note: we don't need to explicitly clear the state of mSpake2p object.
// Clearing the following state takes care of it.
mCommissioningHash.Clear();
mIterationCount = 0;
mSaltLength = 0;
if (mSalt != nullptr)
{
chip::Platform::MemoryFree(mSalt);
mSalt = nullptr;
}
mKeLen = sizeof(mKe);
mPairingComplete = false;
mComputeVerifier = true;
mConnectionState.Reset();
}
CHIP_ERROR PASESession::Serialize(PASESessionSerialized & output)
{
CHIP_ERROR error = CHIP_NO_ERROR;
uint16_t serializedLen = 0;
PASESessionSerializable serializable;
VerifyOrExit(BASE64_ENCODED_LEN(sizeof(serializable)) <= sizeof(output.inner), error = CHIP_ERROR_INVALID_ARGUMENT);
error = ToSerializable(serializable);
SuccessOrExit(error);
serializedLen = chip::Base64Encode(Uint8::to_const_uchar(reinterpret_cast<uint8_t *>(&serializable)),
static_cast<uint16_t>(sizeof(serializable)), Uint8::to_char(output.inner));
VerifyOrExit(serializedLen > 0, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(serializedLen < sizeof(output.inner), error = CHIP_ERROR_INVALID_ARGUMENT);
output.inner[serializedLen] = '\0';
exit:
return error;
}
CHIP_ERROR PASESession::Deserialize(PASESessionSerialized & input)
{
CHIP_ERROR error = CHIP_NO_ERROR;
PASESessionSerializable serializable;
size_t maxlen = BASE64_ENCODED_LEN(sizeof(serializable));
size_t len = strnlen(Uint8::to_char(input.inner), maxlen);
uint16_t deserializedLen = 0;
VerifyOrExit(len < sizeof(PASESessionSerialized), error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(CanCastTo<uint16_t>(len), error = CHIP_ERROR_INVALID_ARGUMENT);
memset(&serializable, 0, sizeof(serializable));
deserializedLen =
Base64Decode(Uint8::to_const_char(input.inner), static_cast<uint16_t>(len), Uint8::to_uchar((uint8_t *) &serializable));
VerifyOrExit(deserializedLen > 0, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(deserializedLen <= sizeof(serializable), error = CHIP_ERROR_INVALID_ARGUMENT);
error = FromSerializable(serializable);
exit:
return error;
}
CHIP_ERROR PASESession::ToSerializable(PASESessionSerializable & serializable)
{
CHIP_ERROR error = CHIP_NO_ERROR;
VerifyOrExit(CanCastTo<uint16_t>(mKeLen), error = CHIP_ERROR_INTERNAL);
memset(&serializable, 0, sizeof(serializable));
serializable.mKeLen = static_cast<uint16_t>(mKeLen);
serializable.mPairingComplete = (mPairingComplete) ? 1 : 0;
serializable.mLocalKeyId = mConnectionState.GetLocalKeyID();
serializable.mPeerKeyId = mConnectionState.GetPeerKeyID();
memcpy(serializable.mKe, mKe, mKeLen);
exit:
return error;
}
CHIP_ERROR PASESession::FromSerializable(const PASESessionSerializable & serializable)
{
CHIP_ERROR error = CHIP_NO_ERROR;
mPairingComplete = (serializable.mPairingComplete == 1);
mKeLen = static_cast<size_t>(serializable.mKeLen);
VerifyOrExit(mKeLen <= sizeof(mKe), error = CHIP_ERROR_INVALID_ARGUMENT);
memset(mKe, 0, sizeof(mKe));
memcpy(mKe, serializable.mKe, mKeLen);
mConnectionState.SetLocalKeyID(serializable.mLocalKeyId);
mConnectionState.SetPeerKeyID(serializable.mPeerKeyId);
exit:
return error;
}
CHIP_ERROR PASESession::Init(uint16_t myKeyId, uint32_t setupCode, SessionEstablishmentDelegate * delegate)
{
CHIP_ERROR err = CHIP_NO_ERROR;
VerifyOrExit(delegate != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
// Reset any state maintained by PASESession object (in case it's being reused for pairing)
Clear();
err = mCommissioningHash.Begin();
SuccessOrExit(err);
err = mCommissioningHash.AddData(Uint8::from_const_char(kSpake2pContext), strlen(kSpake2pContext));
SuccessOrExit(err);
mDelegate = delegate;
mConnectionState.SetLocalKeyID(myKeyId);
mSetupPINCode = setupCode;
mComputeVerifier = true;
exit:
return err;
}
CHIP_ERROR PASESession::ComputePASEVerifier(uint32_t setUpPINCode, uint32_t pbkdf2IterCount, const uint8_t * salt, size_t saltLen,
PASEVerifier & verifier)
{
return pbkdf2_sha256(reinterpret_cast<const uint8_t *>(&setUpPINCode), sizeof(setUpPINCode), salt, saltLen, pbkdf2IterCount,
sizeof(PASEVerifier), &verifier[0][0]);
}
CHIP_ERROR PASESession::GeneratePASEVerifier(PASEVerifier & verifier, bool useRandomPIN, uint32_t & setupPIN)
{
if (useRandomPIN)
{
ReturnErrorOnFailure(DRBG_get_bytes(reinterpret_cast<uint8_t *>(&setupPIN), sizeof(setupPIN)));
// Use only kSetupPINCodeFieldLengthInBits bits out of the code
setupPIN &= ((1 << kSetupPINCodeFieldLengthInBits) - 1);
}
else if (setupPIN >= (1 << kSetupPINCodeFieldLengthInBits))
{
return CHIP_ERROR_INVALID_ARGUMENT;
}
return PASESession::ComputePASEVerifier(setupPIN, kSpake2p_Iteration_Count,
reinterpret_cast<const unsigned char *>(kSpake2pKeyExchangeSalt),
strlen(kSpake2pKeyExchangeSalt), verifier);
}
CHIP_ERROR PASESession::SetupSpake2p(uint32_t pbkdf2IterCount, const uint8_t * salt, size_t saltLen)
{
CHIP_ERROR err = CHIP_NO_ERROR;
uint8_t context[32] = {
0,
};
if (mComputeVerifier)
{
VerifyOrExit(salt != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(saltLen > 0, err = CHIP_ERROR_INVALID_ARGUMENT);
err = PASESession::ComputePASEVerifier(mSetupPINCode, pbkdf2IterCount, salt, saltLen, mPASEVerifier);
SuccessOrExit(err);
}
err = mCommissioningHash.Finish(context);
SuccessOrExit(err);
err = mSpake2p.Init(context, sizeof(context));
SuccessOrExit(err);
exit:
return err;
}
CHIP_ERROR PASESession::WaitForPairing(uint32_t mySetUpPINCode, uint32_t pbkdf2IterCount, const uint8_t * salt, size_t saltLen,
uint16_t myKeyId, SessionEstablishmentDelegate * delegate)
{
CHIP_ERROR err = CHIP_NO_ERROR;
VerifyOrExit(salt != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(saltLen > 0, err = CHIP_ERROR_INVALID_ARGUMENT);
err = Init(myKeyId, mySetUpPINCode, delegate);
SuccessOrExit(err);
VerifyOrExit(CanCastTo<uint16_t>(saltLen), err = CHIP_ERROR_INVALID_ARGUMENT);
mSaltLength = static_cast<uint16_t>(saltLen);
if (mSalt != nullptr)
{
chip::Platform::MemoryFree(mSalt);
mSalt = nullptr;
}
mSalt = static_cast<uint8_t *>(chip::Platform::MemoryAlloc(mSaltLength));
VerifyOrExit(mSalt != nullptr, err = CHIP_ERROR_NO_MEMORY);
memmove(mSalt, salt, mSaltLength);
mIterationCount = pbkdf2IterCount;
mNextExpectedMsg = Protocols::SecureChannel::MsgType::PBKDFParamRequest;
mPairingComplete = false;
ChipLogDetail(Ble, "Waiting for PBKDF param request");
exit:
if (err != CHIP_NO_ERROR)
{
Clear();
}
return err;
}
CHIP_ERROR PASESession::WaitForPairing(const PASEVerifier & verifier, uint16_t myKeyId, SessionEstablishmentDelegate * delegate)
{
CHIP_ERROR err = WaitForPairing(0, kSpake2p_Iteration_Count, reinterpret_cast<const unsigned char *>(kSpake2pKeyExchangeSalt),
strlen(kSpake2pKeyExchangeSalt), myKeyId, delegate);
SuccessOrExit(err);
memmove(&mPASEVerifier, verifier, sizeof(verifier));
mComputeVerifier = false;
exit:
if (err != CHIP_NO_ERROR)
{
Clear();
}
return err;
}
CHIP_ERROR PASESession::AttachHeaderAndSend(Protocols::SecureChannel::MsgType msgType, System::PacketBufferHandle msgBuf)
{
PayloadHeader payloadHeader;
payloadHeader.SetMessageType(msgType);
CHIP_ERROR err = payloadHeader.EncodeBeforeData(msgBuf);
SuccessOrExit(err);
err = mDelegate->SendSessionEstablishmentMessage(PacketHeader().SetEncryptionKeyID(mConnectionState.GetLocalKeyID()),
mConnectionState.GetPeerAddress(), std::move(msgBuf));
SuccessOrExit(err);
exit:
return err;
}
CHIP_ERROR PASESession::Pair(const Transport::PeerAddress peerAddress, uint32_t peerSetUpPINCode, uint16_t myKeyId,
SessionEstablishmentDelegate * delegate)
{
CHIP_ERROR err = Init(myKeyId, peerSetUpPINCode, delegate);
SuccessOrExit(err);
mConnectionState.SetPeerAddress(peerAddress);
err = SendPBKDFParamRequest();
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
Clear();
}
return err;
}
CHIP_ERROR PASESession::Pair(const Transport::PeerAddress peerAddress, const PASEVerifier & verifier, uint16_t myKeyId,
SessionEstablishmentDelegate * delegate)
{
CHIP_ERROR err = Init(myKeyId, 0, delegate);
SuccessOrExit(err);
mConnectionState.SetPeerAddress(peerAddress);
memmove(&mPASEVerifier, verifier, sizeof(verifier));
mComputeVerifier = false;
err = SendPBKDFParamRequest();
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
Clear();
}
return err;
}
CHIP_ERROR PASESession::DeriveSecureSession(const uint8_t * info, size_t info_len, SecureSession & session)
{
CHIP_ERROR err = CHIP_NO_ERROR;
VerifyOrExit(info != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(info_len > 0, err = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(mPairingComplete, err = CHIP_ERROR_INCORRECT_STATE);
err = session.InitFromSecret(mKe, mKeLen, nullptr, 0, info, info_len);
SuccessOrExit(err);
exit:
return err;
}
CHIP_ERROR PASESession::SendPBKDFParamRequest()
{
CHIP_ERROR err = CHIP_NO_ERROR;
System::PacketBufferHandle req = System::PacketBufferHandle::New(kPBKDFParamRandomNumberSize);
VerifyOrExit(!req.IsNull(), err = CHIP_SYSTEM_ERROR_NO_MEMORY);
err = DRBG_get_bytes(req->Start(), kPBKDFParamRandomNumberSize);
SuccessOrExit(err);
req->SetDataLength(kPBKDFParamRandomNumberSize);
// Update commissioning hash with the pbkdf2 param request that's being sent.
err = mCommissioningHash.AddData(req->Start(), req->DataLength());
SuccessOrExit(err);
mNextExpectedMsg = Protocols::SecureChannel::MsgType::PBKDFParamResponse;
err = AttachHeaderAndSend(Protocols::SecureChannel::MsgType::PBKDFParamRequest, std::move(req));
SuccessOrExit(err);
ChipLogDetail(Ble, "Sent PBKDF param request");
exit:
if (err != CHIP_NO_ERROR)
{
Clear();
}
return err;
}
CHIP_ERROR PASESession::HandlePBKDFParamRequest(const PacketHeader & header, const System::PacketBufferHandle & msg)
{
CHIP_ERROR err = CHIP_NO_ERROR;
// Request message processing
const uint8_t * req = msg->Start();
size_t reqlen = msg->DataLength();
VerifyOrExit(req != nullptr, err = CHIP_ERROR_MESSAGE_INCOMPLETE);
VerifyOrExit(reqlen == kPBKDFParamRandomNumberSize, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);
ChipLogDetail(Ble, "Received PBKDF param request");
// Update commissioning hash with the received pbkdf2 param request
err = mCommissioningHash.AddData(req, reqlen);
SuccessOrExit(err);
err = SendPBKDFParamResponse();
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
SendErrorMsg(Spake2pErrorType::kUnexpected);
}
return err;
}
CHIP_ERROR PASESession::SendPBKDFParamResponse()
{
CHIP_ERROR err = CHIP_NO_ERROR;
System::PacketBufferHandle resp;
static_assert(CHAR_BIT == 8, "Assuming sizeof() returns octets here and for sizeof(mPoint)");
size_t resplen = kPBKDFParamRandomNumberSize + sizeof(uint64_t) + sizeof(uint32_t) + mSaltLength;
size_t sizeof_point = sizeof(mPoint);
uint8_t * msg = nullptr;
resp = System::PacketBufferHandle::New(resplen);
VerifyOrExit(!resp.IsNull(), err = CHIP_SYSTEM_ERROR_NO_MEMORY);
msg = resp->Start();
// Fill in the random value
err = DRBG_get_bytes(msg, kPBKDFParamRandomNumberSize);
SuccessOrExit(err);
// Let's construct the rest of the message using BufferWriter
{
Encoding::LittleEndian::BufferWriter bbuf(&msg[kPBKDFParamRandomNumberSize], resplen - kPBKDFParamRandomNumberSize);
bbuf.Put64(mIterationCount);
bbuf.Put32(mSaltLength);
bbuf.Put(mSalt, mSaltLength);
VerifyOrExit(bbuf.Fit(), err = CHIP_ERROR_NO_MEMORY);
}
resp->SetDataLength(static_cast<uint16_t>(resplen));
// Update commissioning hash with the pbkdf2 param response that's being sent.
err = mCommissioningHash.AddData(resp->Start(), resp->DataLength());
SuccessOrExit(err);
err = SetupSpake2p(mIterationCount, mSalt, mSaltLength);
SuccessOrExit(err);
err = mSpake2p.ComputeL(mPoint, &sizeof_point, &mPASEVerifier[1][0], kSpake2p_WS_Length);
SuccessOrExit(err);
mNextExpectedMsg = Protocols::SecureChannel::MsgType::PASE_Spake2p1;
err = AttachHeaderAndSend(Protocols::SecureChannel::MsgType::PBKDFParamResponse, std::move(resp));
SuccessOrExit(err);
ChipLogDetail(Ble, "Sent PBKDF param response");
exit:
return err;
}
CHIP_ERROR PASESession::HandlePBKDFParamResponse(const PacketHeader & header, const System::PacketBufferHandle & msg)
{
CHIP_ERROR err = CHIP_NO_ERROR;
// Response message processing
const uint8_t * resp = msg->Start();
size_t resplen = msg->DataLength();
// This the fixed part of the message. The variable part of the message contains the salt.
// The length of the variable part is determined by the salt length in the fixed header.
static_assert(CHAR_BIT == 8, "Assuming that sizeof returns octets");
size_t fixed_resplen = kPBKDFParamRandomNumberSize + sizeof(uint64_t) + sizeof(uint32_t);
ChipLogDetail(Ble, "Received PBKDF param response");
VerifyOrExit(resp != nullptr, err = CHIP_ERROR_MESSAGE_INCOMPLETE);
VerifyOrExit(resplen >= fixed_resplen, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);
{
// Let's skip the random number portion of the message
const uint8_t * msgptr = &resp[kPBKDFParamRandomNumberSize];
uint64_t iterCount = chip::Encoding::LittleEndian::Read64(msgptr);
uint32_t saltlen = chip::Encoding::LittleEndian::Read32(msgptr);
VerifyOrExit(resplen == fixed_resplen + saltlen, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);
// Specifications allow message to carry a uint64_t sized iteration count. Current APIs are
// limiting it to uint32_t. Let's make sure it'll fit the size limit.
VerifyOrExit(CanCastTo<uint32_t>(iterCount), err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);
// Update commissioning hash with the received pbkdf2 param response
err = mCommissioningHash.AddData(resp, resplen);
SuccessOrExit(err);
err = SetupSpake2p(static_cast<uint32_t>(iterCount), msgptr, saltlen);
SuccessOrExit(err);
}
err = SendMsg1();
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
SendErrorMsg(Spake2pErrorType::kUnexpected);
}
return err;
}
CHIP_ERROR PASESession::SendMsg1()
{
uint8_t X[kMAX_Point_Length];
size_t X_len = sizeof(X);
System::PacketBufferHandle msg_pA;
CHIP_ERROR err = mSpake2p.BeginProver(reinterpret_cast<const uint8_t *>(""), 0, reinterpret_cast<const uint8_t *>(""), 0,
&mPASEVerifier[0][0], kSpake2p_WS_Length, &mPASEVerifier[1][0], kSpake2p_WS_Length);
SuccessOrExit(err);
err = mSpake2p.ComputeRoundOne(X, &X_len);
SuccessOrExit(err);
msg_pA = System::PacketBufferHandle::NewWithData(&X[0], X_len);
VerifyOrExit(!msg_pA.IsNull(), err = CHIP_SYSTEM_ERROR_NO_MEMORY);
mNextExpectedMsg = Protocols::SecureChannel::MsgType::PASE_Spake2p2;
// Call delegate to send the Msg1 to peer
err = AttachHeaderAndSend(Protocols::SecureChannel::MsgType::PASE_Spake2p1, std::move(msg_pA));
SuccessOrExit(err);
ChipLogDetail(Ble, "Sent spake2p msg1");
exit:
return err;
}
CHIP_ERROR PASESession::HandleMsg1_and_SendMsg2(const PacketHeader & header, const System::PacketBufferHandle & msg)
{
CHIP_ERROR err = CHIP_NO_ERROR;
uint8_t Y[kMAX_Point_Length];
size_t Y_len = sizeof(Y);
uint8_t verifier[kMAX_Hash_Length];
size_t verifier_len = kMAX_Hash_Length;
uint16_t data_len; // To be initialized once we compute it.
const uint8_t * buf = msg->Start();
size_t buf_len = msg->DataLength();
ChipLogDetail(Ble, "Received spake2p msg1");
VerifyOrExit(buf != nullptr, err = CHIP_ERROR_MESSAGE_INCOMPLETE);
VerifyOrExit(buf_len == kMAX_Point_Length, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);
err = mSpake2p.BeginVerifier(reinterpret_cast<const uint8_t *>(""), 0, reinterpret_cast<const uint8_t *>(""), 0,
&mPASEVerifier[0][0], kSpake2p_WS_Length, mPoint, sizeof(mPoint));
SuccessOrExit(err);
err = mSpake2p.ComputeRoundOne(Y, &Y_len);
SuccessOrExit(err);
err = mSpake2p.ComputeRoundTwo(buf, buf_len, verifier, &verifier_len);
SuccessOrExit(err);
mConnectionState.SetPeerKeyID(header.GetEncryptionKeyID());
// Make sure our addition doesn't overflow.
VerifyOrExit(UINTMAX_MAX - verifier_len >= Y_len, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);
VerifyOrExit(CanCastTo<uint16_t>(Y_len + verifier_len), err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);
data_len = static_cast<uint16_t>(Y_len + verifier_len);
{
Encoding::PacketBufferWriter bbuf(System::PacketBufferHandle::New(data_len));
VerifyOrExit(!bbuf.IsNull(), err = CHIP_SYSTEM_ERROR_NO_MEMORY);
bbuf.Put(&Y[0], Y_len);
bbuf.Put(verifier, verifier_len);
VerifyOrExit(bbuf.Fit(), err = CHIP_ERROR_NO_MEMORY);
mNextExpectedMsg = Protocols::SecureChannel::MsgType::PASE_Spake2p3;
// Call delegate to send the Msg2 to peer
err = AttachHeaderAndSend(Protocols::SecureChannel::MsgType::PASE_Spake2p2, bbuf.Finalize());
SuccessOrExit(err);
}
ChipLogDetail(Ble, "Sent spake2p msg2");
exit:
if (err != CHIP_NO_ERROR)
{
SendErrorMsg(Spake2pErrorType::kUnexpected);
}
return err;
}
CHIP_ERROR PASESession::HandleMsg2_and_SendMsg3(const PacketHeader & header, const System::PacketBufferHandle & msg)
{
CHIP_ERROR err = CHIP_NO_ERROR;
uint8_t verifier[kMAX_Hash_Length];
size_t verifier_len_raw = kMAX_Hash_Length;
uint16_t verifier_len; // To be inited one we check length is small enough
const uint8_t * buf = msg->Start();
size_t buf_len = msg->DataLength();
System::PacketBufferHandle resp;
Spake2pErrorType spake2pErr = Spake2pErrorType::kUnexpected;
ChipLogDetail(Ble, "Received spake2p msg2");
VerifyOrExit(buf != nullptr, err = CHIP_ERROR_MESSAGE_INCOMPLETE);
VerifyOrExit(buf_len == kMAX_Point_Length + kMAX_Hash_Length, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);
err = mSpake2p.ComputeRoundTwo(buf, kMAX_Point_Length, verifier, &verifier_len_raw);
SuccessOrExit(err);
VerifyOrExit(CanCastTo<uint16_t>(verifier_len_raw), err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);
verifier_len = static_cast<uint16_t>(verifier_len_raw);
mConnectionState.SetPeerKeyID(header.GetEncryptionKeyID());
{
Encoding::PacketBufferWriter bbuf(System::PacketBufferHandle::New(verifier_len));
VerifyOrExit(!bbuf.IsNull(), err = CHIP_SYSTEM_ERROR_NO_MEMORY);
bbuf.Put(verifier, verifier_len);
VerifyOrExit(bbuf.Fit(), err = CHIP_ERROR_NO_MEMORY);
// Call delegate to send the Msg3 to peer
err = AttachHeaderAndSend(Protocols::SecureChannel::MsgType::PASE_Spake2p3, bbuf.Finalize());
SuccessOrExit(err);
}
ChipLogDetail(Ble, "Sent spake2p msg3");
{
const uint8_t * hash = &buf[kMAX_Point_Length];
err = mSpake2p.KeyConfirm(hash, kMAX_Hash_Length);
if (err != CHIP_NO_ERROR)
{
spake2pErr = Spake2pErrorType::kInvalidKeyConfirmation;
SuccessOrExit(err);
}
err = mSpake2p.GetKeys(mKe, &mKeLen);
SuccessOrExit(err);
}
mPairingComplete = true;
// Call delegate to indicate pairing completion
mDelegate->OnSessionEstablished();
exit:
if (err != CHIP_NO_ERROR)
{
SendErrorMsg(spake2pErr);
}
return err;
}
CHIP_ERROR PASESession::HandleMsg3(const PacketHeader & header, const System::PacketBufferHandle & msg)
{
CHIP_ERROR err = CHIP_NO_ERROR;
const uint8_t * hash = msg->Start();
Spake2pErrorType spake2pErr = Spake2pErrorType::kUnexpected;
ChipLogDetail(Ble, "Received spake2p msg3");
// We will set NextExpectedMsg to PASE_Spake2pError in all cases
// However, when we are using IP rendezvous, we might set it to PASE_Spake2p1.
mNextExpectedMsg = Protocols::SecureChannel::MsgType::PASE_Spake2pError;
VerifyOrExit(hash != nullptr, err = CHIP_ERROR_MESSAGE_INCOMPLETE);
VerifyOrExit(msg->DataLength() == kMAX_Hash_Length, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);
VerifyOrExit(header.GetEncryptionKeyID() == mConnectionState.GetPeerKeyID(), err = CHIP_ERROR_INVALID_KEY_ID);
err = mSpake2p.KeyConfirm(hash, kMAX_Hash_Length);
if (err != CHIP_NO_ERROR)
{
spake2pErr = Spake2pErrorType::kInvalidKeyConfirmation;
SuccessOrExit(err);
}
err = mSpake2p.GetKeys(mKe, &mKeLen);
SuccessOrExit(err);
mPairingComplete = true;
// Call delegate to indicate pairing completion
mDelegate->OnSessionEstablished();
exit:
if (err != CHIP_NO_ERROR)
{
SendErrorMsg(spake2pErr);
}
return err;
}
void PASESession::SendErrorMsg(Spake2pErrorType errorCode)
{
CHIP_ERROR err = CHIP_NO_ERROR;
System::PacketBufferHandle msg;
uint16_t msglen = sizeof(Spake2pErrorMsg);
Spake2pErrorMsg * pMsg = nullptr;
msg = System::PacketBufferHandle::New(msglen);
VerifyOrExit(!msg.IsNull(), err = CHIP_SYSTEM_ERROR_NO_MEMORY);
pMsg = reinterpret_cast<Spake2pErrorMsg *>(msg->Start());
pMsg->error = errorCode;
msg->SetDataLength(msglen);
err = AttachHeaderAndSend(Protocols::SecureChannel::MsgType::PASE_Spake2pError, std::move(msg));
SuccessOrExit(err);
exit:
Clear();
}
void PASESession::HandleErrorMsg(const PacketHeader & header, const System::PacketBufferHandle & msg)
{
// Request message processing
const uint8_t * buf = msg->Start();
size_t buflen = msg->DataLength();
Spake2pErrorMsg * pMsg = nullptr;
VerifyOrExit(buf != nullptr, ChipLogError(Ble, "Null error msg received during pairing"));
VerifyOrExit(buflen == sizeof(Spake2pErrorMsg), ChipLogError(Ble, "Error msg with incorrect length received during pairing"));
pMsg = reinterpret_cast<Spake2pErrorMsg *>(msg->Start());
ChipLogError(Ble, "Received error (%d) during pairing process", pMsg->error);
exit:
Clear();
}
CHIP_ERROR PASESession::HandlePeerMessage(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress,
System::PacketBufferHandle msg)
{
CHIP_ERROR err = CHIP_NO_ERROR;
PayloadHeader payloadHeader;
VerifyOrExit(!msg.IsNull(), err = CHIP_ERROR_INVALID_ARGUMENT);
err = payloadHeader.DecodeAndConsume(msg);
SuccessOrExit(err);
VerifyOrExit(payloadHeader.GetProtocolID() == Protocols::kProtocol_SecureChannel, err = CHIP_ERROR_INVALID_MESSAGE_TYPE);
VerifyOrExit(payloadHeader.GetMessageType() == (uint8_t) mNextExpectedMsg, err = CHIP_ERROR_INVALID_MESSAGE_TYPE);
mConnectionState.SetPeerAddress(peerAddress);
switch (static_cast<Protocols::SecureChannel::MsgType>(payloadHeader.GetMessageType()))
{
case Protocols::SecureChannel::MsgType::PBKDFParamRequest:
err = HandlePBKDFParamRequest(packetHeader, msg);
break;
case Protocols::SecureChannel::MsgType::PBKDFParamResponse:
err = HandlePBKDFParamResponse(packetHeader, msg);
break;
case Protocols::SecureChannel::MsgType::PASE_Spake2p1:
err = HandleMsg1_and_SendMsg2(packetHeader, msg);
break;
case Protocols::SecureChannel::MsgType::PASE_Spake2p2:
err = HandleMsg2_and_SendMsg3(packetHeader, msg);
break;
case Protocols::SecureChannel::MsgType::PASE_Spake2p3:
err = HandleMsg3(packetHeader, msg);
break;
default:
err = CHIP_ERROR_INVALID_MESSAGE_TYPE;
break;
};
exit:
// Call delegate to indicate pairing failure
if (err != CHIP_NO_ERROR)
{
mDelegate->OnSessionEstablishmentError(err);
}
return err;
}
} // namespace chip
| 32.686228 | 130 | 0.702378 | hakieyin |
f5fdc9d6ec97f3243f5b022549554d457900938e | 3,117 | cpp | C++ | UVa/UVA - 11476/Accepted (2).cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | UVa/UVA - 11476/Accepted (2).cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | UVa/UVA - 11476/Accepted (2).cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: 2019-02-24 20:08:23
* solution_verdict: Accepted language: C++
* run_time: 9540 memory_used:
* problem: https://vjudge.net/problem/UVA-11476
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e6;
/************ Seive **************/
int IsPrime[N+2];vector<int>Prime;
void Seive(int n)
{
Prime.push_back(2);IsPrime[1]=1;
for(int i=4;i<=n;i+=2)IsPrime[i]=1;
int sq=sqrt(n+1);
for(int i=3;i<=n;i+=2)
{
if(IsPrime[i])continue;Prime.push_back(i);
if(i>sq)continue;
for(int j=i*i;j<=n;j+=2*i)
IsPrime[j]=1;
}
}
///////////////////////////////////
/******************** Pollar-Rho Factorization **************/
unsigned long Multiply(unsigned long a,unsigned long b,unsigned long mod)
{
if(a>b)swap(a,b);unsigned long ret=0;
while(a)
{
if(a%2)ret=(ret+b)%mod;
b=(b+b)%mod;a/=2;
}
return ret;
}
unsigned long Bigmod(unsigned long b,unsigned long p,unsigned long mod)
{
unsigned long ret=1;
while(p)
{
if(p%2)ret=Multiply(ret,b,mod);
b=Multiply(b,b,mod);p/=2;
}
return ret;
}
bool Miller_Test(unsigned long n,int k=5)
{
if(n<2)return false;if(n<4)return true;
if(n%2==0)return false;
unsigned long s=n-1;while(s%2==0)s/=2;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
while(k--)
{
unsigned long a=2+rng()%(n-2),tmp=s;
unsigned long md=Bigmod(a,tmp,n);
if(md==1||md==n-1)continue;
while(tmp!=n-1&&md!=1&&md!=n-1)
md=Multiply(md,md,n),tmp*=2;
if(md!=n-1)return false;
}
return true;
}
unsigned long gcd(unsigned long x,unsigned long y)
{
if(!x||!y)return x+y;unsigned long t;
while(x%y)t=x,x=y,y=t%y;
return y;
}
unsigned long Pollard_Rho(unsigned long n,unsigned long c)
{
unsigned long x=2,y=2,i=1,k=2,d;
while(true)
{
x=Multiply(x,x,n);
x=(x+c)%n;d=gcd(x-y,n);
if(d>1)return d;
if(++i==k)y=x,k<<=1;
}
return n;
}
void Factorize(unsigned long n,vector<unsigned long>&v)
{
if(n==1)return ;
if(Miller_Test(n))
{
v.push_back(n);return ;
}
unsigned long d=n;
for(int i=2;d==n;i++)
d=Pollard_Rho(n,i);
Factorize(d,v);Factorize(n/d,v);
}
//////////////////////////////////////////////////////////
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int t;cin>>t;Seive(N);
while(t--)
{
long n;cin>>n;vector<unsigned long>v;long nn=n;
for(auto x:Prime)
while(n%x==0)
v.push_back(x),n/=x;
Factorize(n,v);map<long,int>mp;
for(auto x:v)mp[x]++;
cout<<nn;int f=0;
for(auto x:mp)
{
if(!f)cout<<" =",f=1;
else cout<<" *";
cout<<" ";cout<<x.first;
if(x.second>1)cout<<"^"<<x.second;
}
cout<<"\n";
}
return 0;
} | 25.760331 | 111 | 0.495348 | kzvd4729 |
f5feb4c8e15c8c3884e4819ae463a4580b8abeea | 1,502 | cpp | C++ | samples/cpp/sync_time_stamp.cpp | huskyroboticsteam/urg-lidar | 6f5cb4f27579a3ef07cbd63d25736905c7b35956 | [
"BSD-2-Clause"
] | null | null | null | samples/cpp/sync_time_stamp.cpp | huskyroboticsteam/urg-lidar | 6f5cb4f27579a3ef07cbd63d25736905c7b35956 | [
"BSD-2-Clause"
] | null | null | null | samples/cpp/sync_time_stamp.cpp | huskyroboticsteam/urg-lidar | 6f5cb4f27579a3ef07cbd63d25736905c7b35956 | [
"BSD-2-Clause"
] | null | null | null | /*!
\example sync_time_stamp.cpp Timestamp synchronization between PC and sensor
\author Satofumi KAMIMURA
$Id$
*/
#include "Urg_driver.h"
#include "Connection_information.h"
#include "ticks.h"
#include <iostream>
using namespace qrk;
using namespace std;
namespace
{
void print_timestamp(Urg_driver& urg)
{
enum { Print_times = 3 };
urg.start_time_stamp_mode();
for (int i = 0; i < Print_times; ++i) {
cout << ticks() << ", " << urg.get_sensor_time_stamp() << endl;
}
urg.stop_time_stamp_mode();
}
}
int main(int argc, char *argv[])
{
Connection_information information(argc, argv);
// Connects to the sensor
Urg_driver urg;
if (!urg.open(information.device_or_ip_name(),
information.baudrate_or_port_number(),
information.connection_type())) {
cout << "Urg_driver::open(): "
<< information.device_or_ip_name() << ": " << urg.what() << endl;
return 1;
}
cout << "# pc,\tsensor" << endl;
// Just to compare, shows the current PC timestamp and sensor timestamp
print_timestamp(urg);
cout << endl;
// Configures the PC timestamp into the sensor
// The timestamp value which comes in the measurement data
// will match the timestamp value from the PC
urg.set_sensor_time_stamp(ticks());
// Displays the PC timestamp and sensor timestamp after configuration
print_timestamp(urg);
return 0;
}
| 23.84127 | 78 | 0.63249 | huskyroboticsteam |
f5ff77f6b94550f451f282bbb72ac88141aa5a8c | 6,249 | cpp | C++ | src/OrbitSshQt/Task.cpp | guruantree/orbit | c59eea66e4dc8313fecef9524850bf58c8ba8c30 | [
"BSD-2-Clause"
] | 2 | 2020-07-31T08:18:58.000Z | 2021-12-26T06:43:07.000Z | src/OrbitSshQt/Task.cpp | guruantree/orbit | c59eea66e4dc8313fecef9524850bf58c8ba8c30 | [
"BSD-2-Clause"
] | null | null | null | src/OrbitSshQt/Task.cpp | guruantree/orbit | c59eea66e4dc8313fecef9524850bf58c8ba8c30 | [
"BSD-2-Clause"
] | null | null | null | // Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "OrbitSshQt/Task.h"
#include <absl/base/macros.h>
#include <type_traits>
#include <utility>
#include "OrbitBase/Logging.h"
#include "OrbitSsh/Error.h"
#include "OrbitSshQt/Error.h"
namespace orbit_ssh_qt {
Task::Task(Session* session, std::string command) : session_(session), command_(command) {
about_to_shutdown_connection_.emplace(
QObject::connect(session_, &Session::aboutToShutdown, this, &Task::HandleSessionShutdown));
}
void Task::Start() {
if (state_ == State::kInitial) {
SetState(State::kNoChannel);
OnEvent();
}
}
void Task::Stop() {
if (state_ == State::kCommandRunning) {
SetState(State::kSignalEOF);
}
OnEvent();
}
std::string Task::ReadStdOut() {
auto tmp = std::move(read_std_out_buffer_);
read_std_out_buffer_ = std::string{};
return tmp;
}
std::string Task::ReadStdErr() {
auto tmp = std::move(read_std_err_buffer_);
read_std_err_buffer_ = std::string{};
return tmp;
}
void Task::Write(std::string_view data) {
write_buffer_.append(data);
OnEvent();
}
outcome::result<void> Task::run() {
// read stdout
bool added_new_data_to_read_buffer = false;
while (true) {
const size_t kChunkSize = 8192;
auto result = channel_->ReadStdOut(kChunkSize);
if (!result && !orbit_ssh::ShouldITryAgain(result)) {
if (added_new_data_to_read_buffer) {
emit readyReadStdOut();
}
return result.error();
} else if (!result) {
if (added_new_data_to_read_buffer) {
emit readyReadStdOut();
}
break;
} else if (result && result.value().empty()) {
// Channel closed
if (added_new_data_to_read_buffer) {
emit readyReadStdOut();
}
SetState(State::kWaitChannelClosed);
break;
} else if (result) {
read_std_out_buffer_.append(std::move(result).value());
added_new_data_to_read_buffer = true;
}
}
// read stderr
added_new_data_to_read_buffer = false;
while (true) {
const size_t kChunkSize = 8192;
auto result = channel_->ReadStdErr(kChunkSize);
if (!result && !orbit_ssh::ShouldITryAgain(result)) {
if (added_new_data_to_read_buffer) {
emit readyReadStdErr();
}
return result.error();
} else if (!result) {
if (added_new_data_to_read_buffer) {
emit readyReadStdErr();
}
break;
} else if (result && result.value().empty()) {
// Channel closed
if (added_new_data_to_read_buffer) {
emit readyReadStdErr();
}
SetState(State::kWaitChannelClosed);
break;
} else if (result) {
read_std_err_buffer_.append(std::move(result).value());
added_new_data_to_read_buffer = true;
}
}
// If the state here is kWaitChannelClosed, that means a close from the remote side was detected.
// This means writing is not possible/necessary anymore, therefore: return early.
if (CurrentState() == State::kWaitChannelClosed) {
return outcome::success();
}
// write
if (!write_buffer_.empty()) {
OUTCOME_TRY(auto&& result, channel_->Write(write_buffer_));
write_buffer_ = write_buffer_.substr(result);
emit bytesWritten(result);
}
return outcome::success();
}
outcome::result<void> Task::startup() {
if (!data_event_connection_) {
data_event_connection_.emplace(
QObject::connect(session_, &Session::dataEvent, this, &Task::OnEvent));
}
switch (CurrentState()) {
case State::kInitial:
case State::kNoChannel: {
auto session = session_->GetRawSession();
if (!session) {
return orbit_ssh::Error::kEagain;
}
OUTCOME_TRY(auto&& channel, orbit_ssh::Channel::OpenChannel(session_->GetRawSession()));
channel_ = std::move(channel);
SetState(State::kChannelInitialized);
ABSL_FALLTHROUGH_INTENDED;
}
case State::kChannelInitialized: {
OUTCOME_TRY(channel_->Exec(command_));
SetState(State::kCommandRunning);
break;
}
case State::kStarted:
case State::kCommandRunning:
case State::kShutdown:
case State::kSignalEOF:
case State::kWaitRemoteEOF:
case State::kSignalChannelClose:
case State::kWaitChannelClosed:
case State::kChannelClosed:
case State::kError:
UNREACHABLE();
}
return outcome::success();
}
outcome::result<void> Task::shutdown() {
switch (state_) {
case State::kInitial:
case State::kNoChannel:
case State::kChannelInitialized:
case State::kStarted:
case State::kCommandRunning:
UNREACHABLE();
case State::kShutdown:
case State::kSignalEOF: {
OUTCOME_TRY(channel_->SendEOF());
SetState(State::kWaitRemoteEOF);
break;
}
case State::kWaitRemoteEOF: {
OUTCOME_TRY(channel_->WaitRemoteEOF());
SetState(State::kSignalChannelClose);
ABSL_FALLTHROUGH_INTENDED;
}
case State::kSignalChannelClose: {
OUTCOME_TRY(channel_->Close());
SetState(State::kWaitChannelClosed);
ABSL_FALLTHROUGH_INTENDED;
}
case State::kWaitChannelClosed: {
OUTCOME_TRY(channel_->WaitClosed());
SetState(State::kChannelClosed);
// The exit status is only guaranteed to be available after the channel is really closed on
// both sides
emit finished(channel_->GetExitStatus());
ABSL_FALLTHROUGH_INTENDED;
}
case State::kChannelClosed:
data_event_connection_ = std::nullopt;
about_to_shutdown_connection_ = std::nullopt;
channel_ = std::nullopt;
break;
case State::kError:
UNREACHABLE();
}
return outcome::success();
}
void Task::SetError(std::error_code e) {
data_event_connection_ = std::nullopt;
about_to_shutdown_connection_ = std::nullopt;
StateMachineHelper::SetError(e);
channel_ = std::nullopt;
}
void Task::HandleSessionShutdown() {
if (CurrentState() != State::kNoChannel && CurrentState() != State::kError) {
SetError(Error::kUncleanSessionShutdown);
}
session_ = nullptr;
}
void Task::HandleEagain() {
if (session_) {
session_->HandleEagain();
}
}
} // namespace orbit_ssh_qt
| 26.591489 | 99 | 0.666667 | guruantree |
eb00ba2e0e8ade66ad4294590669d5ebeb8faf9b | 2,810 | cc | C++ | src/ui-flat-label.cc | emptyland/utaha | d625da3290d7a193c8f18c4575d30178c8b764c1 | [
"MIT"
] | null | null | null | src/ui-flat-label.cc | emptyland/utaha | d625da3290d7a193c8f18c4575d30178c8b764c1 | [
"MIT"
] | null | null | null | src/ui-flat-label.cc | emptyland/utaha | d625da3290d7a193c8f18c4575d30178c8b764c1 | [
"MIT"
] | null | null | null | #include "ui-flat-label.h"
#include "glog/logging.h"
#include SDL_TTF_H
namespace utaha {
UIFlatLabel::UIFlatLabel(TTF_Font *font)
: font_(DCHECK_NOTNULL(font)) {
}
/*virtual*/ UIFlatLabel::~UIFlatLabel() {
if (texture_) {
SDL_DestroyTexture(texture_);
}
}
/*virtual*/ int UIFlatLabel::OnEvent(SDL_Event *, bool *) {
return 0;
}
/*virtual*/ int UIFlatLabel::OnRender(SDL_Renderer *renderer) {
if (!is_show()) {
return 0;
}
int w = 0, h = 0;
if (!texture_) {
SDL_Surface *surface = TTF_RenderUTF8_Blended(font_, text_.c_str(),
font_color_);
if (!surface) {
LOG(ERROR) << "Can not render font." << SDL_GetError();
return -1;
}
w = surface->w;
h = surface->h;
texture_ = SDL_CreateTextureFromSurface(renderer, surface);
if (!texture_) {
LOG(ERROR) << "Can not create texture." << SDL_GetError();
SDL_FreeSurface(surface);
return -1;
}
SDL_FreeSurface(surface);
} else {
if (SDL_QueryTexture(texture_, nullptr, nullptr, &w, &h) < 0) {
LOG(ERROR) << "Invalid texture." << SDL_GetError();
return -1;
}
}
mutable_rect()->w = w + h_padding_size_ * 2;
mutable_rect()->h = h + v_padding_size_ * 2;
SDL_SetRenderDrawColor(renderer, bg_color_.r, bg_color_.g, bg_color_.b,
bg_color_.a);
SDL_RenderFillRect(renderer, &rect());
SDL_SetRenderDrawColor(renderer, font_color_.r, font_color_.g,
font_color_.b, font_color_.a);
SDL_Rect dst = {
rect().x + h_padding_size_,
rect().y + v_padding_size_,
w,
h,
};
SDL_RenderCopy(renderer, texture_, nullptr, &dst);
SDL_SetRenderDrawColor(renderer, border_color_.r, border_color_.g,
border_color_.b, border_color_.a);
SDL_RenderDrawRect(renderer, &rect());
return 0;
}
/*virtual*/ void UIFlatLabel::UpdateRect() {
int w = 0, h = 0;
if (!texture_) {
SDL_Surface *surface = TTF_RenderUTF8_Blended(font_, text_.c_str(),
font_color_);
if (!surface) {
LOG(ERROR) << "Can not render font." << SDL_GetError();
return;
}
w = surface->w;
h = surface->h;
SDL_FreeSurface(surface);
} else {
// Uint32 format;
// int access;
// SDL_QueryTexture(texture_, &format, &access, &w, &h);
SDL_QueryTexture(texture_, nullptr, nullptr, &w, &h);
}
w += h_padding_size_ * 2;
h += v_padding_size_ * 2;
mutable_rect()->w = w;
mutable_rect()->h = h;
}
} // namespace utaha
| 28.383838 | 75 | 0.545907 | emptyland |
eb010aa06ef1e8c9d2c2c33a29647b612e55715e | 431 | cpp | C++ | main.cpp | Algorithms-and-Data-Structures-2021/semester-work-segment-tree-004 | 27b99c860dacb2118d2e6925d45e9a6da5d2bab6 | [
"MIT"
] | null | null | null | main.cpp | Algorithms-and-Data-Structures-2021/semester-work-segment-tree-004 | 27b99c860dacb2118d2e6925d45e9a6da5d2bab6 | [
"MIT"
] | 2 | 2021-05-02T12:53:57.000Z | 2021-05-02T13:09:12.000Z | main.cpp | Algorithms-and-Data-Structures-2021/semester-work-segment-tree-004 | 27b99c860dacb2118d2e6925d45e9a6da5d2bab6 | [
"MIT"
] | null | null | null | #include <iostream>
#include <segment_tree_min.hpp>
#include "segment_tree_sum.hpp"
using namespace itis;
using namespace std;
int main () {
int size;
cin>>size;
int *firstArray = new int[size];
for (int i = 0; i < size; ++i) {
cin>>firstArray[i];
}
SegmentTreeMin *s1 = new SegmentTreeMin (firstArray, size);
s1->update(1,0);
s1->update(2,-1);
s1->update(3,-50);
cout<<s1->getMin(0,7);
delete s1;
return 0;
} | 17.958333 | 60 | 0.651972 | Algorithms-and-Data-Structures-2021 |
eb01478efae467a4db4420913438cce77e0fa061 | 6,744 | cpp | C++ | lib/hx_sbus_decoder_encoder/hx_sbus_decoder.cpp | nkruzan/hx_espnow_rc | 448f8c42bff36f8182665a865fcfe391560b01f0 | [
"MIT"
] | 10 | 2021-07-11T22:24:11.000Z | 2022-02-05T06:13:17.000Z | lib/hx_sbus_decoder_encoder/hx_sbus_decoder.cpp | nkruzan/hx_espnow_rc | 448f8c42bff36f8182665a865fcfe391560b01f0 | [
"MIT"
] | 1 | 2021-11-22T23:09:58.000Z | 2021-11-22T23:35:39.000Z | lib/hx_sbus_decoder_encoder/hx_sbus_decoder.cpp | nkruzan/hx_espnow_rc | 448f8c42bff36f8182665a865fcfe391560b01f0 | [
"MIT"
] | 1 | 2021-11-16T02:41:25.000Z | 2021-11-16T02:41:25.000Z | #include "hx_sbus_decoder.h"
#define SYNC_COUNT 5
//=====================================================================
//=====================================================================
HXSBUSDecoder::HXSBUSDecoder()
{
}
//=====================================================================
//=====================================================================
void HXSBUSDecoder::init(int gpio )
{
lastPacket.init();
lastPacket.failsafe = 1;
lastPacketTime = millis();
#if defined(ESP8266)
Serial1.begin(100000, SERIAL_8E2, SerialMode::SERIAL_RX_ONLY, gpio, false );
#elif defined (ESP32)
Serial1.begin(100000, SERIAL_8E2, gpio, -1, false );
#endif
pinMode(gpio,INPUT);
state = 40;
syncCount = 0;
packetsCount = 0;
resyncSkipCount = 0;
resyncCount = 0;
failsafeCount = 0;
failsafeState = false;
}
//=====================================================================
//=====================================================================
void HXSBUSDecoder::loop()
{
bool reuse = false;
uint8_t incomingByte;
while (Serial1.available() > 0 || reuse)
{
if ( !reuse ) incomingByte = Serial1.read();
reuse = false;
uint8_t* pNext = ((uint8_t*)&packet) + state;
if ( state == 40 ) //sync to the packet end
{
if ( incomingByte == SBUS_FOOTER )
{
state = 0;
syncCount = 0;
}
}
else if ( state >= 30 ) //skip bytes for resync
{
state++;
}
else if ( state == 0 ) //expect packet start
{
if ( incomingByte == SBUS_HEADER )
{
/*
for ( int i = 0; i < SBUS_PACKET_SIZE; i++ )
{
Serial.print(Serial1.read(), HEX);
Serial.print( " ");
}
Serial.println("");
delay(200);
*/
*pNext = incomingByte;
state++;
}
else
{
reuse = true;
resync();
}
}
else if ( state == (SBUS_PACKET_SIZE-1) ) //expect footer
{
if ( incomingByte == SBUS_FOOTER )
{
*pNext = incomingByte;
state++;
}
else
{
reuse = true;
resync();
}
}
else if ( state == SBUS_PACKET_SIZE ) //check if next packet starts as expected
{
if ( incomingByte == SBUS_HEADER ) //next packet started as expected
{
packetsCount++;
if ( syncCount == SYNC_COUNT ) //get good sync ( at least 5 packets) before using data
{
parsePacket();
state = 1;
}
else
{
syncCount++;
state = 1;
}
}
else
{
resync();
}
}
else
{
//receive packet body
*pNext = incomingByte;
state++;
}
}
updateFailsafe();
}
//=====================================================================
//=====================================================================
void HXSBUSDecoder::parsePacket()
{
this->lastPacket = packet;
this->lastPacketTime = millis();
//dump();
//delay(200);
}
//=====================================================================
//=====================================================================
uint16_t HXSBUSDecoder::getChannelValue( uint8_t index ) const
{
return this->lastPacket.getChannelValue( index );
}
//=====================================================================
//=====================================================================
bool HXSBUSDecoder::isOutOfSync() const
{
return (this->syncCount < SYNC_COUNT) || this->lastPacket.failsafe;
}
//=====================================================================
//=====================================================================
bool HXSBUSDecoder::isFailsafe() const
{
return this->failsafeState;
}
//=====================================================================
//=====================================================================
void HXSBUSDecoder::updateFailsafe()
{
bool res = this->lastPacket.failsafe;
unsigned long t = millis();
unsigned long deltaT = t - this->lastPacketTime;
if ( deltaT >= SBUS_SYNC_FAILSAFE_MS )
{
this->lastPacketTime = t - SBUS_SYNC_FAILSAFE_MS;
res = true;
}
if ( !this->failsafeState && res )
{
this->failsafeCount++;
}
this->failsafeState = res;
}
//=====================================================================
//=====================================================================
void HXSBUSDecoder::dump() const
{
Serial.print("Failsafe: ");
Serial.print(this->isFailsafe()?1: 0);
Serial.print(" (");
Serial.print(this->failsafeCount);
Serial.println(")");
Serial.print("OutOfSync:");
Serial.println(this->isOutOfSync()?1: 0);
Serial.print("PacketsCount: ");
Serial.print(this->packetsCount);
Serial.print(" ResyncCount: ");
Serial.println(this->resyncCount);
for ( int i = 0; i < 16; i++ )
{
Serial.print("Channel");
Serial.print(i);
Serial.print(": ");
Serial.println(this->getChannelValue(i));
}
}
//=====================================================================
//=====================================================================
void HXSBUSDecoder::dumpPacket() const
{
uint8_t* p = ((uint8_t*)&packet);
for ( int i = 0; i < SBUS_PACKET_SIZE; i++ )
{
Serial.print(*p++, HEX);
Serial.print( " ");
}
Serial.println("");
}
//=====================================================================
//=====================================================================
void HXSBUSDecoder::resync()
{
resyncSkipCount++;
if ( resyncSkipCount > 10 ) resyncSkipCount = 0;
state = 40 - resyncSkipCount;
resyncCount++;
}
//=====================================================================
//=====================================================================
uint16_t HXSBUSDecoder::getChannelValueInRange( uint8_t index, uint16_t from, uint16_t to ) const
{
return map( constrain( this->getChannelValue(index), SBUS_MIN, SBUS_MAX ), SBUS_MIN, SBUS_MAX, from, to );
} | 27.193548 | 110 | 0.375148 | nkruzan |
eb01b4b1c83e425ef6c274f8713aef325d360bed | 1,297 | cc | C++ | lib/src/util/file.cc | ploubser/cfacter | 269717adb4472a66f9763a228498f47771d41343 | [
"Apache-2.0"
] | null | null | null | lib/src/util/file.cc | ploubser/cfacter | 269717adb4472a66f9763a228498f47771d41343 | [
"Apache-2.0"
] | null | null | null | lib/src/util/file.cc | ploubser/cfacter | 269717adb4472a66f9763a228498f47771d41343 | [
"Apache-2.0"
] | null | null | null | #include <facter/util/file.hpp>
#include <sstream>
#include <fstream>
using namespace std;
namespace facter { namespace util { namespace file {
bool each_line(string const& path, function<bool(string&)> callback)
{
ifstream in(path);
if (!in) {
return false;
}
string line;
while (getline(in, line)) {
if (!callback(line)) {
break;
}
}
return true;
}
string read(string const& path)
{
string contents;
if (!read(path, contents)) {
return {};
}
return contents;
}
bool read(string const& path, string& contents)
{
ifstream in(path, ios::in | ios::binary);
ostringstream buffer;
if (!in) {
return false;
}
buffer << in.rdbuf();
contents = buffer.str();
return true;
}
string read_first_line(string const& path)
{
string line;
if (!read_first_line(path, line)) {
return {};
}
return line;
}
bool read_first_line(string const& path, string& line)
{
ifstream in(path);
return static_cast<bool>(getline(in, line));
}
}}} // namespace facter::util::file
| 20.919355 | 72 | 0.515035 | ploubser |
eb0a9905df545b43a044eeb9db8b9a86e48fff0d | 2,179 | cpp | C++ | actividades/sesion4/Maria/actividad1/actividad 4 vectores.cpp | GonzaCDZ/Programacion-I | 860a39de6b6f337829358881bec5111f9ae25bad | [
"MIT"
] | 1 | 2019-01-12T18:13:54.000Z | 2019-01-12T18:13:54.000Z | actividades/sesion4/Maria/actividad1/actividad 4 vectores.cpp | GonzaCDZ/Programacion-I | 860a39de6b6f337829358881bec5111f9ae25bad | [
"MIT"
] | 1 | 2018-10-14T18:12:28.000Z | 2018-10-14T18:12:28.000Z | actividades/sesion4/Maria/actividad1/actividad 4 vectores.cpp | GonzaCDZ/Programacion-I | 860a39de6b6f337829358881bec5111f9ae25bad | [
"MIT"
] | null | null | null |
#include <iostream>
#include <math.h>
using namespace std;
class Vector3d{
public:
Vector3d(float _x, float _y, float _z){
x = _x;
y = _y;
z = _z;
}
void getCoordenadas(float & a, float & b, float & c){
a = x;
b = y;
c = z;
}
float module(){
return sqrt(x*x+y*y+z*z);
}
void multiplyBy(Vector3d a){
x = x * a.x;
y = y * a.y;
z = z * a.z;
}
void add(Vector3d a){
x = x + a.x;
y = y + a.y;
z = z + a.z;
}
private:
float x, y, z;
};
int main(){
float x, y, z;
cout << "Introduce el valor de x para el primer vector: " << endl;
cin >> x;
cout << "Introduce el valor de y para el primer vector: " << endl;
cin >> y;
cout << "Introduce el valor de z para el primer vector: " << endl;
cin >> z;
Vector3d Vector1{x, y, z};
cout << "Introduce el valor de x para el segundo vector: " << endl;
cin >> x;
cout << "Introduce el valor de y para el segundo vector: " << endl;
cin >> y;
cout << "Introduce el valor de z para el segundo vector: " << endl;
cin >> z;
Vector3d Vector2{x, y, z};
cout << "Introduce el valor de x para el tercer vector: " << endl;
cin >> x;
cout << "Introduce el valor de y para el tercer vector: " << endl;
cin >> y;
cout << "Introduce el valor de z para el tercer vector: " << endl;
cin >> z;
Vector3d Vector3{x, y, z};
cout << "El modulo del primer vector es: " << Vector1.module() << endl;
cout << "El modulo del segundo vector es: " << Vector2.module() << endl;
cout << "El modulo del ptercer vector es: " << Vector3.module() << endl;
Vector1.multiplyBy(Vector2);
Vector1.getCoordenadas(x, y, z);
cout << "Primer vector x segundo vector = x: " << x << " y: " << y << " z: " << z << endl;
Vector2.add(Vector3);
Vector2.getCoordenadas(x, y, z);
cout << "Segundo vector x tercer vector = x: " << x << " y: " << y << " z: " << z << endl;
return 0;
}
| 21.362745 | 94 | 0.494263 | GonzaCDZ |
eb0cac94eebae5baa79a3a46bd2617ee43873bdd | 1,439 | hpp | C++ | bark/world/map/road.hpp | GAIL-4-BARK/bark | 1cfda9ba6e9ec5318fbf01af6b67c242081b516e | [
"MIT"
] | null | null | null | bark/world/map/road.hpp | GAIL-4-BARK/bark | 1cfda9ba6e9ec5318fbf01af6b67c242081b516e | [
"MIT"
] | null | null | null | bark/world/map/road.hpp | GAIL-4-BARK/bark | 1cfda9ba6e9ec5318fbf01af6b67c242081b516e | [
"MIT"
] | null | null | null | // Copyright (c) 2020 Julian Bernhard, Klemens Esterle, Patrick Hart and
// Tobias Kessler
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
#ifndef BARK_WORLD_MAP_ROAD_HPP_
#define BARK_WORLD_MAP_ROAD_HPP_
#include <memory>
#include <map>
#include "bark/world/opendrive/road.hpp"
#include "bark/world/map/lane.hpp"
namespace bark {
namespace world {
namespace map {
using RoadId = unsigned int;
using bark::world::opendrive::XodrRoadPtr;
using bark::world::opendrive::XodrRoad;
using bark::world::opendrive::XodrLanes;
using bark::world::opendrive::XodrLane;
struct Road : public XodrRoad {
explicit Road(const XodrRoadPtr& road) :
XodrRoad(road),
next_road_(nullptr) {}
//! Getter
Lanes GetLanes() const {
return lanes_;
}
LanePtr GetLane(const LaneId& lane_id) const {
if (lanes_.count(lane_id) == 0)
return nullptr;
return lanes_.at(lane_id);
}
std::shared_ptr<Road> GetNextRoad() const {
return next_road_;
}
//! Setter
void SetLanes(const Lanes& lanes) {
lanes_ = lanes;
}
void SetNextRoad(const std::shared_ptr<Road>& road) {
next_road_ = road;
}
std::shared_ptr<Road> next_road_;
Lanes lanes_;
};
using RoadPtr = std::shared_ptr<Road>;
using Roads = std::map<RoadId, RoadPtr>;
} // namespace map
} // namespace world
} // namespace bark
#endif // BARK_WORLD_MAP_ROAD_HPP_
| 21.477612 | 72 | 0.701876 | GAIL-4-BARK |
eb0defa60f96aa232a12c7d08e30137b552fcf4a | 13,671 | cpp | C++ | SerialPrograms/Source/CommonFramework/AudioPipeline/AudioInfo.cpp | BlizzardHero/Arduino-Source | bc4ce6433651b0feef488735098900f8bf4144f8 | [
"MIT"
] | null | null | null | SerialPrograms/Source/CommonFramework/AudioPipeline/AudioInfo.cpp | BlizzardHero/Arduino-Source | bc4ce6433651b0feef488735098900f8bf4144f8 | [
"MIT"
] | null | null | null | SerialPrograms/Source/CommonFramework/AudioPipeline/AudioInfo.cpp | BlizzardHero/Arduino-Source | bc4ce6433651b0feef488735098900f8bf4144f8 | [
"MIT"
] | null | null | null | /* Audio Input Device Info
*
* From: https://github.com/PokemonAutomation/Arduino-Source
*
*/
#include <map>
#include <QtGlobal>
#include "Common/Cpp/Pimpl.tpp"
#include "Common/Cpp/Exceptions.h"
#include "AudioInfo.h"
#include <iostream>
using std::cout;
using std::endl;
#if QT_VERSION_MAJOR == 5
#include <QAudioDeviceInfo>
#elif QT_VERSION_MAJOR == 6
#include <QAudioDevice>
#include <QMediaDevices>
#else
#error "Unsupported Qt version."
#endif
namespace PokemonAutomation{
const char* AUDIO_FORMAT_LABELS[] = {
"(none)",
"1 x 48,000 Hz (Mono)",
"2 x 44,100 Hz (Stereo)",
"2 x 48,000 Hz (Stereo)",
"1 x 96,000 Hz (Mono)",
"1 x 96,000 Hz (Interleaved Stereo L/R)",
"1 x 96,000 Hz (Interleaved Stereo R/L)",
};
void set_format(QAudioFormat& native_format, AudioFormat format){
switch (format){
case AudioFormat::MONO_48000:
if (native_format.channelCount() != 1){
native_format.setChannelCount(1);
}
if (native_format.sampleRate() != 48000){
native_format.setSampleRate(48000);
}
break;
case AudioFormat::DUAL_44100:
if (native_format.channelCount() != 2){
native_format.setChannelCount(2);
}
if (native_format.sampleRate() != 44100){
native_format.setSampleRate(44100);
}
break;
case AudioFormat::DUAL_48000:
if (native_format.channelCount() != 2){
native_format.setChannelCount(2);
}
if (native_format.sampleRate() != 48000){
native_format.setSampleRate(48000);
}
break;
case AudioFormat::MONO_96000:
case AudioFormat::INTERLEAVE_LR_96000:
case AudioFormat::INTERLEAVE_RL_96000:
if (native_format.channelCount() != 1){
native_format.setChannelCount(1);
}
if (native_format.sampleRate() != 96000){
native_format.setSampleRate(96000);
}
break;
default:
throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid AudioFormat: " + std::to_string((size_t)format));
}
#if QT_VERSION_MAJOR == 5
native_format.setSampleType(QAudioFormat::SampleType::Float);
native_format.setSampleSize(32);
#elif QT_VERSION_MAJOR == 6
native_format.setSampleFormat(QAudioFormat::SampleFormat::Float);
#endif
}
// Return a list of our formats that are supported by this device.
// "preferred_index" is set to the index of the list that is preferred by the device.
// If no preferred format matches our formats, -1 is returned.
std::vector<AudioFormat> supported_input_formats(int& preferred_index, const NativeAudioInfo& info, const QString& display_name){
QAudioFormat preferred_format = info.preferredFormat();
int preferred_channels = preferred_format.channelCount();
int preferred_rate = preferred_format.sampleRate();
std::vector<AudioFormat> ret;
preferred_index = -1;
bool stereo = false;
{
QAudioFormat format = preferred_format;
set_format(format, AudioFormat::MONO_48000);
if (info.isFormatSupported(format)){
if (format.channelCount() == preferred_channels && format.sampleRate() == preferred_rate){
preferred_index = (int)ret.size();
}
ret.emplace_back(AudioFormat::MONO_48000);
}
}
#if 1
{
QAudioFormat format = preferred_format;
set_format(format, AudioFormat::DUAL_44100);
if (info.isFormatSupported(format)){
if (format.channelCount() == preferred_channels && format.sampleRate() == preferred_rate){
preferred_index = (int)ret.size();
}
ret.emplace_back(AudioFormat::DUAL_44100);
stereo = true;
}
}
{
QAudioFormat format = preferred_format;
set_format(format, AudioFormat::DUAL_48000);
if (info.isFormatSupported(format)){
if (format.channelCount() == preferred_channels && format.sampleRate() == preferred_rate){
preferred_index = (int)ret.size();
}
ret.emplace_back(AudioFormat::DUAL_48000);
stereo = true;
}
}
#endif
{
QAudioFormat format = preferred_format;
set_format(format, AudioFormat::INTERLEAVE_LR_96000);
if (info.isFormatSupported(format)){
if (format.channelCount() == preferred_channels && format.sampleRate() == preferred_rate){
preferred_index = (int)ret.size();
if (display_name.contains("ShadowCast")){
preferred_index += 1;
}else{
preferred_index += 2;
}
}
ret.emplace_back(AudioFormat::MONO_96000);
ret.emplace_back(AudioFormat::INTERLEAVE_LR_96000);
ret.emplace_back(AudioFormat::INTERLEAVE_RL_96000);
}
}
return ret;
}
std::vector<AudioFormat> supported_output_formats(int& preferred_index, const NativeAudioInfo& info){
QAudioFormat preferred_format = info.preferredFormat();
int preferred_channels = preferred_format.channelCount();
int preferred_rate = preferred_format.sampleRate();
std::vector<AudioFormat> ret;
preferred_index = -1;
{
QAudioFormat format = preferred_format;
set_format(format, AudioFormat::MONO_48000);
if (info.isFormatSupported(format)){
if (format.channelCount() == preferred_channels && format.sampleRate() == preferred_rate){
preferred_index = (int)ret.size();
}
ret.emplace_back(AudioFormat::MONO_48000);
}
}
{
QAudioFormat format = preferred_format;
set_format(format, AudioFormat::DUAL_44100);
if (info.isFormatSupported(format)){
if (format.channelCount() == preferred_channels && format.sampleRate() == preferred_rate){
preferred_index = (int)ret.size();
}
ret.emplace_back(AudioFormat::DUAL_44100);
}
}
{
QAudioFormat format = preferred_format;
set_format(format, AudioFormat::DUAL_48000);
if (info.isFormatSupported(format)){
if (format.channelCount() == preferred_channels && format.sampleRate() == preferred_rate){
preferred_index = (int)ret.size();
}
ret.emplace_back(AudioFormat::DUAL_48000);
}
}
return ret;
}
struct AudioDeviceInfo::Data{
std::string device_name; // For serialization
QString display_name;
std::vector<AudioFormat> supported_formats;
int preferred_format_index;
#if QT_VERSION_MAJOR == 5
QAudioDeviceInfo info;
#elif QT_VERSION_MAJOR == 6
QAudioDevice info;
#endif
};
std::vector<AudioDeviceInfo> AudioDeviceInfo::all_input_devices(){
// The device list that Qt provides above will include duplicates on Windows
// due to Windows having a shadow device (winMM) that seems to be able to
// resample to all formats.
//
// https://bugreports.qt.io/browse/QTBUG-75781
//
// What we need to do here it so try to de-dupe the list while keeping the
// ones that actually support the formats we need the best.
// To do this, for all duplicates we first determine if any of the have a
// preferred format that matches a format that we want. If there is, we
// immediately throw out all the dupes that don't have a preferred format.
// This eliminates all the winMM devices if the primary can be used instead.
//
// Then we throw away all the ones that have fewer supported formats than
// the most. Identical (but different) devices will likely have identical
// names and format support. They won't be deduped.
std::vector<AudioDeviceInfo> list;
#if QT_VERSION_MAJOR == 5
for (NativeAudioInfo& device : QAudioDeviceInfo::availableDevices(QAudio::AudioInput)){
list.emplace_back();
Data& data = list.back().m_body;
QString name = device.deviceName();
data.device_name = name.toStdString();
data.display_name = std::move(name);
data.info = std::move(device);
data.supported_formats = supported_input_formats(data.preferred_format_index, data.info, data.display_name);
}
#elif QT_VERSION_MAJOR == 6
for (NativeAudioInfo& device : QMediaDevices::audioInputs()){
list.emplace_back();
Data& data = list.back().m_body;
data.device_name = device.id().data();
data.display_name = device.description();
data.info = std::move(device);
data.supported_formats = supported_input_formats(data.preferred_format_index, data.info, data.display_name);
}
#endif
// Get map of best devices.
std::map<QString, size_t> best_devices;
for (const AudioDeviceInfo& device : list){
size_t& best_score = best_devices[device.display_name()];
size_t current_score = device.supported_formats().size();
if (device.preferred_format_index() >= 0){
current_score += 100;
}
best_score = std::max(best_score, current_score);
}
// Keep only devices with the most # of formats. Duplicates allowed.
std::vector<AudioDeviceInfo> ret;
for (AudioDeviceInfo& device : list){
size_t best_score = best_devices.find(device.display_name())->second;
size_t current_score = device.supported_formats().size();
if (device.preferred_format_index() >= 0){
current_score += 100;
}
if (current_score >= best_score){
ret.emplace_back(std::move(device));
}
}
return ret;
}
std::vector<AudioDeviceInfo> AudioDeviceInfo::all_output_devices(){
// The device list that Qt provides above will include duplicates on Windows
// due to Windows having a shadow device (winMM) that seems to be able to
// resample to all formats.
//
// https://bugreports.qt.io/browse/QTBUG-75781
//
// What we need to do here it so try to de-dupe the list while keeping the
// ones that actually support the formats we need the best.
// To do this, for all duplicates we throw away the ones that have fewer
// supported formats than the most. Identical (but different) devices will
// likely have identical names and format support. They won't be deduped.
//
// This method will keep the winMM device which we want for audio output.
std::vector<AudioDeviceInfo> list;
#if QT_VERSION_MAJOR == 5
for (NativeAudioInfo& device : QAudioDeviceInfo::availableDevices(QAudio::AudioOutput)){
list.emplace_back();
Data& data = list.back().m_body;
QString name = device.deviceName();
data.device_name = name.toStdString();
data.display_name = std::move(name);
data.info = std::move(device);
data.supported_formats = supported_output_formats(data.preferred_format_index, data.info);
}
#elif QT_VERSION_MAJOR == 6
for (NativeAudioInfo& device : QMediaDevices::audioOutputs()){
list.emplace_back();
Data& data = list.back().m_body;
data.device_name = device.id().data();
data.display_name = device.description();
data.info = std::move(device);
data.supported_formats = supported_output_formats(data.preferred_format_index, data.info);
}
#endif
// Get map of greatest format counts.
std::map<QString, size_t> most_formats;
for (AudioDeviceInfo& device : list){
size_t& count = most_formats[device.display_name()];
count = std::max(count, device.supported_formats().size());
}
// Keep only devices with the most # of formats. Duplicates allowed.
std::vector<AudioDeviceInfo> ret;
for (AudioDeviceInfo& device : list){
auto iter = most_formats.find(device.display_name());
if (device.supported_formats().size() >= iter->second){
ret.emplace_back(std::move(device));
}
}
return ret;
}
AudioDeviceInfo::~AudioDeviceInfo(){}
AudioDeviceInfo::AudioDeviceInfo(const AudioDeviceInfo& x) = default;
void AudioDeviceInfo::operator=(const AudioDeviceInfo& x){
m_body = x.m_body;
}
AudioDeviceInfo::AudioDeviceInfo(){}
AudioDeviceInfo::AudioDeviceInfo(const std::string& device_name){
for (AudioDeviceInfo& info : all_input_devices()){
if (device_name == info.device_name()){
*this = std::move(info);
return;
}
}
for (AudioDeviceInfo& info : all_output_devices()){
if (device_name == info.device_name()){
*this = std::move(info);
return;
}
}
}
AudioDeviceInfo::operator bool() const{
return !m_body->device_name.empty();
}
const QString& AudioDeviceInfo::display_name() const{
return m_body->display_name;
}
const std::string& AudioDeviceInfo::device_name() const{
return m_body->device_name;
}
const std::vector<AudioFormat>& AudioDeviceInfo::supported_formats() const{
return m_body->supported_formats;
}
int AudioDeviceInfo::preferred_format_index() const{
return m_body->preferred_format_index;
}
QAudioFormat AudioDeviceInfo::preferred_format() const{
QAudioFormat format = native_info().preferredFormat();
int index = preferred_format_index();
if (index >= 0){
set_format(format, supported_formats()[index]);
}
return format;
}
const NativeAudioInfo& AudioDeviceInfo::native_info() const{
return m_body->info;
}
bool AudioDeviceInfo::operator==(const AudioDeviceInfo& info){
return device_name() == info.device_name();
}
}
| 31.941589 | 129 | 0.650501 | BlizzardHero |
eb0f619b1a4a387a3b34b870a290f621986d0ca0 | 1,234 | hpp | C++ | project-template/lib/events/EventQueue.hpp | nerudaj/dgm-sdk | 3d0366487a2f4377ba52ab577f990fd8a4bd3e91 | [
"Apache-2.0"
] | null | null | null | project-template/lib/events/EventQueue.hpp | nerudaj/dgm-sdk | 3d0366487a2f4377ba52ab577f990fd8a4bd3e91 | [
"Apache-2.0"
] | null | null | null | project-template/lib/events/EventQueue.hpp | nerudaj/dgm-sdk | 3d0366487a2f4377ba52ab577f990fd8a4bd3e91 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "events/Events.hpp"
#include <vector>
#include <concepts>
#include <memory>
/**
* This is a storage object for object generated each frame
*
* It is a singleton so you can easily add new events from anywhere
* and it contains two methods - add for adding new events like:
* EventQueue::add<EventPlaySound>("kick.wav, 0, false);
*
* and a function process for dealing with the whole queue using
* some EventProcessor. Once the whole queue is processed, all
* events are deleted.
*/
class EventQueue {
protected:
std::vector<EventType> events;
EventQueue() = default;
static EventQueue& get() noexcept {
static EventQueue instance;
return instance;
}
public:
static void process(EventProcessor& p) {
for (auto&& e : get().events)
std::visit(p, e);
get().events.clear();
}
/**
* Add new event to the queue
*
* Event will be processed next time you issue call to process
* Event must derive from EventBase and must be constructible
* from parameters passed to a function.
*/
template<class T, class ... Args>
requires std::constructible_from<T, Args...>
static void add(Args&& ... args) {
get().events.push_back(T(std::forward<Args>(args)...));
}
};
| 25.183673 | 68 | 0.689627 | nerudaj |
eb1061670828bc6ded85057f0d0af05f2b2d27ca | 178 | cpp | C++ | 面试题01.02.判定是否互为字符重排/CheckPermutation.cpp | YichengZhong/Top-Interview-Questions | 124828d321f482a0eaa30012b3706267487bfd24 | [
"MIT"
] | 1 | 2019-10-21T14:40:39.000Z | 2019-10-21T14:40:39.000Z | 面试题01.02.判定是否互为字符重排/CheckPermutation.cpp | YichengZhong/Top-Interview-Questions | 124828d321f482a0eaa30012b3706267487bfd24 | [
"MIT"
] | null | null | null | 面试题01.02.判定是否互为字符重排/CheckPermutation.cpp | YichengZhong/Top-Interview-Questions | 124828d321f482a0eaa30012b3706267487bfd24 | [
"MIT"
] | 1 | 2020-11-04T07:33:34.000Z | 2020-11-04T07:33:34.000Z | class Solution {
public:
bool CheckPermutation(string s1, string s2) {
sort(s1.begin(),s1.end());
sort(s2.begin(),s2.end());
return s1==s2;
}
}; | 17.8 | 49 | 0.544944 | YichengZhong |
eb17ebde879028df29cd6ecd1b150deb05cd1352 | 17,898 | cxx | C++ | Source/VTKExtensions/Meshing/vtkCMBSceneGenPolygon.cxx | developkits/cmb | caaf9cd7ffe0b7c1ac3be9edbce0f9430068d2cb | [
"BSD-3-Clause"
] | null | null | null | Source/VTKExtensions/Meshing/vtkCMBSceneGenPolygon.cxx | developkits/cmb | caaf9cd7ffe0b7c1ac3be9edbce0f9430068d2cb | [
"BSD-3-Clause"
] | null | null | null | Source/VTKExtensions/Meshing/vtkCMBSceneGenPolygon.cxx | developkits/cmb | caaf9cd7ffe0b7c1ac3be9edbce0f9430068d2cb | [
"BSD-3-Clause"
] | null | null | null | //=========================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//=========================================================================
#include "vtkCMBSceneGenPolygon.h"
#include "vtkAppendPolyData.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkCellLocator.h"
#include "vtkCleanPolyData.h"
#include "vtkGenericCell.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkNew.h"
#include "vtkObjectFactory.h"
#include "vtkPolyData.h"
#include "vtkPolygon.h"
#include "smtk/extension/vtk/meshing/vtkCMBPrepareForTriangleMesher.h"
#include "smtk/extension/vtk/meshing/vtkCMBTriangleMesher.h"
#include <algorithm>
#include <deque>
#include <set>
#include <stack>
#include <sys/stat.h>
#include <sys/types.h>
#include <vtksys/SystemTools.hxx>
//for data dumping in debug
//#define DUMP_DEBUG_DATA
#ifdef DUMP_DEBUG_DATA
#define DUMP_DEBUG_DATA_DIR "E:/Work/"
#include "vtkNew.h"
#include "vtkXMLPolyDataWriter.h"
#include <sstream>
#endif
vtkStandardNewMacro(vtkCMBSceneGenPolygon);
namespace
{
class InternalPolygonDetection
{
public:
InternalPolygonDetection(vtkPolyData* arcs);
~InternalPolygonDetection();
bool FindOuterLoop(vtkIdType& startingCellId, std::deque<vtkIdType>& outerLoop);
bool FindInnerLoop(
const std::deque<vtkIdType>& outerLoop, std::vector<std::deque<vtkIdType> >& innerLoops);
protected:
//these are used when finding the outside loop
bool FindLoop(
vtkIdType& startingCellId, std::deque<vtkIdType>& loop, const bool& outerLoopSearch);
int FindNextCellToTraverse(
vtkIdType& currentCellId, vtkIdType& nextCellId, bool& addToBranchStack);
void FindConnectedCells(vtkIdType& currentCellId, std::set<vtkIdType>& connectedCells);
//the input arcs that make up the potential polygon
vtkPolyData* Arcs;
//int store holds if it is visited = 1, visited & deadend = 0
std::map<vtkIdType, int> VisitedNodes;
};
InternalPolygonDetection::InternalPolygonDetection(vtkPolyData* arcs)
{
this->Arcs = arcs;
this->Arcs->BuildLinks();
}
InternalPolygonDetection::~InternalPolygonDetection()
{
this->Arcs = NULL;
}
bool InternalPolygonDetection::FindOuterLoop(
vtkIdType& startingCellId, std::deque<vtkIdType>& outerLoop)
{
return this->FindLoop(startingCellId, outerLoop, true);
}
bool InternalPolygonDetection::FindLoop(
vtkIdType& startingCellId, std::deque<vtkIdType>& loop, const bool& outerLoopSearch)
{
std::stack<vtkIdType> branchCellIds;
//get ready to do a DFS
if (this->Arcs->GetCell(startingCellId)->GetNumberOfPoints() > 2)
{
branchCellIds.push(startingCellId);
}
loop.push_front(startingCellId);
vtkIdType currentCellId = startingCellId;
vtkIdType nextCellId, lastbranchId = -1;
bool hasBranches;
int foundNextCellStatus;
do
{
foundNextCellStatus = this->FindNextCellToTraverse(currentCellId, nextCellId, hasBranches);
if (foundNextCellStatus == 1)
{
loop.push_front(nextCellId);
if (hasBranches && (branchCellIds.size() == 0 || branchCellIds.top() != currentCellId))
{
branchCellIds.push(currentCellId);
}
currentCellId = nextCellId;
}
else if (foundNextCellStatus == 0)
{
if (outerLoopSearch)
{
//we completed the loop. we need to figure out
//if we have unneeded cells on the front, or if
//we are on a dead end
/*need to gather all the connections, once gathered we need
to deque items, and remove them from the gather list
til we have 2 items left
(the cell we came from, and the cell that complets the loop).*/
std::set<vtkIdType> connections;
this->FindConnectedCells(currentCellId, connections);
while (connections.size() > 2)
{
nextCellId = loop.back();
connections.erase(nextCellId);
loop.pop_back();
}
}
loop.push_front(loop.back());
}
else if (foundNextCellStatus == -1)
{
//the second is that we hit a dead branch, so we pop a single element
//from the queue and try that one again
if (branchCellIds.size() == 0 || loop.size() <= 1)
{
//we have a line or polyline.
return false;
}
if (lastbranchId == currentCellId && loop.size() > 0)
{
loop.pop_front();
branchCellIds.pop();
}
//since this is a dead end, we need to mark it visited & a dead end
this->VisitedNodes.insert(std::pair<vtkIdType, int>(currentCellId, 0));
while (loop.front() != branchCellIds.top() && loop.size() > 0)
{
//make sure we clear all the cells since the last branch
loop.pop_front();
}
//try the last branching cell
lastbranchId = currentCellId;
currentCellId = loop.front();
}
} while (loop.front() != loop.back());
return loop.size() > 3;
}
bool InternalPolygonDetection::FindInnerLoop(
const std::deque<vtkIdType>& outerLoop, std::vector<std::deque<vtkIdType> >& innerLoops)
{
if (outerLoop.size() - 1 == static_cast<size_t>(this->Arcs->GetNumberOfLines()))
{
return false;
}
double bounds[6];
this->Arcs->GetBounds(bounds);
//construct the points of the outerloop
int numPolygonPoints = (static_cast<int>(outerLoop.size()) - 1) *
3; //the outerloop will have the same cellId at the starte and end
double* polygonPoints = new double[numPolygonPoints];
double* polygon = polygonPoints; //set the pointer to look at the start
std::deque<vtkIdType>::const_iterator it = outerLoop.begin();
std::set<vtkIdType> usedIds;
vtkIdType cellId;
int index = 0;
while (index < numPolygonPoints)
{
cellId = *it++;
usedIds.insert(cellId);
vtkPoints* cellPoints = this->Arcs->GetCell(cellId)->GetPoints();
if (index != 0)
{
double p0[3], p1[3], p2[3];
p0[0] = polygonPoints[index - 3];
p0[1] = polygonPoints[index - 2];
p0[2] = polygonPoints[index - 1];
cellPoints->GetPoint(0, p1);
cellPoints->GetPoint(1, p2);
if (p0[0] == p1[0] && p0[1] == p1[1] && p0[2] == p1[2])
{
polygonPoints[index] = p2[0];
polygonPoints[index + 1] = p2[1];
polygonPoints[index + 2] = p2[2];
}
else
{
polygonPoints[index] = p1[0];
polygonPoints[index + 1] = p1[1];
polygonPoints[index + 2] = p1[2];
}
}
else
{
cellPoints->GetPoint(0, &polygonPoints[index]);
index += 3;
cellPoints->GetPoint(1, &polygonPoints[index]);
}
index += 3;
}
//since we add two points on the first iteration, we need to add the last id.
cellId = *it++;
usedIds.insert(cellId);
//since we added points based on cell ids, we could
//have a leading and/or trailing point that is not part of the loop
if (polygon[0] == polygon[index - 3] && polygon[1] == polygon[index - 2] &&
polygon[2] == polygon[index - 1])
{
//first id matches second last id
--numPolygonPoints;
}
else if (polygon[0] == polygon[index - 6] && polygon[1] == polygon[index - 5] &&
polygon[2] == polygon[index - 4])
{
//first id matches second last id
numPolygonPoints -= 2;
}
else if (polygon[3] == polygon[index - 3] && polygon[4] == polygon[index - 2] &&
polygon[5] == polygon[index - 1])
{
//second id matches last id
polygon += 3;
--numPolygonPoints;
}
else if (polygon[3] == polygon[index - 6] && polygon[4] == polygon[index - 5] &&
polygon[5] == polygon[index - 4])
{
//second id matches second last id
polygon += 3;
numPolygonPoints -= 2;
}
double normal[3];
vtkPolygon::ComputeNormal(numPolygonPoints, polygonPoints, normal);
//select the first id that isn't part of the outerloop and walk it.
//add all its
vtkCellArray* arcs = this->Arcs->GetLines();
vtkIdType npts, *pts;
cellId = this->Arcs->GetNumberOfVerts(); //this is the id of the current cell;
for (arcs->InitTraversal(); arcs->GetNextCell(npts, pts); ++cellId)
{
//check each of these cells for being part of the innerloop
if (npts == 0)
{
continue;
}
//make sure this isn't part of another loop
if (usedIds.count(cellId) != 0)
{
continue;
}
//presumption: if the first point in the first segment of the inner loop
//is internal all of the loop is internal
int result = vtkPolygon::PointInPolygon(
this->Arcs->GetPoint(pts[0]), numPolygonPoints, polygon, bounds, normal);
if (result == -1)
{
continue;
}
std::deque<vtkIdType> innerLoop;
//good start spot, so start the walk
bool isLoop = this->FindLoop(cellId, innerLoop, false); //returns true only on loops, not lines
bool isLine = innerLoop.size() > 0 && !isLoop;
if (isLoop || isLine)
{
//in the future we are going to need to handle loops and lines different I expect.
innerLoops.push_back(innerLoop);
//we now want to mark all the innerLoop cellIds as invalid start points
//to find other inner loops
for (std::deque<vtkIdType>::const_iterator itIL = innerLoop.begin(); itIL != innerLoop.end();
itIL++)
{
usedIds.insert(*itIL);
}
}
}
delete[] polygonPoints;
return innerLoops.size() > 0;
}
//return codes are:
// 0 - found no next cell, and none of the points were a dead end
// 1 - found the next cell
// -1 - found a single dead end, need to retrace from previous split node
int InternalPolygonDetection::FindNextCellToTraverse(
vtkIdType& currentCellId, vtkIdType& nextCellId, bool& addToBranchStack)
{
addToBranchStack = false;
bool deadEnds = false;
unsigned short ncells;
vtkIdType npts, *pts, *cellIds;
this->Arcs->GetCellPoints(currentCellId, npts, pts);
for (vtkIdType i = 0; i < npts; ++i)
{
this->Arcs->GetPointCells(pts[i], ncells, cellIds);
deadEnds = (!deadEnds) ? (ncells == 1) : deadEnds;
for (vtkIdType j = 0; j < ncells; ++j)
{
nextCellId = cellIds[j];
if (currentCellId != nextCellId &&
this->VisitedNodes.find(nextCellId) == this->VisitedNodes.end())
{
this->VisitedNodes.insert(std::pair<vtkIdType, int>(currentCellId, 1));
addToBranchStack = (ncells > 2);
return 1;
}
}
}
if (deadEnds)
{
return -1;
}
return 0;
}
void InternalPolygonDetection::FindConnectedCells(
vtkIdType& currentCellId, std::set<vtkIdType>& connectedCells)
{
unsigned short ncells;
vtkIdType ci, npts, *pts, *cellIds;
std::map<vtkIdType, int>::iterator it;
this->Arcs->GetCellPoints(currentCellId, npts, pts);
for (vtkIdType i = 0; i < npts; ++i)
{
this->Arcs->GetPointCells(pts[i], ncells, cellIds);
for (vtkIdType j = 0; j < ncells; ++j)
{
ci = cellIds[j];
it = this->VisitedNodes.find(ci);
if (it != this->VisitedNodes.end() && it->second != 0 && ci != currentCellId)
{
//only push back visited nodes that are not dead ends
connectedCells.insert(ci);
}
}
}
}
}
vtkCMBSceneGenPolygon::vtkCMBSceneGenPolygon()
{
this->SetNumberOfInputPorts(1);
}
vtkCMBSceneGenPolygon::~vtkCMBSceneGenPolygon()
{
}
int vtkCMBSceneGenPolygon::FillInputPortInformation(int /*port*/, vtkInformation* info)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkPolyData");
info->Set(vtkAlgorithm::INPUT_IS_REPEATABLE(), 1);
return 1;
}
int vtkCMBSceneGenPolygon::RequestData(vtkInformation* /*request*/,
vtkInformationVector** inputVector, vtkInformationVector* outputVector)
{
//setup the input mesh for the masher
vtkNew<vtkPolyData> preMesh;
//we need to add 3 properties to the polydata to
//correctly prep it for meshing
bool readyForMeshing = this->PrepForMeshing(inputVector[0], preMesh.GetPointer());
#ifdef DUMP_DEBUG_DATA
vtkNew<vtkXMLPolyDataWriter> writer;
writer->SetInputData(preMesh);
std::stringstream buffer;
buffer << DUMP_DEBUG_DATA_DIR << "preMeshedPolygon.vtp";
writer->SetFileName(buffer.str().c_str());
writer->Write();
writer->Update();
#endif
//now lets mesh it
if (readyForMeshing)
{
typedef vtkCMBTriangleMesher vtkTriangleMesher;
vtkNew<vtkTriangleMesher> mesher;
mesher->SetMaxAreaMode(vtkTriangleMesher::RelativeToBounds);
mesher->SetMaxArea(.0005);
mesher->SetPreserveBoundaries(true);
mesher->SetInputData(preMesh.GetPointer());
mesher->Update();
// get the ouptut
vtkPolyData* output = vtkPolyData::SafeDownCast(
outputVector->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT()));
// The arcs may have been on a z plane other than z=0 - lets set the
// value of all the points to be the same as the first point (which
// should belong to one of the original arcs)
vtkPoints* points = mesher->GetOutput(0)->GetPoints();
int i, n = points->GetNumberOfPoints();
double p[3], z;
if (n > 0)
{
// Get the first point
points->GetPoint(0, p);
z = p[2];
for (i = 1; i < n; i++)
{
points->GetPoint(i, p);
p[2] = z;
points->SetPoint(i, p);
}
}
// now move the input through to the output
output->SetPoints(points);
output->SetPolys(mesher->GetOutput(0)->GetPolys());
}
return 1;
}
bool vtkCMBSceneGenPolygon::PrepForMeshing(vtkInformationVector* input, vtkPolyData* mesh)
{
this->AppendArcSets(input, mesh);
bool valid = this->DeterminePolygon(mesh);
return valid;
}
void vtkCMBSceneGenPolygon::AppendArcSets(vtkInformationVector* input, vtkPolyData* mesh)
{
int numInputs = input->GetNumberOfInformationObjects();
vtkCellArray* newCells = vtkCellArray::New();
vtkInformation* inInfo = 0;
for (int idx = 0; idx < numInputs; ++idx)
{
inInfo = input->GetInformationObject(idx);
vtkPolyData* pd = vtkPolyData::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT()));
if (idx == 0)
{
//since the input all share the same point set, we can grab the first input
//object points
mesh->SetPoints(pd->GetPoints());
}
if (pd->GetLines()->GetNumberOfCells() > 0)
{
vtkIdType npts = 0;
vtkIdType* pts = 0;
vtkCellArray* cells = pd->GetLines();
for (cells->InitTraversal(); cells->GetNextCell(npts, pts);)
{
if (npts > 2)
{
for (vtkIdType i = 0; i < (npts - 1); i++)
{
newCells->InsertNextCell(2, pts + i);
}
}
else
{
newCells->InsertNextCell(2, pts);
}
}
}
}
mesh->SetLines(newCells);
newCells->FastDelete();
//make sure we have no verts, triangles, and strips
//reduces possible memory foot print
mesh->SetVerts(NULL);
mesh->SetPolys(NULL);
mesh->SetStrips(NULL);
}
bool vtkCMBSceneGenPolygon::DeterminePolygon(vtkPolyData* mesh)
{
typedef vtkCMBPrepareForTriangleMesher vtkPrepareForMesher;
vtkPrepareForMesher* mapInterface = vtkPrepareForMesher::New();
mapInterface->SetPolyData(mesh);
mapInterface->InitializeNewMapInfo();
//now that we have the properties set with default values
//lets find the external poly boundary
vtkCellLocator* locator = vtkCellLocator::New();
locator->SetDataSet(mesh);
locator->BuildLocator();
//find the starting cell of the outside loop
vtkGenericCell* cell = vtkGenericCell::New();
vtkIdType cellId = 0;
double bounds[6];
mesh->GetBounds(bounds);
//returns the cell, and the cellId
this->FindStartingCellForMesh(locator, cell, cellId, bounds);
locator->Delete();
cell->Delete();
if (cellId == -1)
{
return false;
}
/*
now we are going to have to walk the cells to find the outside loop
we need to setup the InternalPoylgonDetection class
*/
std::deque<vtkIdType> outerLoop;
std::vector<std::deque<vtkIdType> > innerLoops;
InternalPolygonDetection ipd(mesh);
bool outerLoopFound = ipd.FindOuterLoop(cellId, outerLoop);
if (outerLoopFound)
{
bool innerLoopFound = ipd.FindInnerLoop(outerLoop, innerLoops);
vtkIdType minId = (*std::min_element(outerLoop.begin(), outerLoop.end()));
vtkIdType maxId = (*std::max_element(outerLoop.begin(), outerLoop.end()));
//The *3 assumes that all cells are VTK_LINES this may not be the case later on
vtkIdType loopId = mapInterface->AddLoop(1, -1);
mapInterface->AddArc(minId * 3, ((maxId - minId) + 1) * 3, 0, loopId, -1, 0, 0);
if (innerLoopFound)
{
for (unsigned i = 0; i < innerLoops.size(); ++i)
{
std::deque<vtkIdType> innerLoop(innerLoops.at(i));
minId = (*std::min_element(innerLoop.begin(), innerLoop.end()));
maxId = (*std::max_element(innerLoop.begin(), innerLoop.end()));
//The *3 assumes that all cells are VTK_LINES this may not be the case later on
vtkIdType miLoopId = mapInterface->AddLoop(-1, 1);
mapInterface->AddArc(
minId * 3, ((maxId - minId) + 1) * 3, 1 + i, -1, miLoopId, 1 + i, 1 + i);
//This loop can be removed when the new mesher fully takes over
}
}
}
mapInterface->FinalizeNewMapInfo();
mapInterface->Delete();
return outerLoopFound;
}
bool vtkCMBSceneGenPolygon::FindStartingCellForMesh(
vtkCellLocator* locator, vtkGenericCell* cell, vtkIdType& cellId, double bounds[6])
{
double point[3] = { bounds[0], bounds[2], bounds[4] };
double closestPoint[3];
int subId;
double dist2;
locator->FindClosestPoint(point, closestPoint, cell, cellId, subId, dist2);
return (cell != NULL);
}
void vtkCMBSceneGenPolygon::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
| 30.182125 | 99 | 0.655269 | developkits |
a3e2986d7f7858f7cf76fe977c4ddbb7f7c7b338 | 472 | hpp | C++ | src/robolisp/val/float_num.hpp | szsy-robotics/robolisp | 22a9cda2fe43b859a4c5ab559bb7c55756ee0951 | [
"BSD-3-Clause-Clear"
] | 3 | 2020-03-04T16:53:26.000Z | 2020-06-05T08:33:37.000Z | src/robolisp/val/float_num.hpp | szsy-robotics/robolisp | 22a9cda2fe43b859a4c5ab559bb7c55756ee0951 | [
"BSD-3-Clause-Clear"
] | null | null | null | src/robolisp/val/float_num.hpp | szsy-robotics/robolisp | 22a9cda2fe43b859a4c5ab559bb7c55756ee0951 | [
"BSD-3-Clause-Clear"
] | 2 | 2020-03-26T04:14:36.000Z | 2020-06-05T08:33:25.000Z | #pragma once
#include "../val.hpp"
#include <string>
namespace robolisp::impl
{
namespace val
{
class FloatNum : public Val
{
public :
explicit FloatNum(float val);
ValPtr copy() const override;
std::string to_str() const override;
void accept_vis(ValVis *val_vis) override;
const float &get() const;
private :
float val_;
};
ValPtr create_float_num(float val);
}
// namespace val
}
// namespace robolisp::impl
| 12.756757 | 46 | 0.644068 | szsy-robotics |
a3e32b03a0f0a3445b632cdc121a12da04ed9924 | 892 | cpp | C++ | SourceCode/Prototypes/LSystems/LSystems/Vec2.cpp | JosephBarber96/FinalProject | 60400efa64c36b7cdbc975e0df7b937cbaae1d0b | [
"MIT"
] | 2 | 2019-05-18T21:37:17.000Z | 2021-07-16T04:08:23.000Z | SourceCode/Prototypes/LSystems/LSystems/Vec2.cpp | JosephBarber96/FinalProject | 60400efa64c36b7cdbc975e0df7b937cbaae1d0b | [
"MIT"
] | 1 | 2020-04-29T05:37:48.000Z | 2020-04-29T11:14:57.000Z | SourceCode/Prototypes/LSystems/LSystems/Vec2.cpp | JosephBarber96/FinalProject | 60400efa64c36b7cdbc975e0df7b937cbaae1d0b | [
"MIT"
] | 1 | 2021-07-16T04:08:31.000Z | 2021-07-16T04:08:31.000Z | #include <math.h>
#include "Vec2.h"
#include "Utility.h"
Vec2::Vec2(float newAngle)
{
Vec2* temp = Vec2::AngleToVector(newAngle);
x = temp->x;
y = temp->y;
}
Vec2::Vec2(float newX, float newY)
:
x(newX),
y(newY)
{}
Vec2::~Vec2() {}
float Vec2::Length()
{
return sqrt(x * x + y * y);
}
Vec2* Vec2::AngleToVector(float degree)
{
// https://math.stackexchange.com/questions/180874/convert-angle-radians-to-a-heading-vector
float rads = Utility::DegreeToRadians(degree);
float x = cos(rads);
float y = sin(rads);
float roundedX = roundf(x * 100) / 100;
float roundedY = roundf(y * 100) / 100;
return new Vec2(roundedX, roundedY);
}
Vec2* Vec2::operator* (float scale)
{
return new Vec2(x * scale, y * scale);
}
Vec2* Vec2::operator+ (Vec2 vec)
{
return new Vec2(x + vec.x, y + vec.y);
}
Vec2* Vec2::operator/ (float scale)
{
return new Vec2(x / scale, y / scale);
} | 16.218182 | 93 | 0.646861 | JosephBarber96 |
a3e510e171ab9dccb23aa620db50518271206edc | 12,670 | cpp | C++ | src/mongo/s/collection_manager.cpp | wentingwang/morphus | af40299a5f07fd3157946112738f602a566a9908 | [
"Apache-2.0"
] | 5 | 2015-02-03T18:12:03.000Z | 2016-07-09T09:52:00.000Z | src/mongo/s/collection_manager.cpp | stennie/mongo | 9ff44ae9ad16a70e49517a78279260a37d31ac7c | [
"Apache-2.0"
] | null | null | null | src/mongo/s/collection_manager.cpp | stennie/mongo | 9ff44ae9ad16a70e49517a78279260a37d31ac7c | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2012 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mongo/s/collection_manager.h"
#include "mongo/bson/util/builder.h" // for StringBuilder
#include "mongo/util/mongoutils/str.h"
namespace mongo {
using mongoutils::str::stream;
CollectionManager::CollectionManager() { }
CollectionManager::~CollectionManager() { }
CollectionManager* CollectionManager::cloneMinus(const ChunkType& chunk,
const ChunkVersion& newShardVersion,
string* errMsg) const {
// The error message string is optional.
string dummy;
if (errMsg == NULL) {
errMsg = &dummy;
}
// Check that we have the exact chunk that will be subtracted.
if (!chunkExists(chunk, errMsg)) {
// Message was filled in by chunkExists().
return NULL;
}
// If left with no chunks, check that the version is zero.
if (_chunksMap.size() == 1) {
if (newShardVersion.isSet()) {
*errMsg = stream() << "setting version to " << newShardVersion.toString()
<< " on removing last chunk";
return NULL;
}
}
// Can't move version backwards when subtracting chunks. This is what guarantees that
// no read or write would be taken once we subtract data from the current shard.
else if (newShardVersion <= _maxShardVersion) {
*errMsg = stream() << "version " << newShardVersion.toString()
<< " not greater than " << _maxShardVersion.toString();
return NULL;
}
auto_ptr<CollectionManager> manager(new CollectionManager);
manager->_key = this->_key;
manager->_key.getOwned();
manager->_chunksMap = this->_chunksMap;
manager->_chunksMap.erase(chunk.getMin());
manager->_maxShardVersion = newShardVersion;
manager->_maxCollVersion = newShardVersion > _maxCollVersion ?
newShardVersion : this->_maxCollVersion;
manager->fillRanges();
dassert(manager->isValid());
return manager.release();
}
static bool overlap(const ChunkType& chunk,
const BSONObj& l2,
const BSONObj& h2) {
return ! ((chunk.getMax().woCompare(l2) <= 0) ||
(h2.woCompare(chunk.getMin()) <= 0));
}
CollectionManager* CollectionManager::clonePlus(const ChunkType& chunk,
const ChunkVersion& newShardVersion,
string* errMsg) const {
// The error message string is optional.
string dummy;
if (errMsg == NULL) {
errMsg = &dummy;
}
// It is acceptable to move version backwards (e.g., undoing a migration that went bad
// during commit) but only cloning away the last chunk may reset the version to 0.
if (!newShardVersion.isSet()) {
*errMsg = "version can't be set to zero";
return NULL;
}
// Check that there isn't any chunk on the interval to be added.
if (!_chunksMap.empty()) {
RangeMap::const_iterator it = _chunksMap.lower_bound(chunk.getMax());
if (it != _chunksMap.begin()) {
--it;
}
if (overlap(chunk, it->first, it->second)) {
*errMsg = stream() << "ranges overlap, "
<< "requested: " << chunk.getMin()
<<" -> " << chunk.getMax() << " "
<< "existing: " << it->first.toString()
<< " -> " + it->second.toString();
return NULL;
}
}
auto_ptr<CollectionManager> manager(new CollectionManager);
manager->_key = this->_key;
manager->_key.getOwned();
manager->_chunksMap = this->_chunksMap;
manager->_chunksMap.insert(make_pair(chunk.getMin().getOwned(), chunk.getMax().getOwned()));
manager->_maxShardVersion = newShardVersion;
manager->_maxCollVersion = newShardVersion > _maxCollVersion ?
newShardVersion : this->_maxCollVersion;
manager->fillRanges();
dassert(manager->isValid());
return manager.release();
}
static bool contains(const BSONObj& min, const BSONObj& max, const BSONObj& point) {
return point.woCompare(min) >= 0 && point.woCompare(max) < 0;
}
CollectionManager* CollectionManager::cloneSplit(const ChunkType& chunk,
const vector<BSONObj>& splitKeys,
const ChunkVersion& newShardVersion,
string* errMsg) const {
// The error message string is optional.
string dummy;
if (errMsg == NULL) {
errMsg = &dummy;
}
// The version required in both resulting chunks could be simply an increment in the
// minor portion of the current version. However, we are enforcing uniqueness over the
// attributes <ns, version> of the configdb collection 'chunks'. So in practice, a
// migrate somewhere may force this split to pick up a version that has the major
// portion higher than the one that this shard has been using.
//
// TODO drop the uniqueness constraint and tighten the check below so that only the
// minor portion of version changes
if (newShardVersion <= _maxShardVersion) {
*errMsg = stream()<< "version " << newShardVersion.toString()
<< " not greater than " << _maxShardVersion.toString();
return NULL;
}
// Check that we have the exact chunk that will be split and that the split point is
// valid.
if (!chunkExists(chunk, errMsg)) {
return NULL;
}
for (vector<BSONObj>::const_iterator it = splitKeys.begin();
it != splitKeys.end();
++it) {
if (!contains(chunk.getMin(), chunk.getMax(), *it)) {
*errMsg = stream() << "can split " << chunk.getMin()
<< " -> " << chunk.getMax() << " on " << *it;
return NULL;
}
}
auto_ptr<CollectionManager> manager(new CollectionManager);
manager->_key = this->_key;
manager->_key.getOwned();
manager->_chunksMap = this->_chunksMap;
manager->_maxShardVersion = newShardVersion; // will increment 2nd, 3rd,... chunks below
BSONObj startKey = chunk.getMin();
for (vector<BSONObj>::const_iterator it = splitKeys.begin();
it != splitKeys.end();
++it) {
BSONObj split = *it;
manager->_chunksMap[chunk.getMin()] = split.getOwned();
manager->_chunksMap.insert(make_pair(split.getOwned(), chunk.getMax().getOwned()));
manager->_maxShardVersion.incMinor();
startKey = split;
}
manager->_maxCollVersion = manager->_maxShardVersion > _maxCollVersion ?
manager->_maxShardVersion : this->_maxCollVersion;
manager->fillRanges();
dassert(manager->isValid());
return manager.release();
}
bool CollectionManager::belongsToMe(const BSONObj& point) const {
// For now, collections don't move. So if the collection is not sharded, assume
// the documet ca be accessed.
if (_key.isEmpty()) {
return true;
}
if (_rangesMap.size() <= 0) {
return false;
}
RangeMap::const_iterator it = _rangesMap.upper_bound(point);
if (it != _rangesMap.begin())
it--;
bool good = contains(it->first, it->second, point);
// Logs if in debugging mode and the point doesn't belong here.
if(dcompare(!good)) {
log() << "bad: " << point << " "
<< it->first << " " << point.woCompare(it->first) << " "
<< point.woCompare(it->second) << endl;
for (RangeMap::const_iterator i=_rangesMap.begin(); i!=_rangesMap.end(); ++i) {
log() << "\t" << i->first << "\t" << i->second << "\t" << endl;
}
}
return good;
}
bool CollectionManager::getNextChunk(const BSONObj& lookupKey,
ChunkType* chunk) const {
if (_chunksMap.empty()) {
return true;
}
RangeMap::const_iterator it;
if (lookupKey.isEmpty()) {
it = _chunksMap.begin();
chunk->setMin(it->first);
chunk->setMax(it->second);
return _chunksMap.size() == 1;
}
it = _chunksMap.upper_bound(lookupKey);
if (it != _chunksMap.end()) {
chunk->setMin(it->first);
chunk->setMax(it->second);
return false;
}
return true;
}
string CollectionManager::toString() const {
StringBuilder ss;
ss << " CollectionManager version: " << _maxShardVersion.toString() << " key: " << _key;
if (_rangesMap.empty()) {
return ss.str();
}
RangeMap::const_iterator it = _rangesMap.begin();
ss << it->first << " -> " << it->second;
while (it != _rangesMap.end()) {
ss << ", "<< it->first << " -> " << it->second;
}
return ss.str();
}
bool CollectionManager::isValid() const {
if (_maxShardVersion > _maxCollVersion) {
return false;
}
if (_maxCollVersion.majorVersion() == 0)
return false;
return true;
}
bool CollectionManager::chunkExists(const ChunkType& chunk,
string* errMsg) const {
RangeMap::const_iterator it = _chunksMap.find(chunk.getMin());
if (it == _chunksMap.end()) {
*errMsg = stream() << "couldn't find chunk " << chunk.getMin()
<< "->" << chunk.getMax();
return false;
}
if (it->second.woCompare(chunk.getMax()) != 0) {
*errMsg = stream() << "ranges differ, "
<< "requested: " << chunk.getMin()
<< " -> " << chunk.getMax() << " "
<< "existing: "
<< ((it == _chunksMap.end()) ?
"<empty>" :
it->first.toString() + " -> " + it->second.toString());
return false;
}
return true;
}
void CollectionManager::fillRanges() {
if (_chunksMap.empty())
return;
// Load the chunk information, coallesceing their ranges. The version for this shard
// would be the highest version for any of the chunks.
RangeMap::const_iterator it = _chunksMap.begin();
BSONObj min,max;
while (it != _chunksMap.end()) {
BSONObj currMin = it->first;
BSONObj currMax = it->second;
++it;
// coalesce the chunk's bounds in ranges if they are adjacent chunks
if (min.isEmpty()) {
min = currMin;
max = currMax;
continue;
}
if (max == currMin) {
max = currMax;
continue;
}
_rangesMap.insert(make_pair(min, max));
min = currMin;
max = currMax;
}
dassert(!min.isEmpty());
_rangesMap.insert(make_pair(min, max));
}
} // namespace mongo
| 37.485207 | 100 | 0.52423 | wentingwang |
a3e53f89064ea6e089637f6d1b748a3ee617efc3 | 742 | cpp | C++ | src/layers/medCore/process/single_filter/medAbstractAddFilterProcess.cpp | dmargery/medInria-public | c232dbdf9353e14ec6e5184349ef1e523def0b76 | [
"BSD-4-Clause"
] | 61 | 2015-04-14T13:00:50.000Z | 2022-03-09T22:22:18.000Z | src/layers/medCore/process/single_filter/medAbstractAddFilterProcess.cpp | dmargery/medInria-public | c232dbdf9353e14ec6e5184349ef1e523def0b76 | [
"BSD-4-Clause"
] | 510 | 2016-02-03T13:28:18.000Z | 2022-03-23T10:23:44.000Z | src/layers/medCore/process/single_filter/medAbstractAddFilterProcess.cpp | mathildemerle/medInria-public | e8c517ef6263c1d98a62b79ca7aad30a21b61094 | [
"BSD-4-Clause",
"BSD-1-Clause"
] | 36 | 2015-03-03T22:58:19.000Z | 2021-12-28T18:19:23.000Z | /*=========================================================================
medInria
Copyright (c) INRIA 2013 - 2018. All rights reserved.
See LICENSE.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
=========================================================================*/
#include <medAbstractAddFilterProcess.h>
#include <medDoubleParameter.h>
medAbstractAddFilterProcess::medAbstractAddFilterProcess(QObject *parent)
: medAbstractSingleFilterOperationDoubleProcess(parent)
{
this->doubleParameter()->setCaption("Added constant");
this->doubleParameter()->setDescription("Value of added constant");
}
| 32.26087 | 75 | 0.625337 | dmargery |
a3e6650f0b687e06262a76e25947d10fd5a304dc | 1,563 | hpp | C++ | include/sprout/type_traits/aligned_union.hpp | thinkoid/Sprout | a5a5944bb1779d3bb685087c58c20a4e18df2f39 | [
"BSL-1.0"
] | 4 | 2021-12-29T22:17:40.000Z | 2022-03-23T11:53:44.000Z | dsp/lib/sprout/sprout/type_traits/aligned_union.hpp | TheSlowGrowth/TapeLooper | ee8d8dccc27e39a6f6f6f435847e4d5e1b97c264 | [
"MIT"
] | 16 | 2021-10-31T21:41:09.000Z | 2022-01-22T10:51:34.000Z | include/sprout/type_traits/aligned_union.hpp | thinkoid/Sprout | a5a5944bb1779d3bb685087c58c20a4e18df2f39 | [
"BSL-1.0"
] | null | null | null | /*=============================================================================
Copyright (c) 2011-2019 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
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 SPROUT_TYPE_TRAITS_ALIGNED_UNION_HPP
#define SPROUT_TYPE_TRAITS_ALIGNED_UNION_HPP
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/workaround/std/cstddef.hpp>
#include <sprout/type_traits/alignment_of.hpp>
#if !defined(_LIBCPP_VERSION) || (_LIBCPP_VERSION < 1101)
# include <sprout/tpp/algorithm/max_element.hpp>
#endif
namespace sprout {
//
// aligned_union
//
#if !defined(_LIBCPP_VERSION) || (_LIBCPP_VERSION < 1101)
template<std::size_t Len, typename... Types>
struct aligned_union
: public std::aligned_storage<
sprout::tpp::max_element_c<std::size_t, Len, sizeof(Types)...>::value,
sprout::tpp::max_element_c<std::size_t, sprout::alignment_of<Types>::value...>::value
>
{};
#else // #if !defined(_LIBCPP_VERSION) || (_LIBCPP_VERSION < 1101)
using std::aligned_union;
#endif // #if !defined(_LIBCPP_VERSION) || (_LIBCPP_VERSION < 1101)
#if SPROUT_USE_TEMPLATE_ALIASES
template<std::size_t Len, typename... Types>
using aligned_union_t = typename sprout::aligned_union<Len, Types...>::type;
#endif // #if SPROUT_USE_TEMPLATE_ALIASES
} // namespace sprout
#endif // #ifndef SPROUT_TYPE_TRAITS_ALIGNED_UNION_HPP
| 37.214286 | 88 | 0.680742 | thinkoid |
a3eb5ffc026bd6d9b2496f7c2e1c4b69b184af02 | 30,814 | cpp | C++ | products/PurePhone/services/appmgr/ApplicationManager.cpp | mudita/MuditaOS | fc05d5e6188630518f4456b25968ee8ccd618ba7 | [
"BSL-1.0"
] | 369 | 2021-11-10T09:20:29.000Z | 2022-03-30T06:36:58.000Z | products/PurePhone/services/appmgr/ApplicationManager.cpp | mudita/MuditaOS | fc05d5e6188630518f4456b25968ee8ccd618ba7 | [
"BSL-1.0"
] | 149 | 2021-11-10T08:38:35.000Z | 2022-03-31T23:01:52.000Z | products/PurePhone/services/appmgr/ApplicationManager.cpp | mudita/MuditaOS | fc05d5e6188630518f4456b25968ee8ccd618ba7 | [
"BSL-1.0"
] | 41 | 2021-11-10T08:30:37.000Z | 2022-03-29T08:12:46.000Z | // Copyright (c) 2017-2022, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#include <appmgr/ApplicationManager.hpp>
#include <apps-common/popups/data/BluetoothModeParams.hpp>
#include <application-desktop/ApplicationDesktop.hpp>
#include <application-onboarding/ApplicationOnBoarding.hpp>
#include <apps-common/popups/data/PhoneModeParams.hpp>
#include <apps-common/popups/data/PopupRequestParams.hpp>
#include <apps-common/actions/AlarmClockStatusChangeParams.hpp>
#include <module-db/queries/notifications/QueryNotificationsGetAll.hpp>
#include <system/messages/TetheringQuestionRequest.hpp>
#include <Timers/TimerFactory.hpp>
#include <service-appmgr/Constants.hpp>
#include <service-appmgr/messages/AutoLockRequests.hpp>
#include <service-appmgr/messages/GetAllNotificationsRequest.hpp>
#include <service-appmgr/messages/GetWallpaperOptionRequest.hpp>
#include <service-bluetooth/messages/BluetoothModeChanged.hpp>
#include <service-bluetooth/messages/Authenticate.hpp>
#include <service-cellular/CellularMessage.hpp>
#include <service-db/DBNotificationMessage.hpp>
#include <service-db/agents/settings/SystemSettings.hpp>
#include <service-desktop/Constants.hpp>
#include <service-desktop/DesktopMessages.hpp>
#include <service-desktop/DeveloperModeMessage.hpp>
#include <service-evtmgr/EVMessages.hpp>
#include <service-evtmgr/Constants.hpp>
#include <service-evtmgr/torch.hpp>
#include <sys/messages/TetheringPhoneModeChangeProhibitedMessage.hpp>
#include <service-time/include/service-time/AlarmMessage.hpp>
#include <service-time/include/service-time/AlarmServiceAPI.hpp>
namespace app::manager
{
namespace
{
constexpr auto autoLockTimerName = "AutoLockTimer";
} // namespace
ApplicationManager::ApplicationManager(const ApplicationName &serviceName,
std::vector<std::unique_ptr<app::ApplicationLauncher>> &&launchers,
const ApplicationName &_rootApplicationName)
: ApplicationManagerCommon(serviceName, std::move(launchers), _rootApplicationName),
phoneModeObserver(std::make_shared<sys::phone_modes::Observer>()),
phoneLockHandler(locks::PhoneLockHandler(this, settings)),
simLockHandler(this), notificationsConfig{phoneModeObserver, settings, phoneLockHandler},
notificationsHandler{this, notificationsConfig}, notificationProvider{this, notificationsConfig}
{
autoLockTimer = sys::TimerFactory::createSingleShotTimer(
this, autoLockTimerName, sys::timer::InfiniteTimeout, [this](sys::Timer &) { onPhoneLocked(); });
bus.channels.push_back(sys::BusChannel::BluetoothModeChanges);
bus.channels.push_back(sys::BusChannel::BluetoothNotifications);
bus.channels.push_back(sys::BusChannel::PhoneModeChanges);
bus.channels.push_back(sys::BusChannel::PhoneLockChanges);
bus.channels.push_back(sys::BusChannel::ServiceCellularNotifications);
registerMessageHandlers();
}
sys::ReturnCodes ApplicationManager::InitHandler()
{
ApplicationManagerCommon::InitHandler();
startBackgroundApplications();
phoneLockHandler.enablePhoneLock((utils::getNumericValue<bool>(
settings->getValue(settings::SystemProperties::lockScreenPasscodeIsOn, settings::SettingsScope::Global))));
phoneLockHandler.setPhoneLockHash(
settings->getValue(settings::SystemProperties::lockPassHash, settings::SettingsScope::Global));
phoneLockHandler.setPhoneLockTime(utils::getNumericValue<time_t>(
settings->getValue(settings::SystemProperties::unlockLockTime, settings::SettingsScope::Global)));
phoneLockHandler.setNextUnlockAttemptLockTime(utils::getNumericValue<time_t>(
settings->getValue(settings::SystemProperties::unlockAttemptLockTime, settings::SettingsScope::Global)));
phoneLockHandler.setNoLockTimeAttemptsLeft(utils::getNumericValue<unsigned int>(
settings->getValue(settings::SystemProperties::noLockTimeAttemptsLeft, settings::SettingsScope::Global)));
wallpaperModel.setWallpaper(static_cast<gui::WallpaperOption>(utils::getNumericValue<unsigned int>(
settings->getValue(settings::Wallpaper::option, settings::SettingsScope::Global))));
settings->registerValueChange(
settings::SystemProperties::lockScreenPasscodeIsOn,
[this](const std::string &value) { phoneLockHandler.enablePhoneLock(utils::getNumericValue<bool>(value)); },
settings::SettingsScope::Global);
settings->registerValueChange(
settings::SystemProperties::lockPassHash,
[this](const std::string &value) { phoneLockHandler.setPhoneLockHash(value); },
settings::SettingsScope::Global);
settings->registerValueChange(
::settings::KeypadLight::state,
[this](const std::string &value) {
const auto keypadLightState =
static_cast<bsp::keypad_backlight::State>(utils::getNumericValue<int>(value));
processKeypadBacklightState(keypadLightState);
},
::settings::SettingsScope::Global);
settings->registerValueChange(
settings::SystemProperties::autoLockTimeInSec,
[this](std::string value) { lockTimeChanged(std::move(value)); },
settings::SettingsScope::Global);
settings->registerValueChange(
settings::Wallpaper::option,
[this](std::string value) {
wallpaperModel.setWallpaper(
static_cast<gui::WallpaperOption>(utils::getNumericValue<unsigned int>(value)));
},
settings::SettingsScope::Global);
return sys::ReturnCodes::Success;
}
void ApplicationManager::processKeypadBacklightState(bsp::keypad_backlight::State keypadLightState)
{
auto action = bsp::keypad_backlight::Action::turnOff;
switch (keypadLightState) {
case bsp::keypad_backlight::State::activeMode:
action = bsp::keypad_backlight::Action::turnOnActiveMode;
break;
case bsp::keypad_backlight::State::off:
action = bsp::keypad_backlight::Action::turnOff;
break;
}
bus.sendUnicast(std::make_shared<sevm::KeypadBacklightMessage>(action), service::name::evt_manager);
}
void ApplicationManager::startBackgroundApplications()
{
runAppsInBackground();
}
void ApplicationManager::registerMessageHandlers()
{
ApplicationManagerCommon::registerMessageHandlers();
phoneModeObserver->connect(this);
phoneModeObserver->subscribe([this](sys::phone_modes::PhoneMode phoneMode) {
handlePhoneModeChanged(phoneMode);
actionsRegistry.enqueue(
ActionEntry{actions::ShowPopup, std::make_unique<gui::PhoneModePopupRequestParams>(phoneMode)});
});
phoneModeObserver->subscribe(
[this](sys::phone_modes::Tethering tethering) { handleTetheringChanged(tethering); });
notificationsHandler.registerMessageHandlers();
connect(typeid(PreventBlockingRequest), [this]([[maybe_unused]] sys::Message *msg) {
if (!phoneLockHandler.isPhoneLocked()) {
autoLockTimer.start();
}
return std::make_shared<sys::ResponseMessage>();
});
connect(typeid(GetAllNotificationsRequest), [&](sys::Message *request) {
notificationProvider.requestNotSeenNotifications();
notificationProvider.send();
return sys::msgHandled();
});
connect(typeid(GetWallpaperOptionRequest), [&](sys::Message *request) {
return std::make_shared<app::manager::GetWallpaperOptionResponse>(wallpaperModel.getWallpaper());
});
connect(typeid(db::NotificationMessage), [&](sys::Message *msg) {
auto msgl = static_cast<db::NotificationMessage *>(msg);
notificationProvider.handle(msgl);
return sys::msgHandled();
});
connect(typeid(db::QueryResponse), [&](sys::Message *msg) {
auto response = static_cast<db::QueryResponse *>(msg);
handleDBResponse(response);
return sys::msgHandled();
});
// PhoneLock connects
connect(typeid(locks::LockPhone),
[&](sys::Message *request) -> sys::MessagePointer { return phoneLockHandler.handleLockRequest(); });
connect(typeid(locks::UnlockPhone),
[&](sys::Message *request) -> sys::MessagePointer { return phoneLockHandler.handleUnlockRequest(); });
connect(typeid(locks::CancelUnlockPhone), [&](sys::Message *request) -> sys::MessagePointer {
return phoneLockHandler.handleUnlockCancelRequest();
});
connect(typeid(locks::UnLockPhoneInput), [&](sys::Message *request) -> sys::MessagePointer {
auto data = static_cast<locks::UnLockPhoneInput *>(request);
return phoneLockHandler.handlePhoneLockInput(data->getInputData());
});
connect(typeid(locks::EnablePhoneLock),
[&](sys::Message *request) -> sys::MessagePointer { return phoneLockHandler.handleEnablePhoneLock(); });
connect(typeid(locks::DisablePhoneLock), [&](sys::Message *request) -> sys::MessagePointer {
return phoneLockHandler.handleDisablePhoneLock();
});
connect(typeid(locks::UnlockedPhone), [&](sys::Message *request) -> sys::MessagePointer {
autoLockTimer.start();
return simLockHandler.releaseSimUnlockBlockOnLockedPhone();
});
connect(typeid(locks::ChangePhoneLock),
[&](sys::Message *request) -> sys::MessagePointer { return phoneLockHandler.handleChangePhoneLock(); });
connect(typeid(locks::SetPhoneLock),
[&](sys::Message *request) -> sys::MessagePointer { return phoneLockHandler.handleSetPhoneLock(); });
connect(typeid(locks::SkipSetPhoneLock), [&](sys::Message *request) -> sys::MessagePointer {
return phoneLockHandler.handleSkipSetPhoneLock();
});
connect(typeid(locks::PhoneLockTimeUpdate), [&](sys::Message *request) -> sys::MessagePointer {
auto req = static_cast<locks::PhoneLockTimeUpdate *>(request);
notificationProvider.handle(req);
return sys::msgHandled();
});
connect(typeid(SetAutoLockTimeoutRequest), [&](sys::Message *request) -> sys::MessagePointer {
auto req = static_cast<SetAutoLockTimeoutRequest *>(request);
return handleAutoLockSetRequest(req);
});
connect(typeid(locks::ExternalUnLockPhone), [&](sys::Message *request) -> sys::MessagePointer {
auto data = static_cast<locks::ExternalUnLockPhone *>(request);
return phoneLockHandler.handleExternalUnlockRequest(data->getInputData());
});
connect(typeid(locks::ExternalPhoneLockAvailabilityChange), [&](sys::Message *request) -> sys::MessagePointer {
auto data = static_cast<locks::ExternalPhoneLockAvailabilityChange *>(request);
return phoneLockHandler.handleExternalAvailabilityChange(data->getAvailability());
});
// SimLock connects
connect(typeid(cellular::msg::notification::SimNeedPin), [&](sys::Message *request) -> sys::MessagePointer {
auto data = static_cast<cellular::msg::notification::SimNeedPin *>(request);
if (phoneLockHandler.isPhoneLocked()) {
simLockHandler.setSimUnlockBlockOnLockedPhone();
}
return simLockHandler.handleSimPinRequest(data->attempts);
});
connect(typeid(cellular::msg::request::sim::PinUnlock::Response),
[&](sys::Message *request) -> sys::MessagePointer {
auto data = static_cast<cellular::msg::request::sim::PinUnlock::Response *>(request);
if (data->retCode) {
return simLockHandler.handleSimUnlockedMessage();
}
return sys::msgNotHandled();
});
connect(typeid(locks::UnLockSimInput), [&](sys::Message *request) -> sys::MessagePointer {
auto msg = static_cast<locks::UnLockSimInput *>(request);
return simLockHandler.verifySimLockInput(msg->getInputData());
});
connect(typeid(locks::ResetSimLockState), [&](sys::Message *request) -> sys::MessagePointer {
return simLockHandler.handleResetSimLockStateRequest();
});
connect(typeid(cellular::msg::notification::SimNeedPuk), [&](sys::Message *request) -> sys::MessagePointer {
auto data = static_cast<cellular::msg::notification::SimNeedPuk *>(request);
if (phoneLockHandler.isPhoneLocked()) {
simLockHandler.setSimUnlockBlockOnLockedPhone();
}
return simLockHandler.handleSimPukRequest(data->attempts);
});
connect(typeid(cellular::msg::request::sim::UnblockWithPuk::Response),
[&](sys::Message *request) -> sys::MessagePointer {
auto data = static_cast<cellular::msg::request::sim::UnblockWithPuk::Response *>(request);
if (data->retCode) {
return simLockHandler.handleSimUnlockedMessage();
}
return sys::msgNotHandled();
});
connect(typeid(locks::ChangeSimPin), [&](sys::Message *request) -> sys::MessagePointer {
return simLockHandler.handleSimPinChangeRequest();
});
connect(typeid(cellular::msg::request::sim::ChangePin::Response),
[&](sys::Message *request) -> sys::MessagePointer {
auto data = static_cast<cellular::msg::request::sim::ChangePin::Response *>(request);
if (data->retCode) {
return simLockHandler.handleSimPinChangedMessage();
}
else {
return simLockHandler.handleSimPinChangeFailedRequest();
}
});
connect(typeid(locks::EnableSimPin),
[&](sys::Message *request) -> sys::MessagePointer { return simLockHandler.handleSimEnableRequest(); });
connect(typeid(locks::DisableSimPin),
[&](sys::Message *request) -> sys::MessagePointer { return simLockHandler.handleSimDisableRequest(); });
connect(typeid(cellular::msg::request::sim::SetPinLock::Response),
[&](sys::Message *request) -> sys::MessagePointer {
auto data = static_cast<cellular::msg::request::sim::SetPinLock::Response *>(request);
if (data->retCode) {
return simLockHandler.handleSimAvailabilityMessage();
}
else {
if (data->lock == cellular::api::SimLockState::Enabled) {
return simLockHandler.handleSimEnableRequest();
}
else {
return simLockHandler.handleSimDisableRequest();
}
}
});
connect(typeid(cellular::msg::notification::SimBlocked), [&](sys::Message *request) -> sys::MessagePointer {
if (phoneLockHandler.isPhoneLocked()) {
simLockHandler.setSimUnlockBlockOnLockedPhone();
}
return simLockHandler.handleSimBlockedRequest();
});
connect(typeid(cellular::msg::notification::UnhandledCME), [&](sys::Message *request) -> sys::MessagePointer {
auto data = static_cast<cellular::msg::notification::UnhandledCME *>(request);
if (phoneLockHandler.isPhoneLocked()) {
simLockHandler.setSimUnlockBlockOnLockedPhone();
}
return simLockHandler.handleCMEErrorRequest(data->code);
});
connect(typeid(cellular::msg::notification::SimNotInserted), [&](sys::Message *request) -> sys::MessagePointer {
return simLockHandler.handleSimNotInsertedMessage();
});
connect(typeid(locks::SetSim), [&](sys::Message *request) -> sys::MessagePointer {
auto data = static_cast<locks::SetSim *>(request);
simLockHandler.setSim(data->getSimSlot());
return sys::msgHandled();
});
connect(typeid(cellular::msg::request::sim::SetActiveSim::Response),
[&](sys::Message *request) -> sys::MessagePointer {
auto data = static_cast<cellular::msg::request::sim::SetActiveSim::Response *>(request);
if (data->retCode) {
settings->setValue(::settings::SystemProperties::activeSim,
utils::enumToString(Store::GSM::get()->selected),
::settings::SettingsScope::Global);
return sys::msgHandled();
}
return sys::msgNotHandled();
});
connect(typeid(cellular::msg::notification::SimReady),
[&](sys::Message *request) -> sys::MessagePointer { return simLockHandler.handleSimReadyMessage(); });
connect(typeid(cellular::msg::notification::ModemStateChanged),
[&](sys::Message *request) -> sys::MessagePointer {
auto data = static_cast<cellular::msg::notification::ModemStateChanged *>(request);
if (data->state == cellular::api::ModemState::Ready) {
simLockHandler.setSimReady();
simLockHandler.getSettingsSimSelect(
settings->getValue(settings::SystemProperties::activeSim, settings::SettingsScope::Global));
return sys::msgHandled();
}
return sys::msgNotHandled();
});
connect(typeid(sys::bluetooth::BluetoothModeChanged), [&](sys::Message *request) -> sys::MessagePointer {
auto data = static_cast<sys::bluetooth::BluetoothModeChanged *>(request);
handleBluetoothModeChanged(data->getBluetoothMode());
return sys::msgHandled();
});
connect(typeid(message::bluetooth::RequestAuthenticate), [&](sys::Message *msg) {
auto m = dynamic_cast<::message::bluetooth::RequestAuthenticate *>(msg);
auto data = std::make_unique<gui::BluetoothAuthenticateRequestParams>(
m->getDevice(), m->getAuthenticateType(), m->getPairingCode());
data->setDisposition(gui::popup::Disposition{gui::popup::Disposition::Priority::High,
gui::popup::Disposition::WindowType::Popup,
gui::popup::ID::BluetoothAuthenticate});
actionsRegistry.enqueue(ActionEntry{actions::ShowPopup, std::move(data)});
return sys::MessageNone{};
});
connect(typeid(BluetoothPairResultMessage), [&](sys::Message *msg) {
auto m = dynamic_cast<BluetoothPairResultMessage *>(msg);
auto data = std::make_unique<gui::BluetoothInfoParams>(m->getDevice(), m->isSucceed(), m->getErrorCode());
data->setDisposition(gui::popup::Disposition{gui::popup::Disposition::Priority::High,
gui::popup::Disposition::WindowType::Popup,
gui::popup::ID::BluetoothInfo});
actionsRegistry.enqueue(ActionEntry{actions::ShowPopup, std::move(data)});
return sys::MessageNone{};
});
alarms::AlarmServiceAPI::requestRegisterSnoozedAlarmsCountChangeCallback(this);
connect(typeid(alarms::SnoozedAlarmsCountChangeMessage), [&](sys::Message *request) -> sys::MessagePointer {
auto data = static_cast<alarms::SnoozedAlarmsCountChangeMessage *>(request);
handleSnoozeCountChange(data->getSnoozedCount());
return sys::msgHandled();
});
alarms::AlarmServiceAPI::requestRegisterActiveAlarmsIndicatorHandler(this);
connect(typeid(alarms::ActiveAlarmMessage), [&](sys::Message *request) -> sys::MessagePointer {
auto data = static_cast<alarms::ActiveAlarmMessage *>(request);
handleAlarmClockStatusChanged(data->isAnyAlarmActive());
return sys::msgHandled();
});
auto convertibleToActionHandler = [this](sys::Message *request) { return handleMessageAsAction(request); };
connect(typeid(CellularMMIResultMessage), convertibleToActionHandler);
connect(typeid(CellularMMIResponseMessage), convertibleToActionHandler);
connect(typeid(CellularMMIPushMessage), convertibleToActionHandler);
connect(typeid(CellularNoSimNotification), convertibleToActionHandler);
connect(typeid(CellularNotAnEmergencyNotification), convertibleToActionHandler);
connect(typeid(CellularNoNetworkConenctionNotification), convertibleToActionHandler);
connect(typeid(CellularCallRequestGeneralError), convertibleToActionHandler);
connect(typeid(CellularSmsNoSimRequestMessage), convertibleToActionHandler);
connect(typeid(CellularSMSRejectedByOfflineNotification), convertibleToActionHandler);
connect(typeid(CellularCallRejectedByOfflineNotification), convertibleToActionHandler);
connect(typeid(sys::TetheringQuestionRequest), convertibleToActionHandler);
connect(typeid(sys::TetheringQuestionAbort), convertibleToActionHandler);
connect(typeid(sys::TetheringPhoneModeChangeProhibitedMessage), convertibleToActionHandler);
connect(typeid(CellularCallAbortedNotification), convertibleToActionHandler);
connect(typeid(CellularRingingMessage), convertibleToActionHandler);
connect(typeid(CellularCallActiveNotification), convertibleToActionHandler);
connect(typeid(CellularHangupCallMessage), convertibleToActionHandler);
}
void ApplicationManager::handlePhoneModeChanged(sys::phone_modes::PhoneMode phoneMode)
{
for (const auto app : getStackedApplications()) {
changePhoneMode(phoneMode, app);
}
}
void ApplicationManager::changePhoneMode(sys::phone_modes::PhoneMode phoneMode, const ApplicationHandle *app)
{
ActionEntry action{actions::PhoneModeChanged, std::make_unique<gui::PhoneModeParams>(phoneMode)};
action.setTargetApplication(app->name());
actionsRegistry.enqueue(std::move(action));
}
void ApplicationManager::handleBluetoothModeChanged(sys::bluetooth::BluetoothMode mode)
{
bluetoothMode = mode;
for (const auto app : getStackedApplications()) {
changeBluetoothMode(app);
}
}
void ApplicationManager::changeBluetoothMode(const ApplicationHandle *app)
{
ActionEntry action{actions::BluetoothModeChanged, std::make_unique<gui::BluetoothModeParams>(bluetoothMode)};
action.setTargetApplication(app->name());
actionsRegistry.enqueue(std::move(action));
}
void ApplicationManager::handleAlarmClockStatusChanged(bool status)
{
if (alarmClockStatus != status) {
alarmClockStatus = status;
for (const auto app : getStackedApplications()) {
changeAlarmClockStatus(app);
}
}
}
void ApplicationManager::changeAlarmClockStatus(const ApplicationHandle *app)
{
ActionEntry action{actions::AlarmClockStatusChanged,
std::make_unique<app::AlarmClockStatusParams>(alarmClockStatus)};
action.setTargetApplication(app->name());
actionsRegistry.enqueue(std::move(action));
}
void ApplicationManager::handleTetheringChanged(sys::phone_modes::Tethering tethering)
{
notificationProvider.handle(tethering);
}
void ApplicationManager::handleSnoozeCountChange(unsigned snoozeCount)
{
notificationProvider.handleSnooze(snoozeCount);
}
auto ApplicationManager::handleAutoLockSetRequest(SetAutoLockTimeoutRequest *request)
-> std::shared_ptr<sys::ResponseMessage>
{
auto interval = request->getValue();
settings->setValue(settings::SystemProperties::autoLockTimeInSec,
utils::to_string(interval.count()),
settings::SettingsScope::Global);
autoLockTimer.restart(interval);
return std::make_shared<sys::ResponseMessage>();
}
auto ApplicationManager::handleDeveloperModeRequest(sys::Message *request) -> sys::MessagePointer
{
if (auto msg = dynamic_cast<sdesktop::developerMode::DeveloperModeRequest *>(request)) {
if (dynamic_cast<sdesktop::developerMode::ScreenlockCheckEvent *>(msg->event.get())) {
auto response = std::make_shared<sdesktop::developerMode::DeveloperModeRequest>(
std::make_unique<sdesktop::developerMode::ScreenlockCheckEvent>(phoneLockHandler.isPhoneLocked()));
bus.sendUnicast(std::move(response), service::name::service_desktop);
return sys::msgHandled();
}
}
return sys::msgNotHandled();
}
void ApplicationManager::lockTimeChanged(std::string value)
{
if (value.empty()) {
LOG_ERROR("No value for auto-locking time period, request ignored");
return;
}
const auto interval = std::chrono::seconds{utils::getNumericValue<unsigned int>(value)};
if (interval.count() == 0) {
LOG_ERROR("Invalid auto-locking time period of 0s, request ignored");
return;
}
autoLockTimer.restart(interval);
}
void ApplicationManager::onPhoneLocked()
{
if (phoneLockHandler.isPhoneLocked()) {
autoLockTimer.stop();
return;
}
if (auto focusedApp = getFocusedApplication(); focusedApp == nullptr || focusedApp->preventsAutoLocking()) {
autoLockTimer.start();
return;
}
if (phoneModeObserver->isTetheringOn()) {
autoLockTimer.start();
return;
}
if (event::service::api::isTorchOn()) {
autoLockTimer.start();
return;
}
phoneLockHandler.handleLockRequest();
}
auto ApplicationManager::startApplication(ApplicationHandle &app) -> bool
{
if (not ApplicationManagerCommon::startApplication(app)) {
LOG_INFO("Starting application %s", app.name().c_str());
StatusIndicators statusIndicators;
statusIndicators.phoneMode = phoneModeObserver->getCurrentPhoneMode();
statusIndicators.bluetoothMode = bluetoothMode;
statusIndicators.alarmClockStatus = alarmClockStatus;
app.run(statusIndicators, this);
}
return true;
}
auto ApplicationManager::resolveHomeWindow() -> std::string
{
return phoneLockHandler.isPhoneLocked() ? gui::popup::window::phone_lock_window
: gui::name::window::main_window;
}
auto ApplicationManager::resolveHomeApplication() -> std::string
{
if (checkOnBoarding()) {
phoneLockHandler.handleUnlockRequest();
return app::name_onboarding;
}
return rootApplicationName;
}
auto ApplicationManager::handleDBResponse(db::QueryResponse *msg) -> bool
{
auto result = msg->getResult();
if (auto response = dynamic_cast<db::query::notifications::GetAllResult *>(result.get())) {
notificationProvider.handle(response);
return true;
}
return false;
}
auto ApplicationManager::handlePhoneModeChangedAction(ActionEntry &action) -> ActionProcessStatus
{
const auto &targetName = action.target;
auto targetApp = getApplication(targetName);
if (targetApp == nullptr || !targetApp->handles(action.actionId)) {
return ActionProcessStatus::Dropped;
}
if (targetApp->state() == ApplicationHandle::State::ACTIVE_FORGROUND ||
targetApp->state() == ApplicationHandle::State::ACTIVE_BACKGROUND) {
app::ApplicationCommon::requestAction(this, targetName, action.actionId, std::move(action.params));
return ActionProcessStatus::Accepted;
}
return ActionProcessStatus::Skipped;
}
auto ApplicationManager::handleAction(ActionEntry &action) -> ActionProcessStatus
{
switch (action.actionId) {
case actions::BluetoothModeChanged:
case actions::PhoneModeChanged:
case actions::AlarmClockStatusChanged:
return handleActionOnActiveApps(action);
default:
return ApplicationManagerCommon::handleAction(action);
}
}
void ApplicationManager::handleStart(StartAllowedMessage *msg)
{
switch (msg->getStartupType()) {
case StartupType::Regular:
ApplicationManagerCommon::handleStart(msg);
break;
case StartupType::LowBattery:
case StartupType::CriticalBattery:
handleSwitchApplication(std::make_unique<SwitchRequest>(
service::name::appmgr, app::name_desktop, window::name::dead_battery, nullptr)
.get());
break;
case StartupType::LowBatteryCharging:
handleSwitchApplication(
std::make_unique<SwitchRequest>(
service::name::appmgr, app::name_desktop, window::name::charging_battery, nullptr)
.get());
break;
}
}
auto ApplicationManager::handleDisplayLanguageChange(app::manager::DisplayLanguageChangeRequest *msg) -> bool
{
const auto &requestedLanguage = msg->getLanguage();
if (not utils::setDisplayLanguage(requestedLanguage)) {
LOG_WARN("The selected language is already set. Ignore.");
return false;
}
settings->setValue(
settings::SystemProperties::displayLanguage, requestedLanguage, settings::SettingsScope::Global);
rebuildActiveApplications();
DBServiceAPI::InformLanguageChanged(this);
return true;
}
} // namespace app::manager
| 49.460674 | 120 | 0.638963 | mudita |
a3ed862cb12ff3413555029788917084ec13f39b | 280 | hpp | C++ | stat.hpp | syuu1228/procfile_logger | 94a23f18d554603ac1a1a96dd84698a07ebee8ba | [
"Apache-2.0"
] | 1 | 2015-10-26T21:49:33.000Z | 2015-10-26T21:49:33.000Z | stat.hpp | syuu1228/procfile_logger | 94a23f18d554603ac1a1a96dd84698a07ebee8ba | [
"Apache-2.0"
] | null | null | null | stat.hpp | syuu1228/procfile_logger | 94a23f18d554603ac1a1a96dd84698a07ebee8ba | [
"Apache-2.0"
] | null | null | null | #ifndef STAT_HPP
#define STAT_HPP
#include <memory>
#include <vector>
#include <boost/program_options.hpp>
#include "global_stats_logger.hpp"
void init_stat_logger(boost::program_options::variables_map& vm,
std::vector<std::shared_ptr<global_stats_logger> >& loggers);
#endif
| 21.538462 | 64 | 0.789286 | syuu1228 |
a3eef7011e4f6c506bdd0114438e4fa63321e5c3 | 98 | cpp | C++ | NKZX_NOI_OJ/P1500.cpp | Rose2073/RoseCppSource | bdaf5de04049b07bbe0e1ef976d1fbe72520fa03 | [
"Apache-2.0"
] | 1 | 2021-04-05T16:26:00.000Z | 2021-04-05T16:26:00.000Z | NKZX_NOI_OJ/P1500.cpp | Rose2073/RoseCppSource | bdaf5de04049b07bbe0e1ef976d1fbe72520fa03 | [
"Apache-2.0"
] | null | null | null | NKZX_NOI_OJ/P1500.cpp | Rose2073/RoseCppSource | bdaf5de04049b07bbe0e1ef976d1fbe72520fa03 | [
"Apache-2.0"
] | null | null | null | #include<cstdio>
int main(){
double a;scanf("%lf",&a);printf("%.2f %.2f",4*a,a*a);return 0;
}
| 19.6 | 66 | 0.571429 | Rose2073 |
a3f2fcc335f559aca9ae932e6891e1467ba83575 | 19,914 | hpp | C++ | src/xalanc/XMLSupport/XalanXMLSerializerBase.hpp | kidaa/xalan-c | bb666d0ab3d0a192410823e6857c203d83c27b16 | [
"Apache-2.0"
] | null | null | null | src/xalanc/XMLSupport/XalanXMLSerializerBase.hpp | kidaa/xalan-c | bb666d0ab3d0a192410823e6857c203d83c27b16 | [
"Apache-2.0"
] | 1 | 2021-08-18T12:32:31.000Z | 2021-08-18T12:32:31.000Z | src/xalanc/XMLSupport/XalanXMLSerializerBase.hpp | AaronNGray/xalan | 6741bbdcb64a9d33df8bd7e21b558d66bb4292ec | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !defined(XALANXMLSERIALIZERBASE_HEADER_GUARD_1357924680)
#define XALANXMLSERIALIZERBASE_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include "xalanc/XMLSupport/XMLSupportDefinitions.hpp"
#include "xalanc/Include/XalanVector.hpp"
#include "xalanc/XalanDOM/XalanDOMString.hpp"
// Base class header file.
#include "xalanc/PlatformSupport/FormatterListener.hpp"
XALAN_CPP_NAMESPACE_BEGIN
class XalanOutputStream;
XALAN_USING_XERCES(MemoryManager)
/**
* XalanXMLSerializerBase serves as a base class for XML serializers based on
* FormatterListener events.
*/
class XALAN_XMLSUPPORT_EXPORT XalanXMLSerializerBase : public FormatterListener
{
public:
/**
* Perform static initialization. See class XMLSupportInit.
*/
static void
initialize(MemoryManager& theManager);
/**
* Perform static shut down. See class XMLSupportInit.
*/
static void
terminate();
/**
* Constructor
*
* @param theManager The MemoryManager instance to use for any memory
* allocations
* @param doctypeSystem system identifier to be used in the document
* type declaration
* @param doctypePublic public identifier to be used in the document
* type declaration
* @param xmlDecl true if the XSLT processor should output an XML
* declaration
* @param theStandalone The string the XSLT processor should output for
* the standalone document declaration
*/
XalanXMLSerializerBase(
MemoryManager& theManager,
eXMLVersion theXMLVersion,
const XalanDOMString& theEncoding,
const XalanDOMString& theDoctypeSystem,
const XalanDOMString& theDoctypePublic,
bool xmlDecl,
const XalanDOMString& theStandalone);
virtual
~XalanXMLSerializerBase();
MemoryManager&
getMemoryManager()
{
return m_elemStack.getMemoryManager();
}
// These methods are inherited from FormatterListener ...
virtual void
setDocumentLocator(const Locator* const locator);
virtual void
startDocument();
virtual void
startElement(
const XMLCh* const name,
AttributeList& attrs) = 0;
virtual void
endElement(const XMLCh* const name) = 0;
virtual void
characters(
const XMLCh* const chars,
const size_type length);
virtual void
charactersRaw(
const XMLCh* const chars,
const size_type length) = 0;
virtual void
entityReference(const XMLCh* const name) = 0;
virtual void
ignorableWhitespace(
const XMLCh* const chars,
const size_type length);
virtual void
processingInstruction(
const XMLCh* const target,
const XMLCh* const data);
virtual void
resetDocument();
virtual void
comment(const XMLCh* const data) = 0;
virtual void
cdata(
const XMLCh* const ch,
const size_type length);
virtual const XalanDOMString&
getDoctypeSystem() const;
virtual const XalanDOMString&
getDoctypePublic() const;
virtual const XalanDOMString&
getEncoding() const;
const XalanDOMString&
getVersion() const
{
return m_version;
}
const XalanDOMString&
getStandalone() const
{
return m_standalone;
}
bool
getShouldWriteXMLHeader() const
{
return m_shouldWriteXMLHeader;
}
void
setShouldWriteXMLHeader(bool b)
{
m_shouldWriteXMLHeader = b;
}
typedef XalanVector<bool> BoolStackType;
static const XalanDOMString& s_1_0String;
static const XalanDOMString& s_1_1String;
class XALAN_XMLSUPPORT_EXPORT UTF8
{
public:
// Static data members...
/**
* The string "UTF-8".
*/
static const XalanDOMString& s_encodingString;
/**
* The string "<!DOCTYPE ".
*/
static const char s_doctypeHeaderStartString[];
static const size_type s_doctypeHeaderStartStringLength;
/**
* The string " PUBLIC \"".
*/
static const char s_doctypeHeaderPublicString[];
static const size_type s_doctypeHeaderPublicStringLength;
/**
* The string " SYSTEM \"".
*/
static const char s_doctypeHeaderSystemString[];
static const size_type s_doctypeHeaderSystemStringLength;
/**
* The string "<?xml version=\"".
*/
static const char s_xmlHeaderStartString[];
static const size_type s_xmlHeaderStartStringLength;
/**
* The string "\" encoding=\"".
*/
static const char s_xmlHeaderEncodingString[];
static const size_type s_xmlHeaderEncodingStringLength;
/**
* The string "\" standalone=\"".
*/
static const char s_xmlHeaderStandaloneString[];
static const size_type s_xmlHeaderStandaloneStringLength;
/**
* The string "\"?>".
*/
static const char s_xmlHeaderEndString[];
static const size_type s_xmlHeaderEndStringLength;
/**
* The string "1.0".
*/
static const char s_defaultVersionString[];
static const size_type s_defaultVersionStringLength;
/**
* The string "-//W3C//DTD XHTML".
*/
static const XalanDOMChar s_xhtmlDocTypeString[];
static const size_type s_xhtmlDocTypeStringLength;
/**
* The string "<![CDATA[".
*/
static const char s_cdataOpenString[];
static const size_type s_cdataOpenStringLength;
/**
* The string "]]>".
*/
static const char s_cdataCloseString[];
static const size_type s_cdataCloseStringLength;
/**
* The string "<".
*/
static const char s_lessThanEntityString[];
static const size_type s_lessThanEntityStringLength;
/**
* The string ">".
*/
static const char s_greaterThanEntityString[];
static const size_type s_greaterThanEntityStringLength;
/**
* The string "&".
*/
static const char s_ampersandEntityString[];
static const size_type s_ampersandEntityStringLength;
/**
* The string """.
*/
static const char s_quoteEntityString[];
static const size_type s_quoteEntityStringLength;
};
class XALAN_XMLSUPPORT_EXPORT UTF16
{
public:
/**
* The string "UTF-16".
*/
static const XalanDOMString& s_encodingString;
/**
* The string "<!DOCTYPE ".
*/
static const XalanDOMChar s_doctypeHeaderStartString[];
static const size_type s_doctypeHeaderStartStringLength;
/**
* The string " PUBLIC \"".
*/
static const XalanDOMChar s_doctypeHeaderPublicString[];
static const size_type s_doctypeHeaderPublicStringLength;
/**
* The string " SYSTEM \"".
*/
static const XalanDOMChar s_doctypeHeaderSystemString[];
static const size_type s_doctypeHeaderSystemStringLength;
/**
* The string "<?xml version=\"".
*/
static const XalanDOMChar s_xmlHeaderStartString[];
static const size_type s_xmlHeaderStartStringLength;
/**
* The string "\" encoding=\"".
*/
static const XalanDOMChar s_xmlHeaderEncodingString[];
static const size_type s_xmlHeaderEncodingStringLength;
/**
* The string "\" standalone=\"".
*/
static const XalanDOMChar s_xmlHeaderStandaloneString[];
static const size_type s_xmlHeaderStandaloneStringLength;
/**
* The string "\"?>".
*/
static const XalanDOMChar s_xmlHeaderEndString[];
static const size_type s_xmlHeaderEndStringLength;
/**
* The string "1.0".
*/
static const XalanDOMChar s_defaultVersionString[];
static const size_type s_defaultVersionStringLength;
/**
* The string "-//W3C//DTD XHTML".
*/
static const XalanDOMChar s_xhtmlDocTypeString[];
static const size_type s_xhtmlDocTypeStringLength;
/**
* The string "<![CDATA[".
*/
static const XalanDOMChar s_cdataOpenString[];
static const size_type s_cdataOpenStringLength;
/**
* The string "]]>".
*/
static const XalanDOMChar s_cdataCloseString[];
static const size_type s_cdataCloseStringLength;
/**
* The string "<".
*/
static const XalanDOMChar s_lessThanEntityString[];
static const size_type s_lessThanEntityStringLength;
/**
* The string ">".
*/
static const XalanDOMChar s_greaterThanEntityString[];
static const size_type s_greaterThanEntityStringLength;
/**
* The string "&".
*/
static const XalanDOMChar s_ampersandEntityString[];
static const size_type s_ampersandEntityStringLength;
/**
* The string """.
*/
static const XalanDOMChar s_quoteEntityString[];
static const size_type s_quoteEntityStringLength;
};
enum
{
eBufferSize = 512 // The size of the buffer
};
class XALAN_XMLSUPPORT_EXPORT CharFunctor1_0
{
public:
bool
attribute(XalanDOMChar theChar) const
{
return theChar > s_lastSpecial ?
false :
s_specialChars[theChar] > eNone;
}
bool
content(XalanDOMChar theChar) const
{
return theChar > s_lastSpecial ?
false :
s_specialChars[theChar] > eAttr;
}
bool
range(XalanDOMChar theChar) const
{
assert(theChar > 0);
return theChar > s_lastSpecial;
}
bool
isForbidden(XalanDOMChar theChar) const
{
return theChar > s_lastSpecial ?
false :
s_specialChars[theChar] == eForb;
}
bool
isCharRefForbidden(XalanDOMChar theChar) const
{
return theChar > s_lastSpecial ?
false :
s_specialChars[theChar] == eForb;
}
private:
static const size_t s_lastSpecial;
static const char s_specialChars[];
};
class XALAN_XMLSUPPORT_EXPORT CharFunctor1_1
{
public:
bool
attribute(XalanDOMChar theChar) const
{
return theChar > s_lastSpecial ?
false :
s_specialChars[theChar] > eNone;
}
bool
content(XalanDOMChar theChar) const
{
return theChar > s_lastSpecial ?
false :
s_specialChars[theChar] > eAttr;
}
bool
range(XalanDOMChar theChar) const
{
assert(theChar > 0);
return theChar > s_lastSpecial;
}
bool
isForbidden(XalanDOMChar theChar) const
{
return theChar > s_lastSpecial ?
false :
s_specialChars[theChar] == eForb;
}
bool
isCharRefForbidden(XalanDOMChar theChar) const
{
return theChar > s_lastSpecial ?
false :
s_specialChars[theChar] == eCRFb;
}
private:
static const size_t s_lastSpecial;
static const char s_specialChars[];
};
enum
{
eNone = 0u,
eAttr = 1u, // A flag to indicate a value in s_specialChars applies to attributes
eBoth = 2u, // A flag to indicate a value in s_specialChars applies to both content and attributes
eForb = 4u, // A flag to indicate a forbidden value in s_specialChars
// XML1.1 put a requirement to output chars #x1...#x1F and #x7F...#x9F as charRefs only
// In the comments , PI and CDATA usage of charRefs is forbidden, so we will report an error in
eCRFb = 5u // that case. For the elemets and attributes is should work the same as eBoth
};
protected:
virtual void
writeXMLHeader() = 0;
virtual void
flushBuffer() = 0;
virtual void
writeDoctypeDecl(const XalanDOMChar* name) = 0;
virtual void
writeProcessingInstruction(
const XMLCh* target,
const XMLCh* data) = 0;
virtual void
writeCharacters(
const XMLCh* chars,
size_type length) = 0;
virtual void
writeCDATA(
const XMLCh* chars,
size_type length) = 0;
virtual void
outputNewline() = 0;
/**
* Mark the parent element as having a child. If this
* is the first child, return true, otherwise, return
* false. This allows the child element to determine
* if the parent tag has already been closed.
*
* @return true if the parent element has not been previously marked for children.
*/
bool
markParentForChildren()
{
if(!m_elemStack.empty())
{
// See if the parent element has already been flagged as having children.
if(false == m_elemStack.back())
{
m_elemStack.back() = true;
return true;
}
}
return false;
}
/**
* Determine if it a DOCTYPE declaration needs to
* be written.
*/
bool
getNeedToOutputDoctypeDecl() const
{
return m_needToOutputDoctypeDecl;
}
/**
* Open an element for possibile children
*/
void
openElementForChildren()
{
m_elemStack.push_back(false);
}
bool
outsideDocumentElement() const
{
return m_elemStack.empty();
}
/**
* Determine if an element ever had any children added.
*
* @return true if the children were added, false if not.
*/
bool
childNodesWereAdded()
{
bool fResult = false;
if (m_elemStack.empty() == false)
{
fResult = m_elemStack.back();
m_elemStack.pop_back();
}
return fResult;
}
void
generateDoctypeDecl(const XalanDOMChar* name)
{
if(true == m_needToOutputDoctypeDecl)
{
assert(m_doctypeSystem.empty() == false);
writeDoctypeDecl(name);
m_needToOutputDoctypeDecl = false;
}
}
/**
* Tell if the next text should be raw.
*/
bool m_nextIsRaw;
/**
* Add space before '/>' for XHTML.
*/
bool m_spaceBeforeClose;
/**
* The System ID for the doc type.
*/
const XalanDOMString m_doctypeSystem;
/**
* The public ID for the doc type.
*/
const XalanDOMString m_doctypePublic;
/**
* Tells the XML version, for writing out to the XML decl.
*/
const XalanDOMString& m_version;
/**
* Text for standalone part of header.
*/
const XalanDOMString m_standalone;
const XalanDOMString m_encoding;
static bool
isUTF16HighSurrogate(XalanDOMChar theChar)
{
return 0xD800u <= theChar && theChar <= 0xDBFFu ? true : false;
}
static bool
isUTF16LowSurrogate(XalanDOMChar theChar)
{
return 0xDC00u <= theChar && theChar <= 0xDFFFu ? true : false;
}
static XalanUnicodeChar
decodeUTF16SurrogatePair(
XalanDOMChar theHighSurrogate,
XalanDOMChar theLowSurrogate,
MemoryManager& theManager);
/**
* Throw an exception when an invalid
* surrogate is encountered.
* @param ch The first character in the surrogate
*/
static void
throwInvalidUTF16SurrogateException(
XalanDOMChar ch,
MemoryManager& theManager);
/**
* Throw an exception when an invalid
* surrogate is encountered.
* @param ch The first character in the surrogate
* @param next The next character in the surrogate
*/
static void
throwInvalidUTF16SurrogateException(
XalanDOMChar ch,
XalanDOMChar next,
MemoryManager& theManager);
/**
* Throw an exception when an invalid
* character is encountered.
* @param ch The first character in the surrogate
* @param next The next character in the surrogate
*/
static void
throwInvalidCharacterException(
XalanUnicodeChar ch,
MemoryManager& theManager);
/**
* Throw an exception when an invalid
* character for the specific XML version is encountered.
* @param ch The first character in the surrogate
* @param next The next character in the surrogate
*/
static void
throwInvalidXMLCharacterException(
XalanUnicodeChar ch,
const XalanDOMString& theXMLversion,
MemoryManager& theManager);
private:
// These are not implemented.
XalanXMLSerializerBase(const XalanXMLSerializerBase&);
XalanXMLSerializerBase&
operator=(const XalanXMLSerializerBase&);
bool
operator==(const XalanXMLSerializerBase&) const;
// Data members...
/**
* Flag to tell that we need to add the doctype decl,
* which we can't do until the first element is
* encountered.
*/
bool m_needToOutputDoctypeDecl;
/**
* If true, XML header should be written to output.
*/
bool m_shouldWriteXMLHeader;
/**
* A stack of Boolean objects that tell if the given element
* has children.
*/
BoolStackType m_elemStack;
/**
* The string "-//W3C//DTD XHTML".
*/
static const XalanDOMChar s_xhtmlDocTypeString[];
static const size_type s_xhtmlDocTypeStringLength;
};
XALAN_CPP_NAMESPACE_END
#endif // XALANXMLSERIALIZERBASE_HEADER_GUARD_1357924680
| 24.67658 | 117 | 0.578287 | kidaa |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.