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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
08a8b25904d305e39dceace1ce1e0c6d96131f5d
| 112
|
hpp
|
C++
|
FirstOrderLogic/libfol-basictypes/variable.hpp
|
s3ponia/FOL-parser
|
5cbfc1bf02acae78104238781b9c5c4e71ffe925
|
[
"MIT"
] | null | null | null |
FirstOrderLogic/libfol-basictypes/variable.hpp
|
s3ponia/FOL-parser
|
5cbfc1bf02acae78104238781b9c5c4e71ffe925
|
[
"MIT"
] | null | null | null |
FirstOrderLogic/libfol-basictypes/variable.hpp
|
s3ponia/FOL-parser
|
5cbfc1bf02acae78104238781b9c5c4e71ffe925
|
[
"MIT"
] | null | null | null |
#pragma once
#include <string>
namespace fol::types {
using Variable = std::string;
} // namespace fol::types
| 16
| 29
| 0.705357
|
s3ponia
|
08ab76ca3c0ca3f8ab82aa7833aa8cd8883d7e82
| 7,091
|
cpp
|
C++
|
test/rocprim/test_thread.cpp
|
stanleytsang-amd/rocPRIM
|
1a4135dfc43f90f465c336a551bccbe359d40f11
|
[
"MIT"
] | null | null | null |
test/rocprim/test_thread.cpp
|
stanleytsang-amd/rocPRIM
|
1a4135dfc43f90f465c336a551bccbe359d40f11
|
[
"MIT"
] | null | null | null |
test/rocprim/test_thread.cpp
|
stanleytsang-amd/rocPRIM
|
1a4135dfc43f90f465c336a551bccbe359d40f11
|
[
"MIT"
] | null | null | null |
// MIT License
//
// Copyright (c) 2020 Advanced Micro Devices, Inc. All rights reserved.
//
// 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 "common_test_header.hpp"
// required rocprim headers
#include <rocprim/intrinsics/thread.hpp>
#include "test_utils.hpp"
template<
unsigned int BlockSizeX,
unsigned int BlockSizeY,
unsigned int BlockSizeZ
>
struct params
{
static constexpr unsigned int block_size_x = BlockSizeX;
static constexpr unsigned int block_size_y = BlockSizeY;
static constexpr unsigned int block_size_z = BlockSizeZ;
};
template<class Params>
class RocprimThreadTests : public ::testing::Test {
public:
using params = Params;
};
typedef ::testing::Types<
params<32, 1, 1>,
params<64, 1, 1>,
params<128, 1, 1>,
params<256, 1, 1>,
params<512, 1, 1>,
params<1024, 1, 1>,
params<16, 2, 1>,
params<32, 2, 1>,
params<64, 2, 1>,
params<128, 2, 1>,
params<256, 2, 1>,
params<512, 2, 1>,
params<8, 2, 2>,
params<16, 2, 2>,
params<32, 2, 2>,
params<64, 2, 2>,
params<128, 2, 2>,
params<256, 2, 2>
> Params;
TYPED_TEST_CASE(RocprimThreadTests, Params);
template<
unsigned int BlockSizeX,
unsigned int BlockSizeY,
unsigned int BlockSizeZ
>
__global__
__launch_bounds__(1024, ROCPRIM_DEFAULT_MIN_WARPS_PER_EU)
void flat_id_kernel(unsigned int* device_output)
{
unsigned int thread_id = rocprim::flat_block_thread_id<BlockSizeX, BlockSizeY, BlockSizeZ>();
device_output[thread_id] = thread_id;
}
TYPED_TEST(RocprimThreadTests, FlatBlockThreadID)
{
using Type = unsigned int;
constexpr size_t block_size_x = TestFixture::params::block_size_x;
constexpr size_t block_size_y = TestFixture::params::block_size_y;
constexpr size_t block_size_z = TestFixture::params::block_size_z;
constexpr size_t block_size = block_size_x * block_size_y * block_size_z;
// Given block size not supported
if(block_size > test_utils::get_max_block_size() || (block_size & (block_size - 1)) != 0)
{
return;
}
for(size_t seed_index = 0; seed_index < random_seeds_count + seed_size; seed_index++)
{
unsigned int seed_value = seed_index < random_seeds_count ? rand() : seeds[seed_index - random_seeds_count];
SCOPED_TRACE(testing::Message() << "with seed= " << seed_value);
// Generate data
std::vector<Type> output(block_size, 0);
// Calculate expected results on host
std::vector<Type> expected(block_size, 0);
for(size_t i = 0; i < block_size; i++)
{
expected[i] = i;
}
// Preparing device
Type* device_output;
HIP_CHECK(hipMalloc(&device_output, block_size * sizeof(typename decltype(output)::value_type)));
// Running kernel
hipLaunchKernelGGL(
HIP_KERNEL_NAME(
flat_id_kernel<
block_size_x, block_size_y, block_size_z
>
),
dim3(1), dim3(block_size_x, block_size_y, block_size_z), 0, 0,
device_output
);
// Reading results from device
HIP_CHECK(
hipMemcpy(
output.data(), device_output,
output.size() * sizeof(typename decltype(output)::value_type),
hipMemcpyDeviceToHost
)
);
// Validating results
ASSERT_NO_FATAL_FAILURE(test_utils::assert_eq(output, expected));
HIP_CHECK(hipFree(device_output));
}
}
template<
unsigned int BlockSizeX,
unsigned int BlockSizeY,
unsigned int BlockSizeZ
>
__global__
__launch_bounds__(1024, ROCPRIM_DEFAULT_MIN_WARPS_PER_EU)
void block_id_kernel(unsigned int* device_output)
{
unsigned int block_id = rocprim::flat_block_id<BlockSizeX, BlockSizeY, BlockSizeZ>();
if(hipThreadIdx_x)
{
device_output[block_id] = block_id;
}
}
TYPED_TEST(RocprimThreadTests, FlatBlockID)
{
using Type = unsigned int;
constexpr size_t block_size_x = TestFixture::params::block_size_x;
constexpr size_t block_size_y = TestFixture::params::block_size_y;
constexpr size_t block_size_z = TestFixture::params::block_size_z;
constexpr size_t block_size = block_size_x * block_size_y * block_size_z;
const size_t size = block_size * block_size;
const auto grid_size = size / block_size;
// Given block size not supported
if(block_size > test_utils::get_max_block_size() || (block_size & (block_size - 1)) != 0)
{
return;
}
for(size_t seed_index = 0; seed_index < random_seeds_count + seed_size; seed_index++)
{
unsigned int seed_value = seed_index < random_seeds_count ? rand() : seeds[seed_index - random_seeds_count];
SCOPED_TRACE(testing::Message() << "with seed= " << seed_value);
// Generate data
std::vector<Type> output(grid_size, 0);
// Calculate expected results on host
std::vector<Type> expected(grid_size, 0);
for(size_t i = 0; i < grid_size; i++)
{
expected[i] = i;
}
// Preparing device
Type* device_output;
HIP_CHECK(hipMalloc(&device_output, output.size() * sizeof(typename decltype(output)::value_type)));
// Running kernel
hipLaunchKernelGGL(
HIP_KERNEL_NAME(
block_id_kernel<
block_size_x, block_size_y, block_size_z
>
),
dim3(block_size_x, block_size_y, block_size_z), dim3(block_size_x, block_size_y, block_size_z), 0, 0,
device_output
);
// Reading results from device
HIP_CHECK(
hipMemcpy(
output.data(), device_output,
output.size() * sizeof(typename decltype(output)::value_type),
hipMemcpyDeviceToHost
)
);
// Validating results
ASSERT_NO_FATAL_FAILURE(test_utils::assert_eq(output, expected));
HIP_CHECK(hipFree(device_output));
}
}
| 32.231818
| 117
| 0.659145
|
stanleytsang-amd
|
08ad68ed8a061fe0c92070d98e01f28801f24c23
| 541
|
cpp
|
C++
|
source/365.cpp
|
narikbi/LeetCode
|
835215c21d1bd6820b20c253026bcb6f889ed3fc
|
[
"MIT"
] | 2
|
2017-02-28T11:39:13.000Z
|
2019-12-07T17:23:20.000Z
|
source/365.cpp
|
narikbi/LeetCode
|
835215c21d1bd6820b20c253026bcb6f889ed3fc
|
[
"MIT"
] | null | null | null |
source/365.cpp
|
narikbi/LeetCode
|
835215c21d1bd6820b20c253026bcb6f889ed3fc
|
[
"MIT"
] | null | null | null |
//
// 365.cpp
// LeetCode
//
// Created by Narikbi on 19.04.17.
// Copyright © 2017 app.leetcode.kz. All rights reserved.
//
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <deque>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <cmath>
#include <numeric>
#include <unordered_map>
#include <sstream>
#include <unordered_set>
using namespace std;
bool canMeasureWater(int x, int y, int z) {
return z == 0 || (z - x <= y && z % __gcd(x, y) == 0);
}
| 17.451613
| 58
| 0.656192
|
narikbi
|
08b3ce0e16746a951c5b63cc25ca988acd273a75
| 13,128
|
hpp
|
C++
|
include/state_saver.hpp
|
Neargye/yacppl
|
032d8c044c84e0942607220679ca2d4da48631bd
|
[
"MIT"
] | 10
|
2018-12-13T06:52:13.000Z
|
2022-02-21T16:39:58.000Z
|
include/state_saver.hpp
|
Neargye/yacppl
|
032d8c044c84e0942607220679ca2d4da48631bd
|
[
"MIT"
] | null | null | null |
include/state_saver.hpp
|
Neargye/yacppl
|
032d8c044c84e0942607220679ca2d4da48631bd
|
[
"MIT"
] | 1
|
2020-06-02T08:05:13.000Z
|
2020-06-02T08:05:13.000Z
|
// _____ _ _ _____ _____
// / ____| | | | / ____| / ____|_ _
// | (___ | |_ __ _| |_ ___ | (___ __ ___ _____ _ __ | | _| |_ _| |_
// \___ \| __/ _` | __/ _ \ \___ \ / _` \ \ / / _ \ '__| | | |_ _|_ _|
// ____) | || (_| | || __/ ____) | (_| |\ V / __/ | | |____|_| |_|
// |_____/ \__\__,_|\__\___| |_____/ \__,_| \_/ \___|_| \_____|
//
// Licensed under the MIT License <http://opensource.org/licenses/MIT>.
// SPDX-License-Identifier: MIT
// Copyright (c) 2018 - 2021 Daniil Goncharov <neargye@gmail.com>.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#ifndef NEARGYE_STATE_SAVER_HPP
#define NEARGYE_STATE_SAVER_HPP
// Sometimes a certain value has to change only for a limited scope.
// This class wrapper saves a copy of the current state of some object,
// and resets the object’s state at destruction time, undoing any change the object may have gone through.
// * saver_exit - saves the original variable value and restores on scope exit.
// * saver_fail - saves the original variable value and restores on scope exit when an exception has been thrown.
// * saver_success - saves the original variable value and restores on scope exit when no exceptions have been thrown.
// Interface of state_saver:
// * constructor state_saver(T& object) - construct state_saver with saved object.
// * dismiss() - dismiss restore on scope exit.
// * restore() - resets the object’s state. Requirements copy operator =.
// Requirements to saved object:
// * Object semantic (cannot be reference, function, ...).
// * Copy constructor.
// * operator= (no-throw one preferred).
// Throwable settings:
// STATE_SAVER_NO_THROW_CONSTRUCTIBLE requires nothrow constructible action.
// STATE_SAVER_MAY_THROW_RESTORE restore may throw exceptions.
// STATE_SAVER_NO_THROW_RESTORE requires noexcept restore.
// STATE_SAVER_SUPPRESS_THROW_RESTORE exceptions during restore will be suppressed.
// STATE_SAVER_CATCH_HANDLER exceptions handler. If STATE_SAVER_SUPPRESS_THROW_RESTORE is not defined, it will do nothing.
// Assignable settings:
// STATE_SAVER_FORCE_MOVE_ASSIGNABLE restore on scope exit will be move assigned.
// STATE_SAVER_FORCE_COPY_ASSIGNABLE restore on scope exit will be copy assigned.
#include <type_traits>
#if (defined(_MSC_VER) && _MSC_VER >= 1900) || ((defined(__clang__) || defined(__GNUC__)) && __cplusplus >= 201700L)
#include <exception>
#endif
#if !defined(STATE_SAVER_MAY_THROW_RESTORE) && !defined(STATE_SAVER_NO_THROW_RESTORE) && !defined(STATE_SAVER_SUPPRESS_THROW_RESTORE)
# define STATE_SAVER_MAY_THROW_RESTORE
#elif (defined(STATE_SAVER_MAY_THROW_RESTORE) + defined(STATE_SAVER_NO_THROW_RESTORE) + defined(STATE_SAVER_SUPPRESS_THROW_RESTORE)) > 1
# error Only one of STATE_SAVER_MAY_THROW_RESTORE and STATE_SAVER_NO_THROW_RESTORE and STATE_SAVER_SUPPRESS_THROW_RESTORE may be defined.
#endif
#if (defined(STATE_SAVER_FORCE_MOVE_ASSIGNABLE) + defined(STATE_SAVER_FORCE_COPY_ASSIGNABLE)) > 1
# error Only one of STATE_SAVER_FORCE_MOVE_ASSIGNABLE and STATE_SAVER_FORCE_COPY_ASSIGNABLE may be defined.
#endif
#if !defined(STATE_SAVER_CATCH_HANDLER)
# define STATE_SAVER_CATCH_HANDLER /* Suppress exception.*/
#endif
namespace nstd {
namespace detail {
#if defined(STATE_SAVER_SUPPRESS_THROW_RESTORE) && (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND))
# define NEARGYE_NOEXCEPT(...) noexcept
# define NEARGYE_TRY try {
# define NEARGYE_CATCH } catch (...) { SCOPE_GUARD_CATCH_HANDLER }
#else
# define NEARGYE_NOEXCEPT(...) noexcept(__VA_ARGS__)
# define NEARGYE_TRY
# define NEARGYE_CATCH
#endif
#if defined(_MSC_VER) && _MSC_VER < 1900
inline int uncaught_exceptions() noexcept {
return *(reinterpret_cast<int*>(static_cast<char*>(static_cast<void*>(_getptd())) + (sizeof(void*) == 8 ? 0x100 : 0x90)));
}
#elif (defined(__clang__) || defined(__GNUC__)) && __cplusplus < 201700L
struct __cxa_eh_globals;
extern "C" __cxa_eh_globals* __cxa_get_globals() noexcept;
inline int uncaught_exceptions() noexcept {
return static_cast<int>(*(reinterpret_cast<unsigned int*>(static_cast<char*>(static_cast<void*>(__cxa_get_globals())) + sizeof(void*))));
}
#else
inline int uncaught_exceptions() noexcept {
return std::uncaught_exceptions();
}
#endif
class on_exit_policy {
bool execute_;
public:
explicit on_exit_policy(bool execute) noexcept : execute_{execute} {}
void dismiss() noexcept {
execute_ = false;
}
bool should_execute() const noexcept {
return execute_;
}
};
class on_fail_policy {
int ec_;
public:
explicit on_fail_policy(bool execute) noexcept : ec_{execute ? uncaught_exceptions() : -1} {}
void dismiss() noexcept {
ec_ = -1;
}
bool should_execute() const noexcept {
return ec_ != -1 && ec_ < uncaught_exceptions();
}
};
class on_success_policy {
int ec_;
public:
explicit on_success_policy(bool execute) noexcept : ec_{execute ? uncaught_exceptions() : -1} {}
void dismiss() noexcept {
ec_ = -1;
}
bool should_execute() const noexcept {
return ec_ != -1 && ec_ >= uncaught_exceptions();
}
};
template <typename U, typename P>
class state_saver {
using T = typename std::remove_reference<U>::type;
#if defined(STATE_SAVER_FORCE_MOVE_ASSIGNABLE)
using assignable_t = T&&;
#elif defined(STATE_SAVER_FORCE_COPY_ASSIGNABLE)
using assignable_t = T&;
#else
using assignable_t = typename std::conditional<
std::is_nothrow_assignable<T&, T&&>::value ||
!std::is_assignable<T&, T&>::value ||
(!std::is_nothrow_assignable<T&, T&>::value && std::is_assignable<T&, T&&>::value),
T&&, T&>::type;
#endif
static_assert(!std::is_const<T>::value,
"state_saver requires not const type.");
static_assert(!std::is_rvalue_reference<U>::value && (std::is_lvalue_reference<U>::value || std::is_same<T, U>::value),
"state_saver requires lvalue type.");
static_assert(!std::is_array<T>::value,
"state_saver requires not array type.");
static_assert(!std::is_pointer<T>::value,
"state_saver requires not pointer type.");
static_assert(!std::is_function<T>::value,
"state_saver requires not function type.");
static_assert(std::is_constructible<T, T&>::value,
"state_saver requires copy constructible.");
static_assert(std::is_assignable<T&, assignable_t>::value,
"state_saver requires operator=.");
static_assert(std::is_same<P, on_exit_policy>::value || std::is_same<P, on_fail_policy>::value || std::is_same<P, on_success_policy>::value,
"state_saver requires on_exit_policy, on_fail_policy or on_success_policy.");
#if defined(STATE_SAVER_NO_THROW_RESTORE)
static_assert(std::is_nothrow_assignable<T&, assignable_t>::value,
"state_saver requires noexcept operator=.");
#endif
#if defined(STATE_SAVER_NO_THROW_CONSTRUCTIBLE)
static_assert(std::is_nothrow_constructible<T, T&>::value,
"state_saver requires nothrow constructible.");
#endif
P policy_;
T& previous_ref_;
T previous_value_;
public:
state_saver() = delete;
state_saver(const state_saver&) = delete;
state_saver(state_saver&&) = delete;
state_saver& operator=(const state_saver&) = delete;
state_saver& operator=(state_saver&&) = delete;
state_saver(T&&) = delete;
state_saver(const T&) = delete;
explicit state_saver(T& object) noexcept(std::is_nothrow_constructible<T, T&>::value)
: policy_{true},
previous_ref_{object},
previous_value_{object} {}
void dismiss() noexcept {
policy_.dismiss();
}
template <typename O = T>
auto restore() NEARGYE_NOEXCEPT(std::is_nothrow_assignable<O&, O&>::value) -> typename std::enable_if<std::is_same<T, O>::value && std::is_assignable<O&, O&>::value>::type {
static_assert(std::is_assignable<O&, O&>::value, "state_saver::restore requires copy operator=.");
#if defined(STATE_SAVER_NO_THROW_RESTORE)
static_assert(std::is_nothrow_assignable<O&, O&>::value, "state_saver::restore requires noexcept copy operator=.");
#endif
NEARGYE_TRY
previous_ref_ = previous_value_;
NEARGYE_CATCH
}
~state_saver() NEARGYE_NOEXCEPT(std::is_nothrow_assignable<T&, assignable_t>::value) {
if (policy_.should_execute()) {
NEARGYE_TRY
previous_ref_ = static_cast<assignable_t>(previous_value_);
NEARGYE_CATCH
}
}
};
#undef NEARGYE_NOEXCEPT
#undef NEARGYE_TRY
#undef NEARGYE_CATCH
} // namespace nstd::detail
template <typename U>
class saver_exit : public detail::state_saver<U, detail::on_exit_policy> {
public:
using detail::state_saver<U, detail::on_exit_policy>::state_saver;
};
template <typename U>
class saver_fail : public detail::state_saver<U, detail::on_fail_policy> {
public:
using detail::state_saver<U, detail::on_fail_policy>::state_saver;
};
template <typename U>
class saver_success : public detail::state_saver<U, detail::on_success_policy> {
public:
using detail::state_saver<U, detail::on_success_policy>::state_saver;
};
#if defined(__cpp_deduction_guides) && __cpp_deduction_guides >= 201611L
template <typename U>
saver_exit(U&) -> saver_exit<U>;
template <typename U>
saver_fail(U&) -> saver_fail<U>;
template <typename U>
saver_success(U&) -> saver_success<U>;
#endif
} // namespace nstd
// NEARGYE_MAYBE_UNUSED suppresses compiler warnings on unused entities, if any.
#if !defined(NEARGYE_MAYBE_UNUSED)
# if defined(__clang__)
# if (__clang_major__ * 10 + __clang_minor__) >= 39 && __cplusplus >= 201703L
# define NEARGYE_MAYBE_UNUSED [[maybe_unused]]
# else
# define NEARGYE_MAYBE_UNUSED __attribute__((__unused__))
# endif
# elif defined(__GNUC__)
# if __GNUC__ >= 7 && __cplusplus >= 201703L
# define NEARGYE_MAYBE_UNUSED [[maybe_unused]]
# else
# define NEARGYE_MAYBE_UNUSED __attribute__((__unused__))
# endif
# elif defined(_MSC_VER)
# if _MSC_VER >= 1911 && defined(_MSVC_LANG) && _MSVC_LANG >= 201703L
# define NEARGYE_MAYBE_UNUSED [[maybe_unused]]
# else
# define NEARGYE_MAYBE_UNUSED __pragma(warning(suppress : 4100 4101 4189))
# endif
# else
# define NEARGYE_MAYBE_UNUSED
# endif
#endif
#if !defined(NEARGYE_STR_CONCAT)
# define NEARGYE_STR_CONCAT_(s1, s2) s1##s2
# define NEARGYE_STR_CONCAT(s1, s2) NEARGYE_STR_CONCAT_(s1, s2)
#endif
#if !defined(NEARGYE_COUNTER)
# if defined(__COUNTER__)
# define NEARGYE_COUNTER __COUNTER__
# elif defined(__LINE__)
# define NEARGYE_COUNTER __LINE__
# endif
#endif
#define NEARGYE_STATE_SAVER_WITH_(s, i) for (int i = 1; i--; s)
#define NEARGYE_STATE_SAVER_WITH(s) NEARGYE_STATE_SAVER_WITH_(s, NEARGYE_STR_CONCAT(NEARGYE_INTERNAL_OBJECT_, NEARGYE_COUNTER))
// SAVER_EXIT saves the original variable value and restores on scope exit.
#define MAKE_SAVER_EXIT(name, x) ::nstd::saver_exit<decltype(x)> name{x}
#define SAVER_EXIT(x) NEARGYE_MAYBE_UNUSED const MAKE_SAVER_EXIT(NEARGYE_STR_CONCAT(SAVER_EXIT_, NEARGYE_COUNTER), x)
#define WITH_SAVER_EXIT(x) NEARGYE_STATE_SAVER_WITH(::nstd::saver_exit<decltype(x)>{x})
// SAVER_FAIL saves the original variable value and restores on scope exit when an exception has been thrown.
#define MAKE_SAVER_FAIL(name, x) ::nstd::saver_fail<decltype(x)> name{x}
#define SAVER_FAIL(x) NEARGYE_MAYBE_UNUSED const MAKE_SAVER_FAIL(NEARGYE_STR_CONCAT(SAVER_FAIL_, NEARGYE_COUNTER), x)
#define WITH_SAVER_FAIL(x) NEARGYE_STATE_SAVER_WITH(::nstd::saver_fail<decltype(x)>{x})
// SAVER_SUCCESS saves the original variable value and restores on scope exit when no exceptions have been thrown.
#define MAKE_SAVER_SUCCESS(name, x) ::nstd::saver_success<decltype(x)> name{x}
#define SAVER_SUCCESS(x) NEARGYE_MAYBE_UNUSED const MAKE_SAVER_SUCCESS(NEARGYE_STR_CONCAT(SAVER_SUCCES_, NEARGYE_COUNTER), x)
#define WITH_SAVER_SUCCESS(x) NEARGYE_STATE_SAVER_WITH(::nstd::saver_success<decltype(x)>{x})
#endif // NEARGYE_STATE_SAVER_HPP
| 39.542169
| 175
| 0.722273
|
Neargye
|
08be2b29cbe58b463019d929c190fd62ce6dd37a
| 2,238
|
cpp
|
C++
|
src/mlpack/methods/gmm/gmm_probability_main.cpp
|
NaxAlpha/mlpack-build
|
1f0c1454d4b35eb97ff115669919c205cee5bd1c
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2
|
2018-05-21T11:08:36.000Z
|
2022-03-12T07:52:14.000Z
|
src/mlpack/methods/gmm/gmm_probability_main.cpp
|
okmegy/Mlpack
|
ac9abef3c1353f483ed1af42ba5a7432f291ca1a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
src/mlpack/methods/gmm/gmm_probability_main.cpp
|
okmegy/Mlpack
|
ac9abef3c1353f483ed1af42ba5a7432f291ca1a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
/**
* @file gmm_probability_main.cpp
* @author Ryan Curtin
*
* Given a GMM, calculate the probability of points coming from it.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#include <mlpack/prereqs.hpp>
#include "gmm.hpp"
#include <mlpack/core/data/load.hpp>
#include <mlpack/core/data/save.hpp>
using namespace std;
using namespace mlpack;
using namespace mlpack::gmm;
PROGRAM_INFO("GMM Probability Calculator",
"This program calculates the probability that given points came from a "
"given GMM (that is, P(X | gmm)). The GMM is specified with the "
"--input_model_file option, and the points are specified with the "
"--input_file option. The output probabilities are stored in the file "
"specified by the --output_file option.");
PARAM_STRING_IN_REQ("input_model_file", "File containing input GMM.", "m");
PARAM_STRING_IN_REQ("input_file", "File containing points.", "i");
PARAM_STRING_OUT("output_file", "File to save calculated probabilities to.",
"o");
int main(int argc, char** argv)
{
CLI::ParseCommandLine(argc, argv);
const string inputFile = CLI::GetParam<string>("input_file");
const string inputModelFile = CLI::GetParam<string>("input_model_file");
const string outputFile = CLI::GetParam<string>("output_file");
if (!CLI::HasParam("output_file"))
Log::Warn << "--output_file (-o) is not specified;"
<< "no results will be saved!" << endl;
// Get the GMM and the points.
GMM gmm;
data::Load(inputModelFile, "gmm", gmm);
arma::mat dataset;
data::Load(inputFile, dataset);
// Now calculate the probabilities.
arma::rowvec probabilities(dataset.n_cols);
for (size_t i = 0; i < dataset.n_cols; ++i)
probabilities[i] = gmm.Probability(dataset.unsafe_col(i));
// And save the result.
if (CLI::HasParam("output_file"))
data::Save(CLI::GetParam<string>("output_file"), probabilities);
else
Log::Warn << "--output_file was not specified, so no output will be saved!"
<< endl;
}
| 34.430769
| 79
| 0.703753
|
NaxAlpha
|
08bec8b14d8f7c6c750f4cab4eafaed88a6db114
| 2,028
|
cpp
|
C++
|
wide-IDE/cpwin.cpp
|
nickmain/Amzi-Prolog
|
6ce17a494fc93f3f27e02896a6a5ff7ac4b33c3e
|
[
"MIT"
] | 86
|
2016-04-16T06:35:44.000Z
|
2021-04-14T05:46:32.000Z
|
wide-IDE/cpwin.cpp
|
nickmain/Amzi-Prolog
|
6ce17a494fc93f3f27e02896a6a5ff7ac4b33c3e
|
[
"MIT"
] | 20
|
2021-05-09T20:54:54.000Z
|
2021-05-14T13:12:05.000Z
|
wide-IDE/cpwin.cpp
|
nickmain/Amzi-Prolog
|
6ce17a494fc93f3f27e02896a6a5ff7ac4b33c3e
|
[
"MIT"
] | 15
|
2016-04-16T19:10:45.000Z
|
2020-11-04T04:07:21.000Z
|
//-----------------------------------------------------------
// Extended Windows Predicates, MFC version
//
#include "stdafx.h"
#include <direct.h>
#include <io.h>
#include "amzi.h"
#include "conview.h"
#include "proprog.h"
#include "cpwin.h"
/*
TF EXPFUNC p_keyb(ENGid);
PRED_INIT winPreds[] =
{
// keyboard predicates
{_T("keyb"), 1, p_keyb},
{NULL, 0, NULL}
};
TF EXPFUNC p_keyb(ENGid eid)
{
// get the ASCII value for the next key struck
// use the listener window's GetCh method
int a;
a = (int)(g_pConView->GetCh());
if (! lsUnifyParm(eid, 1, cINT, &a)) return FALSE;
return TRUE;
}
*/
///////////////////////////////////////////////////////////
// Utility Functions
//
void slashslash2(_TCHAR* sout, const _TCHAR* sin)
/* Any string of _TCHARacters sent to Prolog is read using the
Prolog reader, which interprets a backslash as an escape
_TCHARacter. So, this means if you really want a backslash,
such as in a file path, then it has to be a double
backslash. This function makes that conversion. */
{
while(*sin)
{
if (*sin == _T('\\'))
{
*sout++ = *sin;
*sout++ = *sin++;
}
else
*sout++ = *sin++;
}
*sout = *sin;
return;
}
void slashslash1(_TCHAR* s)
/* Same as slashslash2 except conversion is done in place.
Therefor, the input buffer must be large enough to handle
the expanded string. */
{
int nslash=0;
int len=0;
int i;
_TCHAR* s1;
_TCHAR* s2;
/* Count the slashes, then copy in place from right to
left so we don't write on ourself. */
s1 = s;
while(*s1)
{
len++;
if (*s1++ == _T('\\')) nslash++;
}
s2 = s + len + nslash;
s1 = s + len;
for(i=0; i<=len; i++)
{
if (*s1 == _T('\\'))
{
*s2-- = *s1;
*s2-- = *s1--;
}
else
*s2-- = *s1--;
}
return;
}
| 20.28
| 64
| 0.496055
|
nickmain
|
08c2f4a2a8b272af322be5139ca8ca252d73d27b
| 270
|
cpp
|
C++
|
src/CountingBits.cpp
|
yanzhe-chen/LeetCode
|
d82f0b9721ea613ab216c78e7286671d0e9e4187
|
[
"MIT"
] | 43
|
2015-10-10T12:59:52.000Z
|
2018-07-11T18:07:00.000Z
|
src/CountingBits.cpp
|
yanzhe-chen/LeetCode
|
d82f0b9721ea613ab216c78e7286671d0e9e4187
|
[
"MIT"
] | null | null | null |
src/CountingBits.cpp
|
yanzhe-chen/LeetCode
|
d82f0b9721ea613ab216c78e7286671d0e9e4187
|
[
"MIT"
] | 11
|
2015-10-10T14:41:11.000Z
|
2018-07-28T06:03:16.000Z
|
#include "CountingBits.hpp"
vector<int> CountingBits::countBits(int num) {
vector<int> ret(num + 1, 0);
if (num == 0) return ret;
ret[1] = 1;
for (int i = 2; i <= num; i++)
ret[i] = (i & 0x1) ? ret[i / 2] + 1 : ret[i / 2];
return ret;
}
| 18
| 57
| 0.503704
|
yanzhe-chen
|
c0934c3e35e6384d025f570650d814fc9101700a
| 2,717
|
hpp
|
C++
|
ql/experimental/exoticoptions/writerextensibleoption.hpp
|
urgu00/QuantLib
|
fecce0abb0ff3d50da29c129f8f9e73176e20ab9
|
[
"BSD-3-Clause"
] | 2
|
2021-12-12T01:27:45.000Z
|
2022-01-25T17:44:12.000Z
|
ql/experimental/exoticoptions/writerextensibleoption.hpp
|
urgu00/QuantLib
|
fecce0abb0ff3d50da29c129f8f9e73176e20ab9
|
[
"BSD-3-Clause"
] | 19
|
2020-11-23T08:36:10.000Z
|
2022-03-28T10:06:53.000Z
|
ql/experimental/exoticoptions/writerextensibleoption.hpp
|
urgu00/QuantLib
|
fecce0abb0ff3d50da29c129f8f9e73176e20ab9
|
[
"BSD-3-Clause"
] | 5
|
2020-06-04T15:19:22.000Z
|
2020-06-18T08:24:37.000Z
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2011 Master IMAFA - Polytech'Nice Sophia - Université de Nice Sophia Antipolis
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
/*! \file writerextensibleoption.hpp
\brief Writer-extensible option
*/
#ifndef quantlib_writer_extensible_option_hpp
#define quantlib_writer_extensible_option_hpp
#include <ql/instruments/oneassetoption.hpp>
#include <ql/instruments/payoffs.hpp>
#include <ql/exercise.hpp>
namespace QuantLib {
//! Writer-extensible option
class WriterExtensibleOption : public OneAssetOption {
public:
class arguments;
class engine;
/*!
\param payoff1 The first payoff
\param exercise1 The first exercise date
\param payoff2 The payoff of the extended option
\param exercise2 The second exercise date
*/
WriterExtensibleOption(
const ext::shared_ptr<PlainVanillaPayoff>& payoff1,
const ext::shared_ptr<Exercise>& exercise1,
const ext::shared_ptr<PlainVanillaPayoff>& payoff2,
const ext::shared_ptr<Exercise>& exercise2);
// inspectors
ext::shared_ptr<Payoff> payoff2() { return payoff2_; }
ext::shared_ptr<Exercise> exercise2() { return exercise2_; };
// Instrument interface
bool isExpired() const;
void setupArguments(PricingEngine::arguments*) const;
private:
ext::shared_ptr<StrikedTypePayoff> payoff2_;
ext::shared_ptr<Exercise> exercise2_;
};
//! Additional arguments for writer-extensible option
class WriterExtensibleOption::arguments
: public OneAssetOption::arguments {
public:
void validate() const;
ext::shared_ptr<Payoff> payoff2;
ext::shared_ptr<Exercise> exercise2;
};
//! Base engine
class WriterExtensibleOption::engine :
public GenericEngine<WriterExtensibleOption::arguments,
WriterExtensibleOption::results> {};
}
#endif
| 35.285714
| 93
| 0.691204
|
urgu00
|
c09e50a22c50058c83d458917f2448e63981aad9
| 3,919
|
cpp
|
C++
|
src/placeholder.cpp
|
matt-harvey/swx
|
e7b10fe7d4bf0bd6581ceada53ad14b08bc1d852
|
[
"Apache-2.0"
] | 7
|
2017-10-08T08:08:25.000Z
|
2020-04-27T09:25:00.000Z
|
src/placeholder.cpp
|
matt-harvey/swx
|
e7b10fe7d4bf0bd6581ceada53ad14b08bc1d852
|
[
"Apache-2.0"
] | null | null | null |
src/placeholder.cpp
|
matt-harvey/swx
|
e7b10fe7d4bf0bd6581ceada53ad14b08bc1d852
|
[
"Apache-2.0"
] | 1
|
2020-04-27T09:24:42.000Z
|
2020-04-27T09:24:42.000Z
|
/*
* Copyright 2014 Matthew Harvey
*
* 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 "placeholder.hpp"
#include "stream_utilities.hpp"
#include "string_utilities.hpp"
#include "time_log.hpp"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <ostream>
#include <sstream>
#include <string>
#include <vector>
using std::back_inserter;
using std::copy;
using std::endl;
using std::ostream;
using std::ostringstream;
using std::size_t;
using std::string;
using std::vector;
namespace swx
{
namespace
{
char const k_tree_traversal_char = '_';
/**
* @returns \e true if p_str successfully expands into an
* activity string, in the context of p_time_log; otherwise, returns \e
* false.
*
* If successful, pushes the resulting activity components to \e p_vec;
* otherwise, it leaves \e p_vec unchanged.
*/
bool parse_placeholder
( string const& p_str,
vector<string>& p_vec,
TimeLog& p_time_log
)
{
size_t depth = 0;
if (p_str.empty())
{
return false;
}
for (char c: p_str)
{
if (c == k_tree_traversal_char) ++depth;
else return false;
}
if (p_time_log.is_active())
{
auto const last_activities = p_time_log.last_activities(1);
assert (!last_activities.empty());
string const activity = last_activities.front();
auto const components = split(activity);
assert (depth > 0);
--depth;
auto const b = components.begin();
auto it = components.end();
for ( ; (it != b) && (depth != 0); --it, --depth)
{
}
copy(b, it, back_inserter(p_vec));
}
else
{
p_vec.push_back("");
}
return true;
}
} // end anonymous namespace
string
expand_placeholders(vector<string> const& p_components, TimeLog& p_time_log)
{
vector<string> vec;
vec.reserve(p_components.size());
for (auto const& component: p_components)
{
if (!parse_placeholder(component, vec, p_time_log))
{
if (!component.empty()) vec.push_back(component);
}
}
return squish(vec.begin(), vec.end());
}
void
write_placeholder_help(ostream& p_os, string::size_type p_margin, string::size_type p_width)
{
string::size_type const num_lines = 3;
string::size_type const min_margin = num_lines + 1;
if (min_margin > p_margin) p_margin = min_margin;
for (string::size_type i = 1; i <= num_lines; ++i)
{
assert (p_margin >= i);
p_os << endl;
p_os << " " << string(i, k_tree_traversal_char)
<< string(p_margin - i, ' ') << ": ";
string help;
switch (i)
{
case 1:
help = "Expands into name of current activity (or empty string if inactive)";
break;
case 2:
help = "Expands into name of parent of current activity (or empty string if "\
"no parent)";
break;
case 3:
help = "Expands into name of parent of parent (etc.)";
break;
default:
assert (false);
}
p_os << wrap(help, p_margin + 4, p_width);
}
}
} // namespace swx
| 27.405594
| 92
| 0.592498
|
matt-harvey
|
c0a474de71bc395d6c17a885e849620c4148b3ec
| 965
|
cpp
|
C++
|
src/physical_device.cpp
|
QSXW/VKCPP
|
c3fed2159dca0d63b4eb5e15b9a1e5fbcf05bfb8
|
[
"Apache-2.0"
] | null | null | null |
src/physical_device.cpp
|
QSXW/VKCPP
|
c3fed2159dca0d63b4eb5e15b9a1e5fbcf05bfb8
|
[
"Apache-2.0"
] | null | null | null |
src/physical_device.cpp
|
QSXW/VKCPP
|
c3fed2159dca0d63b4eb5e15b9a1e5fbcf05bfb8
|
[
"Apache-2.0"
] | null | null | null |
#include "physical_device.h"
namespace VKCPP
{
PFN_vkGetPhysicalDeviceFeatures PhysicalDevice::GetFeatures;
PFN_vkGetPhysicalDeviceFormatProperties PhysicalDevice::GetFormatProperties;
PFN_vkGetPhysicalDeviceImageFormatProperties PhysicalDevice::GetImageFormatProperties;
PFN_vkGetPhysicalDeviceMemoryProperties PhysicalDevice::GetMemoryProperties;
PFN_vkGetPhysicalDeviceProperties PhysicalDevice::GetProperties;
PFN_vkGetPhysicalDeviceQueueFamilyProperties PhysicalDevice::GetQueueFamilyProperties;
PFN_vkGetPhysicalDeviceSparseImageFormatProperties PhysicalDevice::GetSparseImageFormatProperties;
PhysicalDevice::PhysicalDevice(Primitive other) :
handle{ other }
{
uint32_t count = 0;
get_queue_family_properties(&count, nullptr);
queue_family_properties.resize(count);
get_queue_family_properties(&count, queue_family_properties.data());
}
}
| 38.6
| 99
| 0.781347
|
QSXW
|
c0a85d85b9a9db48247620e73d9af2698fa24d24
| 3,101
|
cpp
|
C++
|
libs/fnd/algorithm/test/src/ranges/unit_test_fnd_algorithm_ranges_copy_n.cpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 4
|
2018-06-10T13:35:32.000Z
|
2021-06-03T14:27:41.000Z
|
libs/fnd/algorithm/test/src/ranges/unit_test_fnd_algorithm_ranges_copy_n.cpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 566
|
2017-01-31T05:36:09.000Z
|
2022-02-09T05:04:37.000Z
|
libs/fnd/algorithm/test/src/ranges/unit_test_fnd_algorithm_ranges_copy_n.cpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 1
|
2018-07-05T04:40:53.000Z
|
2018-07-05T04:40:53.000Z
|
/**
* @file unit_test_fnd_algorithm_ranges_copy_n.cpp
*
* @brief ranges::copy_n のテスト
*
* @author myoukaku
*/
#include <bksge/fnd/algorithm/ranges/copy_n.hpp>
#include <bksge/fnd/algorithm/ranges/equal.hpp>
#include <bksge/fnd/iterator/ranges/next.hpp>
#include <gtest/gtest.h>
#include "constexpr_test.hpp"
#include "ranges_test.hpp"
namespace bksge_algorithm_test
{
namespace ranges_copy_n_test
{
#define VERIFY(...) if (!(__VA_ARGS__)) { return false; }
inline BKSGE_CXX14_CONSTEXPR bool test01()
{
namespace ranges = bksge::ranges;
int const x[7] = { 1, 2, 3, 4, 5, 6, 7 };
{
int w[7] = {};
auto res = ranges::copy_n(x, -1, w);
VERIFY(res.in == x+0);
VERIFY(res.out == w+0);
}
{
int w[7] = {};
auto res = ranges::copy_n(x, 0, w);
VERIFY(res.in == x+0);
VERIFY(res.out == w+0);
}
{
int w[7] = {};
auto res = ranges::copy_n(x, 1, w);
VERIFY(res.in == x+1);
VERIFY(res.out == w+1);
int const y[7] = { 1, 0, 0, 0, 0, 0, 0 };
VERIFY(ranges::equal(w, y));
}
{
int w[7] = {};
auto res = ranges::copy_n(x, 7, w);
VERIFY(res.in == x+7);
VERIFY(res.out == w+7);
int const y[7] = { 1, 2, 3, 4, 5, 6, 7 };
VERIFY(ranges::equal(w, y));
}
return true;
}
template <
template <typename> class in_wrapper,
template <typename> class out_wrapper
>
inline BKSGE_CXX14_CONSTEXPR bool test02()
{
namespace ranges = bksge::ranges;
int x[7] = { 1, 2, 3, 4, 5, 6, 7 };
{
int w[7] = {};
test_range<int, in_wrapper> rx(x);
test_range<int, out_wrapper> rw(w);
auto res = ranges::copy_n(rx.begin(), -1, rw.begin());
VERIFY(res.in == rx.begin());
VERIFY(res.out.m_ptr == w);
}
{
int w[7] = {};
test_range<int, in_wrapper> rx(x);
test_range<int, out_wrapper> rw(w);
auto res = ranges::copy_n(rx.begin(), 0, rw.begin());
VERIFY(res.in == rx.begin());
VERIFY(res.out.m_ptr == w);
}
{
int w[7] = {};
test_range<int, in_wrapper> rx(x);
test_range<int, out_wrapper> rw(w);
auto res = ranges::copy_n(rx.begin(), 1, rw.begin());
VERIFY(res.in == ranges::next(rx.begin(), 1));
VERIFY(res.out.m_ptr == w+1);
int const y[7] = { 1, 0, 0, 0, 0, 0, 0 };
VERIFY(ranges::equal(w, y));
}
{
int w[7] = {};
test_range<int, in_wrapper> rx(x);
test_range<int, out_wrapper> rw(w);
auto res = ranges::copy_n(rx.begin(), 7, rw.begin());
VERIFY(res.in == rx.end());
VERIFY(res.out == rw.end());
int const y[7] = { 1, 2, 3, 4, 5, 6, 7 };
VERIFY(ranges::equal(w, y));
}
return true;
}
#undef VERIFY
GTEST_TEST(AlgorithmTest, RangesCopyNTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(test01());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(
(test02<input_iterator_wrapper, output_iterator_wrapper>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(
(test02<random_access_iterator_wrapper, output_iterator_wrapper>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(
(test02<random_access_iterator_wrapper, random_access_iterator_wrapper>()));
}
} // namespace ranges_copy_n_test
} // namespace bksge_algorithm_test
| 25.418033
| 79
| 0.610448
|
myoukaku
|
c0ac3c7e1842e42aa82dc05fc477a5a50b9e0e4f
| 400
|
cpp
|
C++
|
MaxConsecutiveOnes/main.cpp
|
warjiang/leetcode
|
2c00b1406fc3680a7a0ecf1842b3544a0ca28185
|
[
"MIT"
] | null | null | null |
MaxConsecutiveOnes/main.cpp
|
warjiang/leetcode
|
2c00b1406fc3680a7a0ecf1842b3544a0ca28185
|
[
"MIT"
] | null | null | null |
MaxConsecutiveOnes/main.cpp
|
warjiang/leetcode
|
2c00b1406fc3680a7a0ecf1842b3544a0ca28185
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#include "Solution.cpp"
using namespace std;
void tranverseVector(vector<int> v){
for(int i = 0; i < v.size(); i++){
cout << v[i] << endl;
}
}
int main(){
Solution* s = new Solution;
int arr[] = {1,1,0,1,1,1};
vector<int> v(arr, arr+sizeof(arr)/sizeof(int));
int n = s->findMaxConsecutiveOnes(v);
cout << n << endl;
//tranverseVector(v);
return 0;
}
| 20
| 49
| 0.625
|
warjiang
|
c0b22e9afc40aa14c293cad55ca091272311ddba
| 5,413
|
cpp
|
C++
|
src/statespace/SO3.cpp
|
usc-csci-545/aikido
|
afd8b203c17cb0b05d7db436f8bffbbe2111a75a
|
[
"BSD-3-Clause"
] | null | null | null |
src/statespace/SO3.cpp
|
usc-csci-545/aikido
|
afd8b203c17cb0b05d7db436f8bffbbe2111a75a
|
[
"BSD-3-Clause"
] | null | null | null |
src/statespace/SO3.cpp
|
usc-csci-545/aikido
|
afd8b203c17cb0b05d7db436f8bffbbe2111a75a
|
[
"BSD-3-Clause"
] | null | null | null |
#include <iostream>
#include <dart/math/Geometry.hpp>
#include <aikido/statespace/SO3.hpp>
namespace aikido {
namespace statespace {
//==============================================================================
SO3::SO3::State::State() : mValue(1., 0., 0., 0.)
{
}
//==============================================================================
SO3::SO3::State::State(const Quaternion& _quaternion) : mValue(_quaternion)
{
// TODO: Check if normalized.
}
//==============================================================================
auto SO3::State::getQuaternion() const -> const Quaternion&
{
return mValue;
}
//==============================================================================
void SO3::State::setQuaternion(const Quaternion& _quaternion)
{
// TODO: Check if normalized.
mValue = _quaternion;
}
//==============================================================================
auto SO3::createState() const -> ScopedState
{
return ScopedState(this);
}
//==============================================================================
auto SO3::cloneState(const StateSpace::State* stateIn) const -> ScopedState
{
auto newState = createState();
copyState(stateIn, newState);
return newState;
}
//==============================================================================
auto SO3::getQuaternion(const State* _state) const -> const Quaternion&
{
return _state->mValue;
}
//==============================================================================
void SO3::setQuaternion(State* _state, const Quaternion& _quaternion) const
{
_state->mValue = _quaternion;
}
//==============================================================================
std::size_t SO3::getStateSizeInBytes() const
{
return sizeof(State);
}
//==============================================================================
StateSpace::State* SO3::allocateStateInBuffer(void* _buffer) const
{
return new (_buffer) State;
}
//==============================================================================
void SO3::freeStateInBuffer(StateSpace::State* _state) const
{
static_cast<State*>(_state)->~State();
}
//==============================================================================
void SO3::compose(
const StateSpace::State* _state1,
const StateSpace::State* _state2,
StateSpace::State* _out) const
{
// TODO: Disable this in release mode.
if (_state1 == _out || _state2 == _out)
throw std::invalid_argument("Output aliases input.");
auto state1 = static_cast<const State*>(_state1);
auto state2 = static_cast<const State*>(_state2);
auto out = static_cast<State*>(_out);
out->mValue = state1->mValue * state2->mValue;
}
//==============================================================================
void SO3::getIdentity(StateSpace::State* _out) const
{
auto out = static_cast<State*>(_out);
setQuaternion(out, Quaternion::Identity());
}
//==============================================================================
void SO3::getInverse(
const StateSpace::State* _in, StateSpace::State* _out) const
{
// TODO: Disable this in release mode.
if (_out == _in)
throw std::invalid_argument("Output aliases input.");
auto in = static_cast<const State*>(_in);
auto out = static_cast<State*>(_out);
setQuaternion(out, getQuaternion(in).inverse());
}
//==============================================================================
std::size_t SO3::getDimension() const
{
return 3;
}
//==============================================================================
void SO3::copyState(
const StateSpace::State* _source, StateSpace::State* _destination) const
{
auto destination = static_cast<State*>(_destination);
auto source = static_cast<const State*>(_source);
setQuaternion(destination, getQuaternion(source));
}
//==============================================================================
void SO3::expMap(const Eigen::VectorXd& _tangent, StateSpace::State* _out) const
{
auto out = static_cast<State*>(_out);
// TODO: Skip these checks in release mode.
if (_tangent.rows() != 3)
{
std::stringstream msg;
msg << "_tangent has incorrect size: expected 3"
<< ", got " << _tangent.rows() << ".\n";
throw std::runtime_error(msg.str());
}
Eigen::Vector6d tangent(Eigen::Vector6d::Zero());
tangent.head<3>() = _tangent;
Eigen::Isometry3d transform = dart::math::expMap(tangent);
out->setQuaternion(Quaternion(transform.rotation()));
}
//==============================================================================
void SO3::logMap(const StateSpace::State* _in, Eigen::VectorXd& _tangent) const
{
if (_tangent.rows() != 3)
{
_tangent.resize(3);
}
auto in = static_cast<const State*>(_in);
// Compute rotation matrix from quaternion
Eigen::Matrix3d rotMat = getQuaternion(in).toRotationMatrix();
_tangent = dart::math::logMap(rotMat);
}
//==============================================================================
void SO3::print(const StateSpace::State* _state, std::ostream& _os) const
{
auto state = static_cast<const State*>(_state);
Eigen::IOFormat cleanFmt(
Eigen::StreamPrecision, Eigen::DontAlignCols, ",", ",", "", "", "[", "]");
auto quat = getQuaternion(state);
_os << Eigen::Vector4d(quat.w(), quat.x(), quat.y(), quat.z())
.format(cleanFmt);
}
} // namespace statespace
} // namespace aikido
| 30.240223
| 80
| 0.493257
|
usc-csci-545
|
c0b700887c45e60309776b904abf5458b0837f04
| 3,267
|
cpp
|
C++
|
Projects/HW1P3/URLParser.cpp
|
iamjeffx/CSCE-463
|
c9724a993909db2f9cb58e9835e8c0ec6efa49e5
|
[
"MIT"
] | null | null | null |
Projects/HW1P3/URLParser.cpp
|
iamjeffx/CSCE-463
|
c9724a993909db2f9cb58e9835e8c0ec6efa49e5
|
[
"MIT"
] | null | null | null |
Projects/HW1P3/URLParser.cpp
|
iamjeffx/CSCE-463
|
c9724a993909db2f9cb58e9835e8c0ec6efa49e5
|
[
"MIT"
] | 1
|
2022-01-24T09:01:59.000Z
|
2022-01-24T09:01:59.000Z
|
/** CSCE 463 Homework 1 Part 3: Spring 2021
*
Author: Jeffrey Xu
UIN: 527008162
Email: jeffreyxu@tamu.edu
Professor Dmitri Loguinov
Filename: URLParser.cpp
Definition of URLParser functions. Note that fragments are not included in this parser.
**/
#include "pch.h"
#include "URLParser.h"
using namespace std;
#define MAX_HOST_LEN 256
URLParser::URLParser(std::string url) {
// Set values to default values (except for URL)
reset(url);
};
URLParser::~URLParser() {
// Clear all fields to default values
reset("");
};
void URLParser::reset(string URL) {
this->url = URL;
this->host = "";
this->path = "/";
this->port = 80;
this->query = "";
};
int URLParser::parse() {
string URL = this->url;
// Check that the HTTP protocol is being used (HTTPS not considered at this stage)
if (URL.substr(0, 7) != "http://") {
reset("");
return -1;
}
// Remove the HTTP scheme and fragments
URL = URL.substr(7, (int)URL.size());
int fragmentIndex = (int)URL.find_first_of("#");
URL = URL.substr(0, fragmentIndex);
// Extract query
int queryIndex = (int)URL.find_first_of("?");
if (queryIndex != -1) {
setQuery(URL.substr(queryIndex, (int)URL.size()));
URL = URL.substr(0, queryIndex);
}
// Extract path
int pathIndex = (int)URL.find_first_of("/");
if (pathIndex != -1) {
setPath(URL.substr(pathIndex, (int)URL.size()));
URL = URL.substr(0, pathIndex);
}
// Extract host and port number
int portIndex = (int)URL.find_first_of(":");
if (portIndex == -1) {
setHost(URL);
}
else {
// No port specified
if (portIndex == URL.size() - 1) {
reset("");
return -2;
}
// Initialize port number
this->port = atoi(URL.substr((size_t)portIndex + 1, (int)URL.size()).c_str());
// Invalid port number provided (handles case if port number is negative or isn't numeric)
if (port <= 0) {
reset("");
return -2;
}
setHost(URL.substr(0, portIndex));
}
if (this->getHost().size() > MAX_HOST_LEN) {
return -1;
}
// URL successfully parsed
return 0;
};
string URLParser::generateQuery() {
// Concatenates path and query to generate the entire query
return getPath() + getQuery();
}
string URLParser::generateRequest(string requestType) {
// Generates entire HTTP request
string request = requestType + " " + generateQuery() + " HTTP/1.0\r\n";
request += "User-agent: JXCrawler/1.2\r\n";
request += "Host: " + getHost() + "\r\n";
request += "Connection: close\r\n\r\n";
return request;
}
string URLParser::bonusGenerateRobotsRequest() {
string request = "HEAD /robots.txt HTTP/1.1\r\n";
request += "User-agent: JXCrawler/1.2\r\n";
request += "Host: " + getHost() + "\r\n";
request += "Connection: close\r\n\r\n";
return request;
}
string URLParser::bonusGenerateRequest(string requestType) {
// Generates entire HTTP request
string request = requestType + " " + generateQuery() + " HTTP/1.1\r\n";
request += "User-agent: JXCrawler/1.2\r\n";
request += "Host: " + getHost() + "\r\n";
request += "Connection: close\r\n\r\n";
return request;
}
string URLParser::generateRobotsRequest() {
string request = "HEAD /robots.txt HTTP/1.0\r\n";
request += "User-agent: JXCrawler/1.2\r\n";
request += "Host: " + getHost() + "\r\n";
request += "Connection: close\r\n\r\n";
return request;
}
| 25.130769
| 92
| 0.655647
|
iamjeffx
|
c0b7a6df226bbee4791a4cd6732a3f240379872e
| 6,489
|
cpp
|
C++
|
src/mf.cpp
|
durgeshra/libDAI-1
|
f72414d4381e302c0655f4055dbf526c738bf485
|
[
"BSD-2-Clause"
] | null | null | null |
src/mf.cpp
|
durgeshra/libDAI-1
|
f72414d4381e302c0655f4055dbf526c738bf485
|
[
"BSD-2-Clause"
] | null | null | null |
src/mf.cpp
|
durgeshra/libDAI-1
|
f72414d4381e302c0655f4055dbf526c738bf485
|
[
"BSD-2-Clause"
] | null | null | null |
/* This file is part of libDAI - http://www.libdai.org/
*
* Copyright (c) 2006-2011, The libDAI 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 <iostream>
#include <sstream>
#include <map>
#include <set>
#include <dai/mf.h>
#include <dai/util.h>
namespace dai {
using namespace std;
void MF::setProperties( const PropertySet &opts ) {
DAI_ASSERT( opts.hasKey("tol") );
DAI_ASSERT( opts.hasKey("maxiter") );
props.tol = opts.getStringAs<Real>("tol");
props.maxiter = opts.getStringAs<size_t>("maxiter");
if( opts.hasKey("verbose") )
props.verbose = opts.getStringAs<size_t>("verbose");
else
props.verbose = 0U;
if( opts.hasKey("damping") )
props.damping = opts.getStringAs<Real>("damping");
else
props.damping = 0.0;
if( opts.hasKey("maxtime") )
props.maxtime = opts.getStringAs<double>("maxtime");
else
props.maxtime = INFINITY;
if( opts.hasKey("init") )
props.init = opts.getStringAs<Properties::InitType>("init");
else
props.init = Properties::InitType::UNIFORM;
if( opts.hasKey("updates") )
props.updates = opts.getStringAs<Properties::UpdateType>("updates");
else
props.updates = Properties::UpdateType::NAIVE;
}
PropertySet MF::getProperties() const {
PropertySet opts;
opts.set( "tol", props.tol );
opts.set( "maxiter", props.maxiter );
opts.set( "maxtime", props.maxtime );
opts.set( "verbose", props.verbose );
opts.set( "damping", props.damping );
opts.set( "init", props.init );
opts.set( "updates", props.updates );
return opts;
}
string MF::printProperties() const {
stringstream s( stringstream::out );
s << "[";
s << "tol=" << props.tol << ",";
s << "maxiter=" << props.maxiter << ",";
s << "maxtime=" << props.maxtime << ",";
s << "verbose=" << props.verbose << ",";
s << "init=" << props.init << ",";
s << "updates=" << props.updates << ",";
s << "damping=" << props.damping << "]";
return s.str();
}
void MF::construct() {
// create beliefs
_beliefs.clear();
_beliefs.reserve( nrVars() );
for( size_t i = 0; i < nrVars(); ++i )
_beliefs.push_back( Factor( var(i) ) );
}
void MF::init() {
if( props.init == Properties::InitType::UNIFORM )
for( size_t i = 0; i < nrVars(); i++ )
_beliefs[i].fill( 1.0 );
else
for( size_t i = 0; i < nrVars(); i++ )
_beliefs[i].randomize();
}
Factor MF::calcNewBelief( size_t i ) {
Factor result;
bforeach( const Neighbor &I, nbV(i) ) {
Factor belief_I_minus_i;
bforeach( const Neighbor &j, nbF(I) ) // for all j in I \ i
if( j != i )
belief_I_minus_i *= _beliefs[j];
Factor f_I = factor(I);
if( props.updates == Properties::UpdateType::NAIVE )
f_I.takeLog(true);
Factor msg_I_i = (belief_I_minus_i * f_I).marginal( var(i), false );
if( props.updates == Properties::UpdateType::NAIVE )
result *= msg_I_i.exp();
else
result *= msg_I_i;
}
result.normalize();
return result;
}
Real MF::run() {
if( props.verbose >= 1 )
cerr << "Starting " << identify() << "...";
double tic = toc();
vector<size_t> update_seq;
update_seq.reserve( nrVars() );
for( size_t i = 0; i < nrVars(); i++ )
update_seq.push_back( i );
// do several passes over the network until maximum number of iterations has
// been reached or until the maximum belief difference is smaller than tolerance
Real maxDiff = INFINITY;
for( _iters = 0; _iters < props.maxiter && maxDiff > props.tol && (toc()-tic)<props.maxtime; _iters++ ) {
random_shuffle( update_seq.begin(), update_seq.end(), rnd );
maxDiff = -INFINITY;
bforeach( const size_t &i, update_seq ) {
Factor nb = calcNewBelief( i );
if( nb.hasNaNs() ) {
cerr << name() << "::run(): ERROR: new belief of variable " << var(i) << " has NaNs!" << endl;
return 1.0;
}
if( props.damping != 0.0 )
nb = (nb^(1.0 - props.damping)) * (_beliefs[i]^props.damping);
maxDiff = std::max( maxDiff, dist( nb, _beliefs[i], DISTLINF ) );
_beliefs[i] = nb;
}
if( props.verbose >= 3 )
cerr << name() << "::run: maxdiff " << maxDiff << " after " << _iters+1 << " passes" << endl;
}
if( maxDiff > _maxdiff )
_maxdiff = maxDiff;
if( props.verbose >= 1 ) {
if( maxDiff > props.tol ) {
if( props.verbose == 1 )
cerr << endl;
cerr << name() << "::run: WARNING: not converged within " << props.maxiter << " passes (" << toc() - tic << " seconds)...final maxdiff:" << maxDiff << endl;
} else {
if( props.verbose >= 3 )
cerr << name() << "::run: ";
cerr << "converged in " << _iters << " passes (" << toc() - tic << " seconds)." << endl;
}
}
return maxDiff;
}
Factor MF::beliefV( size_t i ) const {
return _beliefs[i].normalized();
}
Factor MF::belief (const VarSet &ns) const {
if( ns.size() == 0 )
return Factor();
else if( ns.size() == 1 )
return beliefV( findVar( *(ns.begin()) ) );
else {
DAI_THROW(BELIEF_NOT_AVAILABLE);
return Factor();
}
}
vector<Factor> MF::beliefs() const {
vector<Factor> result;
for( size_t i = 0; i < nrVars(); i++ )
result.push_back( beliefV(i) );
return result;
}
Real MF::logZ() const {
Real s = 0.0;
for( size_t i = 0; i < nrVars(); i++ )
s -= beliefV(i).entropy();
for( size_t I = 0; I < nrFactors(); I++ ) {
Factor henk;
bforeach( const Neighbor &j, nbF(I) ) // for all j in I
henk *= _beliefs[j];
henk.normalize();
Factor piet;
piet = factor(I).log(true);
piet *= henk;
s -= piet.sum();
}
return -s;
}
void MF::init( const VarSet &ns ) {
for( size_t i = 0; i < nrVars(); i++ )
if( ns.contains(var(i) ) ) {
if( props.init == Properties::InitType::UNIFORM )
_beliefs[i].fill( 1.0 );
else
_beliefs[i].randomize();
}
}
} // end of namespace dai
| 28.213043
| 169
| 0.540145
|
durgeshra
|
c0b9bc1b7d09c268d1fee8a9f49be94cc20c2e44
| 9,923
|
cpp
|
C++
|
Modules/Core/src/Controllers/mitkVtkLayerController.cpp
|
zhaomengxiao/MITK
|
a09fd849a4328276806008bfa92487f83a9e2437
|
[
"BSD-3-Clause"
] | 1
|
2022-03-03T12:03:32.000Z
|
2022-03-03T12:03:32.000Z
|
Modules/Core/src/Controllers/mitkVtkLayerController.cpp
|
zhaomengxiao/MITK
|
a09fd849a4328276806008bfa92487f83a9e2437
|
[
"BSD-3-Clause"
] | 1
|
2021-12-22T10:19:02.000Z
|
2021-12-22T10:19:02.000Z
|
Modules/Core/src/Controllers/mitkVtkLayerController.cpp
|
zhaomengxiao/MITK_lancet
|
a09fd849a4328276806008bfa92487f83a9e2437
|
[
"BSD-3-Clause"
] | 1
|
2020-11-27T09:41:18.000Z
|
2020-11-27T09:41:18.000Z
|
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "mitkVtkLayerController.h"
#include <algorithm>
#include <vtkObjectFactory.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkRendererCollection.h>
mitk::VtkLayerController::vtkLayerControllerMapType mitk::VtkLayerController::s_LayerControllerMap;
mitk::VtkLayerController *mitk::VtkLayerController::GetInstance(vtkSmartPointer<vtkRenderWindow> renWin)
{
for (auto mapit = s_LayerControllerMap.begin(); mapit != s_LayerControllerMap.end(); ++mapit)
{
if ((*mapit).first == renWin)
return (*mapit).second;
}
return nullptr;
}
void mitk::VtkLayerController::AddInstance(vtkSmartPointer<vtkRenderWindow> renWin,
vtkSmartPointer<vtkRenderer> mitkSceneRenderer)
{
// ensure that no vtkRenderWindow is managed twice
mitk::VtkLayerController::RemoveInstance(renWin);
// instanciate controller, add it to the map
mitk::VtkLayerController *ControllerInstance = new mitk::VtkLayerController(renWin);
ControllerInstance->InsertSceneRenderer(mitkSceneRenderer);
s_LayerControllerMap.insert(vtkLayerControllerMapType::value_type(renWin, ControllerInstance));
}
void mitk::VtkLayerController::RemoveInstance(vtkSmartPointer<vtkRenderWindow> renWin)
{
auto mapit = s_LayerControllerMap.find(renWin);
if (mapit != s_LayerControllerMap.end())
{
delete mapit->second;
s_LayerControllerMap.erase(mapit);
}
}
mitk::VtkLayerController::VtkLayerController(vtkSmartPointer<vtkRenderWindow> renderWindow)
{
m_RenderWindow = renderWindow;
m_RenderWindow->Register(nullptr);
m_BackgroundRenderers.clear();
m_ForegroundRenderers.clear();
m_SceneRenderers.clear();
}
mitk::VtkLayerController::~VtkLayerController()
{
if (m_RenderWindow != nullptr)
{
m_RenderWindow->UnRegister(nullptr);
}
}
/**
* Connects a VTK renderer with a vtk renderwindow. The renderer will be rendered in the background.
* With forceAbsoluteBackground set true a renderer can be placed at the absolute background of the scene.
* Multiple calls with forceAbsoluteBackground set true will set the latest registered renderer as background.
*/
void mitk::VtkLayerController::InsertBackgroundRenderer(vtkSmartPointer<vtkRenderer> renderer,
bool forceAbsoluteBackground)
{
if (renderer == nullptr)
return;
// Remove renderer if it already exists
RemoveRenderer(renderer);
if (forceAbsoluteBackground)
{
auto it = m_BackgroundRenderers.begin();
m_BackgroundRenderers.insert(it, renderer);
}
else
m_BackgroundRenderers.push_back(renderer);
UpdateLayers();
}
/**
* Connects a VTK renderer with a vtk renderwindow. The renderer will be rendered in the foreground.
* With forceAbsoluteBackground set true a renderer can be placed at the absolute foreground of the scene.
* Multiple calls with forceAbsoluteForeground set true will set the latest registered renderer as foreground.
*/
void mitk::VtkLayerController::InsertForegroundRenderer(vtkSmartPointer<vtkRenderer> renderer,
bool forceAbsoluteForeground)
{
if (renderer == nullptr)
return;
// Remove renderer if it already exists
RemoveRenderer(renderer);
if (forceAbsoluteForeground)
{
auto it = m_ForegroundRenderers.begin();
m_ForegroundRenderers.insert(it, renderer);
}
else
m_ForegroundRenderers.push_back(renderer);
renderer->PreserveDepthBufferOn();
UpdateLayers();
}
/**
* Returns the Scene Renderer
*/
vtkSmartPointer<vtkRenderer> mitk::VtkLayerController::GetSceneRenderer()
{
if (m_SceneRenderers.size() > 0)
{
auto it = m_SceneRenderers.begin();
return (*it);
}
else
return nullptr;
}
/**
* Connects a VTK renderer with a vtk renderwindow. The renderer will be rendered between background renderers and
* foreground renderers.
*/
void mitk::VtkLayerController::InsertSceneRenderer(vtkSmartPointer<vtkRenderer> renderer)
{
if (renderer == nullptr)
return;
// Remove renderer if it already exists
RemoveRenderer(renderer);
m_SceneRenderers.push_back(renderer);
UpdateLayers();
}
/**
* A renderer which has been inserted via a insert... function can be removed from the vtkRenderWindow with
* RemoveRenderer.
*/
void mitk::VtkLayerController::RemoveRenderer(vtkSmartPointer<vtkRenderer> renderer)
{
RendererVectorType::iterator it;
// background layers
if (m_BackgroundRenderers.size() > 0)
{
it = std::find(m_BackgroundRenderers.begin(), m_BackgroundRenderers.end(), renderer);
if (it != m_BackgroundRenderers.end())
{
m_BackgroundRenderers.erase(it);
UpdateLayers();
return;
}
}
// scene layers
if (m_SceneRenderers.size() > 0)
{
it = std::find(m_SceneRenderers.begin(), m_SceneRenderers.end(), renderer);
if (it != m_SceneRenderers.end())
{
m_SceneRenderers.erase(it);
UpdateLayers();
return;
}
}
// foreground layers
if (m_ForegroundRenderers.size() > 0)
{
it = std::find(m_ForegroundRenderers.begin(), m_ForegroundRenderers.end(), renderer);
if (it != m_ForegroundRenderers.end())
{
m_ForegroundRenderers.erase(it);
UpdateLayers();
return;
}
}
}
/**
* Connects a VtkRenderWindow with the layer controller.
*/
void mitk::VtkLayerController::SetRenderWindow(vtkSmartPointer<vtkRenderWindow> renwin)
{
if (renwin != nullptr)
{
RendererVectorType::iterator it;
// Tell all renderers that there is a new renderwindow
for (it = m_BackgroundRenderers.begin(); it != m_BackgroundRenderers.end(); ++it)
{
(*it)->SetRenderWindow(renwin);
}
for (it = m_SceneRenderers.begin(); it != m_SceneRenderers.end(); ++it)
{
(*it)->SetRenderWindow(renwin);
}
for (it = m_ForegroundRenderers.begin(); it != m_ForegroundRenderers.end(); ++it)
{
(*it)->SetRenderWindow(renwin);
}
// Set the new RenderWindow
m_RenderWindow = renwin;
}
// Now sort renderers and add them to the renderwindow
UpdateLayers();
}
/**
* Returns true if a renderer has been inserted
*/
bool mitk::VtkLayerController::IsRendererInserted(vtkSmartPointer<vtkRenderer> renderer)
{
RendererVectorType::iterator it;
// background layers
if (m_BackgroundRenderers.size() > 0)
{
it = std::find(m_BackgroundRenderers.begin(), m_BackgroundRenderers.end(), renderer);
if (it != m_BackgroundRenderers.end())
{
return true;
}
}
// scene layers
if (m_SceneRenderers.size() > 0)
{
it = std::find(m_SceneRenderers.begin(), m_SceneRenderers.end(), renderer);
if (it != m_SceneRenderers.end())
{
return true;
}
}
// foreground layers
if (m_ForegroundRenderers.size() > 0)
{
it = std::find(m_ForegroundRenderers.begin(), m_ForegroundRenderers.end(), renderer);
if (it != m_ForegroundRenderers.end())
{
return true;
}
}
return false;
}
/**
* Internally used to sort all registered renderers and to connect the with the vtkRenderWindow.
* Mention that VTK Version 5 and above is rendering higher numbers in the background and VTK
* Verison < 5 in the foreground.
*/
void mitk::VtkLayerController::UpdateLayers()
{
// Remove all Renderers from renderwindow
vtkSmartPointer<vtkRendererCollection> v = m_RenderWindow->GetRenderers();
v->RemoveAllItems();
auto numberOfLayers =
static_cast<unsigned int>(m_BackgroundRenderers.size() + m_SceneRenderers.size() + m_ForegroundRenderers.size());
int currentLayerNumber;
bool traverseUpwards;
currentLayerNumber = 0;
traverseUpwards = true;
m_RenderWindow->SetNumberOfLayers(numberOfLayers);
RendererVectorType::iterator it;
// assign a layer number for the backround renderers
for (it = m_BackgroundRenderers.begin(); it != m_BackgroundRenderers.end(); ++it)
{
(*it)->SetRenderWindow(m_RenderWindow);
(*it)->SetLayer(currentLayerNumber);
m_RenderWindow->AddRenderer((*it));
if (traverseUpwards)
currentLayerNumber++;
else
currentLayerNumber--;
}
// assign a layer number for the scene renderers
for (it = m_SceneRenderers.begin(); it != m_SceneRenderers.end(); ++it)
{
(*it)->SetRenderWindow(m_RenderWindow);
(*it)->SetLayer(currentLayerNumber);
m_RenderWindow->AddRenderer((*it));
if (traverseUpwards)
currentLayerNumber++;
else
currentLayerNumber--;
}
// assign a layer number for the foreground renderers
for (it = m_ForegroundRenderers.begin(); it != m_ForegroundRenderers.end(); ++it)
{
(*it)->SetRenderWindow(m_RenderWindow);
(*it)->SetLayer(currentLayerNumber);
m_RenderWindow->AddRenderer((*it));
if (traverseUpwards)
currentLayerNumber++;
else
currentLayerNumber--;
}
}
/**
* Returns the number of renderers in the renderwindow.
*/
unsigned int mitk::VtkLayerController::GetNumberOfRenderers()
{
return static_cast<unsigned int>(m_BackgroundRenderers.size() + m_SceneRenderers.size() +
m_ForegroundRenderers.size());
}
void mitk::VtkLayerController::SetEraseForAllRenderers(int i)
{
this->m_RenderWindow->SetErase(i);
RendererVectorType::iterator it;
for (it = m_BackgroundRenderers.begin(); it != m_BackgroundRenderers.end(); ++it)
(*it)->SetErase(i);
for (it = m_SceneRenderers.begin(); it != m_SceneRenderers.end(); ++it)
(*it)->SetErase(i);
for (it = m_ForegroundRenderers.begin(); it != m_ForegroundRenderers.end(); ++it)
(*it)->SetErase(i);
}
| 29.709581
| 117
| 0.695354
|
zhaomengxiao
|
c0bb66c2a0e4b93c897664e3a62284459aeac8ee
| 3,683
|
cpp
|
C++
|
libraries/animation/src/AnimStateMachine.cpp
|
stojce/hifi
|
8e6c860a243131859c0706424097db56e6a604bd
|
[
"Apache-2.0"
] | null | null | null |
libraries/animation/src/AnimStateMachine.cpp
|
stojce/hifi
|
8e6c860a243131859c0706424097db56e6a604bd
|
[
"Apache-2.0"
] | null | null | null |
libraries/animation/src/AnimStateMachine.cpp
|
stojce/hifi
|
8e6c860a243131859c0706424097db56e6a604bd
|
[
"Apache-2.0"
] | null | null | null |
//
// AnimStateMachine.cpp
//
// Created by Anthony J. Thibault on 9/2/15.
// Copyright (c) 2015 High Fidelity, Inc. All rights reserved.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "AnimStateMachine.h"
#include "AnimUtil.h"
#include "AnimationLogging.h"
AnimStateMachine::AnimStateMachine(const QString& id) :
AnimNode(AnimNode::Type::StateMachine, id) {
}
AnimStateMachine::~AnimStateMachine() {
}
const AnimPoseVec& AnimStateMachine::evaluate(const AnimVariantMap& animVars, float dt, Triggers& triggersOut) {
QString desiredStateID = animVars.lookup(_currentStateVar, _currentState->getID());
if (_currentState->getID() != desiredStateID) {
// switch states
bool foundState = false;
for (auto& state : _states) {
if (state->getID() == desiredStateID) {
switchState(animVars, state);
foundState = true;
break;
}
}
if (!foundState) {
qCCritical(animation) << "AnimStateMachine could not find state =" << desiredStateID << ", referenced by _currentStateVar =" << _currentStateVar;
}
}
// evaluate currentState transitions
auto desiredState = evaluateTransitions(animVars);
if (desiredState != _currentState) {
switchState(animVars, desiredState);
}
assert(_currentState);
auto currentStateNode = _currentState->getNode();
assert(currentStateNode);
if (_duringInterp) {
_alpha += _alphaVel * dt;
if (_alpha < 1.0f) {
if (_poses.size() > 0 && _nextPoses.size() > 0 && _prevPoses.size() > 0) {
::blend(_poses.size(), &_prevPoses[0], &_nextPoses[0], _alpha, &_poses[0]);
}
} else {
_duringInterp = false;
_prevPoses.clear();
_nextPoses.clear();
}
}
if (!_duringInterp) {
_poses = currentStateNode->evaluate(animVars, dt, triggersOut);
}
return _poses;
}
void AnimStateMachine::setCurrentState(State::Pointer state) {
_currentState = state;
}
void AnimStateMachine::addState(State::Pointer state) {
_states.push_back(state);
}
void AnimStateMachine::switchState(const AnimVariantMap& animVars, State::Pointer desiredState) {
const float FRAMES_PER_SECOND = 30.0f;
auto prevStateNode = _currentState->getNode();
auto nextStateNode = desiredState->getNode();
_duringInterp = true;
_alpha = 0.0f;
float duration = std::max(0.001f, animVars.lookup(desiredState->_interpDurationVar, desiredState->_interpDuration));
_alphaVel = FRAMES_PER_SECOND / duration;
_prevPoses = _poses;
nextStateNode->setCurrentFrame(desiredState->_interpTarget);
// because dt is 0, we should not encounter any triggers
const float dt = 0.0f;
Triggers triggers;
_nextPoses = nextStateNode->evaluate(animVars, dt, triggers);
#if WANT_DEBUG
qCDebug(animation) << "AnimStateMachine::switchState:" << _currentState->getID() << "->" << desiredState->getID() << "duration =" << duration << "targetFrame =" << desiredState->_interpTarget;
#endif
_currentState = desiredState;
}
AnimStateMachine::State::Pointer AnimStateMachine::evaluateTransitions(const AnimVariantMap& animVars) const {
assert(_currentState);
for (auto& transition : _currentState->_transitions) {
if (animVars.lookup(transition._var, false)) {
return transition._state;
}
}
return _currentState;
}
const AnimPoseVec& AnimStateMachine::getPosesInternal() const {
return _poses;
}
| 32.026087
| 196
| 0.661146
|
stojce
|
c0bf83e3248888e2752193872664437f5be09efd
| 156
|
cc
|
C++
|
cmake/code_tests/rt_test.cc
|
liubangchen/seastar
|
5bf108406ae79a5f30383bf8e498dd9d4b51d1a5
|
[
"Apache-2.0"
] | 6,526
|
2015-09-22T16:47:59.000Z
|
2022-03-31T07:31:07.000Z
|
cmake/code_tests/rt_test.cc
|
liubangchen/seastar
|
5bf108406ae79a5f30383bf8e498dd9d4b51d1a5
|
[
"Apache-2.0"
] | 925
|
2015-09-23T13:52:53.000Z
|
2022-03-31T21:33:25.000Z
|
cmake/code_tests/rt_test.cc
|
liubangchen/seastar
|
5bf108406ae79a5f30383bf8e498dd9d4b51d1a5
|
[
"Apache-2.0"
] | 1,473
|
2015-09-22T23:19:04.000Z
|
2022-03-31T21:09:00.000Z
|
extern "C" {
#include <signal.h>
#include <time.h>
}
int main() {
timer_t td;
struct sigevent sev;
timer_create(CLOCK_MONOTONIC, &sev, &td);
}
| 14.181818
| 45
| 0.628205
|
liubangchen
|
c0c2e51ef67a2a61b1673bba69cb9de169a89972
| 1,089
|
hpp
|
C++
|
libs/core/include/fcppt/type_traits/is_value.hpp
|
pmiddend/fcppt
|
9f437acbb10258e6df6982a550213a05815eb2be
|
[
"BSL-1.0"
] | null | null | null |
libs/core/include/fcppt/type_traits/is_value.hpp
|
pmiddend/fcppt
|
9f437acbb10258e6df6982a550213a05815eb2be
|
[
"BSL-1.0"
] | null | null | null |
libs/core/include/fcppt/type_traits/is_value.hpp
|
pmiddend/fcppt
|
9f437acbb10258e6df6982a550213a05815eb2be
|
[
"BSL-1.0"
] | null | null | null |
// Copyright Carl Philipp Reh 2009 - 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)
#ifndef FCPPT_TYPE_TRAITS_IS_VALUE_HPP_INCLUDED
#define FCPPT_TYPE_TRAITS_IS_VALUE_HPP_INCLUDED
#include <fcppt/config/external_begin.hpp>
#include <type_traits>
#include <fcppt/config/external_end.hpp>
namespace fcppt
{
namespace type_traits
{
/**
\brief Checks if the type behaves like a value type.
\ingroup fcppttypetraits
A type is a <em>value type</em> if it is not cv-qualified, it is not void, not
an array, not a function and not a reference. In essence, value types behave
normally regarding copying, moving and assignment.
*/
template<
typename Type
>
using is_value
=
std::integral_constant<
bool,
!std::is_void<
Type
>::value
&&
!std::is_array<
Type
>::value
&&
!std::is_function<
Type
>::value
&&
!std::is_reference<
Type
>::value
&&
!std::is_const<
Type
>::value
&&
!std::is_volatile<
Type
>::value
>;
}
}
#endif
| 16.753846
| 78
| 0.707989
|
pmiddend
|
c0c6351340585eb3f4d5f036d9ee6128112a4c4d
| 4,167
|
cpp
|
C++
|
src/http/File.cpp
|
amoscykl98/Catrine
|
300b3bcf33cedd73b634526a581a3fb82e4dd71e
|
[
"MIT"
] | 4
|
2019-03-22T23:26:49.000Z
|
2020-10-14T11:53:26.000Z
|
src/http/File.cpp
|
amoscykl98/Catrine
|
300b3bcf33cedd73b634526a581a3fb82e4dd71e
|
[
"MIT"
] | null | null | null |
src/http/File.cpp
|
amoscykl98/Catrine
|
300b3bcf33cedd73b634526a581a3fb82e4dd71e
|
[
"MIT"
] | null | null | null |
/*************************************************************************
> File Name: File.cpp
> Author: amoscykl
> Mail: amoscykl@163.com
************************************************************************/
#include "File.h"
#include "Util.h"
#include "Iobuffer.h"
#include <sys/mman.h>
#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>
#include <fstream>
// 静态成员变量初始化
std::unordered_map<std::string, std::string> File::mime_ = {
{"default", "text/plain"},
{"html", "text/html"},
{"htm", "text/html"},
{"css", "text/css"},
{"js", "text/javascript"},
{"txt", "text/plain"},
{"csv", "text/csv"},
{"jpeg", "image/jpeg"},
{"jpg", "image/jpeg"},
{"png", "image/png"},
{"gif", "image/gif"},
{"bmp", "image/bmp"},
{"ico", "image/x_icon"},
{"mp3", "audio/mp3"},
{"avi", "video/x-msvideo"},
{"json", "application/json"},
{"doc", "application/msword"},
{"doc", "application/msword"},
{"ppt", "application/vnd.ms-powerpoint"},
{"pdf", "application/pdf"},
{"gz", "application/x-gzip"},
{"tar", "application/x-tar"}
};
File::File(std::string path) :
path_(path)
{
// 将路径后多余的斜杠去掉
if (path_[path_.size() - 1] == '/')
path_.pop_back();
exist_ = (stat(path_.c_str(), &file_stat_) == 0);
}
bool File::Exist()
{
return exist_;
}
bool File::IsFile()
{
if (!exist_)
return false;
return S_ISREG(file_stat_.st_mode);
}
bool File::IsDir()
{
if (!exist_)
return false;
return S_ISDIR(file_stat_.st_mode);
}
bool File::IsLink()
{
if (!exist_)
return false;
return S_ISLNK(file_stat_.st_mode);
}
Timestamp File::GetCreateTime()
{
if (!exist_)
return system_clock::now();
return Util::TimespecToTimestamp(file_stat_.st_ctim);
}
Timestamp File::GetModifyTime()
{
if (!exist_)
return system_clock::now();
return Util::TimespecToTimestamp(file_stat_.st_mtim);
}
std::string File::GetName()
{
std::string absolute_path = path_;
// 取路径最后一个斜杠后的内容
return absolute_path.erase(0, absolute_path.find_last_of("/") + 1);
}
std::string File::GetExt()
{
std::string name = GetName();
int p = name.find_last_of('.');
// 没有拓展名或者为空直接返回“”
if(p == -1 || p == (int)name.length() - 1)
return "";
else
{
std::string ext = name.substr(p + 1);
Util::ToLower(ext);
return ext;
}
}
std::string File::GetMimeType()
{
if (mime_.find(GetExt()) == mime_.end())
{
return mime_["default"];
}
return mime_[GetExt()];
}
off_t File::GetSize()
{
if(!exist_)
return 0;
return file_stat_.st_size;
}
std::string File::ReadAsText()
{
std::ifstream in(path_, std::ios_base::in);
if(!in)
return "";
// 将文件每一行内容读取出来添加到string中
std::string content = "";
std::string line;
while(!in.eof())
{
getline(in, line);
content += line;
content += '\n';
}
content.erase(content.end()-1);
return content;
}
std::vector<File> File::ListDir()
{
std::string absolute_path = path_;
DIR *ptr_dir;
struct dirent *dir_entry;
ptr_dir = opendir(absolute_path.c_str());
std::vector<File> files;
while((dir_entry = readdir(ptr_dir)) != NULL){
// 忽略"." & ".."
if(strcmp(dir_entry->d_name, ".") == 0 || strcmp(dir_entry->d_name, "..") == 0 )
continue;
// 创建文件或子目录的file类
files.push_back(File(absolute_path+"/"+dir_entry->d_name));
}
closedir(ptr_dir);
return files;
}
void File::ReadToBuffer(IOBuffer& buffer)
{
// 打开文件描述符
int src_fd = open(path_.c_str(), O_RDONLY, 0);
if (src_fd < 0)
{
close(src_fd);
return;
}
// 映射文件到内存中
void *mmap_ret = mmap(NULL, file_stat_.st_size, PROT_READ, MAP_PRIVATE, src_fd, 0);
close(src_fd);
if (mmap_ret == (void*)-1)
{
munmap(mmap_ret, file_stat_.st_size);
return;
}
// 读取文件
char *src_addr = static_cast<char*>(mmap_ret);
buffer.Append(src_addr, file_stat_.st_size);
// 取消映射
munmap(mmap_ret, file_stat_.st_size);
return;
}
| 21.152284
| 88
| 0.551956
|
amoscykl98
|
c0c6fdce0e03179fef9911f56f741873be3dff85
| 15,491
|
cpp
|
C++
|
src/lexer/handlers.cpp
|
Zoxc/mirb
|
14c2fe2d2a026fb3bb62c883e8839e1078ebc3b6
|
[
"BSD-3-Clause"
] | 10
|
2016-10-06T06:22:20.000Z
|
2022-02-28T05:33:09.000Z
|
src/lexer/handlers.cpp
|
Zoxc/mirb
|
14c2fe2d2a026fb3bb62c883e8839e1078ebc3b6
|
[
"BSD-3-Clause"
] | null | null | null |
src/lexer/handlers.cpp
|
Zoxc/mirb
|
14c2fe2d2a026fb3bb62c883e8839e1078ebc3b6
|
[
"BSD-3-Clause"
] | 3
|
2018-01-08T03:34:34.000Z
|
2021-09-12T12:12:22.000Z
|
#include "lexer.hpp"
#include "../symbol-pool.hpp"
#include "../parser/parser.hpp"
#include "../tree/nodes.hpp"
namespace Mirb
{
bool Lexer::is_white()
{
return (input.in(1, 9) || input.in(11, 12) || input.in(14, 32));
}
void Lexer::white()
{
input++;
while(is_white())
input++;
restep(true);
}
bool Lexer::whitespace_after()
{
return input.in(1, 32);
}
void Lexer::unknown()
{
input++;
while(jump_table[input] == &Lexer::unknown)
input++;
lexeme.stop = &input;
lexeme.type = Lexeme::NONE;
if (lexeme.length() == 1)
report(lexeme, "Invalid character '" + lexeme.string() + "'");
else
report(lexeme, "Invalid characters '" + lexeme.string() + "'");
restep();
}
void Lexer::skip_line()
{
input++;
if(input == '\n')
{
newline();
return restep();
}
else if(input == '\r')
{
carrige_return();
return restep();
}
input--;
unknown();
}
void Lexer::expand_to_unary()
{
if(input == '@')
{
input++;
lexeme.stop = &input;
lexeme.type = Lexeme::operator_to_unary(lexeme.type);
}
}
void Lexer::parse_delimited_data(Lexeme::Type type)
{
InterpolateState state;
state.type = type;
state.opener = input;
state.terminator = delimiter_mapping.try_get(input, [&]{
return input;
});
if(input != '\0' || !process_null(&input, true))
input++;
parse_interpolate(&state, false);
}
void Lexer::left_shift_to_heredoc()
{
auto heredoc = new (memory_pool) Heredoc;
heredoc->scope = parser.scope;
if(input == '-')
{
input++;
heredoc->remove_ident = true;
}
else
heredoc->remove_ident = false;
CharArray name;
if(is_ident(input))
{
heredoc->type = 0;
while(is_ident(input))
{
name += input;
input++;
}
}
else
{
auto get_name = [&]() {
heredoc->type = input++;
if(input == heredoc->type)
{
input++;
const char_t *start = lexeme.start;
lexeme.start = &input - 2;
lexeme.stop = &input;
report(lexeme, "Expected heredoc delimiter");
lexeme.start = start;
return;
}
while(input != heredoc->type)
{
if(input == 0 && process_null(&input))
return;
if(input == '\n' || input == '\r')
{
lexeme.stop = &input;
report(lexeme, "Unterminated heredoc delimiter");
return;
}
name += input++;
}
input++;
};
switch(input)
{
case '`':
case '"':
case '\'':
get_name();
break;
default:
lexeme.stop = &input;
report(lexeme, "Expected heredoc delimiter");
return;
}
}
heredoc->name.set<MemoryPool>(name, memory_pool);
heredocs.push(heredoc);
heredoc->node = new (Tree::Fragment(*heredoc->scope->fragment)) Tree::HeredocNode;
lexeme.stop = &input;
heredoc->range = lexeme;
lexeme.type = Lexeme::HEREDOC;
lexeme.heredoc = heredoc->node;
}
void Lexer::mod_to_literal()
{
input.set(lexeme.start + 1);
switch(input)
{
case 'r':
input++;
return parse_delimited_data(Lexeme::REGEXP);
case 's':
input++;
return parse_delimited_data(Lexeme::SYMBOL);
case 'x':
input++;
return parse_delimited_data(Lexeme::COMMAND);
case 'Q':
input++;
return parse_delimited_data(Lexeme::STRING);
case 'q':
{
input++;
char_t opener = input;
char_t terminator = delimiter_mapping.try_get(input, [&]{
return input;
});
input++;
return parse_simple_string(opener, terminator, opener != terminator);
}
case 'w':
{
input++;
char_t opener = input;
char_t terminator = delimiter_mapping.try_get(input, [&]{
return input;
});
if(input == 0 && process_null(&input))
return;
input++;
CharArray result;
size_t nested = 0;
while(input != terminator || nested > 0)
{
if(opener != terminator)
{
if(input == opener)
nested++;
else if(input == terminator)
nested--;
}
switch(input)
{
case '\n':
result += input++;
process_newline(false, false);
break;
case '\r':
result += input++;
if(input == '\n')
result += input++;
process_newline(false, false);
break;
case 0:
if(process_null(&input))
{
lexeme.stop = &input;
report(lexeme, "Unterminated array literal");
goto exit_array_literal;
return;
}
// Fallthrough
default:
result += input++;
}
}
input++;
exit_array_literal:
lexeme.stop = &input;
lexeme.data = new (memory_pool) InterpolateData(memory_pool);
lexeme.data->tail.set<MemoryPool>(result, memory_pool);
lexeme.type = Lexeme::ARRAY;
return;
}
case 'W':
input++;
return parse_delimited_data(Lexeme::ARRAY);
default:
break;
}
if(is_alpha(input))
return;
return parse_delimited_data(Lexeme::STRING);
}
void Lexer::regexp_options()
{
while(is_char(input))
{
switch(input)
{
case 'i':
case 'm':
case 'u':
case 's':
case 'n':
case 'o':
case 'e':
case 'x':
break;
default:
report(range(&input, &input + 1), "Unknown regular expression option '" + CharArray(&input, 1) + "'");
}
input++;
}
}
void Lexer::div_to_regexp()
{
input.set(lexeme.start + 1);
InterpolateState state;
state.type = Lexeme::REGEXP;
state.terminator = state.opener = '/';
parse_interpolate(&state, false);
}
void Lexer::question_to_character()
{
CharArray result;
if(input == '\\')
{
input++;
bool dummy;
if(!parse_escape(result, true, false, dummy))
{
if(input == 0 && process_null(&input))
{
lexeme.stop = &input;
lexeme.data = new (memory_pool) InterpolateData(memory_pool);
lexeme.type = Lexeme::STRING;
report(lexeme, "Expected escape string");
return;
}
}
else
goto result;
}
else if(input == 0)
{
if(process_null(&input))
{
lexeme.stop = &input;
lexeme.data = new (memory_pool) InterpolateData(memory_pool);
lexeme.type = Lexeme::STRING;
report(lexeme, "Expected escape string");
return;
}
}
result = input++;
result:
lexeme.data = new (memory_pool) InterpolateData(memory_pool);
lexeme.data->tail.set<MemoryPool>(result, memory_pool);
lexeme.stop = &input;
lexeme.type = Lexeme::STRING;
}
bool Lexer::process_null(const char_t *input, bool expected)
{
bool result = (size_t)(input - input_str) >= length;
if(!result && !expected)
report_null();
return result;
}
void Lexer::null()
{
if(process_null(&input, true))
{
lexeme.stop = &input;
lexeme.type = Lexeme::END;
}
else
unknown();
}
void Lexer::parse_interpolate_heredoc(Heredoc *heredoc)
{
InterpolateState state;
state.type = heredoc->type == '`' ? Lexeme::COMMAND : Lexeme::STRING;
state.heredoc = heredoc;
parse_interpolate(&state, false);
heredoc->node->data = parser.parse_data(Lexeme::STRING);
}
bool Lexer::heredoc_terminates(Heredoc *heredoc)
{
const char_t *start = &input;
size_t line = lexeme.current_line;
const char_t *line_start = lexeme.current_line_start;
if(input == '\n')
{
input++;
line++;
line_start = &input;
}
else if(input == '\r')
{
input++;
line++;
if(input == '\n')
input++;
line_start = &input;
}
if(heredoc->remove_ident)
while(is_white())
input++;
const char_t *str = &input;
while(input != '\n' && input != '\r' && (input != 0 || !process_null(&input)))
input++;
if((size_t)&input - (size_t)str != heredoc->name.length)
{
input.set(start);
return false;
}
if(std::memcmp(str, heredoc->name.data, heredoc->name.length) == 0)
{
lexeme.current_line = line;
lexeme.current_line_start = line_start;
return true;
}
input.set(start);
return false;
}
void Lexer::process_comment()
{
if((std::strncmp((const char *)&input, "=begin", 6) == 0) && !is_ident((&input)[6]))
{
auto terminate = [&]() -> bool {
if((std::strncmp((const char *)&input, "=end", 4) == 0) && !is_ident((&input)[4]))
{
input.set(&input + 4);
return true;
}
else
return false;
};
while(true)
{
switch(input)
{
case '\r':
{
if(input == '\n')
input++;
lexeme.current_line++;
lexeme.current_line_start = &input;
if(terminate())
goto exit_comment;
break;
}
case '\n':
{
input++;
lexeme.current_line++;
lexeme.current_line_start = &input;
if(terminate())
goto exit_comment;
break;
}
case 0:
if(process_null(&input))
{
lexeme.stop = &input;
report(lexeme, "Unterminated multi-line comment");
goto exit_comment;
}
break;
default:
input++;
break;
}
}
exit_comment:;
}
}
void Lexer::process_newline(bool no_heredoc, bool allow_comment)
{
lexeme.current_line++;
lexeme.current_line_start = &input;
if(heredocs.size() && !no_heredoc)
{
Heredoc *heredoc = heredocs.pop();
Lexeme old = lexeme;
lexeme.start = &input;
lexeme.line = lexeme.current_line;
lexeme.line_start = lexeme.current_line_start;
parser.enter_scope(heredoc->scope, [&] {
parse_interpolate_heredoc(heredoc);
});
old.current_line = lexeme.current_line;
old.current_line_start = lexeme.current_line_start;
lexeme = old;
if(input == '\n')
newline();
else if(input == '\r')
carrige_return();
}
if(allow_comment)
process_comment();
}
void Lexer::newline()
{
input++;
lexeme.type = Lexeme::LINE;
process_newline(false, true);
lexeme.start = &input;
lexeme.stop = &input;
}
void Lexer::carrige_return()
{
input++;
lexeme.type = Lexeme::LINE;
if(input == '\n')
input++;
process_newline(false, true);
lexeme.start = &input;
lexeme.stop = &input;
}
void Lexer::eol()
{
while(input != '\n' && input != '\r' && input != 0)
input++;
}
void Lexer::curly_open()
{
input++;
lexeme.curlies.push(nullptr);
lexeme.stop = &input;
lexeme.type = Lexeme::CURLY_OPEN;
}
void Lexer::exclamation()
{
input++;
switch(input)
{
case '=':
{
input++;
lexeme.type = Lexeme::NO_EQUALITY;
break;
}
case '~':
{
input++;
lexeme.type = Lexeme::NOT_MATCHES;
break;
}
default:
{
lexeme.type = Lexeme::LOGICAL_NOT;
break;
}
}
lexeme.stop = &input;
}
void Lexer::colon()
{
input++;
if(input == ':')
{
input++;
lexeme.type = Lexeme::SCOPE;
}
else
lexeme.type = Lexeme::COLON;
lexeme.stop = &input;
}
void Lexer::assign_equal()
{
input++;
switch(input)
{
case '=':
{
input++;
if(input == '=')
{
input++;
lexeme.type = Lexeme::CASE_EQUALITY;
}
else
lexeme.type = Lexeme::EQUALITY;
break;
}
case '>':
{
input++;
lexeme.type = Lexeme::ASSOC;
break;
}
case '~':
{
input++;
lexeme.type = Lexeme::MATCHES;
break;
}
default:
{
lexeme.type = Lexeme::ASSIGN;
break;
}
}
lexeme.stop = &input;
}
void Lexer::compare()
{
input++;
switch(input)
{
case '<':
input++;
if(input == '=')
{
input++;
lexeme.stop = &input;
lexeme.type = Lexeme::ASSIGN_LEFT_SHIFT;
}
else
{
lexeme.stop = &input;
lexeme.type = Lexeme::LEFT_SHIFT;
}
break;
case '=':
input++;
if(input == '>')
{
input++;
lexeme.stop = &input;
lexeme.type = Lexeme::COMPARE;
}
else
{
lexeme.stop = &input;
lexeme.type = Lexeme::LESS_OR_EQUAL;
}
break;
default:
lexeme.stop = &input;
lexeme.type = Lexeme::LESS;
}
}
void Lexer::comment()
{
eol();
restep();
}
bool Lexer::is_char(char_t c)
{
return Input::char_in(c, 'a', 'z') || Input::char_in(c, 'A', 'Z');
}
bool Lexer::is_alpha(char_t c)
{
return is_char(c) || Input::char_in(c, '0', '9');
}
bool Lexer::is_start_ident(char_t c)
{
return is_char(c) || c == '_';
}
bool Lexer::is_ident(char_t c)
{
return is_start_ident(c) || Input::char_in(c, '0', '9');
}
void Lexer::skip_ident()
{
while(is_ident(input))
input++;
}
void Lexer::ivar()
{
input++;
if(is_ident(input))
{
bool error = !is_start_ident(input);
input++;
skip_ident();
lexeme.stop = &input;
lexeme.type = Lexeme::IVAR;
lexeme.symbol = symbol_pool.get(lexeme);
if(error)
report(lexeme, "Instance variable names cannot start with a number");
}
else if(input == '@')
{
input++;
if(is_ident(input))
{
bool error = !is_start_ident(input);
input++;
skip_ident();
lexeme.stop = &input;
lexeme.type = Lexeme::CVAR;
lexeme.symbol = symbol_pool.get(lexeme);
if(error)
report(lexeme, "Class variable names cannot start with a number");
}
else
{
lexeme.stop = &input;
lexeme.type = Lexeme::CVAR;
lexeme.symbol = symbol_pool.get(lexeme);
report(lexeme, "Expected a class variable name");
}
}
else
{
lexeme.stop = &input;
lexeme.type = Lexeme::IVAR;
lexeme.symbol = symbol_pool.get(lexeme);
report(lexeme, "Expected a instance variable name");
}
}
void Lexer::global()
{
input++;
if(!is_ident(input))
{
switch(input)
{
case '-':
{
input++;
if(is_ident(input))
input++;
lexeme.stop = &input;
lexeme.type = Lexeme::GLOBAL;
lexeme.symbol = symbol_pool.get(lexeme);
break;
};
case ':':
case '>':
case '<':
case '\\':
case '/':
case '@':
case '$':
case '`':
case '&':
case '_':
case '+':
case '.':
case ',':
case '~':
case ';':
case '"':
case '\'':
case '*':
case '?':
case '!':
input++;
lexeme.stop = &input;
lexeme.type = Lexeme::GLOBAL;
lexeme.symbol = symbol_pool.get(lexeme);
break;
default:
lexeme.stop = &input;
lexeme.type = Lexeme::GLOBAL;
lexeme.symbol = symbol_pool.get(lexeme);
report(lexeme, "Expected a global variable name");
break;
}
return;
}
skip_ident();
lexeme.stop = &input;
lexeme.type = Lexeme::GLOBAL;
lexeme.symbol = symbol_pool.get(lexeme);
}
void Lexer::sub()
{
input++;
switch(input)
{
case '=':
{
input++;
lexeme.type = Lexeme::ASSIGN_SUB;
break;
}
case '>':
{
input++;
lexeme.type = Lexeme::BLOCK_POINT;
break;
}
default:
lexeme.type = Lexeme::SUB;
}
lexeme.stop = &input;
}
void Lexer::ident()
{
input++;
skip_ident();
switch(input)
{
case '?':
case '!':
{
input++;
lexeme.type = Lexeme::EXT_IDENT;
break;
}
default:
{
lexeme.type = Lexeme::IDENT;
break;
}
}
lexeme.stop = &input;
lexeme.symbol = symbol_pool.get(lexeme);
if(lexeme.allow_keywords)
{
Lexeme::Type keyword = keywords.mapping.try_get(lexeme.symbol, [] { return Lexeme::NONE; });
if(keyword != Lexeme::NONE)
lexeme.type = keyword;
}
}
};
| 16.05285
| 107
| 0.556646
|
Zoxc
|
c0c89e38a9d4bd865f6e0071a68f7328077bd4d3
| 633
|
cpp
|
C++
|
src/Distance.cpp
|
SeanStarkey/map-utilities
|
bb3b29722c24a784d3f3ad34947042fb7449a1f0
|
[
"Apache-2.0"
] | 1
|
2015-06-03T21:59:01.000Z
|
2015-06-03T21:59:01.000Z
|
src/Distance.cpp
|
SeanStarkey/map-utilities
|
bb3b29722c24a784d3f3ad34947042fb7449a1f0
|
[
"Apache-2.0"
] | null | null | null |
src/Distance.cpp
|
SeanStarkey/map-utilities
|
bb3b29722c24a784d3f3ad34947042fb7449a1f0
|
[
"Apache-2.0"
] | null | null | null |
#include "Distance.h"
#include <math.h>
#include <iostream>
#include "Constants.h"
double distance(const Location* c1, const Location* c2)
{
double dLat = toRadians(c1->getLatitude() - c2->getLatitude());
double dLon = toRadians(c1->getLongitude() - c2->getLongitude());
double lat1 = toRadians(c1->getLatitude());
double lat2 = toRadians(c2->getLatitude());
double halfdLatSin = sin(dLat/2.0);
double halfdLonSin = sin(dLon/2.0);
double a = halfdLatSin * halfdLatSin +
halfdLonSin * halfdLonSin * cos(lat1) * cos(lat2);
double c = 2*atan2(sqrt(a), sqrt(1-a));
return RADIUSEARTH*c;
}
| 28.772727
| 69
| 0.661927
|
SeanStarkey
|
c0d3b7e4daae0a18dda73585d91461202d75845e
| 6,336
|
hpp
|
C++
|
include/Bit/Graphics/TextureProperties.hpp
|
jimmiebergmann/Bit-Engine
|
39324a9e7fb5ab4b1cf3738f871470e0a9ef7575
|
[
"Zlib"
] | null | null | null |
include/Bit/Graphics/TextureProperties.hpp
|
jimmiebergmann/Bit-Engine
|
39324a9e7fb5ab4b1cf3738f871470e0a9ef7575
|
[
"Zlib"
] | null | null | null |
include/Bit/Graphics/TextureProperties.hpp
|
jimmiebergmann/Bit-Engine
|
39324a9e7fb5ab4b1cf3738f871470e0a9ef7575
|
[
"Zlib"
] | null | null | null |
// ///////////////////////////////////////////////////////////////////////////
// Copyright (C) 2013 Jimmie Bergmann - jimmiebergmann@gmail.com
//
// 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 BIT_GRAPHICS_TEXTURE_PROPERTIES_HPP
#define BIT_GRAPHICS_TEXTURE_PROPERTIES_HPP
#include <Bit/Build.hpp>
#include <Bit/NonCopyable.hpp>
namespace Bit
{
////////////////////////////////////////////////////////////////
/// \ingroup Graphics
/// \brief Texture properties class.
///
/// Flag bits:
/// - 0x01 Magnification filter.
/// - 0x02 Minification filter.
/// - 0x04 Wrapping X.
/// - 0x08 Wrapping Y.
/// - 0x10 Anisotrpical level.
///
////////////////////////////////////////////////////////////////
class BIT_API TextureProperties : public NonCopyable
{
public:
////////////////////////////////////////////////////////////////
/// \brief Filter enumerator
///
/// Do not use mipmap filters for magnification.
///
////////////////////////////////////////////////////////////////
enum eFilter
{
Nearest, ///< Nearest neighbor blending.
NearestMipmapNearest, ///< Not linear within mip-level.
NearestMipmapLinear, ///< Same as previous, but linear between mip-levels.
Linear, ///< Linear blend between texels.
LinearMipmapNearest, ///< Linear within mip-level.
LinearMipmapLinear ///< Same as previous, but linear between mip-levels.
};
////////////////////////////////////////////////////////////////
/// \brief Wrapping enumerator
///
////////////////////////////////////////////////////////////////
enum eWarpping
{
Repeat,
Clamp
};
////////////////////////////////////////////////////////////////
/// \brief Default constructor.
///
////////////////////////////////////////////////////////////////
TextureProperties( );
////////////////////////////////////////////////////////////////
/// \brief Set magnification filter
///
////////////////////////////////////////////////////////////////
void SetMagnificationFilter( const eFilter p_Filter );
////////////////////////////////////////////////////////////////
/// \brief Set minification filter
///
////////////////////////////////////////////////////////////////
void SetMinificationFilter( const eFilter p_Filter );
////////////////////////////////////////////////////////////////
/// \brief Set wrapping for
///
////////////////////////////////////////////////////////////////
void SetWrapping( const eWarpping p_WrapX, const eWarpping p_WrapY );
////////////////////////////////////////////////////////////////
/// \brief Set wrapping for X axis.
///
////////////////////////////////////////////////////////////////
void SetWrappingX( const eWarpping p_WrapX );
////////////////////////////////////////////////////////////////
/// \brief Set wrapping for Y axis.
///
////////////////////////////////////////////////////////////////
void SetWrappingY( const eWarpping p_WrapY );
////////////////////////////////////////////////////////////////
/// \brief Set mipmapping status.
///
////////////////////////////////////////////////////////////////
void SetMipmapping( Bool p_Status );
////////////////////////////////////////////////////////////////
/// \brief Set anisotropic level.
///
////////////////////////////////////////////////////////////////
void SetAnisotropic( const Uint32 p_Level );
////////////////////////////////////////////////////////////////
/// \brief Set update flags. For advanced users only.
///
////////////////////////////////////////////////////////////////
void SetFlags( const Uint8 p_Flags );
////////////////////////////////////////////////////////////////
/// \brief Get magnification filter
///
////////////////////////////////////////////////////////////////
eFilter GetMagnificationFilter( ) const;
////////////////////////////////////////////////////////////////
/// \brief Get minification filter
///
////////////////////////////////////////////////////////////////
eFilter GetMinificationFilter( ) const;
////////////////////////////////////////////////////////////////
/// \brief Get wrapping for X axis.
///
////////////////////////////////////////////////////////////////
eWarpping GetWrappingX( ) const;
////////////////////////////////////////////////////////////////
/// \brief Get wrapping for Y axis.
///
////////////////////////////////////////////////////////////////
eWarpping GetWrappingY( ) const;
////////////////////////////////////////////////////////////////
/// \brief Get mipmapping status.
///
////////////////////////////////////////////////////////////////
Bool GetMipmapping( ) const;
////////////////////////////////////////////////////////////////
/// \brief Get anisotropic level.
///
////////////////////////////////////////////////////////////////
Uint32 GetAnisotropic( ) const;
////////////////////////////////////////////////////////////////
/// \brief Get update flags. For advanced users only.
///
////////////////////////////////////////////////////////////////
Uint8 GetFlags( ) const;
private:
eFilter m_MagnificationFilter;
eFilter m_MinificationFilter;
eWarpping m_WrappingX;
eWarpping m_WrappingY;
Bool m_Mipmapping;
Uint32 m_AnisotropicLevel;
Uint8 m_Flags; ///< Update flag.
};
}
#endif
| 33.882353
| 78
| 0.395991
|
jimmiebergmann
|
c0d7f59b8f82d16052ae48c3a72b1ac5ff05af37
| 209
|
cpp
|
C++
|
extras/general_pipelines/py2_10_20_20/py2_10_20_20.cpp
|
nvpro-samples/vk_compute_mipmaps
|
613b94e4d36e6f357472e9c7a3163046deb55678
|
[
"Apache-2.0"
] | 12
|
2021-07-24T18:33:22.000Z
|
2022-03-12T16:20:49.000Z
|
extras/general_pipelines/py2_10_20_20/py2_10_20_20.cpp
|
nvpro-samples/vk_compute_mipmaps
|
613b94e4d36e6f357472e9c7a3163046deb55678
|
[
"Apache-2.0"
] | null | null | null |
extras/general_pipelines/py2_10_20_20/py2_10_20_20.cpp
|
nvpro-samples/vk_compute_mipmaps
|
613b94e4d36e6f357472e9c7a3163046deb55678
|
[
"Apache-2.0"
] | 3
|
2021-08-04T02:27:12.000Z
|
2022-03-13T08:43:24.000Z
|
#include "nvpro_pyramid_dispatch_alternative.hpp"
#include "../py2_dispatch_impl.hpp"
NVPRO_PYRAMID_ADD_GENERAL_DISPATCHER(py2_10_20_20,
(py2_dispatch_impl<10, 20, 20>))
| 29.857143
| 69
| 0.679426
|
nvpro-samples
|
c0d80a3d569a6a3522b2ebc38a601525ece54649
| 518
|
hpp
|
C++
|
src/Tools/Display/Dumper/Dumper_reduction.hpp
|
codechecker123/aff3ct
|
030af3e990027fa803fb2c68f974c9ec0ee79b5d
|
[
"MIT"
] | null | null | null |
src/Tools/Display/Dumper/Dumper_reduction.hpp
|
codechecker123/aff3ct
|
030af3e990027fa803fb2c68f974c9ec0ee79b5d
|
[
"MIT"
] | null | null | null |
src/Tools/Display/Dumper/Dumper_reduction.hpp
|
codechecker123/aff3ct
|
030af3e990027fa803fb2c68f974c9ec0ee79b5d
|
[
"MIT"
] | null | null | null |
#ifndef DUMPER_REDUCTION_HPP_
#define DUMPER_REDUCTION_HPP_
#include "Dumper.hpp"
namespace aff3ct
{
namespace tools
{
class Dumper_reduction : Dumper
{
protected:
std::vector<Dumper*> dumpers;
public:
explicit Dumper_reduction(std::vector<Dumper*> &dumpers);
virtual ~Dumper_reduction();
virtual void dump (const std::string& base_path);
virtual void add (const int frame_id = 0 );
virtual void clear( );
private:
void checks();
};
}
}
#endif /* DUMPER_REDUCTION_HPP_ */
| 17.266667
| 58
| 0.694981
|
codechecker123
|
c0d97772a1c1e4eaf6658cb081639fc2fea493a0
| 10,506
|
cpp
|
C++
|
src/maxon_epos_ethercat_sdk/Configuration.cpp
|
zoenglinghou/maxon_epos_ethercat_sdk
|
4127085e33dfdbe08061b30941eaac4f5a5e0686
|
[
"BSD-3-Clause"
] | 5
|
2021-04-06T13:42:34.000Z
|
2022-02-22T08:37:20.000Z
|
src/maxon_epos_ethercat_sdk/Configuration.cpp
|
zoenglinghou/maxon_epos_ethercat_sdk
|
4127085e33dfdbe08061b30941eaac4f5a5e0686
|
[
"BSD-3-Clause"
] | 2
|
2021-04-29T15:42:38.000Z
|
2022-02-23T15:07:31.000Z
|
src/maxon_epos_ethercat_sdk/Configuration.cpp
|
zoenglinghou/maxon_epos_ethercat_sdk
|
4127085e33dfdbe08061b30941eaac4f5a5e0686
|
[
"BSD-3-Clause"
] | 5
|
2021-04-28T15:06:15.000Z
|
2022-02-23T09:09:55.000Z
|
// clang-format off
/*
** Copyright 2021 Robotic Systems Lab - ETH Zurich:
** Linghao Zhang, Jonas Junger, Lennart Nachtigall
**
** 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.
*/
// clang-format on
#include "maxon_epos_ethercat_sdk/Configuration.hpp"
#include <iomanip>
#include <vector>
#include <map>
#include <algorithm>
#include <utility>
namespace maxon {
std::string modeOfOperationString(ModeOfOperationEnum modeOfOperation_) {
switch (modeOfOperation_) {
case ModeOfOperationEnum::ProfiledPositionMode:
return "Profiled Position Mode";
case ModeOfOperationEnum::ProfiledVelocityMode:
return "Profiled Velocity Mode";
case ModeOfOperationEnum::HomingMode:
return "Homing Mode";
case ModeOfOperationEnum::CyclicSynchronousPositionMode:
return "Cyclic Synchronous Position Mode";
case ModeOfOperationEnum::CyclicSynchronousVelocityMode:
return "Cyclic Synchronous Velocity Mode";
case ModeOfOperationEnum::CyclicSynchronousTorqueMode:
return "Cyclic Synchronous Torque Mode";
default:
return "Unsupported Mode of Operation";
}
}
std::string rxPdoString(RxPdoTypeEnum rxPdo) {
switch (rxPdo) {
case RxPdoTypeEnum::NA:
return "NA";
case RxPdoTypeEnum::RxPdoStandard:
return "Rx PDO Standard";
case RxPdoTypeEnum::RxPdoCSP:
return "Rx PDO CSP";
case RxPdoTypeEnum::RxPdoCST:
return "Rx PDO CST";
case RxPdoTypeEnum::RxPdoCSV:
return "Rx PDO CSV";
case RxPdoTypeEnum::RxPdoCSTCSP:
return "Rx PDO CST/CSP mixed mode";
case RxPdoTypeEnum::RxPdoCSTCSPCSV:
return "Rx PDO CST/CSP/CSV mixed mode";
case RxPdoTypeEnum::RxPdoPVM:
return "Rx PDO PVM";
default:
return "Unsupported Type";
}
}
std::string txPdoString(TxPdoTypeEnum txPdo) {
switch (txPdo) {
case TxPdoTypeEnum::NA:
return "NA";
case TxPdoTypeEnum::TxPdoCSP:
return "Tx PDO CSP";
case TxPdoTypeEnum::TxPdoCST:
return "Tx PDO CST";
case TxPdoTypeEnum::TxPdoCSV:
return "Tx PDO CSV";
case TxPdoTypeEnum::TxPdoCSTCSP:
return "Tx PDO CST/CSP mixed mode";
case TxPdoTypeEnum::TxPdoCSTCSPCSV:
return "Rx PDO CST/CSP/CSV mixed mode";
case TxPdoTypeEnum::TxPdoPVM:
return "Tx PDO PVM";
case TxPdoTypeEnum::TxPdoStandard:
return "Tx PDO Standard";
default:
return "Unsupported Type";
}
}
std::ostream& operator<<(std::ostream& os, const Configuration& configuration) {
std::string modeOfOperation_ =
modeOfOperationString(configuration.modesOfOperation[0]);
unsigned int tmp3 = modeOfOperation_.size();
unsigned int len2 = tmp3;
len2++;
os << std::boolalpha << std::left << std::setw(43) << std::setfill('-') << "|"
<< std::setw(len2 + 2) << "-"
<< "|\n"
<< std::setfill(' ') << std::setw(43 + len2 + 2) << "| Configuration"
<< "|\n"
<< std::setw(43) << std::setfill('-') << "|" << std::setw(len2 + 2) << "+"
<< "|\n"
<< std::setfill(' ') << std::setw(43) << "| 1st Mode of Operation:"
<< "| " << std::setw(len2) << modeOfOperation_ << "|\n"
<< std::setw(43) << "| Config Run SDO verify timeout:"
<< "| " << std::setw(len2) << configuration.configRunSdoVerifyTimeout
<< "|\n"
<< std::setw(43) << "| Print Debug Messages:"
<< "| " << std::setw(len2) << configuration.printDebugMessages << "|\n"
<< std::setw(43) << "| Drive State Change Min Timeout:"
<< "| " << std::setw(len2) << configuration.driveStateChangeMinTimeout
<< "|\n"
<< std::setw(43) << "| Drive State Change Max Timeout:"
<< "| " << std::setw(len2) << configuration.driveStateChangeMaxTimeout
<< "|\n"
<< std::setw(43) << "| Min Successful Target State Readings:"
<< "| " << std::setw(len2)
<< configuration.minNumberOfSuccessfulTargetStateReadings << "|\n"
<< std::setw(43) << "| Force Append Equal Error:"
<< "| " << std::setw(len2) << configuration.forceAppendEqualError << "|\n"
<< std::setw(43) << "| Force Append Equal Fault:"
<< "| " << std::setw(len2) << configuration.forceAppendEqualFault << "|\n"
<< std::setw(43) << "| Error Storage Capacity"
<< "| " << std::setw(len2) << configuration.errorStorageCapacity << "|\n"
<< std::setw(43) << "| Fault Storage Capacity"
<< "| " << std::setw(len2) << configuration.faultStorageCapacity << "|\n"
<< std::setw(43) << std::setfill('-') << "|" << std::setw(len2 + 2) << "+"
<< "|\n"
<< std::setfill(' ') << std::noboolalpha << std::right;
return os;
}
std::pair<RxPdoTypeEnum, TxPdoTypeEnum> Configuration::getPdoTypeSolution()
const {
// clang-format off
// {ModeOfOperationEnum1, ..., ModeOfOperationEnumN} -> {RxPdoTypeEnum, TxPdoTypeEnum}
const std::map<std::vector<ModeOfOperationEnum>, std::pair<RxPdoTypeEnum, TxPdoTypeEnum>> modes2PdoTypeMap = {
{
{ ModeOfOperationEnum::CyclicSynchronousTorqueMode, ModeOfOperationEnum::CyclicSynchronousPositionMode },
{ RxPdoTypeEnum::RxPdoCSTCSP, TxPdoTypeEnum::TxPdoCSTCSP }
},
{
{ ModeOfOperationEnum::CyclicSynchronousTorqueMode, ModeOfOperationEnum::CyclicSynchronousPositionMode,
ModeOfOperationEnum::CyclicSynchronousVelocityMode },
{ RxPdoTypeEnum::RxPdoCSTCSPCSV, TxPdoTypeEnum::TxPdoCSTCSPCSV }
},
{
{ ModeOfOperationEnum::CyclicSynchronousPositionMode },
{ RxPdoTypeEnum::RxPdoCSP, TxPdoTypeEnum::TxPdoCSP }
},
{
{ ModeOfOperationEnum::CyclicSynchronousTorqueMode },
{ RxPdoTypeEnum::RxPdoCST, TxPdoTypeEnum::TxPdoCST }
},
{
{ ModeOfOperationEnum::CyclicSynchronousVelocityMode },
{ RxPdoTypeEnum::RxPdoCSV, TxPdoTypeEnum::TxPdoCSV }
},
{
{ ModeOfOperationEnum::HomingMode },
{ RxPdoTypeEnum::NA, TxPdoTypeEnum::NA }
},
{
{ ModeOfOperationEnum::ProfiledPositionMode },
{ RxPdoTypeEnum::NA, TxPdoTypeEnum::NA }
},
{
{ ModeOfOperationEnum::ProfiledVelocityMode },
{ RxPdoTypeEnum::RxPdoPVM, TxPdoTypeEnum::TxPdoPVM }
},
{
{ ModeOfOperationEnum::NA },
{ RxPdoTypeEnum::NA, TxPdoTypeEnum::NA }
},
};
// clang-format on
bool setsAreEqual;
for (const auto& modes2PdoTypeEntry : modes2PdoTypeMap) {
setsAreEqual = true;
for (const auto& modeOfOperation : modesOfOperation)
setsAreEqual &=
std::find(modes2PdoTypeEntry.first.begin(),
modes2PdoTypeEntry.first.end(),
modeOfOperation) != modes2PdoTypeEntry.first.end();
for (const auto& modeOfOperation : modes2PdoTypeEntry.first)
setsAreEqual &=
std::find(modesOfOperation.begin(), modesOfOperation.end(),
modeOfOperation) != modesOfOperation.end();
if (setsAreEqual) return modes2PdoTypeEntry.second;
}
return std::pair<RxPdoTypeEnum, TxPdoTypeEnum>{RxPdoTypeEnum::NA,
TxPdoTypeEnum::NA};
}
bool Configuration::sanityCheck(bool silent) const {
bool success = true;
std::string message = "";
auto check_and_inform = [&message,
&success](std::pair<bool, std::string> test) {
if (test.first) {
message += "\033[32m✓\t";
message += test.second;
message += "\033[m\n";
success &= true;
} else {
message += "\033[31m✕\t";
message += test.second;
message += "\033[m\n";
success = false;
}
};
auto pdoTypePair = getPdoTypeSolution();
// clang-format off
const std::vector<std::pair<bool, std::string>> sanity_tests = {
{
(polePairs > 0),
"pole_pairs > 0"
},
{
(motorConstant > 0),
"motor_constant > 0"
},
{
(nominalCurrentA > 0),
"nominal_current > 0"
},
{
(maxCurrentA > 0),
"max_current > 0"
},
{
(torqueConstantNmA > 0),
"torque_constant > 0"
},
{
(maxProfileVelocity > 0),
"max_profile_velocity > 0"
},
{
(quickStopDecel > 0),
"quick_stop_decel > 0"
},
{
(profileDecel > 0),
"profile_decel > 0"
},
{
(profileDecel > 0),
"profile_decel > 0"
},
{
(positionEncoderResolution > 0),
"position_encoder_resolution > 0"
},
{
(gearRatio > 0),
"gear_ratio > 0"
},
{
(pdoTypePair.first != RxPdoTypeEnum::NA && pdoTypePair.second != TxPdoTypeEnum::NA),
"modes of operation combination allowed"
},
{
(driveStateChangeMinTimeout <= driveStateChangeMaxTimeout),
"drive_state_change_min_timeout ≤ drive_state_change_max_timeout"
},
};
// clang-format on
std::for_each(sanity_tests.begin(), sanity_tests.end(), check_and_inform);
if (!silent) {
std::cout << message << std::endl;
}
return success;
}
} // namespace maxon
| 35.137124
| 113
| 0.63202
|
zoenglinghou
|
c0db91560356c7a14f2665a38bc5f060cfdfe65c
| 389
|
cpp
|
C++
|
test_Graph/main.cpp
|
Dieupix/Graph
|
c57f17808e274f3c0f9d2829ecf58daec8983fd6
|
[
"MIT"
] | 4
|
2021-11-30T18:21:06.000Z
|
2022-01-05T19:01:57.000Z
|
test_Graph/main.cpp
|
Dieupix/Graph
|
c57f17808e274f3c0f9d2829ecf58daec8983fd6
|
[
"MIT"
] | null | null | null |
test_Graph/main.cpp
|
Dieupix/Graph
|
c57f17808e274f3c0f9d2829ecf58daec8983fd6
|
[
"MIT"
] | null | null | null |
#define DOCTEST_CONFIG_IMPLEMENT
#include "doctest.h"
int main() {
doctest::Context context;
context.setOption("order-by", "name"); // sort the test cases by their name
//context.setOption("duration", true); // print the duration of each test case
//context.setOption("success", true); // print all tests
return context.run(); // run
}
| 29.923077
| 85
| 0.627249
|
Dieupix
|
c0de1d6831a09889f4f65cf431903ff4700f369f
| 28,755
|
cpp
|
C++
|
tests/unit/utils/test_mem.cpp
|
bruingineer/sACN-1
|
aef4a38f025f3800248ac24e377485dba27ed16f
|
[
"Apache-2.0"
] | null | null | null |
tests/unit/utils/test_mem.cpp
|
bruingineer/sACN-1
|
aef4a38f025f3800248ac24e377485dba27ed16f
|
[
"Apache-2.0"
] | null | null | null |
tests/unit/utils/test_mem.cpp
|
bruingineer/sACN-1
|
aef4a38f025f3800248ac24e377485dba27ed16f
|
[
"Apache-2.0"
] | null | null | null |
/******************************************************************************
* Copyright 2021 ETC Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************
* This file is a part of sACN. For more information, go to:
* https://github.com/ETCLabs/sACN
*****************************************************************************/
#include "sacn/private/mem.h"
#include <string>
#include "etcpal/cpp/uuid.h"
#include "etcpal_mock/common.h"
#include "sacn/private/common.h"
#include "sacn/private/opts.h"
#include "sacn_mock/private/common.h"
#include "gtest/gtest.h"
#include "fff.h"
#if SACN_DYNAMIC_MEM
#define TestMem TestMemDynamic
#else
#define TestMem TestMemStatic
#endif
static constexpr sacn_merge_receiver_t kTestMergeReceiverHandle = 1;
static constexpr SacnMergeReceiverConfig kTestMergeReceiverConfig = {
1u,
{[](sacn_merge_receiver_t, uint16_t, const uint8_t*, const sacn_remote_source_t*, void*) {},
[](sacn_merge_receiver_t, uint16_t, const EtcPalSockAddr*, const SacnHeaderData*, const uint8_t*, void*) {}, NULL,
NULL},
SACN_RECEIVER_INFINITE_SOURCES,
true,
kSacnIpV4AndIpV6};
class TestMem : public ::testing::Test
{
protected:
static constexpr unsigned int kTestNumThreads = 1; // TODO: Set back to 4 if/when SACN_RECEIVER_MAX_THREADS increases
static constexpr intptr_t kMagicPointerValue = 0xdeadbeef;
void SetUp() override
{
etcpal_reset_all_fakes();
sacn_common_reset_all_fakes();
ASSERT_EQ(sacn_mem_init(kTestNumThreads), kEtcPalErrOk);
}
void TearDown() override { sacn_mem_deinit(); }
void DoForEachThread(std::function<void(sacn_thread_id_t)>&& fn)
{
for (sacn_thread_id_t thread = 0; thread < kTestNumThreads; ++thread)
{
SCOPED_TRACE("While testing thread ID " + std::to_string(thread));
fn(thread);
}
}
};
TEST_F(TestMem, GetNumThreadsWorks)
{
EXPECT_EQ(sacn_mem_get_num_threads(), kTestNumThreads);
}
TEST_F(TestMem, ValidInitializedStatusLists)
{
DoForEachThread([](sacn_thread_id_t thread) {
SacnSourceStatusLists* status_lists = get_status_lists(thread);
ASSERT_NE(status_lists, nullptr);
EXPECT_EQ(status_lists->num_online, 0u);
EXPECT_EQ(status_lists->num_offline, 0u);
EXPECT_EQ(status_lists->num_unknown, 0u);
});
}
TEST_F(TestMem, StatusListsAreReZeroedWithEachGet)
{
SacnSourceStatusLists* status_lists = get_status_lists(0);
ASSERT_NE(status_lists, nullptr);
// Modify some elements
status_lists->num_online = 20;
status_lists->num_offline = 40;
status_lists->num_unknown = 60;
// Now get again and make sure they are re-zeroed
status_lists = get_status_lists(0);
ASSERT_NE(status_lists, nullptr);
EXPECT_EQ(status_lists->num_online, 0u);
EXPECT_EQ(status_lists->num_offline, 0u);
EXPECT_EQ(status_lists->num_unknown, 0u);
}
TEST_F(TestMem, StatusListsAddOfflineWorks)
{
DoForEachThread([](sacn_thread_id_t thread) {
SacnSourceStatusLists* status_lists = get_status_lists(thread);
ASSERT_NE(status_lists, nullptr);
sacn_remote_source_t handle_to_add = 0u;
#if SACN_DYNAMIC_MEM
// Just test some arbitrary number
for (size_t i = 0; i < 20; ++i)
{
std::string test_name = "test name " + std::to_string(i);
ASSERT_TRUE(add_offline_source(status_lists, handle_to_add, test_name.c_str(), true));
EXPECT_EQ(status_lists->num_offline, i + 1);
EXPECT_EQ(status_lists->offline[i].handle, handle_to_add);
EXPECT_STREQ(status_lists->offline[i].name, test_name.c_str());
EXPECT_EQ(status_lists->offline[i].terminated, true);
++handle_to_add;
}
#else
// Test up to the maximum capacity
for (size_t i = 0; i < SACN_RECEIVER_MAX_SOURCES_PER_UNIVERSE; ++i)
{
std::string test_name = "test name " + std::to_string(i);
ASSERT_TRUE(add_offline_source(status_lists, handle_to_add, test_name.c_str(), true));
EXPECT_EQ(status_lists->num_offline, i + 1);
EXPECT_EQ(status_lists->offline[i].handle, handle_to_add);
EXPECT_STREQ(status_lists->offline[i].name, test_name.c_str());
EXPECT_EQ(status_lists->offline[i].terminated, true);
++handle_to_add;
}
// And make sure we can't add another
EXPECT_FALSE(add_offline_source(status_lists, handle_to_add, "test name", true));
#endif
});
}
TEST_F(TestMem, StatusListsAddOnlineWorks)
{
DoForEachThread([](sacn_thread_id_t thread) {
SacnSourceStatusLists* status_lists = get_status_lists(thread);
ASSERT_NE(status_lists, nullptr);
sacn_remote_source_t handle_to_add = 0u;
#if SACN_DYNAMIC_MEM
// Just test some arbitrary number
for (size_t i = 0; i < 20; ++i)
{
std::string test_name = "test name " + std::to_string(i);
ASSERT_TRUE(add_online_source(status_lists, handle_to_add, test_name.c_str()));
EXPECT_EQ(status_lists->num_online, i + 1);
EXPECT_EQ(status_lists->online[i].handle, handle_to_add);
EXPECT_STREQ(status_lists->online[i].name, test_name.c_str());
++handle_to_add;
}
#else
// Test up to the maximum capacity
for (size_t i = 0; i < SACN_RECEIVER_MAX_SOURCES_PER_UNIVERSE; ++i)
{
std::string test_name = "test name " + std::to_string(i);
ASSERT_TRUE(add_online_source(status_lists, handle_to_add, test_name.c_str()));
EXPECT_EQ(status_lists->num_online, i + 1);
EXPECT_EQ(status_lists->online[i].handle, handle_to_add);
EXPECT_STREQ(status_lists->online[i].name, test_name.c_str());
++handle_to_add;
}
// And make sure we can't add another
EXPECT_FALSE(add_online_source(status_lists, handle_to_add, "test name"));
#endif
});
}
TEST_F(TestMem, StatusListsAddUnknownWorks)
{
DoForEachThread([](sacn_thread_id_t thread) {
SacnSourceStatusLists* status_lists = get_status_lists(thread);
ASSERT_NE(status_lists, nullptr);
sacn_remote_source_t handle_to_add = 0u;
#if SACN_DYNAMIC_MEM
// Just test some arbitrary number
for (size_t i = 0; i < 20; ++i)
{
std::string test_name = "test name " + std::to_string(i);
ASSERT_TRUE(add_unknown_source(status_lists, handle_to_add, test_name.c_str()));
EXPECT_EQ(status_lists->num_unknown, i + 1);
EXPECT_EQ(status_lists->unknown[i].handle, handle_to_add);
EXPECT_STREQ(status_lists->unknown[i].name, test_name.c_str());
++handle_to_add;
}
#else
// Test up to the maximum capacity
for (size_t i = 0; i < SACN_RECEIVER_MAX_SOURCES_PER_UNIVERSE; ++i)
{
std::string test_name = "test name " + std::to_string(i);
ASSERT_TRUE(add_unknown_source(status_lists, handle_to_add, test_name.c_str()));
EXPECT_EQ(status_lists->num_unknown, i + 1);
EXPECT_EQ(status_lists->unknown[i].handle, handle_to_add);
EXPECT_STREQ(status_lists->unknown[i].name, test_name.c_str());
++handle_to_add;
}
// And make sure we can't add another
EXPECT_FALSE(add_unknown_source(status_lists, handle_to_add, "test name"));
#endif
});
}
TEST_F(TestMem, ValidInitializedToEraseBuffer)
{
DoForEachThread([](sacn_thread_id_t thread) {
#if SACN_DYNAMIC_MEM
// Just test some arbitrary number for the buffer size
SacnTrackedSource** to_erase_buf = get_to_erase_buffer(thread, 20);
ASSERT_NE(to_erase_buf, nullptr);
for (size_t i = 0; i < 20; ++i)
EXPECT_EQ(to_erase_buf[i], nullptr);
#else
// Just test some arbitrary number for the buffer size
SacnTrackedSource** to_erase_buf = get_to_erase_buffer(thread, SACN_RECEIVER_MAX_SOURCES_PER_UNIVERSE);
ASSERT_NE(to_erase_buf, nullptr);
for (size_t i = 0; i < SACN_RECEIVER_MAX_SOURCES_PER_UNIVERSE; ++i)
EXPECT_EQ(to_erase_buf[i], nullptr);
// Trying to get more than the max capacity should not work
to_erase_buf = get_to_erase_buffer(thread, SACN_RECEIVER_MAX_SOURCES_PER_UNIVERSE + 1);
EXPECT_EQ(to_erase_buf, nullptr);
#endif
});
}
TEST_F(TestMem, ToEraseIsReZeroedWithEachGet)
{
SacnTrackedSource** to_erase = get_to_erase_buffer(0, 1);
ASSERT_NE(to_erase, nullptr);
// Modify some elements
to_erase[0] = reinterpret_cast<SacnTrackedSource*>(kMagicPointerValue);
// Now get again and make sure they are re-zeroed
to_erase = get_to_erase_buffer(0, 1);
ASSERT_NE(to_erase, nullptr);
EXPECT_EQ(to_erase[0], nullptr);
}
TEST_F(TestMem, ValidInitializedRecvThreadContext)
{
DoForEachThread([](sacn_thread_id_t thread) {
SacnRecvThreadContext* recv_thread_context = get_recv_thread_context(thread);
ASSERT_NE(recv_thread_context, nullptr);
EXPECT_EQ(recv_thread_context->thread_id, thread);
EXPECT_EQ(recv_thread_context->receivers, nullptr);
EXPECT_EQ(recv_thread_context->num_receivers, 0u);
#if SACN_DYNAMIC_MEM
EXPECT_NE(recv_thread_context->dead_sockets, nullptr);
EXPECT_NE(recv_thread_context->socket_refs, nullptr);
#endif
EXPECT_EQ(recv_thread_context->num_dead_sockets, 0u);
EXPECT_EQ(recv_thread_context->num_socket_refs, 0u);
EXPECT_EQ(recv_thread_context->new_socket_refs, 0u);
});
}
TEST_F(TestMem, AddDeadSocketWorks)
{
DoForEachThread([](sacn_thread_id_t thread) {
SacnRecvThreadContext* recv_thread_context = get_recv_thread_context(thread);
ASSERT_NE(recv_thread_context, nullptr);
#if SACN_DYNAMIC_MEM
// Just test some arbitrary number
for (size_t i = 0; i < 20; ++i)
{
ASSERT_TRUE(add_dead_socket(recv_thread_context, (etcpal_socket_t)i));
EXPECT_EQ(recv_thread_context->num_dead_sockets, i + 1);
EXPECT_EQ(recv_thread_context->dead_sockets[i], (etcpal_socket_t)i);
}
#else
// Test up to the maximum capacity
for (size_t i = 0; i < SACN_RECEIVER_MAX_UNIVERSES * 2; ++i)
{
ASSERT_TRUE(add_dead_socket(recv_thread_context, (etcpal_socket_t)i));
EXPECT_EQ(recv_thread_context->num_dead_sockets, i + 1);
EXPECT_EQ(recv_thread_context->dead_sockets[i], (etcpal_socket_t)i);
}
// And make sure we can't add another
EXPECT_FALSE(add_dead_socket(recv_thread_context, (etcpal_socket_t)SACN_RECEIVER_MAX_UNIVERSES));
#endif
});
}
TEST_F(TestMem, AddSocketRefWorks)
{
DoForEachThread([](sacn_thread_id_t thread) {
SacnRecvThreadContext* recv_thread_context = get_recv_thread_context(thread);
ASSERT_NE(recv_thread_context, nullptr);
#if SACN_DYNAMIC_MEM
// Just test some arbitrary number
for (size_t i = 0; i < 20; ++i)
{
ASSERT_TRUE(add_socket_ref(recv_thread_context, (etcpal_socket_t)i, kEtcPalIpTypeInvalid, false));
EXPECT_EQ(recv_thread_context->num_socket_refs, i + 1);
EXPECT_EQ(recv_thread_context->new_socket_refs, i + 1);
EXPECT_EQ(recv_thread_context->socket_refs[i].sock, (etcpal_socket_t)i);
EXPECT_EQ(recv_thread_context->socket_refs[i].refcount, 1u);
}
#else
// Test up to the maximum capacity
for (size_t i = 0; i < SACN_RECEIVER_MAX_SOCKET_REFS; ++i)
{
ASSERT_TRUE(add_socket_ref(recv_thread_context, (etcpal_socket_t)i, kEtcPalIpTypeInvalid, false));
EXPECT_EQ(recv_thread_context->num_socket_refs, i + 1);
EXPECT_EQ(recv_thread_context->new_socket_refs, i + 1);
EXPECT_EQ(recv_thread_context->socket_refs[i].sock, (etcpal_socket_t)i);
EXPECT_EQ(recv_thread_context->socket_refs[i].refcount, 1u);
}
// And make sure we can't add another
EXPECT_FALSE(add_socket_ref(recv_thread_context, (etcpal_socket_t)SACN_RECEIVER_MAX_SOCKET_REFS,
kEtcPalIpTypeInvalid, false));
#endif
});
}
TEST_F(TestMem, RemoveSocketRefWorks)
{
DoForEachThread([](sacn_thread_id_t thread) {
SacnRecvThreadContext* recv_thread_context = get_recv_thread_context(thread);
ASSERT_NE(recv_thread_context, nullptr);
recv_thread_context->socket_refs[0] = SocketRef{(etcpal_socket_t)0, 1};
recv_thread_context->socket_refs[1] = SocketRef{(etcpal_socket_t)1, 20};
recv_thread_context->socket_refs[2] = SocketRef{(etcpal_socket_t)2, 3};
recv_thread_context->num_socket_refs = 3;
recv_thread_context->new_socket_refs = 1;
// Remove a socket ref that has a refcount of 1, the other ones should be shifted
ASSERT_TRUE(remove_socket_ref(recv_thread_context, (etcpal_socket_t)0));
ASSERT_EQ(recv_thread_context->num_socket_refs, 2u);
EXPECT_EQ(recv_thread_context->new_socket_refs, 1u);
EXPECT_EQ(recv_thread_context->socket_refs[0].sock, (etcpal_socket_t)1);
EXPECT_EQ(recv_thread_context->socket_refs[0].refcount, 20u);
EXPECT_EQ(recv_thread_context->socket_refs[1].sock, (etcpal_socket_t)2);
EXPECT_EQ(recv_thread_context->socket_refs[1].refcount, 3u);
// Remove one with multiple references
for (int i = 0; i < 2; ++i)
ASSERT_FALSE(remove_socket_ref(recv_thread_context, (etcpal_socket_t)2));
EXPECT_TRUE(remove_socket_ref(recv_thread_context, (etcpal_socket_t)2));
EXPECT_EQ(recv_thread_context->num_socket_refs, 1u);
});
}
TEST_F(TestMem, ValidInitializedUniverseData)
{
DoForEachThread([](sacn_thread_id_t thread) {
UniverseDataNotification* universe_data = get_universe_data(thread);
ASSERT_NE(universe_data, nullptr);
EXPECT_EQ(universe_data->callback, nullptr);
EXPECT_EQ(universe_data->receiver_handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(universe_data->pdata, nullptr);
EXPECT_EQ(universe_data->context, nullptr);
});
}
TEST_F(TestMem, UniverseDataIsReZeroedWithEachGet)
{
UniverseDataNotification* universe_data = get_universe_data(0);
ASSERT_NE(universe_data, nullptr);
// Modify some elements
universe_data->receiver_handle = 2;
universe_data->callback = reinterpret_cast<SacnUniverseDataCallback>(kMagicPointerValue);
universe_data->context = reinterpret_cast<void*>(kMagicPointerValue);
// Now get again and make sure they are re-zeroed
universe_data = get_universe_data(0);
ASSERT_NE(universe_data, nullptr);
EXPECT_EQ(universe_data->callback, nullptr);
EXPECT_EQ(universe_data->receiver_handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(universe_data->pdata, nullptr);
EXPECT_EQ(universe_data->context, nullptr);
}
TEST_F(TestMem, ValidInitializedSourcesLostBuf)
{
DoForEachThread([](sacn_thread_id_t thread) {
#if SACN_DYNAMIC_MEM
// Just test some arbitrary number for the buffer size
SourcesLostNotification* sources_lost_buf = get_sources_lost_buffer(thread, 20);
ASSERT_NE(sources_lost_buf, nullptr);
for (int i = 0; i < 20; ++i)
{
auto sources_lost = &sources_lost_buf[i];
EXPECT_EQ(sources_lost->callback, nullptr);
EXPECT_EQ(sources_lost->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(sources_lost->num_lost_sources, 0u);
EXPECT_EQ(sources_lost->context, nullptr);
}
#else
SourcesLostNotification* sources_lost_buf = get_sources_lost_buffer(thread, SACN_RECEIVER_MAX_UNIVERSES);
ASSERT_NE(sources_lost_buf, nullptr);
// Test up to the maximum capacity
for (int i = 0; i < SACN_RECEIVER_MAX_THREADS; ++i)
{
auto sources_lost = &sources_lost_buf[i];
EXPECT_EQ(sources_lost->callback, nullptr);
EXPECT_EQ(sources_lost->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(sources_lost->num_lost_sources, 0u);
EXPECT_EQ(sources_lost->context, nullptr);
}
// Trying to get more than the max capacity should not work
sources_lost_buf = get_sources_lost_buffer(thread, SACN_RECEIVER_MAX_UNIVERSES + 1);
EXPECT_EQ(sources_lost_buf, nullptr);
#endif
});
}
TEST_F(TestMem, AddLostSourceWorks)
{
DoForEachThread([](sacn_thread_id_t thread) {
SourcesLostNotification* sources_lost = get_sources_lost_buffer(thread, 1);
ASSERT_NE(sources_lost, nullptr);
#if SACN_DYNAMIC_MEM
// Just test some arbitrary number
for (size_t i = 0; i < 20; ++i)
{
auto cid_to_add = etcpal::Uuid::V4();
std::string test_name = "test name " + std::to_string(i);
ASSERT_TRUE(
add_lost_source(sources_lost, SACN_REMOTE_SOURCE_INVALID, &cid_to_add.get(), test_name.c_str(), true));
EXPECT_EQ(sources_lost->num_lost_sources, i + 1);
EXPECT_EQ(sources_lost->lost_sources[i].cid, cid_to_add);
EXPECT_STREQ(sources_lost->lost_sources[i].name, test_name.c_str());
EXPECT_EQ(sources_lost->lost_sources[i].terminated, true);
}
#else
// Test up to the maximum capacity
for (size_t i = 0; i < SACN_RECEIVER_MAX_SOURCES_PER_UNIVERSE; ++i)
{
auto cid_to_add = etcpal::Uuid::V4();
std::string test_name = "test name " + std::to_string(i);
ASSERT_TRUE(
add_lost_source(sources_lost, SACN_REMOTE_SOURCE_INVALID, &cid_to_add.get(), test_name.c_str(), true));
EXPECT_EQ(sources_lost->num_lost_sources, i + 1);
EXPECT_EQ(sources_lost->lost_sources[i].cid, cid_to_add);
EXPECT_STREQ(sources_lost->lost_sources[i].name, test_name.c_str());
EXPECT_EQ(sources_lost->lost_sources[i].terminated, true);
}
// And make sure we can't add another
auto cid_to_add = etcpal::Uuid::V4();
EXPECT_FALSE(add_lost_source(sources_lost, SACN_REMOTE_SOURCE_INVALID, &cid_to_add.get(), "test name", true));
#endif
});
}
TEST_F(TestMem, SourcesLostIsReZeroedWithEachGet)
{
SourcesLostNotification* sources_lost = get_sources_lost_buffer(0, 1);
ASSERT_NE(sources_lost, nullptr);
// Modify some elements
sources_lost->handle = 2;
sources_lost->callback = reinterpret_cast<SacnSourcesLostCallback>(kMagicPointerValue);
sources_lost->num_lost_sources = 10;
sources_lost->context = reinterpret_cast<void*>(kMagicPointerValue);
// Now get again and make sure they are re-zeroed
sources_lost = get_sources_lost_buffer(0, 1);
ASSERT_NE(sources_lost, nullptr);
EXPECT_EQ(sources_lost->callback, nullptr);
EXPECT_EQ(sources_lost->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(sources_lost->num_lost_sources, 0u);
EXPECT_EQ(sources_lost->context, nullptr);
}
TEST_F(TestMem, ValidInitializedSourcePapLost)
{
DoForEachThread([](sacn_thread_id_t thread) {
SourcePapLostNotification* source_pap_lost = get_source_pap_lost(thread);
ASSERT_NE(source_pap_lost, nullptr);
EXPECT_EQ(source_pap_lost->callback, nullptr);
EXPECT_EQ(source_pap_lost->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(source_pap_lost->context, nullptr);
});
}
TEST_F(TestMem, SourcePapLostIsReZeroedWithEachGet)
{
SourcePapLostNotification* source_pap_lost = get_source_pap_lost(0);
ASSERT_NE(source_pap_lost, nullptr);
// Modify some elements
source_pap_lost->handle = 2;
source_pap_lost->callback = reinterpret_cast<SacnSourcePapLostCallback>(kMagicPointerValue);
source_pap_lost->context = reinterpret_cast<void*>(kMagicPointerValue);
// Now get again and make sure they are re-zeroed
source_pap_lost = get_source_pap_lost(0);
ASSERT_NE(source_pap_lost, nullptr);
EXPECT_EQ(source_pap_lost->callback, nullptr);
EXPECT_EQ(source_pap_lost->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(source_pap_lost->context, nullptr);
}
TEST_F(TestMem, ValidInitializedSamplingStartedBuf)
{
DoForEachThread([](sacn_thread_id_t thread) {
#if SACN_DYNAMIC_MEM
// Just test some arbitrary number for the buffer size
SamplingStartedNotification* sampling_started_buf = get_sampling_started_buffer(thread, 20);
ASSERT_NE(sampling_started_buf, nullptr);
for (int i = 0; i < 20; ++i)
{
auto sampling_started = &sampling_started_buf[i];
EXPECT_EQ(sampling_started->callback, nullptr);
EXPECT_EQ(sampling_started->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(sampling_started->context, nullptr);
}
#else
SamplingStartedNotification* sampling_started_buf =
get_sampling_started_buffer(thread, SACN_RECEIVER_MAX_UNIVERSES);
ASSERT_NE(sampling_started_buf, nullptr);
// Test up to the maximum capacity
for (int i = 0; i < SACN_RECEIVER_MAX_THREADS; ++i)
{
auto sampling_started = &sampling_started_buf[i];
EXPECT_EQ(sampling_started->callback, nullptr);
EXPECT_EQ(sampling_started->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(sampling_started->context, nullptr);
}
// Trying to get more than the max capacity should not work
sampling_started_buf = get_sampling_started_buffer(thread, SACN_RECEIVER_MAX_UNIVERSES + 1);
EXPECT_EQ(sampling_started_buf, nullptr);
#endif
});
}
TEST_F(TestMem, SamplingStartedIsReZeroedWithEachGet)
{
SamplingStartedNotification* sampling_started = get_sampling_started_buffer(0, 1);
ASSERT_NE(sampling_started, nullptr);
// Modify some elements
sampling_started->handle = 2;
sampling_started->callback = reinterpret_cast<SacnSamplingPeriodStartedCallback>(kMagicPointerValue);
sampling_started->context = reinterpret_cast<void*>(kMagicPointerValue);
// Now get again and make sure they are re-zeroed
sampling_started = get_sampling_started_buffer(0, 1);
ASSERT_NE(sampling_started, nullptr);
EXPECT_EQ(sampling_started->callback, nullptr);
EXPECT_EQ(sampling_started->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(sampling_started->context, nullptr);
}
TEST_F(TestMem, ValidInitializedSamplingEndedBuf)
{
DoForEachThread([](sacn_thread_id_t thread) {
#if SACN_DYNAMIC_MEM
// Just test some arbitrary number for the buffer size
SamplingEndedNotification* sampling_ended_buf = get_sampling_ended_buffer(thread, 20);
ASSERT_NE(sampling_ended_buf, nullptr);
for (int i = 0; i < 20; ++i)
{
auto sampling_ended = &sampling_ended_buf[i];
EXPECT_EQ(sampling_ended->callback, nullptr);
EXPECT_EQ(sampling_ended->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(sampling_ended->context, nullptr);
}
#else
SamplingEndedNotification* sampling_ended_buf = get_sampling_ended_buffer(thread, SACN_RECEIVER_MAX_UNIVERSES);
ASSERT_NE(sampling_ended_buf, nullptr);
// Test up to the maximum capacity
for (int i = 0; i < SACN_RECEIVER_MAX_THREADS; ++i)
{
auto sampling_ended = &sampling_ended_buf[i];
EXPECT_EQ(sampling_ended->callback, nullptr);
EXPECT_EQ(sampling_ended->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(sampling_ended->context, nullptr);
}
// Trying to get more than the max capacity should not work
sampling_ended_buf = get_sampling_ended_buffer(thread, SACN_RECEIVER_MAX_UNIVERSES + 1);
EXPECT_EQ(sampling_ended_buf, nullptr);
#endif
});
}
TEST_F(TestMem, SamplingEndedIsReZeroedWithEachGet)
{
SamplingEndedNotification* sampling_ended = get_sampling_ended_buffer(0, 1);
ASSERT_NE(sampling_ended, nullptr);
// Modify some elements
sampling_ended->handle = 2;
sampling_ended->callback = reinterpret_cast<SacnSamplingPeriodEndedCallback>(kMagicPointerValue);
sampling_ended->context = reinterpret_cast<void*>(kMagicPointerValue);
// Now get again and make sure they are re-zeroed
sampling_ended = get_sampling_ended_buffer(0, 1);
ASSERT_NE(sampling_ended, nullptr);
EXPECT_EQ(sampling_ended->callback, nullptr);
EXPECT_EQ(sampling_ended->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(sampling_ended->context, nullptr);
}
TEST_F(TestMem, ValidInitializedSourceLimitExceeded)
{
DoForEachThread([](sacn_thread_id_t thread) {
SourceLimitExceededNotification* source_limit_exceeded = get_source_limit_exceeded(thread);
ASSERT_NE(source_limit_exceeded, nullptr);
EXPECT_EQ(source_limit_exceeded->callback, nullptr);
EXPECT_EQ(source_limit_exceeded->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(source_limit_exceeded->context, nullptr);
});
}
TEST_F(TestMem, SourceLimitExceededIsReZeroedWithEachGet)
{
SourceLimitExceededNotification* source_limit_exceeded = get_source_limit_exceeded(0);
ASSERT_NE(source_limit_exceeded, nullptr);
// Modify some elements
source_limit_exceeded->handle = 2;
source_limit_exceeded->callback = reinterpret_cast<SacnSourceLimitExceededCallback>(kMagicPointerValue);
source_limit_exceeded->context = reinterpret_cast<void*>(kMagicPointerValue);
// Now get again and make sure they are re-zeroed
source_limit_exceeded = get_source_limit_exceeded(0);
ASSERT_NE(source_limit_exceeded, nullptr);
EXPECT_EQ(source_limit_exceeded->callback, nullptr);
EXPECT_EQ(source_limit_exceeded->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(source_limit_exceeded->context, nullptr);
}
TEST_F(TestMem, AddReceiverToListWorks)
{
SacnRecvThreadContext rtc{};
#if SACN_DYNAMIC_MEM
SacnReceiver receiver{};
#else
SacnReceiver receiver{{}, {}, {}, {}}; // Fixes error C3852
#endif
add_receiver_to_list(&rtc, &receiver);
ASSERT_EQ(rtc.receivers, &receiver);
EXPECT_EQ(rtc.receivers->next, nullptr);
EXPECT_EQ(rtc.num_receivers, 1u);
#if SACN_DYNAMIC_MEM
SacnReceiver receiver2{};
#else
SacnReceiver receiver2{{}, {}, {}, {}}; // Fixes error C3852
#endif
add_receiver_to_list(&rtc, &receiver2);
ASSERT_EQ(rtc.receivers, &receiver);
ASSERT_EQ(rtc.receivers->next, &receiver2);
EXPECT_EQ(rtc.receivers->next->next, nullptr);
EXPECT_EQ(rtc.num_receivers, 2u);
}
TEST_F(TestMem, RemoveReceiverFromListWorks)
{
SacnRecvThreadContext rtc{};
#if SACN_DYNAMIC_MEM
SacnReceiver receiver{};
SacnReceiver receiver2{};
SacnReceiver receiver3{};
#else
SacnReceiver receiver{{}, {}, {}, {}}; // Fixes error C3852
SacnReceiver receiver2{{}, {}, {}, {}};
SacnReceiver receiver3{{}, {}, {}, {}};
#endif
rtc.receivers = &receiver;
receiver.next = &receiver2;
receiver2.next = &receiver3;
rtc.num_receivers = 3;
// Remove from the middle
remove_receiver_from_list(&rtc, &receiver2);
ASSERT_EQ(rtc.receivers, &receiver);
ASSERT_EQ(rtc.receivers->next, &receiver3);
EXPECT_EQ(rtc.receivers->next->next, nullptr);
EXPECT_EQ(rtc.num_receivers, 2u);
EXPECT_EQ(receiver2.next, nullptr);
// Remove from the head
remove_receiver_from_list(&rtc, &receiver);
ASSERT_EQ(rtc.receivers, &receiver3);
EXPECT_EQ(rtc.receivers->next, nullptr);
EXPECT_EQ(rtc.num_receivers, 1u);
EXPECT_EQ(receiver.next, nullptr);
}
TEST_F(TestMem, AddSacnMergeReceiverWorks)
{
SacnMergeReceiver* merge_receiver = nullptr;
EXPECT_EQ(add_sacn_merge_receiver(kTestMergeReceiverHandle, &kTestMergeReceiverConfig, &merge_receiver),
kEtcPalErrOk);
ASSERT_NE(merge_receiver, nullptr);
EXPECT_EQ(merge_receiver->merge_receiver_handle, kTestMergeReceiverHandle);
EXPECT_EQ(merge_receiver->merger_handle, SACN_DMX_MERGER_INVALID);
EXPECT_EQ(merge_receiver->callbacks.universe_data, kTestMergeReceiverConfig.callbacks.universe_data);
EXPECT_EQ(merge_receiver->callbacks.universe_non_dmx, kTestMergeReceiverConfig.callbacks.universe_non_dmx);
EXPECT_EQ(merge_receiver->callbacks.source_limit_exceeded, nullptr);
}
TEST_F(TestMem, AddSacnMergeReceiverSourceWorks)
{
static constexpr size_t kNumSources = 5u;
SacnMergeReceiver* merge_receiver = nullptr;
EXPECT_EQ(add_sacn_merge_receiver(kTestMergeReceiverHandle, &kTestMergeReceiverConfig, &merge_receiver),
kEtcPalErrOk);
etcpal::Uuid last_cid;
for (size_t i = 0u; i < kNumSources; ++i)
{
EXPECT_EQ(etcpal_rbtree_size(&merge_receiver->sources), i);
last_cid = etcpal::Uuid::V4();
EXPECT_EQ(add_sacn_merge_receiver_source(merge_receiver, static_cast<sacn_remote_source_t>(i), false),
kEtcPalErrOk);
}
EXPECT_EQ(etcpal_rbtree_size(&merge_receiver->sources), kNumSources);
EXPECT_EQ(add_sacn_merge_receiver_source(merge_receiver, static_cast<sacn_remote_source_t>(kNumSources - 1u), false),
kEtcPalErrExists);
EXPECT_EQ(etcpal_rbtree_size(&merge_receiver->sources), kNumSources);
}
TEST_F(TestMem, RemoveSacnMergeReceiverSourceWorks)
{
static constexpr size_t kNumSources = 5u;
SacnMergeReceiver* merge_receiver = nullptr;
EXPECT_EQ(add_sacn_merge_receiver(kTestMergeReceiverHandle, &kTestMergeReceiverConfig, &merge_receiver),
kEtcPalErrOk);
for (size_t i = 0u; i < kNumSources; ++i)
{
EXPECT_EQ(add_sacn_merge_receiver_source(merge_receiver, static_cast<sacn_remote_source_t>(i), false),
kEtcPalErrOk);
}
for (size_t i = 0u; i < kNumSources; ++i)
{
EXPECT_EQ(etcpal_rbtree_size(&merge_receiver->sources), kNumSources - i);
remove_sacn_merge_receiver_source(merge_receiver, static_cast<sacn_remote_source_t>(i));
}
EXPECT_EQ(etcpal_rbtree_size(&merge_receiver->sources), 0u);
}
| 36.215365
| 120
| 0.738028
|
bruingineer
|
c0e29d1aa63bcd5ba3fc737bcaeac7f0ab055c62
| 5,929
|
cpp
|
C++
|
Acrylic_Backend/BackendAPIs/Plexi2DRenderer/PlexiBackend/PlexiBackend_Vulkan/vulkanMain.cpp
|
TriHardStudios/TSA-Software-2019
|
c64a1462640124f750ee1d33239f4476ace7fcb6
|
[
"Apache-2.0"
] | 2
|
2019-09-03T16:48:20.000Z
|
2019-09-03T23:00:48.000Z
|
Acrylic_Backend/BackendAPIs/Plexi2DRenderer/PlexiBackend/PlexiBackend_Vulkan/vulkanMain.cpp
|
TriHardStudios/TSA-Software-2019
|
c64a1462640124f750ee1d33239f4476ace7fcb6
|
[
"Apache-2.0"
] | 8
|
2019-11-22T21:34:15.000Z
|
2020-02-24T16:25:21.000Z
|
Acrylic_Backend/BackendAPIs/Plexi2DRenderer/PlexiBackend/PlexiBackend_Vulkan/vulkanMain.cpp
|
TriHardStudios/TSA-Software-2019
|
c64a1462640124f750ee1d33239f4476ace7fcb6
|
[
"Apache-2.0"
] | null | null | null |
//Dependencies
//#include "./../../plexi_usrStructs.hpp"
#include "../plexi_shaders.hpp"
#include "../plexi_buffer.hpp"
#include "../plexi_helper.hpp"
#include "vulkanMain.hpp"
#include "./VulkanHelpers/validationLayers.hpp"
#include "./VulkanHelpers/queueFamilies.hpp"
#include "./VulkanHelpers/swapChains.hpp"
bool Vulkan::setRequiredInformation(const PlexiGFX_RequiredInformation &requiredInformation) {
if(requiredInformation.vulkan_EXT_SIZE <= 0){
std::cerr << "ERROR: Required Extensions are missing data: Required Extension Length > 0" << std::endl;
return false;
}
requiredExtensions.reserve(requiredInformation.vulkan_EXT_SIZE);
for(size_t i = 0; i < requiredInformation.vulkan_EXT_SIZE; i++){
requiredExtensions.push_back(requiredInformation.vulkan_DEVICE_EXTENSIONS[i]);
}
this->applicationName = requiredInformation.appName.c_str();
requiredExtensionsSet = !requiredExtensions.empty();
return requiredExtensionsSet;
}
void Vulkan::setOptionInformation(const PlexiGFX_OptionalInformation &optionalInformation) {
if(optionalInformation.vulkan_EXT_SIZE < 0){
std::cerr << "ERROR: Optional Extensions are missing data: Optional Extension Length > 0" << std::endl;
}
if(optionalInformation.vulkan_VALID_LAYER_SIZE < 0){
std::cerr << "ERROR: Optional Validation Layers are missing data: Optional Validation Length > 0" << std::endl;
}
//Todo: Warning if length = 0
optionalExtensions.reserve(optionalInformation.vulkan_EXT_SIZE);
optionalValidationLayers.reserve(optionalInformation.vulkan_VALID_LAYER_SIZE);
for(size_t i = 0; i < optionalInformation.vulkan_EXT_SIZE; i++){
optionalExtensions.push_back(optionalInformation.vulkan_DEVICE_EXTENSIONS[i]);
}
for(size_t i = 0; i < optionalInformation.vulkan_VALID_LAYER_SIZE; i++){
optionalValidationLayers.push_back(optionalInformation.vulkan_VALIDATION_LAYERS[i]);
}
validationLayersEnabled = !optionalValidationLayers.empty();
}
std::vector<const char*> Vulkan::getRequiredExtensions() {
uint32_t glfwExtensionsCount = 0;
const char** glfwExtensions;
std::vector<const char*> extensions;
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionsCount);
extensions.reserve(glfwExtensionsCount);
for(size_t i = 0; i < glfwExtensionsCount; i++){
extensions.push_back(glfwExtensions[i]);
}
if(validationLayersEnabled){
extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
}
//Maybe add status message here
return extensions;
}
void Vulkan::initWindow() {
// glfwInit();
// glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
//
// //glfwWindow = glfwCreateWindow(800, 600, applicationName, glfwGetPrimaryMonitor(), nullptr);//Makes full screen w/ res 800x600
// glfwWindow = glfwCreateWindow(800, 600, applicationName, nullptr, nullptr);
//
// //glfwSetWindowUserPointer(glfwWindow, this);
//
//// glfwSetFramebufferSizeCallback(glfwWindow, frameBufferResizeCallBack);//TODO: Implement Later
}
bool Vulkan::createInstance() {
return false;
// if(!requiredExtensionsSet) {
// std::cerr << "ERROR: No Vulkan Extensions have been set: Ensure that required extensions are set in Plexi Config" << std::endl;
// return false;
// }
// auto extensions = getRequiredExtensions();
//
//
// VkApplicationInfo appInfo = {};
// appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
// appInfo.pApplicationName = applicationName;
// appInfo.applicationVersion = VK_MAKE_VERSION(0,1,0);
// appInfo.pEngineName = "No Engine";
// appInfo.engineVersion = VK_MAKE_VERSION(1,0,0);
// appInfo.apiVersion = VK_API_VERSION_1_0;
//
// VkInstanceCreateInfo instanceInfo = {};
// instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
// instanceInfo.pApplicationInfo = &appInfo;
// instanceInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
// instanceInfo.ppEnabledExtensionNames = extensions.data();
// if(validationLayersEnabled){
// instanceInfo.enabledLayerCount = static_cast<uint32_t>(optionalValidationLayers.size());
// instanceInfo.ppEnabledLayerNames = optionalValidationLayers.data();
// } else{
// instanceInfo.enabledLayerCount = 0;
// }
//
// VkResult err = vkCreateInstance(&instanceInfo, nullptr, &vulkanInstance);
//
//
// if(err != VK_SUCCESS){
// std::cerr << "ERROR: Failed to create Vulkan instance: Device or required extensions may not be supported. Check Plexi Config. VK Error Code: " << err << std::endl;
// return false;
// }
//
// return true;
}
bool Vulkan::isSupported() {
return false;
// if(!requiredExtensionsSet) {
// std::cerr << "ERROR: No Vulkan Extensions have been set: Ensure that required extensions are set in Plexi Config" << std::endl;
// return false;
// }
//
// //validation layer support - Extensions are checked in the instance
// if(validationLayersEnabled){
// if(!checkValidationLayerSupport(optionalValidationLayers)) {
// std::cerr << "WARNING: Validation Layers requested but unsupported: Verify device support and check Plexi Config" << std::endl;
// validationLayersEnabled = false;
// }
// }
//
// initWindow();
//
// return createInstance();
}
bool Vulkan::initBackend() {
return false;
}
void Vulkan::createGraphicsPipeline(const Plexi::Shaders::ShaderCreateInfo& shaderCreateInfo, const Plexi::Buffer::BufferCreateInfo& bufferCreateInfo) {
}
void Vulkan::submitScene() {
}
void Vulkan::destroyWindow() {
glfwDestroyWindow(glfwWindow);
glfwTerminate();
}
void Vulkan::cleanup() {
//clean Up all other stuff up here
vkDestroyInstance(vulkanInstance, nullptr);
destroyWindow();
}
GLFWwindow* Vulkan::getWindowRef() {
return glfwWindow;
}
| 31.876344
| 174
| 0.708889
|
TriHardStudios
|
c0e3aa189fef7d1f17301079c7f7547aed289bec
| 458
|
cpp
|
C++
|
oj/sp/ACPC10A.cpp
|
shivanib01/codes
|
f0761472a4b4bea3667c0c13b1c9bcfe5b2597a3
|
[
"MIT"
] | null | null | null |
oj/sp/ACPC10A.cpp
|
shivanib01/codes
|
f0761472a4b4bea3667c0c13b1c9bcfe5b2597a3
|
[
"MIT"
] | null | null | null |
oj/sp/ACPC10A.cpp
|
shivanib01/codes
|
f0761472a4b4bea3667c0c13b1c9bcfe5b2597a3
|
[
"MIT"
] | null | null | null |
/*
* Created by
* Shivani Bhardwaj <shivanib134@gmail.com>
*/
#include<bits/stdc++.h>
using namespace std;
int main()
{
float a1,a2,a3;
while(1){
cin>>a1>>a2>>a3;
if(a1==0 && a2==0 &&a3==0)
break;
float APExp=(a3+a1)/2;
if(a2==APExp){
cout<<"AP "<<a1+3*(a2-a1)<<"\n";
}
else{
float r=a2/a1;
cout<<"GP "<<a1*r*r*r<<"\n";
}
}
return 0;
}
| 16.962963
| 44
| 0.427948
|
shivanib01
|
c0e4eb218634e84afa44387f81e6e2b349175b78
| 317
|
hpp
|
C++
|
include/tdc/util/likely.hpp
|
herlez/tdc
|
3b85ae183c21410e65f1e739736287df46c38d1d
|
[
"MIT"
] | 1
|
2021-05-06T13:39:22.000Z
|
2021-05-06T13:39:22.000Z
|
include/tdc/util/likely.hpp
|
herlez/tdc
|
3b85ae183c21410e65f1e739736287df46c38d1d
|
[
"MIT"
] | 1
|
2020-03-07T08:05:20.000Z
|
2020-03-07T08:05:20.000Z
|
include/tdc/util/likely.hpp
|
herlez/tdc
|
3b85ae183c21410e65f1e739736287df46c38d1d
|
[
"MIT"
] | 2
|
2020-05-27T07:54:43.000Z
|
2021-11-18T13:29:14.000Z
|
#pragma once
namespace tdc {
/// \brief Shortcut for \c __builtin_expect for expressions that are likely \c true.
#define tdc_likely(x) __builtin_expect(x, 1)
/// \brief Shortcut for \c __builtin_expect for expressions that are likely \c false.
#define tdc_unlikely(x) __builtin_expect(x, 0)
} // namespace tdc
| 26.416667
| 85
| 0.747634
|
herlez
|
c0e664b82f99587986a9e57bec939117aa6be51e
| 12,806
|
cc
|
C++
|
src/tests/numerics/test_fvm_nabla_validation.cc
|
wdeconinck/atlas
|
8949d2b362b9b5431023a967bcf4ca84f6b8ce05
|
[
"Apache-2.0"
] | 3
|
2020-04-28T20:07:25.000Z
|
2020-05-01T19:07:00.000Z
|
src/tests/numerics/test_fvm_nabla_validation.cc
|
pmarguinaud/atlas
|
7e0a1251685e07a5dcccc84f4d9251d5a066e2ee
|
[
"Apache-2.0"
] | null | null | null |
src/tests/numerics/test_fvm_nabla_validation.cc
|
pmarguinaud/atlas
|
7e0a1251685e07a5dcccc84f4d9251d5a066e2ee
|
[
"Apache-2.0"
] | null | null | null |
/*
* (C) Copyright 2013 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation
* nor does it submit to any jurisdiction.
*/
#include <cmath>
#include <iomanip>
#include <iostream>
#include "eckit/config/Resource.h"
#include "atlas/array/MakeView.h"
#include "atlas/field/Field.h"
#include "atlas/field/FieldSet.h"
#include "atlas/grid/Distribution.h"
#include "atlas/grid/Grid.h"
#include "atlas/grid/Partitioner.h"
#include "atlas/mesh/Mesh.h"
#include "atlas/mesh/Nodes.h"
#include "atlas/meshgenerator.h"
#include "atlas/numerics/Nabla.h"
#include "atlas/numerics/fvm/Method.h"
#include "atlas/option.h"
#include "atlas/output/Gmsh.h"
#include "atlas/parallel/mpi/mpi.h"
#include "atlas/util/Config.h"
#include "atlas/util/Constants.h"
#include "atlas/util/CoordinateEnums.h"
#include "atlas/util/Earth.h"
#include "tests/AtlasTestEnvironment.h"
using namespace eckit;
using namespace atlas::numerics;
using namespace atlas::meshgenerator;
using namespace atlas::grid;
namespace atlas {
namespace test {
// This test relates to JIRA issues METV-2657 , MIR-459
static std::string griduid() {
//return "O80";
//return "Slat80";
return "Slat720x360";
}
static double radius() {
return util::Earth::radius();
}
static double beta_in_degrees() {
return 90.;
}
static bool output_gmsh() {
return false;
}
static bool mask_polar_values() {
return false;
}
static int metric_approach() {
// Experimental!!!
// approach = 0 ORIGINAL, DEFAULT
// metric_term cos(y) is multiplied with each wind component
// --> cell-interface: avg = 0.5*( cos(y1)*u1 + cos(y2)*u2 )
// approach = 1:
// metric_term cos(0.5*(y1+y2)) is used at cell interface
// --> cell-interface: avg = 0.5*(u1+u2)*cos(0.5*(y1+y2))
// Results seem to indicate that approach=0 is overall better, although approach=1
// seems to handle pole slightly better (error factor 2 to 4 times lower)
return 0;
}
class SolidBodyRotation {
double radius;
double beta;
double sin_beta;
double cos_beta;
public:
SolidBodyRotation( const double _radius, const double _beta ) : radius{_radius}, beta{_beta} {
sin_beta = std::sin( beta );
cos_beta = std::cos( beta );
}
void wind( const double x, const double y, double& u, double& v ) {
double cos_x = std::cos( x );
double cos_y = std::cos( y );
double sin_x = std::sin( x );
double sin_y = std::sin( y );
u = cos_y * cos_beta + cos_x * sin_y * sin_beta;
v = -sin_x * sin_beta;
}
void vordiv( const double x, const double y, double& vor, double& div ) {
double cos_x = std::cos( x );
double cos_y = std::cos( y );
double sin_x = std::sin( x );
double sin_y = std::sin( y );
// Divergence = 1./(R*cos(y)) * ( d/dx( u ) + d/dy( v * cos(y) ) )
// Vorticity = 1./(R*cos(y)) * ( d/dx( v ) - d/dy( u * cos(y) ) )
double ddx_u = -sin_x * sin_y * sin_beta;
double ddy_cosy_v = ( -sin_x * sin_beta ) * ( -sin_y );
double ddx_v = -cos_x * sin_beta;
double ddy_cosy_u = 2 * cos_y * ( -sin_y ) * cos_beta + ( -sin_y ) * cos_x * sin_y * sin_beta +
cos_y * cos_x * cos_y * sin_beta;
double metric = 1. / ( radius * cos_y );
div = metric * ( ddx_u + ddy_cosy_v );
vor = metric * ( ddx_v - ddy_cosy_u );
}
void wind_magnitude_squared( const double x, const double y, double& f ) {
double u, v;
wind( x, y, u, v );
f = u * u + v * v;
}
void wind_magnitude_squared_gradient( const double x, const double y, double& dfdx, double& dfdy ) {
double cos_x = std::cos( x );
double cos_y = std::cos( y );
double sin_x = std::sin( x );
double sin_y = std::sin( y );
double metric_y = 1. / radius;
double metric_x = metric_y / cos_y;
double u = cos_y * cos_beta + cos_x * sin_y * sin_beta;
double v = -sin_x * sin_beta;
double dudx = metric_x * ( -sin_x * sin_y * sin_beta );
double dudy = metric_y * ( -sin_y * cos_beta + cos_x * cos_y * sin_beta );
double dvdx = metric_x * ( -cos_x * sin_beta );
double dvdy = metric_y * ( 0. );
dfdx = 2 * u * dudx + 2 * v * dvdx;
dfdy = 2 * u * dudy + 2 * v * dvdy;
}
};
FieldSet analytical_fields( const fvm::Method& fvm ) {
constexpr double deg2rad = M_PI / 180.;
const double radius = fvm.radius();
auto lonlat_deg = array::make_view<double, 2>( fvm.mesh().nodes().lonlat() );
FieldSet fields;
auto add_scalar_field = [&]( const std::string& name ) {
return array::make_view<double, 1>(
fields.add( fvm.node_columns().createField<double>( option::name( name ) ) ) );
};
auto add_vector_field = [&]( const std::string& name ) {
return array::make_view<double, 2>( fields.add( fvm.node_columns().createField<double>(
option::name( name ) | option::type( "vector" ) | option::variables( 2 ) ) ) );
};
auto f = add_scalar_field( "f" );
auto uv = add_vector_field( "uv" );
auto u = add_scalar_field( "u" );
auto v = add_scalar_field( "v" );
auto grad_f = add_vector_field( "ref_grad_f" );
auto dfdx = add_scalar_field( "ref_dfdx" );
auto dfdy = add_scalar_field( "ref_dfdy" );
auto div = add_scalar_field( "ref_div" );
auto vor = add_scalar_field( "ref_vor" );
auto flow = SolidBodyRotation{radius, beta_in_degrees() * deg2rad};
auto is_ghost = array::make_view<int, 1>( fvm.mesh().nodes().ghost() );
const idx_t nnodes = fvm.mesh().nodes().size();
for ( idx_t jnode = 0; jnode < nnodes; ++jnode ) {
if ( is_ghost( jnode ) ) {
continue;
}
double x = lonlat_deg( jnode, LON ) * deg2rad;
double y = lonlat_deg( jnode, LAT ) * deg2rad;
flow.wind( x, y, u( jnode ), v( jnode ) );
flow.vordiv( x, y, vor( jnode ), div( jnode ) );
flow.wind_magnitude_squared( x, y, f( jnode ) );
flow.wind_magnitude_squared_gradient( x, y, dfdx( jnode ), dfdy( jnode ) );
uv( jnode, XX ) = u( jnode );
uv( jnode, YY ) = v( jnode );
grad_f( jnode, XX ) = dfdx( jnode );
grad_f( jnode, YY ) = dfdy( jnode );
}
fields.set_dirty();
fields.haloExchange();
return fields;
}
//-----------------------------------------------------------------------------
CASE( "test_analytical" ) {
Grid grid( griduid(), GlobalDomain( -180. ) );
Mesh mesh = MeshGenerator{"structured"}.generate( grid );
fvm::Method fvm( mesh, option::radius( radius() ) );
Nabla nabla( fvm, util::Config( "metric_approach", metric_approach() ) );
FieldSet fields = analytical_fields( fvm );
Field div = fields.add( fvm.node_columns().createField<double>( option::name( "div" ) ) );
Field vor = fields.add( fvm.node_columns().createField<double>( option::name( "vor" ) ) );
Field grad_f =
fields.add( fvm.node_columns().createField<double>( option::name( "grad_f" ) | option::variables( 2 ) ) );
Field dfdx = fields.add( fvm.node_columns().createField<double>( option::name( "dfdx" ) ) );
Field dfdy = fields.add( fvm.node_columns().createField<double>( option::name( "dfdy" ) ) );
auto split = []( const Field& vector, Field& component_x, Field& component_y ) {
auto v = array::make_view<double, 2>( vector );
auto x = array::make_view<double, 1>( component_x );
auto y = array::make_view<double, 1>( component_y );
for ( idx_t j = 0; j < v.shape( 0 ); ++j ) {
x( j ) = v( j, XX );
y( j ) = v( j, YY );
}
};
ATLAS_TRACE_SCOPE( "gradient" ) nabla.gradient( fields["f"], grad_f );
split( grad_f, dfdx, dfdy );
ATLAS_TRACE_SCOPE( "divergence" ) nabla.divergence( fields["uv"], div );
ATLAS_TRACE_SCOPE( "vorticity" ) nabla.curl( fields["uv"], vor );
auto do_mask_polar_values = [&]( Field& field, double mask ) {
using Topology = atlas::mesh::Nodes::Topology;
using Range = atlas::array::Range;
auto node_flags = array::make_view<int, 1>( fvm.node_columns().nodes().flags() );
auto is_polar = [&]( idx_t j ) {
return Topology::check( node_flags( j ), Topology::BC | Topology::NORTH ) ||
Topology::check( node_flags( j ), Topology::BC | Topology::SOUTH );
};
auto apply = [&]( array::LocalView<double, 2>&& view ) {
for ( idx_t j = 0; j < view.shape( 0 ); ++j ) {
if ( is_polar( j ) ) {
for ( idx_t v = 0; v < view.shape( 1 ); ++v ) {
view( j, v ) = mask;
}
}
}
};
if ( field.rank() == 1 ) {
apply( array::make_view<double, 1>( field ).slice( Range::all(), Range::dummy() ) );
}
else if ( field.rank() == 2 ) {
apply( array::make_view<double, 2>( field ).slice( Range::all(), Range::all() ) );
}
};
for ( auto fieldname : std::vector<std::string>{"dfdx", "dfdy", "div", "vor"} ) {
auto err_field = fields.add( fvm.node_columns().createField<double>( option::name( "err_" + fieldname ) ) );
auto err2_field = fields.add( fvm.node_columns().createField<double>( option::name( "err2_" + fieldname ) ) );
auto fld = array::make_view<double, 1>( fields[fieldname] );
auto ref = array::make_view<double, 1>( fields["ref_" + fieldname] );
auto err = array::make_view<double, 1>( fields["err_" + fieldname] );
auto err2 = array::make_view<double, 1>( fields["err2_" + fieldname] );
for ( idx_t j = 0; j < fld.shape( 0 ); ++j ) {
err( j ) = fld( j ) - ref( j );
err2( j ) = err( j ) * err( j );
}
if ( mask_polar_values() ) {
do_mask_polar_values( fields["err_" + fieldname], 0. );
do_mask_polar_values( fields["err2_" + fieldname], 0. );
}
}
fields.haloExchange();
// output to gmsh
if ( output_gmsh() ) {
output::Gmsh{"mesh_2d.msh", util::Config( "coordinates", "lonlat" )}.write( mesh );
output::Gmsh{"mesh_3d.msh", util::Config( "coordinates", "xyz" )}.write( mesh );
output::Gmsh{"fields.msh"}.write( fields );
}
auto minmax_within_error = [&]( const std::string& name, double error ) {
Field field = fields["err_" + name];
error = std::abs( error );
double min, max;
fvm.node_columns().minimum( field, min );
fvm.node_columns().maximum( field, max );
bool success = true;
if ( min < -error ) {
Log::warning() << "minumum " << min << " smaller than error " << -error << std::endl;
success = false;
}
if ( max > error ) {
Log::warning() << "maximum " << max << " greater than error " << error << std::endl;
success = false;
}
Log::info() << name << "\t: minmax error between { " << min << " , " << max << " }" << std::endl;
return success;
};
EXPECT( minmax_within_error( "dfdx", 1.e-11 ) );
EXPECT( minmax_within_error( "dfdy", 1.e-11 ) );
EXPECT( minmax_within_error( "div", 1.e-16 ) );
EXPECT( minmax_within_error( "vor", 1.5e-9 ) );
auto rms_within_error = [&]( const std::string& name, double error ) {
Field field = fields["err2_" + name];
double mean;
idx_t N;
fvm.node_columns().mean( field, mean, N );
double rms = std::sqrt( mean / double( N ) );
bool success = true;
if ( rms > error ) {
Log::warning() << "rms " << rms << " greater than error " << error << std::endl;
success = false;
}
Log::info() << name << "\t: rms error = " << rms << std::endl;
return success;
};
EXPECT( rms_within_error( "dfdx", 1.e-14 ) );
EXPECT( rms_within_error( "dfdy", 1.e-14 ) );
EXPECT( rms_within_error( "div", 5.e-20 ) );
EXPECT( rms_within_error( "vor", 5.e-13 ) );
// error for vorticity seems too high ?
}
//-----------------------------------------------------------------------------
} // namespace test
} // namespace atlas
int main( int argc, char** argv ) {
return atlas::test::run( argc, argv );
}
| 37.887574
| 118
| 0.559972
|
wdeconinck
|
c0e6c3ab3b5ff7369e7cd7df4378d65641c6d183
| 1,522
|
hpp
|
C++
|
include/xtd/wrapped_type.hpp
|
djmott/xtl
|
cadb963a3d1ad292033f08f4754c545066be75f7
|
[
"BSL-1.0"
] | 6
|
2016-06-30T11:23:33.000Z
|
2019-10-22T13:09:49.000Z
|
include/xtd/wrapped_type.hpp
|
djmott/xtl
|
cadb963a3d1ad292033f08f4754c545066be75f7
|
[
"BSL-1.0"
] | null | null | null |
include/xtd/wrapped_type.hpp
|
djmott/xtl
|
cadb963a3d1ad292033f08f4754c545066be75f7
|
[
"BSL-1.0"
] | 4
|
2016-07-24T10:38:43.000Z
|
2021-04-02T11:18:09.000Z
|
/** @file
* wraps a type in a class for compiler type deductive distinction
* @copyright David Mott (c) 2016. Distributed under the Boost Software License Version 1.0. See LICENSE.md or http://boost.org/LICENSE_1_0.txt for details.
*/
#pragma once
namespace xtd {
#define WRAPPED(_type) xtd::wrapped<_type, __COUNTER__>
template <typename _ty, size_t> class wrapped {
_ty _inner;
public:
using value_type = _ty;
template <typename ... _arg_ts> wrapped(_arg_ts...oArgs) : _inner(std::forward<_arg_ts>(oArgs)...) {}
wrapped(wrapped&& src) : _inner(std::move(src._inner)) {}
wrapped(const wrapped& src) : _inner(src._inner) {}
template <typename _ArgT> wrapped& operator=(_ArgT&& oArg) {
_inner = std::move(oArg);
return *this;
}
wrapped& operator=(wrapped&& src) {
_inner = std::move(src._inner);
return *this;
}
wrapped& operator=(const wrapped& src) {
_inner = src._inner;
return *this;
}
value_type& operator*() { return _inner; }
const value_type& operator*() const { return _inner; }
value_type* operator->() { return &_inner; }
const value_type* operator->() const { return &_inner; }
operator value_type() const { return _inner; }
operator value_type&() { return _inner; }
operator const value_type&() const { return _inner; }
value_type& operator()() { return _inner; }
const value_type& operator()() const { return _inner; }
};
}
| 29.843137
| 156
| 0.630092
|
djmott
|
c0ebf25c626bacc9378ff2cebfc441db711850ee
| 633
|
cpp
|
C++
|
arch/m68k/m68k_isa.cpp
|
ismaell/libcpu
|
3a82a1ab0b99e439e6fbcafca71e9d3d7fe06b12
|
[
"BSD-2-Clause"
] | 277
|
2015-01-04T23:33:37.000Z
|
2022-03-24T20:38:51.000Z
|
arch/m68k/m68k_isa.cpp
|
farmdve/libcpu
|
d624f5863f49b059726bce83e4da944ed4b4764c
|
[
"BSD-2-Clause"
] | 7
|
2015-02-18T12:41:18.000Z
|
2021-08-21T14:07:53.000Z
|
arch/m68k/m68k_isa.cpp
|
farmdve/libcpu
|
d624f5863f49b059726bce83e4da944ed4b4764c
|
[
"BSD-2-Clause"
] | 44
|
2015-02-03T09:08:14.000Z
|
2022-03-14T16:35:31.000Z
|
#include "m68k_isa.h"
const char sizechar[] = { '?', 'b', 'l', 'w' };
const char *condstr[] = {
/*[0]*/ "ra",
/*[1]*/ "sr", // 68030?
/*[2]*/ "hi",
/*[3]*/ "ls",
/*[4]*/ "cc",
/*[5]*/ "cs",
/*[6]*/ "ne",
/*[7]*/ "eq",
/*[8]*/ "vc",
/*[9]*/ "vs",
/*[10]*/ "pl",
/*[11]*/ "mi",
/*[12]*/ "ge",
/*[13]*/ "lt",
/*[14]*/ "gt",
/*[15]*/ "le"
};
const char *condstr_db[] = {
/*[0]*/ "t",
/*[1]*/ "f",
/*[2]*/ "hi",
/*[3]*/ "ls",
/*[4]*/ "cc",
/*[5]*/ "cs",
/*[6]*/ "ne",
/*[7]*/ "eq",
/*[8]*/ "vc",
/*[9]*/ "vs",
/*[10]*/ "pl",
/*[11]*/ "mi",
/*[12]*/ "ge",
/*[13]*/ "lt",
/*[14]*/ "gt",
/*[15]*/ "le"
};
| 14.72093
| 47
| 0.28752
|
ismaell
|
c0ecdbbab19f7b8861f0406f0fed157d4ae24848
| 2,557
|
cpp
|
C++
|
ural/1901.cpp
|
jffifa/algo-solution
|
af2400d6071ee8f777f9473d6a34698ceef08355
|
[
"MIT"
] | 5
|
2015-07-14T10:29:25.000Z
|
2016-10-11T12:45:18.000Z
|
ural/1901.cpp
|
jffifa/algo-solution
|
af2400d6071ee8f777f9473d6a34698ceef08355
|
[
"MIT"
] | null | null | null |
ural/1901.cpp
|
jffifa/algo-solution
|
af2400d6071ee8f777f9473d6a34698ceef08355
|
[
"MIT"
] | 3
|
2016-08-23T01:05:26.000Z
|
2017-05-28T02:04:20.000Z
|
#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<cstring>
#include<string>
#include<ctime>
#include<cmath>
using namespace std;
typedef long long ll;
multiset<int> S;
int n,m;
int a[120000];
int b[120000];
bool bi[120000];
int main(){
while (~scanf("%d%d",&n,&m)){
S.clear();
for (int i=1;i<=n;i++){
scanf("%d",&a[i]);
S.insert(a[i]);
}
if (n==1){
printf("1\n%d\n",a[1]);
continue;
}
if (n==2){
if (a[1]+a[2]>m)
printf("2\n%d %d\n",a[1],a[2]);
else
printf("1\n%d %d\n",a[1],a[2]);
continue;
}
memset(bi,true,sizeof(bi));
sort(a+1,a+n+1);
b[2]=a[n];
multiset<int>::iterator it;
/*
it=S.lower_bound(b[2]);
S.erase(it);
it=S.upper_bound(m-b[2]);
if (it==S.end()) --it;
b[1]=(*it);
S.erase(it);
for (int i=2;i<n;++i){
it=S.upper_bound(m-b[i]);
if (it==S.end()) --it;
b[i+1]=(*it);
S.erase(it);
}
*/
bool flag=true;
for (int i=1;i<=n;i++)
{
if (flag)
{
if (i<n)
{
it=S.end();it--;
b[i+1]=(*it);
S.erase(it);
it=S.upper_bound(m-b[i+1]);
if (it==S.end()) it=S.begin();
b[i]=(*it);
S.erase(it);
i++;
if (b[i-1]+b[i]<=m)
flag=true;
else flag=false;
}
else
{
it=S.begin();
b[i]=(*it);
S.erase(it);
}
}
else
{
it=S.upper_bound(m-b[i-1]);
if (it==S.end())
{
it=S.begin();
flag=true;
}
else flag=false;
b[i]=(*it);
S.erase(it);
}
}
int ans=0;
b[n+1]=0;
for (int i=1;i<=n;++i){
if (b[i]+b[i+1]<=m) i++;
ans++;
}
printf("%d\n",ans);
for (int i=1;i<=n;++i) printf("%d%c",b[i],i==n?'\n':' ');
}
return 0;
}
| 23.036036
| 65
| 0.332421
|
jffifa
|
c0ee95d13b958a8311145cd416d1753cf104af42
| 12,504
|
cpp
|
C++
|
object_detection/haar_detection.cpp
|
dustsigns/lecture-demos
|
50d5abb252e7e467e9648b61310ce93b85c6c5f0
|
[
"BSD-3-Clause"
] | 14
|
2018-03-26T13:43:58.000Z
|
2022-03-03T13:04:36.000Z
|
object_detection/haar_detection.cpp
|
dustsigns/lecture-demos
|
50d5abb252e7e467e9648b61310ce93b85c6c5f0
|
[
"BSD-3-Clause"
] | null | null | null |
object_detection/haar_detection.cpp
|
dustsigns/lecture-demos
|
50d5abb252e7e467e9648b61310ce93b85c6c5f0
|
[
"BSD-3-Clause"
] | 1
|
2019-08-03T23:12:08.000Z
|
2019-08-03T23:12:08.000Z
|
//Illustration of Haar features for object detection
// Andreas Unterweger, 2017-2022
//This code is licensed under the 3-Clause BSD License. See LICENSE file for details.
#include <iostream>
#include <limits>
#include <atomic>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include "format.hpp"
#include "colors.hpp"
static constexpr unsigned int block_width = 100;
static constexpr unsigned int block_height = 50;
static_assert(block_width % 2 == 0, "Block width must be even");
static_assert(block_height % 2 == 0, "Block height must be even");
struct haar_data
{
const cv::Mat feature_image;
const cv::Mat original_image;
cv::Mat annotated_image;
cv::Rect current_block;
std::atomic_bool running;
const std::string window_name;
void ResetAnnotatedImage()
{
cv::cvtColor(original_image, annotated_image, cv::COLOR_GRAY2BGRA);
}
haar_data(const cv::Mat &feature_image, const cv::Mat &original_image, const std::string &window_name)
: feature_image(feature_image), original_image(original_image),
current_block(cv::Rect(0, 0, block_width, block_height)), running(false),
window_name(window_name)
{
ResetAnnotatedImage();
}
};
static constexpr unsigned int border_size = 1;
static_assert(border_size < (block_width + 1) / 2, "Border size must be smaller than half the block width");
static_assert(border_size < (block_height + 1) / 2, "Border size must be smaller than half the block height");
static constexpr auto detection_threshold = 80000; //Feature-dependent threshold
static_assert(detection_threshold >= 1, "The detection threshold must be positive and non-zero");
static cv::Rect ExtendRect(const cv::Rect &rect, const unsigned int border)
{
return cv::Rect(rect.x - border, rect.y - border, rect.width + 2 * border, rect.height + 2 * border);
}
static void HighlightBlock(cv::Mat &image, const cv::Rect &block, const cv::Scalar &color)
{
const cv::Rect block_with_border = ExtendRect(block, border_size);
rectangle(image, block_with_border, color, border_size);
}
static void OverlayImages(cv::Mat &original_image, const cv::Rect &image_block, const cv::Mat &overlay, const double alpha)
{
assert(overlay.type() == CV_8UC1);
cv::Mat image_region = original_image(image_block);
cv::Mat converted_overlay;
cv::cvtColor(overlay, converted_overlay, cv::COLOR_GRAY2BGRA);
image_region = image_region * (1 - alpha) + converted_overlay * alpha;
}
static cv::Mat GetAnnotatedImage(haar_data &data, bool persist_changes)
{
constexpr auto overlay_alpha = 0.33;
if (persist_changes)
HighlightBlock(data.annotated_image, data.current_block, imgutils::Green); //Draw detected faces in green and persist changes
cv::Mat temporary_annotated_image = data.annotated_image.clone();
if (!persist_changes)
HighlightBlock(temporary_annotated_image, data.current_block, imgutils::Red); //Draw non-faces in red temporarily
OverlayImages(temporary_annotated_image, data.current_block, data.feature_image, overlay_alpha);
return temporary_annotated_image;
}
static double GetFeatureValue(const cv::Mat &block, const cv::Mat &feature)
{
assert(block.size() == feature.size());
assert(feature.type() == CV_8UC1);
assert(feature.type() == block.type());
cv::Mat block_signed;
block.convertTo(block_signed, CV_16SC1);
cv::Mat feature_signed;
feature.convertTo(feature_signed, CV_16SC1, 1.0 / 127, -1); //Convert [0, 255] range to [0 / 127 - 1, 255 / 127 - 1] = [-1, 1]
const cv::Mat weighted_pixels = block_signed.mul(feature_signed); //Multiply black pixels by (-1) and white pixels by 1
const auto difference = sum(weighted_pixels); //Value is difference between weighted pixels
const auto difference_1d = difference[0];
return difference_1d;
}
static double UpdateImage(haar_data &data, const bool update_GUI = true)
{
const cv::Mat block_pixels = data.original_image(data.current_block);
const double feature_value = GetFeatureValue(block_pixels, data.feature_image);
if (update_GUI)
{
const auto permanent_annotation = feature_value > detection_threshold;
const cv::Mat annotated_image = GetAnnotatedImage(data, permanent_annotation);
const std::string status_text = "Pixel difference (feature value): " + comutils::FormatValue(feature_value, 0);
cv::displayStatusBar(data.window_name, status_text);
cv::imshow(data.window_name, annotated_image);
}
return feature_value;
}
static double SetCurrentPosition(haar_data &data, const cv::Point &top_left, const bool update_GUI = true)
{
data.current_block = cv::Rect(top_left, cv::Size(block_width, block_height));
return UpdateImage(data, update_GUI);
}
static cv::Mat_<double> PerformSearch(haar_data &data, const bool update_GUI = true)
{
constexpr auto search_step_delay = 1; //Animation delay in ms
cv::Mat_<double> score_map(data.original_image.size(), std::numeric_limits<double>::infinity());
for (int y = border_size; y <= data.original_image.cols - static_cast<int>(block_height + border_size); y++)
{
for (int x = border_size; x <= data.original_image.rows - static_cast<int>(block_width + border_size); x++)
{
if (update_GUI && !data.running) //Skip the rest when the user aborts
return score_map;
const cv::Point current_position(x, y);
const double current_score = SetCurrentPosition(data, current_position, update_GUI);
score_map(current_position - cv::Point(border_size, border_size)) = current_score;
if (update_GUI)
cv::waitKey(search_step_delay);
}
}
return score_map;
}
static void ResetImage(haar_data &data)
{
SetCurrentPosition(data, cv::Point(border_size, border_size)); //Set current position to (0, 0) plus border
}
static void SelectPointInImage(const int event, const int x, const int y, const int, void * const userdata)
{
auto &data = *(static_cast<haar_data*>(userdata));
if (!data.running && event == cv::EVENT_LBUTTONUP) //Only react when the left mouse button is being pressed while no motion estimation is running
{
const cv::Point mouse_point(x + border_size, y + border_size); //Assume mouse position is in the top-left of the search block (on the outside border which is border_size pixels in width)
if (mouse_point.x <= data.original_image.cols - static_cast<int>(block_width + border_size) &&
mouse_point.y <= data.original_image.rows - static_cast<int>(block_height + border_size)) //If the mouse is within the image area (minus the positions on the bottom which would lead to the block exceeding the borders)...
SetCurrentPosition(data, mouse_point); //... set the current position according to the mouse position
}
}
static cv::Mat MakeColorMap(const cv::Mat_<double> &diff_map)
{
cv::Mat color_map(diff_map.size(), CV_8UC3);
std::transform(diff_map.begin(), diff_map.end(), color_map.begin<cv::Vec3b>(),
[](const double value) -> cv::Vec3b
{
if (std::isinf(value))
return 0.5 * imgutils::White; //The border is gray
else if (value < detection_threshold) //Values below the threshold are more red the further away they are from the threshold
return ((detection_threshold - value) / (2 * detection_threshold)) * imgutils::Red; //0 is half-way, -threshold and below are full red
else if (value >= detection_threshold) //Values above the threshold are always 25% green and more green the further away they are from the threshold
return 0.25 * imgutils::Green + 0.75 * ((value - detection_threshold) / detection_threshold) * imgutils::Green;
else
return imgutils::Black;
});
return color_map;
}
static void ShowImage(const cv::Mat &feature_image, const cv::Mat &image)
{
constexpr auto window_name = "Image with objects to detect";
cv::namedWindow(window_name);
cv::moveWindow(window_name, 0, 0);
static haar_data data(feature_image, image, window_name); //Make variable global so that it is not destroyed after the function returns (for the variable is needed later)
cv::setMouseCallback(window_name, SelectPointInImage, static_cast<void*>(&data));
constexpr auto clear_button_name = "Clear detections";
cv::createButton(clear_button_name, [](const int, void * const user_data)
{
auto &data = *(static_cast<haar_data*>(user_data));
data.ResetAnnotatedImage();
ResetImage(data); //Force redraw
}, static_cast<void*>(&data), cv::QT_PUSH_BUTTON);
constexpr auto perform_button_name = "Search whole image";
cv::createButton(perform_button_name, [](const int, void * const user_data)
{
auto &data = *(static_cast<haar_data*>(user_data));
if (!data.running)
{
data.running = true;
PerformSearch(data);
data.running = false;
}
}, static_cast<void*>(&data), cv::QT_PUSH_BUTTON);
constexpr auto stop_button_name = "Stop search";
cv::createButton(stop_button_name, [](const int, void * const user_data)
{
auto &data = *(static_cast<haar_data*>(user_data));
data.running = false;
}, static_cast<void*>(&data), cv::QT_PUSH_BUTTON);
constexpr auto map_button_name = "Show map of differences";
cv::createButton(map_button_name, [](const int, void * const user_data)
{
auto &data = *(static_cast<haar_data*>(user_data));
if (data.running) //Abort when the search is already running
return;
auto diff_map = PerformSearch(data, false);
const auto color_map = MakeColorMap(diff_map);
constexpr auto map_window_name = "Difference map";
cv::namedWindow(map_window_name);
cv::moveWindow(map_window_name, data.original_image.cols + 3, 0); //Move difference window right of the main window (image size plus 3 border pixels)
cv::imshow(map_window_name, color_map);
cv::setMouseCallback(map_window_name, SelectPointInImage, static_cast<void*>(&data)); //Perform the same action as in the main window
}, static_cast<void*>(&data), cv::QT_PUSH_BUTTON);
ResetImage(data); //Implies cv::imshow with default position
}
static cv::Mat GetFeatureImage()
{
cv::Mat feature_image(block_height, block_width, CV_8UC1, cv::Scalar(0));
auto lower_half = feature_image(cv::Rect(0, block_height / 2, block_width, block_height / 2));
lower_half = cv::Scalar(255);
return feature_image;
}
int main(const int argc, const char * const argv[])
{
if (argc != 2)
{
std::cout << "Illustrates object detection with Haar features." << std::endl;
std::cout << "Usage: " << argv[0] << " <input image>" << std::endl;
return 1;
}
const auto image_filename = argv[1];
const cv::Mat image = cv::imread(image_filename, cv::IMREAD_GRAYSCALE);
if (image.empty())
{
std::cerr << "Could not read input image '" << image_filename << "'" << std::endl;
return 2;
}
const cv::Mat feature_image = GetFeatureImage();
if (image.rows < feature_image.rows + static_cast<int>(2 * border_size) && image.cols < feature_image.cols + static_cast<int>(2 * border_size))
{
std::cerr << "The input image must be larger than " << (feature_image.rows + 2 * border_size) << "x" << (feature_image.cols + 2 * border_size) << " pixels" << std::endl;
return 3;
}
ShowImage(feature_image, image);
cv::waitKey(0);
return 0;
}
| 48.465116
| 228
| 0.646673
|
dustsigns
|
c0ef885aa2104d510a2717b2c41affc74db88100
| 734
|
cpp
|
C++
|
Example/Source/Main.cpp
|
eugen-bondarev/AssetSupplier
|
90e3d3e5fd7890c945dfc1975e7767d87221e53f
|
[
"MIT"
] | null | null | null |
Example/Source/Main.cpp
|
eugen-bondarev/AssetSupplier
|
90e3d3e5fd7890c945dfc1975e7767d87221e53f
|
[
"MIT"
] | null | null | null |
Example/Source/Main.cpp
|
eugen-bondarev/AssetSupplier
|
90e3d3e5fd7890c945dfc1975e7767d87221e53f
|
[
"MIT"
] | null | null | null |
#include <SRM/SRM.h>
#ifndef EXAMPLE_ROOT_DIR
# define EXAMPLE_ROOT_DIR
#endif
int main(const int argc, const char* argv[])
{
const srm::String root{ EXAMPLE_ROOT_DIR "/Assets" };
srm::ResourceManager resourceManager{
root,
"table.asu",
"data.asu",
srm::ResourceManager::Mode::Create
};
srm::Resource resource;
try
{
//resource = resourceManager.Load("a/b/c/d/e/deep-file.deep");
resource = resourceManager.Load("a/new-file.file");
}
catch (const srm::Exception& exception)
{
SRM_CONSOLE_OUT("[Error] %s", exception.what());
}
if (resource)
{
srm::String str{ "" };
for (size_t i = 0; i < resource.data.size(); ++i)
{
str += resource.data[i];
}
SRM_CONSOLE_INFO(str);
}
return 0;
}
| 17.902439
| 64
| 0.651226
|
eugen-bondarev
|
c0f21a781ccc0dd88313ea39ebb33c5485bd0b6b
| 427
|
cpp
|
C++
|
legend/legend/App.cpp
|
Sathorael/legendary-computing-machine
|
34273b6e50edb9211f11488d247df74aef56448a
|
[
"MIT"
] | null | null | null |
legend/legend/App.cpp
|
Sathorael/legendary-computing-machine
|
34273b6e50edb9211f11488d247df74aef56448a
|
[
"MIT"
] | null | null | null |
legend/legend/App.cpp
|
Sathorael/legendary-computing-machine
|
34273b6e50edb9211f11488d247df74aef56448a
|
[
"MIT"
] | 1
|
2019-05-28T18:32:30.000Z
|
2019-05-28T18:32:30.000Z
|
#include "App.h"
#include "SDL\SDL.h"
#include "Window.h"
App::App()
{
}
App::~App()
{
}
void App::run()
{
bool running = true;
SDL_Event e;
Window* window = new Window();
window->init();
while (running)
{
// Handle events in queue
while (SDL_PollEvent(&e) != 0)
{
// Quit if the user requests it.
if (e.type == SDL_QUIT)
{
running = false;
}
}
}
window->destroy();
SDL_Quit();
}
| 10.414634
| 36
| 0.559719
|
Sathorael
|
c0f21db838e35070a41786bf0221e8599672e95f
| 3,836
|
cc
|
C++
|
src/server/server_unix_socket.cc
|
kofuk/pixel-terrain
|
f39e2a0120aab5a11311f57cfd1ab46efa65fddd
|
[
"MIT"
] | 2
|
2020-10-16T08:46:45.000Z
|
2020-11-04T02:19:19.000Z
|
src/server/server_unix_socket.cc
|
kofuk/minecraft-image-generator
|
ef2f7deb2daac7f7c2cfb468ef39e0cdc8b33db7
|
[
"MIT"
] | null | null | null |
src/server/server_unix_socket.cc
|
kofuk/minecraft-image-generator
|
ef2f7deb2daac7f7c2cfb468ef39e0cdc8b33db7
|
[
"MIT"
] | null | null | null |
// SPDX-License-Identifier: MIT
#include <csignal>
#include <cstring>
#include <iostream>
#include <mutex>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <unistd.h>
#include "server/reader.hh"
#include "server/reader_unix.hh"
#include "server/request.hh"
#include "server/server.hh"
#include "server/server_unix_socket.hh"
#include "server/writer.hh"
#include "server/writer_unix.hh"
#include "utils/threaded_worker.hh"
namespace pixel_terrain::server {
namespace {
threaded_worker<int> *worker;
std::mutex worker_mutex;
void terminate_server() {
::unlink("/tmp/mcmap.sock");
std::exit(0);
}
void handle_signals(sigset_t sigs) {
int sig;
for (;;) {
if (::sigwait(&sigs, &sig) != 0) {
std::exit(1);
}
std::unique_lock<std::mutex> lock(worker_mutex);
if (sig == SIGUSR1) {
if (worker != nullptr) {
worker->finish();
delete worker;
}
terminate_server();
}
}
}
void prepare_signel_handle_thread() {
::sigset_t sigs;
::sigemptyset(&sigs);
::sigaddset(&sigs, SIGPIPE);
::sigaddset(&sigs, SIGUSR1);
::sigaddset(&sigs, SIGINT);
::pthread_sigmask(SIG_BLOCK, &sigs, nullptr);
std::thread t(&handle_signals, sigs);
t.detach();
}
void handle_request_unix(int const fd) {
reader *r = new reader_unix(fd);
auto *req = new request(r);
writer *w = new writer_unix(fd);
handle_request(req, w);
delete w;
delete req;
delete r;
::close(fd);
}
} // namespace
server_unix_socket::server_unix_socket(bool const daemon)
: daemon_mode(daemon) {}
void server_unix_socket::start_server() {
if (daemon_mode) {
if (::daemon(0, 0) == -1) {
std::cerr << "cannot run in daemon mode\n";
std::exit(1);
}
}
prepare_signel_handle_thread();
worker = new threaded_worker<int>(std::thread::hardware_concurrency(),
&handle_request_unix);
worker->start();
int ssock;
::sockaddr_un sa;
std::memset(&sa, 0, sizeof(sa));
::sockaddr_un sa_peer;
std::memset(&sa_peer, 0, sizeof(sa));
::socklen_t addr_len = sizeof(sockaddr_un);
if ((ssock = ::socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
std::perror("server");
std::exit(1);
}
sa.sun_family = AF_UNIX;
std::strcpy(sa.sun_path, "/tmp/mcmap.sock");
if (::bind(ssock, reinterpret_cast<::sockaddr *>(&sa),
sizeof(::sockaddr_un)) == -1) {
goto fail;
}
if (::listen(ssock, 4) == -1) {
goto fail;
}
if (::chmod("/tmp/mcmap.sock", S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP |
S_IROTH | S_IWOTH) == -1) {
goto fail;
}
for (;;) {
int fd;
if ((fd = ::accept(ssock, reinterpret_cast<::sockaddr *>(&sa_peer),
&addr_len)) > 0) {
std::unique_lock<std::mutex> lock(worker_mutex);
worker->queue_job(fd);
}
}
fail:
std::perror("server");
::close(ssock);
if (worker != nullptr) {
worker->finish();
}
}
} // namespace pixel_terrain::server
| 26.638889
| 79
| 0.486184
|
kofuk
|
c0f4d5e77c83ae6a7e9d85781c216756d877646c
| 4,789
|
cpp
|
C++
|
src/rtplugins/SuperSampleAdaptiveRenderer.cpp
|
potato3d/rtrt2
|
5c135c1aea0ded2898e16220cec5ed2860dcc9b3
|
[
"MIT"
] | 1
|
2021-11-06T06:13:05.000Z
|
2021-11-06T06:13:05.000Z
|
src/rtplugins/SuperSampleAdaptiveRenderer.cpp
|
potato3d/rtrt2
|
5c135c1aea0ded2898e16220cec5ed2860dcc9b3
|
[
"MIT"
] | null | null | null |
src/rtplugins/SuperSampleAdaptiveRenderer.cpp
|
potato3d/rtrt2
|
5c135c1aea0ded2898e16220cec5ed2860dcc9b3
|
[
"MIT"
] | null | null | null |
#include <rtp/SuperSampleAdaptiveRenderer.h>
#include <rt/Context.h>
#include <rti/ICamera.h>
#include <vr/random.h>
#include <omp.h>
using namespace rtp;
SuperSampleAdaptiveRenderer::SuperSampleAdaptiveRenderer()
{
vr::Random::autoSeed();
_epsilon = 0.01f;
_maxRecursionDepth = 3;
}
void SuperSampleAdaptiveRenderer::render()
{
uint32 width;
uint32 height;
rt::Context* ctx = rt::Context::get();
ctx->getCamera()->getViewport( width, height );
float* frameBuffer = ctx->getFrameBuffer();
int32 w = (int32)width;
int32 h = (int32)height;
vr::vec3f resultColor;
int32 x, y;
int32 chunk = 16;
#pragma omp parallel for shared( frameBuffer, h, w ) private( y ) schedule( dynamic, chunk )
for( y = 0; y < h; ++y )
{
#pragma omp parallel for shared( frameBuffer, h, w, y ) private( x, resultColor ) schedule( dynamic, chunk )
for( x = 0; x < w; ++x )
{
adaptiveSupersample( x, y, resultColor, 1 );
frameBuffer[(x+y*w)*3] = resultColor.r;
frameBuffer[(x+y*w)*3+1] = resultColor.g;
frameBuffer[(x+y*w)*3+2] = resultColor.b;
}
}
}
void SuperSampleAdaptiveRenderer::adaptiveSupersample( float x, float y, vr::vec3f& resultColor, uint32 recursionDepth )
{
rt::Context* ctx = rt::Context::get();
const float deltaRatio = 0.5f / (float)recursionDepth;
float deltaX;
float deltaY;
rt::Sample upperLeftSample;
rt::Sample upperRightSample;
rt::Sample lowerLeftSample;
rt::Sample lowerRightSample;
// Upper left (A)
deltaX = vr::Random::real( -deltaRatio, 0.0f );
deltaY = vr::Random::real( 0.0f, deltaRatio );
upperLeftSample.initPrimaryRay( x + deltaX, y + deltaY );
ctx->traceNearest( upperLeftSample );
vr::vec3f upperLeftColor = upperLeftSample.color;
// Upper right (B)
deltaX = vr::Random::real( 0.0f, deltaRatio );
deltaY = vr::Random::real( 0.0f, deltaRatio );
upperRightSample.initPrimaryRay( x + deltaX, y + deltaY );
ctx->traceNearest( upperRightSample );
vr::vec3f upperRightColor = upperRightSample.color;
// Lower left (C)
deltaX = vr::Random::real( -deltaRatio, 0.0f );
deltaY = vr::Random::real( -deltaRatio, 0.0f );
lowerLeftSample.initPrimaryRay( x + deltaX, y + deltaY );
ctx->traceNearest( lowerLeftSample );
vr::vec3f lowerLeftColor = lowerLeftSample.color;
// Lower right (D)
deltaX = vr::Random::real( 0.0f, deltaRatio );
deltaY = vr::Random::real( -deltaRatio, 0.0f );
lowerRightSample.initPrimaryRay( x + deltaX, y + deltaY );
ctx->traceNearest( lowerRightSample );
vr::vec3f lowerRightColor = lowerRightSample.color;
if( recursionDepth < _maxRecursionDepth )
{
// If too much difference in sample values
vr::vec3f ab = upperLeftColor - upperRightColor;
ab.set( vr::abs( ab.r ), vr::abs( ab.g ), vr::abs( ab.b ) );
vr::vec3f ac = upperLeftColor - lowerLeftColor;
ac.set( vr::abs( ac.r ), vr::abs( ac.g ), vr::abs( ac.b ) );
vr::vec3f ad = upperLeftColor - lowerRightColor;
ad.set( vr::abs( ad.r ), vr::abs( ad.g ), vr::abs( ad.b ) );
vr::vec3f bc = upperRightColor - lowerLeftColor;
bc.set( vr::abs( bc.r ), vr::abs( bc.g ), vr::abs( bc.b ) );
vr::vec3f bd = upperRightColor - lowerRightColor;
bd.set( vr::abs( bd.r ), vr::abs( bd.g ), vr::abs( bd.b ) );
vr::vec3f cd = upperLeftColor - lowerRightColor;
cd.set( vr::abs( cd.r ), vr::abs( cd.g ), vr::abs( cd.b ) );
if( ( ab.r > _epsilon ) || ( ab.g > _epsilon ) || ( ab.b > _epsilon ) ||
( ac.r > _epsilon ) || ( ac.g > _epsilon ) || ( ac.b > _epsilon ) ||
( ad.r > _epsilon ) || ( ad.g > _epsilon ) || ( ad.b > _epsilon ) ||
( bc.r > _epsilon ) || ( bc.g > _epsilon ) || ( bc.b > _epsilon ) ||
( bd.r > _epsilon ) || ( bd.g > _epsilon ) || ( bd.b > _epsilon ) ||
( cd.r > _epsilon ) || ( cd.g > _epsilon ) || ( cd.b > _epsilon ) )
{
// Recursive supersample
const float recDelta = 0.5f / ( (float)recursionDepth + 1.0f );
vr::vec3f recUpperLeft;
vr::vec3f recUpperRight;
vr::vec3f recLowerLeft;
vr::vec3f recLowerRight;
adaptiveSupersample( x - recDelta, y + recDelta, recUpperLeft, recursionDepth + 1 );
adaptiveSupersample( x + recDelta, y + recDelta, recUpperRight, recursionDepth + 1 );
adaptiveSupersample( x - recDelta, y - recDelta, recLowerLeft, recursionDepth + 1 );
adaptiveSupersample( x + recDelta, y - recDelta, recLowerRight, recursionDepth + 1 );
// Average results
resultColor = ( upperLeftColor * 0.125f ) + ( recUpperLeft * 0.125f ) +
( upperRightColor * 0.125f ) + ( recUpperRight * 0.125f ) +
( lowerLeftColor * 0.125f ) + ( recLowerLeft * 0.125f ) +
( lowerRightColor * 0.125f ) + ( recLowerRight * 0.125f );
return;
}
}
// Average results
resultColor = ( upperLeftColor * 0.25f ) + ( upperRightColor * 0.25f ) +
( lowerLeftColor * 0.25f ) + ( lowerRightColor * 0.25f );
}
| 34.207143
| 120
| 0.647108
|
potato3d
|
c0f841ff3bfcf22e1244e3fc2bfd9b3193a62b29
| 367
|
cpp
|
C++
|
src/jitcat/TypeInfoDeleter.cpp
|
Zueuk/JitCat
|
04eb77a9acf6f8b36689c0aabcb6d68edd28f0fc
|
[
"MIT"
] | 14
|
2019-03-16T07:00:44.000Z
|
2021-10-20T23:36:51.000Z
|
src/jitcat/TypeInfoDeleter.cpp
|
Zueuk/JitCat
|
04eb77a9acf6f8b36689c0aabcb6d68edd28f0fc
|
[
"MIT"
] | 13
|
2019-11-22T12:43:55.000Z
|
2020-05-25T13:09:08.000Z
|
src/jitcat/TypeInfoDeleter.cpp
|
Zueuk/JitCat
|
04eb77a9acf6f8b36689c0aabcb6d68edd28f0fc
|
[
"MIT"
] | 1
|
2019-11-23T17:59:58.000Z
|
2019-11-23T17:59:58.000Z
|
/*
This file is part of the JitCat library.
Copyright (C) Machiel van Hooren 2020
Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT).
*/
#include "jitcat/TypeInfoDeleter.h"
#include "jitcat/TypeInfo.h"
void jitcat::Reflection::TypeInfoDeleter::operator()(TypeInfo* typeInfo) const
{
TypeInfo::destroy(typeInfo);
}
| 22.9375
| 94
| 0.746594
|
Zueuk
|
c0f94c1d95812e041af5802cf0bc130c2bb8c249
| 1,635
|
cpp
|
C++
|
Chapter_03/sample6.cpp
|
expoli/Learn-OpenCV-4-By-Building-Projects-Second-Edition
|
f0288b6a303923da100393b60b79f8eaf3a03165
|
[
"MIT"
] | 1
|
2020-07-30T10:30:29.000Z
|
2020-07-30T10:30:29.000Z
|
Chapter_03/sample6.cpp
|
expoli/Learn-OpenCV-4-By-Building-Projects-Second-Edition
|
f0288b6a303923da100393b60b79f8eaf3a03165
|
[
"MIT"
] | null | null | null |
Chapter_03/sample6.cpp
|
expoli/Learn-OpenCV-4-By-Building-Projects-Second-Edition
|
f0288b6a303923da100393b60b79f8eaf3a03165
|
[
"MIT"
] | null | null | null |
#include <opencv2/viz.hpp>
#include <opencv2/calib3d.hpp>
#include <iostream>
using namespace cv;
using namespace std;
/*
* @function main
*/
int main() {
/// Create a window
viz::Viz3d myWindow("Coordinate Frame");
/// Add coordinate axes
myWindow.showWidget("Coordinate Widget", viz::WCoordinateSystem());
/// Add line to represent (1,1,1) axis
viz::WLine axis(Point3f(-1.0f, -1.0f, -1.0f), Point3f(1.0f, 1.0f, 1.0f));
axis.setRenderingProperty(viz::LINE_WIDTH, 4.0);
myWindow.showWidget("Line Widget", axis);
/// Construct a cube widget
viz::WCube cube_widget(Point3f(0.5, 0.5, 0.0), Point3f(0.0, 0.0, -0.5), true, viz::Color::blue());
cube_widget.setRenderingProperty(viz::LINE_WIDTH, 4.0);
/// Display widget (update if already displayed)
myWindow.showWidget("Cube Widget", cube_widget);
/// Rodrigues vector
Mat rot_vec = Mat::zeros(1, 3, CV_32F);
float translation_phase = 0.0, translation = 0.0;
while (!myWindow.wasStopped()) {
/* Rotation using rodrigues */
/// Rotate around (1,1,1)
rot_vec.at<float>(0, 0) += CV_PI * 0.01f;
rot_vec.at<float>(0, 1) += CV_PI * 0.01f;
rot_vec.at<float>(0, 2) += CV_PI * 0.01f;
/// Shift on (1,1,1)
translation_phase += CV_PI * 0.01f;
translation = sin(translation_phase);
Mat rot_mat;
Rodrigues(rot_vec, rot_mat);
/// Construct pose
Affine3f pose(rot_mat, Vec3f(translation, translation, translation));
myWindow.setWidgetPose("Cube Widget", pose);
myWindow.spinOnce(1, true);
}
return 0;
}
| 29.196429
| 102
| 0.620795
|
expoli
|
c0fb9efba1193e769ef84210ae216e8c50113513
| 844
|
hpp
|
C++
|
src/main/include/StarDust/file/ConfigParser.hpp
|
4H-Botsmiths/InfiniteRecharge2020
|
811d71a49a50f38f44dcc7139786caaeaa99f739
|
[
"BSD-3-Clause"
] | null | null | null |
src/main/include/StarDust/file/ConfigParser.hpp
|
4H-Botsmiths/InfiniteRecharge2020
|
811d71a49a50f38f44dcc7139786caaeaa99f739
|
[
"BSD-3-Clause"
] | 1
|
2021-12-27T04:40:42.000Z
|
2021-12-27T04:40:42.000Z
|
src/main/include/StarDust/file/ConfigParser.hpp
|
4H-Botsmiths/InfiniteRecharge2020
|
811d71a49a50f38f44dcc7139786caaeaa99f739
|
[
"BSD-3-Clause"
] | null | null | null |
#pragma once
#include <iostream>
#include <vector>
#include <memory>
#include <string>
#include "StarDust\core\StarDustComponent.hpp"
#include "StarDust\file\ParserParamBase.hpp"
#include "StarDust\file\ParserParam.hpp"
#define CONFIG_FILE_PATH "/home/lvuser/config.dat"
class ConfigParser : public StarDustComponent {
public:
//takes in a vector of ParserParams to be parsed
ConfigParser(std::vector<ParserParamBase*> parameters);
//same as above but overrides default filename with a diffent one
ConfigParser(std::vector<ParserParamBase*> parameters, std::string filename);
void __RobotInit__() override;
void __AutonomousInit__() override;
void __TeleopInit__() override;
private:
void autorun();
std::vector<ParserParamBase*> parameters;
std::string filename;
};
| 27.225806
| 82
| 0.722749
|
4H-Botsmiths
|
8d0634b3b1f3d755352f283a3da9cd691f7b4425
| 2,011
|
hpp
|
C++
|
include/psinc/handlers/helpers/Filter.hpp
|
emergent-design/libpsinc
|
8a30ebc2838d205b214e5f2e523b6bf558b0a41e
|
[
"MIT"
] | 2
|
2017-02-28T11:27:38.000Z
|
2019-01-23T06:10:49.000Z
|
include/psinc/handlers/helpers/Filter.hpp
|
emergent-design/libpsinc
|
8a30ebc2838d205b214e5f2e523b6bf558b0a41e
|
[
"MIT"
] | 6
|
2015-06-26T13:01:49.000Z
|
2020-07-31T15:08:55.000Z
|
include/psinc/handlers/helpers/Filter.hpp
|
emergent-design/libpsinc
|
8a30ebc2838d205b214e5f2e523b6bf558b0a41e
|
[
"MIT"
] | 1
|
2017-02-28T10:55:30.000Z
|
2017-02-28T10:55:30.000Z
|
#pragma once
#include <emergent/Maths.hpp>
#include <emergent/image/Image.hpp>
namespace psinc
{
class Filter
{
public:
enum Mode
{
Disabled,
RowOffset, // Adjust brightness of specific rows by a fixed offset
RowGain // Adjust brightness of specific rows by a gain multiplier
};
struct Configuration
{
Mode mode = Mode::Disabled;
int start = 0; // Starting row of the mark-space pattern
int mark = 2; // Number of rows to apply the offset/gain to
int space = 5; // Number of rows to then skip
int offset = 0; // Offset to be applied to pixel values in mark rows
double gain = 1.0; // Gain multiplier to be applied to pixel values in mark rows
};
template <typename T> static void Process(const Configuration &configuration, emg::ImageBase<T> &image)
{
switch (configuration.mode)
{
case Mode::Disabled: break;
case Mode::RowOffset: Apply(configuration, image, [=](const T s) { return s + configuration.offset; }); break;
case Mode::RowGain: Apply(configuration, image, [=](const T s) { return std::lrint(configuration.gain * s); }); break;
}
}
private:
template <typename T, typename Operation> static void Apply(const Configuration &configuration, emg::ImageBase<T> &image, Operation operation)
{
int x, y;
const int width = image.Width();
const int height = image.Height();
const int depth = image.Depth();
const int row = width * depth;
const int mark = configuration.mark * row;
const int space = configuration.space * row;
const int limit = height - configuration.mark;
const int window = configuration.mark + configuration.space;
T *src = image + configuration.start * row;
for (y=configuration.start; y<height; y+=window, src+=space)
{
const int end = y < limit ? mark : (height - y) * row;
for (x=0; x<end; x++, src++)
{
*src = emg::Maths::clamp<T>(operation(*src));
}
}
}
};
}
| 28.728571
| 145
| 0.637991
|
emergent-design
|
8d0b5e39b44128a906a78b45bce4c9f8933b89f4
| 830
|
cpp
|
C++
|
platform/OSP/JS/Web/src/JSServletExecutorCache.cpp
|
gboyraz/macchina.io
|
3e26fea95e87512459693831242b297f0780cc21
|
[
"Apache-2.0"
] | 2
|
2020-11-23T23:37:00.000Z
|
2020-12-22T04:02:41.000Z
|
platform/OSP/JS/Web/src/JSServletExecutorCache.cpp
|
bas524/cmake.macchina.io
|
22a21d78f8075fd145b788b41a23603591e91c9f
|
[
"Apache-2.0"
] | null | null | null |
platform/OSP/JS/Web/src/JSServletExecutorCache.cpp
|
bas524/cmake.macchina.io
|
22a21d78f8075fd145b788b41a23603591e91c9f
|
[
"Apache-2.0"
] | 1
|
2020-11-23T23:37:09.000Z
|
2020-11-23T23:37:09.000Z
|
//
// JSServletExecutorCache.cpp
//
// Copyright (c) 2016, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: Apache-2.0
//
#include "JSServletExecutorCache.h"
#include "Poco/SingletonHolder.h"
namespace Poco {
namespace OSP {
namespace JS {
namespace Web {
//
// JSServletExecutorHolder
//
JSServletExecutorHolder::JSServletExecutorHolder(JSServletExecutor::Ptr pExecutor):
_pExecutor(pExecutor)
{
}
//
// JSServletExecutorCache
//
JSServletExecutorCache::JSServletExecutorCache(long size):
Poco::LRUCache<std::string, JSServletExecutorHolder, Poco::Mutex>(size)
{
}
namespace
{
static Poco::SingletonHolder<JSServletExecutorCache> sh;
}
JSServletExecutorCache& JSServletExecutorCache::instance()
{
return *sh.get();
}
} } } } // namespace Poco::OSP::JS::Web
| 14.821429
| 83
| 0.745783
|
gboyraz
|
8d0b96f3958c3e97495049259b1da3186b50642a
| 7,013
|
cpp
|
C++
|
abcg/abcg_image.cpp
|
guiarqueiro/entrega3
|
48d7d9828b44f232b51044269a4164056fbe95b8
|
[
"MIT"
] | 11
|
2021-03-23T00:06:20.000Z
|
2021-10-02T22:13:37.000Z
|
abcg/abcg_image.cpp
|
guiarqueiro/entrega3
|
48d7d9828b44f232b51044269a4164056fbe95b8
|
[
"MIT"
] | 2
|
2021-03-11T23:31:39.000Z
|
2021-10-04T22:21:57.000Z
|
abcg/abcg_image.cpp
|
guiarqueiro/entrega3
|
48d7d9828b44f232b51044269a4164056fbe95b8
|
[
"MIT"
] | 101
|
2021-02-08T18:48:02.000Z
|
2022-03-16T03:51:09.000Z
|
/**
* @file abcg_image.cpp
* @brief Definition of texture loading helper functions.
*
* This project is released under the MIT License.
*/
#include "abcg_image.hpp"
#include <fmt/core.h>
#include <cppitertools/itertools.hpp>
#include <fstream>
#include <gsl/gsl>
#include <span>
#include <vector>
#include "SDL_image.h"
#include "abcg_exception.hpp"
#include "abcg_external.hpp"
void flipHorizontally(gsl::not_null<SDL_Surface*> surface) {
auto width{static_cast<size_t>(surface->w * surface->format->BytesPerPixel)};
auto height{static_cast<size_t>(surface->h)};
std::span pixels{static_cast<std::byte*>(surface->pixels), width * height};
// Row of pixels for the swap
std::vector<std::byte> pixelRow(width, std::byte{});
// For each row
for (auto rowIndex : iter::range(height)) {
auto rowStart{width * rowIndex};
auto rowEnd{rowStart + width - 1};
// For each RGB triplet of this row
// C++23: for (auto tripletStart : iter::range(0uz, width, 3uz)) {
for (auto tripletStart : iter::range<std::size_t>(0, width, 3)) {
pixelRow.at(tripletStart + 0) = pixels[rowEnd - tripletStart - 2];
pixelRow.at(tripletStart + 1) = pixels[rowEnd - tripletStart - 1];
pixelRow.at(tripletStart + 2) = pixels[rowEnd - tripletStart - 0];
}
memcpy(pixels.subspan(rowStart).data(), pixelRow.data(), width);
}
}
void flipVertically(gsl::not_null<SDL_Surface*> surface) {
auto width{static_cast<size_t>(surface->w * surface->format->BytesPerPixel)};
auto height{static_cast<size_t>(surface->h)};
std::span pixels{static_cast<std::byte*>(surface->pixels), width * height};
// Row of pixels for the swap
std::vector<std::byte> pixelRow(width, std::byte{});
// If height is odd, don't need to swap middle row
size_t halfHeight{height / 2};
for (auto rowIndex : iter::range(halfHeight)) {
auto rowStartFromTop{width * rowIndex};
auto rowStartFromBottom{width * (height - rowIndex - 1)};
memcpy(pixelRow.data(), pixels.subspan(rowStartFromTop).data(), width);
memcpy(pixels.subspan(rowStartFromTop).data(),
pixels.subspan(rowStartFromBottom).data(), width);
memcpy(pixels.subspan(rowStartFromBottom).data(), pixelRow.data(), width);
}
}
GLuint abcg::opengl::loadTexture(std::string_view path, bool generateMipmaps) {
GLuint textureID{};
// Copy file data into buffer
std::ifstream input(path.data(), std::ios::binary);
if (!input) {
throw abcg::Exception{abcg::Exception::Runtime(
fmt::format("Failed to open texture file {}", path))};
}
std::vector<char> buffer((std::istreambuf_iterator<char>(input)),
std::istreambuf_iterator<char>());
// Load the bitmap
if (SDL_Surface * surface{IMG_Load(path.data())}) {
// Enforce RGB/RGBA
GLenum format{0};
SDL_Surface* formattedSurface{nullptr};
if (surface->format->BytesPerPixel == 3) {
formattedSurface =
SDL_ConvertSurfaceFormat(surface, SDL_PIXELFORMAT_RGB24, 0);
format = GL_RGB;
} else {
formattedSurface =
SDL_ConvertSurfaceFormat(surface, SDL_PIXELFORMAT_RGBA32, 0);
format = GL_RGBA;
}
SDL_FreeSurface(surface);
// Flip upside down
flipVertically(formattedSurface);
// Generate the texture
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, static_cast<GLint>(format),
formattedSurface->w, formattedSurface->h, 0, format,
GL_UNSIGNED_BYTE, formattedSurface->pixels);
SDL_FreeSurface(formattedSurface);
// Set texture filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// Generate the mipmap levels
if (generateMipmaps) {
glGenerateMipmap(GL_TEXTURE_2D);
// Override minifying filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_LINEAR_MIPMAP_LINEAR);
}
// Set texture wrapping
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
} else {
throw abcg::Exception{abcg::Exception::Runtime(
fmt::format("Failed to load texture file {}", path))};
}
glBindTexture(GL_TEXTURE_2D, 0);
return textureID;
}
GLuint abcg::opengl::loadCubemap(std::array<std::string_view, 6> paths,
bool generateMipmaps, bool rightHandedSystem) {
GLuint textureID{};
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
for (auto&& [index, path] : iter::enumerate(paths)) {
// Copy file data into buffer
std::ifstream input(path.data(), std::ios::binary);
if (!input) {
throw abcg::Exception{abcg::Exception::Runtime(
fmt::format("Failed to open texture file {}", path))};
}
std::vector<char> buffer((std::istreambuf_iterator<char>(input)),
std::istreambuf_iterator<char>());
// Load the bitmap
if (SDL_Surface * surface{IMG_Load(path.data())}) {
// Enforce RGB
SDL_Surface* formattedSurface{
SDL_ConvertSurfaceFormat(surface, SDL_PIXELFORMAT_RGB24, 0)};
SDL_FreeSurface(surface);
auto target{GL_TEXTURE_CUBE_MAP_POSITIVE_X + static_cast<GLenum>(index)};
// LHS to RHS
if (rightHandedSystem) {
if (target == GL_TEXTURE_CUBE_MAP_POSITIVE_Y ||
target == GL_TEXTURE_CUBE_MAP_NEGATIVE_Y) {
// Flip upside down
flipVertically(formattedSurface);
} else {
flipHorizontally(formattedSurface);
}
// Swap -z with +z
if (target == GL_TEXTURE_CUBE_MAP_POSITIVE_Z)
target = GL_TEXTURE_CUBE_MAP_NEGATIVE_Z;
else if (target == GL_TEXTURE_CUBE_MAP_NEGATIVE_Z)
target = GL_TEXTURE_CUBE_MAP_POSITIVE_Z;
}
// Create texture
glTexImage2D(target, 0, GL_RGB, formattedSurface->w, formattedSurface->h,
0, GL_RGB, GL_UNSIGNED_BYTE, formattedSurface->pixels);
SDL_FreeSurface(formattedSurface);
} else {
throw abcg::Exception{abcg::Exception::Runtime(
fmt::format("Failed to load texture file {}", path))};
}
}
// Set texture wrapping
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
// Set texture filtering
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// Generate the mipmap levels
if (generateMipmaps) {
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
// Override minifying filtering
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER,
GL_LINEAR_MIPMAP_LINEAR);
}
return textureID;
}
| 34.377451
| 80
| 0.67988
|
guiarqueiro
|
8d10dad0aa7ca5f8ea463a773574078df5b9e9ad
| 5,235
|
hpp
|
C++
|
include/SSVOpenHexagon/Global/Config.hpp
|
AlphaPromethium/SSVOpenHexagon
|
f9e15e9397d6188e3dced97da97d5c6e2de4186a
|
[
"AFL-3.0"
] | null | null | null |
include/SSVOpenHexagon/Global/Config.hpp
|
AlphaPromethium/SSVOpenHexagon
|
f9e15e9397d6188e3dced97da97d5c6e2de4186a
|
[
"AFL-3.0"
] | null | null | null |
include/SSVOpenHexagon/Global/Config.hpp
|
AlphaPromethium/SSVOpenHexagon
|
f9e15e9397d6188e3dced97da97d5c6e2de4186a
|
[
"AFL-3.0"
] | null | null | null |
// Copyright (c) 2013-2020 Vittorio Romeo
// License: Academic Free License ("AFL") v. 3.0
// AFL License page: http://opensource.org/licenses/AFL-3.0
#pragma once
#include <vector>
#include <string>
namespace ssvs
{
class GameWindow;
} // namespace ssvs
namespace ssvs::Input
{
class Trigger;
} // namespace ssvs::Input
namespace hg::Config
{
void loadConfig(const std::vector<std::string>& mOverridesIds);
void saveConfig();
[[nodiscard]] bool isEligibleForScore();
void recalculateSizes();
void setFullscreen(ssvs::GameWindow& mWindow, bool mFullscreen);
void refreshWindowSize(unsigned int mWidth, unsigned int mHeight);
void setCurrentResolution(
ssvs::GameWindow& mWindow, unsigned int mWidth, unsigned int mHeight);
void setCurrentResolutionAuto(ssvs::GameWindow& mWindow);
void setVsync(ssvs::GameWindow& mWindow, bool mValue);
void setLimitFPS(ssvs::GameWindow& mWindow, bool mValue);
void setMaxFPS(ssvs::GameWindow& mWindow, unsigned int mValue);
void setTimerStatic(ssvs::GameWindow& mWindow, bool mValue);
void setAntialiasingLevel(ssvs::GameWindow& mWindow, unsigned int mValue);
void setOnline(bool mOnline);
void setOfficial(bool mOfficial);
void setDebug(bool mDebug);
void setNoRotation(bool mNoRotation);
void setNoBackground(bool mNoBackground);
void setBlackAndWhite(bool mBlackAndWhite);
void setNoSound(bool mNoSound);
void setNoMusic(bool mNoMusic);
void setPulse(bool mPulse);
void set3D(bool m3D);
void setInvincible(bool mInvincible);
void setAutoRestart(bool mAutoRestart);
void setSoundVolume(float mVolume);
void setMusicVolume(float mVolume);
void setFlash(bool mFlash);
void setMusicSpeedDMSync(bool mValue);
void setShowFPS(bool mValue);
void setServerLocal(bool mValue);
void setServerVerbose(bool mValue);
void setMouseVisible(bool mValue);
void setMusicSpeedMult(float mValue);
void setDrawTextOutlines(bool mX);
void setDarkenUnevenBackgroundChunk(bool mX);
void setRotateToStart(bool mX);
void setJoystickDeadzone(float mX);
void setTextPadding(float mX);
void setTextScaling(float mX);
void setTimescale(float mX);
void setShowKeyIcons(bool mX);
void setKeyIconsScale(float mX);
void setFirstTimePlaying(bool mX);
[[nodiscard]] bool getOnline();
[[nodiscard]] bool getOfficial();
[[nodiscard]] std::string getUneligibilityReason();
[[nodiscard]] float getSizeX();
[[nodiscard]] float getSizeY();
[[nodiscard]] float getSpawnDistance();
[[nodiscard]] float getZoomFactor();
[[nodiscard]] int getPixelMultiplier();
[[nodiscard]] float getPlayerSpeed();
[[nodiscard]] float getPlayerFocusSpeed();
[[nodiscard]] float getPlayerSize();
[[nodiscard]] bool getNoRotation();
[[nodiscard]] bool getNoBackground();
[[nodiscard]] bool getBlackAndWhite();
[[nodiscard]] bool getNoSound();
[[nodiscard]] bool getNoMusic();
[[nodiscard]] float getSoundVolume();
[[nodiscard]] float getMusicVolume();
[[nodiscard]] bool getLimitFPS();
[[nodiscard]] bool getVsync();
[[nodiscard]] bool getAutoZoomFactor();
[[nodiscard]] bool getFullscreen();
[[nodiscard]] float getVersion();
[[nodiscard]] const char* getVersionString();
[[nodiscard]] bool getWindowedAutoResolution();
[[nodiscard]] bool getFullscreenAutoResolution();
[[nodiscard]] unsigned int getFullscreenWidth();
[[nodiscard]] unsigned int getFullscreenHeight();
[[nodiscard]] unsigned int getWindowedWidth();
[[nodiscard]] unsigned int getWindowedHeight();
[[nodiscard]] unsigned int getWidth();
[[nodiscard]] unsigned int getHeight();
[[nodiscard]] bool getShowMessages();
[[nodiscard]] bool getRotateToStart();
[[nodiscard]] bool getDebug();
[[nodiscard]] bool getPulse();
[[nodiscard]] bool getBeatPulse();
[[nodiscard]] bool getInvincible();
[[nodiscard]] bool get3D();
[[nodiscard]] unsigned int get3DMaxDepth();
[[nodiscard]] float get3DMultiplier();
[[nodiscard]] bool getAutoRestart();
[[nodiscard]] bool getFlash();
[[nodiscard]] bool getShowTrackedVariables();
[[nodiscard]] bool getMusicSpeedDMSync();
[[nodiscard]] unsigned int getMaxFPS();
[[nodiscard]] bool getShowFPS();
[[nodiscard]] bool getTimerStatic();
[[nodiscard]] unsigned int getAntialiasingLevel();
[[nodiscard]] bool getServerLocal();
[[nodiscard]] bool getServerVerbose();
[[nodiscard]] bool getMouseVisible();
[[nodiscard]] float getMusicSpeedMult();
[[nodiscard]] bool getDrawTextOutlines();
[[nodiscard]] bool getDarkenUnevenBackgroundChunk();
[[nodiscard]] float getJoystickDeadzone();
[[nodiscard]] float getTextPadding();
[[nodiscard]] float getTextScaling();
[[nodiscard]] float getTimescale();
[[nodiscard]] bool getShowKeyIcons();
[[nodiscard]] float getKeyIconsScale();
[[nodiscard]] bool getFirstTimePlaying();
[[nodiscard]] ssvs::Input::Trigger getTriggerRotateCCW();
[[nodiscard]] ssvs::Input::Trigger getTriggerRotateCW();
[[nodiscard]] ssvs::Input::Trigger getTriggerFocus();
[[nodiscard]] ssvs::Input::Trigger getTriggerExit();
[[nodiscard]] ssvs::Input::Trigger getTriggerForceRestart();
[[nodiscard]] ssvs::Input::Trigger getTriggerRestart();
[[nodiscard]] ssvs::Input::Trigger getTriggerReplay();
[[nodiscard]] ssvs::Input::Trigger getTriggerScreenshot();
[[nodiscard]] ssvs::Input::Trigger getTriggerSwap();
[[nodiscard]] ssvs::Input::Trigger getTriggerUp();
[[nodiscard]] ssvs::Input::Trigger getTriggerDown();
} // namespace hg::Config
| 34.668874
| 74
| 0.762751
|
AlphaPromethium
|
8d148b40414b0e2292a3fc9ef685f0d63a0d7cfc
| 9,383
|
hpp
|
C++
|
far/uuids.far.dialogs.hpp
|
skipik/FarManager
|
0080534fd8b8246b31f9587d8e15fe313849e801
|
[
"BSD-3-Clause"
] | null | null | null |
far/uuids.far.dialogs.hpp
|
skipik/FarManager
|
0080534fd8b8246b31f9587d8e15fe313849e801
|
[
"BSD-3-Clause"
] | null | null | null |
far/uuids.far.dialogs.hpp
|
skipik/FarManager
|
0080534fd8b8246b31f9587d8e15fe313849e801
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef UUIDS_FAR_DIALOGS_HPP_760BACF0_E0D8_4C67_A732_5C075A1CC176
#define UUIDS_FAR_DIALOGS_HPP_760BACF0_E0D8_4C67_A732_5C075A1CC176
#pragma once
/*
uuids.far.dialogs.hpp
UUIDs of common dialogs
*/
/*
Copyright © 2010 Far Group
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. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Internal:
// Platform:
// Common:
#include "common/uuid.hpp"
// External:
//----------------------------------------------------------------------------
namespace uuids::far::dialogs
{
constexpr inline auto
FindFileId = "8C9EAD29-910F-4B24-A669-EDAFBA6ED964"_uuid,
FindFileResultId = "536754EB-C2D1-4626-933F-A25D1E1D110A"_uuid,
CopyOverwriteId = "9FBCB7E1-ACA2-475D-B40D-0F7365B632FF"_uuid,
FileOpenCreateId = "1D07CEE2-8F4F-480A-BE93-069B4FF59A2B"_uuid,
FileSaveAsId = "9162F965-78B8-4476-98AC-D699E5B6AFE7"_uuid,
EditorSavedROId = "3F9311F5-3CA3-4169-A41C-89C76B3A8C1D"_uuid,
EditorSaveF6DeletedId = "85532BD5-1583-456D-A810-41AB345995A9"_uuid,
EditorSaveExitDeletedId = "2D71DCCE-F0B8-4E29-A3A9-1F6D8C1128C2"_uuid,
EditorAskOverwriteId = "4109C8B3-760D-4011-B1D5-14C36763B23E"_uuid,
EditorOpenRSHId = "D8AA706F-DA7E-4BBF-AB78-6B7BDB49E006"_uuid,
EditAskSaveExtId = "40A699F1-BBDD-4E21-A137-97FFF798B0C8"_uuid,
EditAskSaveId = "F776FEC0-50F7-4E7E-BDA6-2A63F84A957B"_uuid,
MakeFolderId = "FAD00DBE-3FFF-4095-9232-E1CC70C67737"_uuid,
FileAttrDlgId = "80695D20-1085-44D6-8061-F3C41AB5569C"_uuid,
CopyReadOnlyId = "879A8DE6-3108-4BEB-80DE-6F264991CE98"_uuid,
CopyFilesId = "FCEF11C4-5490-451D-8B4A-62FA03F52759"_uuid,
CopyCurrentOnlyFileId = "502D00DF-EE31-41CF-9028-442D2E352990"_uuid,
MoveFilesId = "431A2F37-AC01-4ECD-BB6F-8CDE584E5A03"_uuid,
MoveCurrentOnlyFileId = "89664EF4-BB8C-4932-A8C0-59CAFD937ABA"_uuid,
HardSymLinkId = "5EB266F4-980D-46AF-B3D2-2C50E64BCA81"_uuid,
PluginsMenuId = "937F0B1C-7690-4F85-8469-AA935517F202"_uuid,
EditorReloadId = "AFDAD388-494C-41E8-BAC6-BBE9115E1CC0"_uuid,
FarAskQuitId = "72E6E6D8-0BC6-4265-B9C4-C8DB712136AF"_uuid,
AdvancedConfigId = "A204FF09-07FA-478C-98C9-E56F61377BDE"_uuid,
FolderShortcutsId = "4CD742BC-295F-4AFA-A158-7AA05A16BEA1"_uuid,
FolderShortcutsDlgId = "DC8D98AC-475C-4F37-AB1D-45765EF06269"_uuid,
FolderShortcutsMoreId = "601DD149-92FA-4601-B489-74C981BC8E38"_uuid,
ScreensSwitchId = "72EB948A-5F1D-4481-9A91-A4BFD869D127"_uuid,
SelectSortModeId = "B8B6E1DA-4221-47D2-AB2E-9EC67D0DC1E3"_uuid,
HistoryCmdId = "880968A6-6258-43E0-9BDC-F2B8678EC278"_uuid,
HistoryFolderId = "FC3384A8-6608-4C9B-8D6B-EE105F4C5A54"_uuid,
HistoryEditViewId = "E770E044-23A8-4F4D-B268-0E602B98CCF9"_uuid,
PanelViewModesId = "B56D5C08-0336-418B-A2A7-CF0C80F93ACC"_uuid,
PanelViewModesEditId = "98B75500-4A97-4299-BFAD-C3E349BF3674"_uuid,
CodePagesMenuId = "78A4A4E3-C2F0-40BD-9AA7-EAAC11836631"_uuid,
EditorReplaceId = "8BCCDFFD-3B34-49F8-87CD-F4D885B75873"_uuid,
EditorSearchId = "5D3CBA90-F32D-433C-B016-9BB4AF96FACC"_uuid,
HelpSearchId = "F63B558F-9185-46BA-8701-D143B8F62658"_uuid,
FiltersMenuId = "5B87B32E-494A-4982-AF55-DAFFCD251383"_uuid,
FiltersConfigId = "EDDB9286-3B08-4593-8F7F-E5925A3A0FF8"_uuid,
HighlightMenuId = "D0422DF0-AAF5-46E0-B98B-1776B427E70D"_uuid,
HighlightConfigId = "51B6E342-B499-464D-978C-029F18ECCE59"_uuid,
PluginsConfigMenuId = "B4C242E7-AA8E-4449-B0C3-BD8D9FA11AED"_uuid,
ChangeDiskMenuId = "252CE4A3-C415-4B19-956B-83E2FDD85960"_uuid,
FileAssocMenuId = "F6D2437C-FEDC-4075-AA56-275666FC8979"_uuid,
SelectAssocMenuId = "D2BCB5A5-6B82-4EB5-B321-1AE7607A6236"_uuid,
FileAssocModifyId = "6F245B1A-47D9-41A6-AF3F-FA2C8DBEEBD0"_uuid,
EditorSwitchUnicodeCPDisabledId = "15568DC5-4D6B-4C60-B43D-2040EE39871A"_uuid,
GetNameAndPasswordId = "CD2AC546-9E4F-4445-A258-AB5F7A7800E0"_uuid,
SelectFromEditHistoryId = "4406C688-209F-4378-8B7B-465BF16205FF"_uuid,
EditorReloadModalId = "D6F557E8-7E89-4895-BD75-4D3F2C30E382"_uuid,
EditorCanNotEditDirectoryId = "CCA2C4D0-8705-4FA1-9B10-C9E3C8F37A65"_uuid,
EditorFileLongId = "E3AFCD2D-BDE5-4E92-82B6-87C6A7B78FB6"_uuid,
EditorFileGetSizeErrorId = "6AD4B317-C1ED-44C8-A76A-9146CA8AF984"_uuid,
DisconnectDriveId = "A1BDBEB1-2911-41FF-BC08-EEBC44040B50"_uuid,
ChangeDriveModeId = "F87F9351-6A80-4872-BEEE-96EF80C809FB"_uuid,
SUBSTDisconnectDriveId = "75554EEB-A3A7-45FD-9795-4A85887A75A0"_uuid,
VHDDisconnectDriveId = "629A8CA6-25C6-498C-B3DD-0E18D1CC0BCD"_uuid,
EditorFindAllListId = "9BD3E306-EFB8-4113-8405-E7BADE8F0A59"_uuid,
BadEditorCodePageId = "4811039D-03A3-4F15-8D7A-8EBC4BCC97F9"_uuid,
UserMenuUserInputId = "D2750B57-D3E6-42F4-8137-231C50DDC6E4"_uuid,
DescribeFileId = "D8AF7A38-8357-44A5-A44B-A595CF707549"_uuid,
SelectDialogId = "29C03C36-9C50-4F78-AB99-F5DC1A9C67CD"_uuid,
UnSelectDialogId = "34614DDB-2A22-4EA9-BD4A-2DC075643F1B"_uuid,
SUBSTDisconnectDriveError1Id = "FF18299E-1881-42FA-AF7E-AC05D99F269C"_uuid,
SUBSTDisconnectDriveError2Id = "43B0FFC2-70BE-4289-91E6-FE9A3D54311B"_uuid,
EjectHotPlugMediaErrorId = "D6DC3621-877E-4BE2-80CC-BDB2864CE038"_uuid,
RemoteDisconnectDriveError2Id = "F06953B8-25AA-4FC0-9899-422FC1D49F7A"_uuid,
RemoteDisconnectDriveError1Id = "C9439386-9544-49BF-954B-6BEEDE7F1BD0"_uuid,
VHDDisconnectDriveErrorId = "B890E6B0-05A9-4ED8-A4C3-BBC4D29DA3BE"_uuid,
ChangeDriveCannotReadDiskErrorId = "F3D46DC3-380B-4264-8BF8-10B05B897A5E"_uuid,
ApplyCommandId = "044EF83E-8146-41B2-97F0-404C2F4C7B69"_uuid,
DeleteFileFolderId = "6EF09401-6FE1-495A-8539-61B0F761408E"_uuid,
DeleteRecycleId = "85A5F779-A881-4B0B-ACEE-6D05653AE0EB"_uuid,
DeleteWipeId = "9C054039-5C7E-4B04-96CD-3585228C916F"_uuid,
DeleteLinkId = "B1099BC3-14BD-4B22-87AC-44770D4189A3"_uuid,
DeleteFolderId = "4E714029-11BF-476F-9B17-9E47AA0DA8EA"_uuid,
WipeFolderId = "E23BB390-036E-4A30-A9E6-DC621617C7F5"_uuid,
DeleteFolderRecycleId = "A318CBDC-DBA9-49E9-A248-E6A9FF8EC849"_uuid,
DeleteAskWipeROId = "6792A975-57C5-4110-8129-2D8045120964"_uuid,
DeleteAskDeleteROId = "8D4E84B3-08F6-47DF-8C40-7130CD31D0E6"_uuid,
WipeHardLinkId = "5297DDFE-0A37-4465-85EF-CBF9006D65C6"_uuid,
RecycleFolderConfirmDeleteLinkId = "26A7AB9F-51F5-40F7-9061-1AE6E2FBD00A"_uuid,
CannotRecycleFileId = "52CEB5A5-06FA-43DD-B37C-239C02652C99"_uuid,
CannotRecycleFolderId = "BBD9B7AE-9F6B-4444-89BF-C6124A5A83A4"_uuid,
AskInsertMenuOrCommandId = "57209AD5-51F6-4257-BAB6-837462BBCE74"_uuid,
EditUserMenuId = "73BC6E3E-4CC3-4FE3-8709-545FF72B49B4"_uuid,
PluginInformationId = "FC4FD19A-43D2-4987-AC31-0F7A94901692"_uuid,
EditMaskGroupId = "C57682CA-8DC9-4D62-B3F5-9ED37CD207B9"_uuid,
ViewerSearchId = "03B6C098-A3D6-4DFB-AED4-EB32D711D9AA"_uuid;
}
// TODO: Use fully qualified names everywhere
inline namespace uuids_inline
{
using namespace uuids::far::dialogs;
}
#endif // UUIDS_FAR_DIALOGS_HPP_760BACF0_E0D8_4C67_A732_5C075A1CC176
| 62.553333
| 81
| 0.688905
|
skipik
|
8d14c8506388bf847a1dd3203ede096ac4aa2f20
| 6,671
|
cc
|
C++
|
server/core/maxpasswd.cc
|
Daniel-Xu/MaxScale
|
35d12c0c9b75c4571dbbeb983c740de098661de6
|
[
"BSD-3-Clause"
] | null | null | null |
server/core/maxpasswd.cc
|
Daniel-Xu/MaxScale
|
35d12c0c9b75c4571dbbeb983c740de098661de6
|
[
"BSD-3-Clause"
] | null | null | null |
server/core/maxpasswd.cc
|
Daniel-Xu/MaxScale
|
35d12c0c9b75c4571dbbeb983c740de098661de6
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) 2016 MariaDB Corporation Ab
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file and at www.mariadb.com/bsl11.
*
* Change Date: 2025-04-28
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2 or later of the General
* Public License.
*/
/**
* @file maxpasswd.c - Implementation of pasword encoding
*/
#include <maxscale/ccdefs.hh>
#include <cstdio>
#include <getopt.h>
#include <termios.h>
#include <unistd.h>
#include <maxbase/log.hh>
#include <maxscale/paths.hh>
#include <iostream>
#include "internal/secrets.hh"
using std::cin;
using std::cout;
using std::endl;
using std::flush;
using std::string;
struct option options[] =
{
{"help", no_argument, nullptr, 'h'},
{"decrypt", no_argument, nullptr, 'd'},
{"interactive", no_argument, nullptr, 'i'},
{nullptr, 0, nullptr, 0 }
};
void print_usage(const char* executable, const char* directory)
{
const char msg[] =
R"(Usage: %s [-h|--help] [-i|--interactive] [-d|--decrypt] [path] password
Encrypt a MaxScale plaintext password using the encryption key in the key file
'%s'. The key file may be generated using the 'maxkeys'-utility.
-h, --help Display this help.
-d, --decrypt Decrypt an encrypted password instead.
-i, --interactive - If maxpasswd is reading from a pipe, it will read a line and
use that as the password.
- If maxpasswd is connected to a terminal console, it will prompt
for the password.
If '-i' is specified, a single argument is assumed to be the path
and two arguments is treated like an error.
path The key file directory (default: '%s')
password The password to encrypt or decrypt
)";
printf(msg, executable, SECRETS_FILENAME, directory);
}
bool read_password(string* pPassword)
{
bool rv = false;
string password;
if (isatty(STDIN_FILENO))
{
struct termios tty;
tcgetattr(STDIN_FILENO, &tty);
bool echo = (tty.c_lflag & ECHO);
if (echo)
{
tty.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &tty);
}
cout << "Enter password : " << flush;
string s1;
std::getline(std::cin, s1);
cout << endl;
cout << "Repeat password: " << flush;
string s2;
std::getline(std::cin, s2);
cout << endl;
if (echo)
{
tty.c_lflag |= ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &tty);
}
if (s1 == s2)
{
password = s1;
rv = true;
}
else
{
cout << "Passwords are not identical." << endl;
}
}
else
{
std::getline(std::cin, password);
rv = true;
}
if (rv)
{
*pPassword = password;
}
return rv;
}
int main(int argc, char** argv)
{
std::ios::sync_with_stdio();
mxb::Log log(MXB_LOG_TARGET_STDOUT);
const char* default_directory = mxs::datadir();
enum class Mode
{
ENCRYPT,
DECRYPT
};
auto mode = Mode::ENCRYPT;
bool interactive = false;
int c;
while ((c = getopt_long(argc, argv, "hdi", options, NULL)) != -1)
{
switch (c)
{
case 'h':
print_usage(argv[0], default_directory);
return EXIT_SUCCESS;
case 'd':
mode = Mode::DECRYPT;
break;
case 'i':
interactive = true;
break;
default:
print_usage(argv[0], default_directory);
return EXIT_FAILURE;
}
}
string input;
string path = default_directory;
switch (argc - optind)
{
case 2:
// Two args provided.
path = argv[optind];
if (!interactive)
{
input = argv[optind + 1];
}
else
{
print_usage(argv[0], default_directory);
return EXIT_FAILURE;
}
break;
case 1:
// One arg provided.
if (!interactive)
{
input = argv[optind];
}
else
{
path = argv[optind];
}
break;
case 0:
if (!interactive)
{
print_usage(argv[0], default_directory);
return EXIT_FAILURE;
}
break;
default:
print_usage(argv[0], default_directory);
return EXIT_FAILURE;
}
if (interactive)
{
if (!read_password(&input))
{
return EXIT_FAILURE;
}
}
int rval = EXIT_FAILURE;
string filepath = path;
filepath.append("/").append(SECRETS_FILENAME);
auto keydata = secrets_readkeys(filepath);
if (keydata.ok)
{
bool encrypting = (mode == Mode::ENCRYPT);
bool new_mode = keydata.iv.empty(); // false -> constant IV from file
if (keydata.key.empty())
{
printf("Password encryption key file '%s' not found, cannot %s password.\n",
filepath.c_str(), encrypting ? "encrypt" : "decrypt");
}
else if (encrypting)
{
string encrypted = new_mode ? encrypt_password(keydata.key, input) :
encrypt_password_old(keydata.key, keydata.iv, input);
if (!encrypted.empty())
{
printf("%s\n", encrypted.c_str());
rval = EXIT_SUCCESS;
}
else
{
printf("Password encryption failed.\n");
}
}
else
{
auto is_hex = std::all_of(input.begin(), input.end(), isxdigit);
if (is_hex && input.length() % 2 == 0)
{
string decrypted = new_mode ? decrypt_password(keydata.key, input) :
decrypt_password_old(keydata.key, keydata.iv, input);
if (!decrypted.empty())
{
printf("%s\n", decrypted.c_str());
rval = EXIT_SUCCESS;
}
else
{
printf("Password decryption failed.\n");
}
}
else
{
printf("Input is not a valid hex-encoded encrypted password.\n");
}
}
}
else
{
printf("Could not read encryption key file '%s'.\n", filepath.c_str());
}
return rval;
}
| 24.258182
| 88
| 0.519412
|
Daniel-Xu
|
8d16fababc5043fac3767090f8c0966ed4bd9480
| 6,194
|
cpp
|
C++
|
cpp/template/template.cpp
|
HieuuuLeee/WorldFinal
|
ea1b1e697e6e7987018a5a79402d1a2659270591
|
[
"MIT"
] | null | null | null |
cpp/template/template.cpp
|
HieuuuLeee/WorldFinal
|
ea1b1e697e6e7987018a5a79402d1a2659270591
|
[
"MIT"
] | null | null | null |
cpp/template/template.cpp
|
HieuuuLeee/WorldFinal
|
ea1b1e697e6e7987018a5a79402d1a2659270591
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define pb push_back
#define pf push_front
#define pp push
#define et empty
#define mp make_pair
#define For(i,a,b) for (int i=a;i<=b;i++)
#define Fod(i,b,a) for (int i=b;i>=a;i--)
#define Forl(i,a,b) for (ll i=a;i<=b;i++)
#define Fodl(i,b,a) for (ll i=b;i>=a;i--)
typedef int64_t ll;
typedef uint64_t ull;
#define prno cout<<"NO\n"
#define pryes cout<<"YES\n"
#define pryon pryes; else prno;
#define brln cout << "\n";
#define el "\n"
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define prarr(a,n) For(i,1,n)cout<<a[i]<<" "; brln;
#define bitcount(n) __builtin_popcountll(n)
#define INFILE(name) freopen(name, "r", stdin)
#define OUFILE(name) freopen(name, "w", stdout)
#define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
const int inf = 1e6+5;
// sort(arr, arr+n, greater<int>());
int sum() { return 0; }
template<typename T, typename... Args>
T sum(T a, Args... args) { return a + sum(args...); }
#define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
void err(istream_iterator<string> it) {}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
// cout << "\n";
cout << *it << " = " << a << endl;
err(++it, args...);
// cout << "\n";
}
inline ll read(){
ll x=0,t=1;char ch=getchar();
while(ch>'9'||ch<'0'){if(ch=='-')t=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9')
x=x*10+ch-'0',ch=getchar();
return x*t;
}
bool compare(pair<ll,ll> a, pair<ll,ll> b){
return a.second - a.first < b.second -
b.first;
}
pair<ll, ll> factor(ll n) {
ll s = 0;
while ((n & 1) == 0) {
s++;
n >>= 1;
}
return {s, n};
}
ll pow(ll a, ll d, ll n) {
ll result = 1;
a = a % n;
while (d > 0) {
if (d & 1) result = result * a % n;
d >>= 1;
a = a * a % n;
}
return result;
}
bool test_a(ll s, ll d, ll n, ll a) {
if (n == a) return true;
ll p = pow(a, d, n);
if (p == 1) return true;
for (; s > 0; s--) {
if (p == n-1) return true;
p = p * p % n;
}
return false;
}
bool miller(ll n) {
if (n < 2) return false;
if ((n & 1) == 0) return n == 2;
ll s, d;
tie(s, d) = factor(n-1);
// return test_a(s, d, n, 2) && test_a(s, d, n, 3);
return test_a(s, d, n, 2) && test_a(s, d, n, 7) && test_a(s, d, n, 61);
}
ll nCr(ll n, ll r){
ll tmp = n-r;
for(ll i = n-1; i > tmp; i--)
n *= i;
for(ll i = r-1; i > 1; i--)
r *= i;
return n/r;
}
ll NCR(int n, int r){
ll p = 1, k = 1;
if (n - r < r)
r = n - r;
if (r != 0) {
while (r) {
p *= n; k *= r;
ll m = __gcd(p, k);
p /= m; k /= m;
n--; r--;
}
}
else p = 1;
return p;
}
inline ll mul(ll a, ll b, ll MOD = (1LL<<62)){
return ((((a)%MOD)*((b)%MOD))%MOD);
}
inline ll add(ll a, ll b, ll MOD = (1LL<<62)){
return ((((a)%MOD)+((b)%MOD))%MOD);
}
inline ll Pow(ll base, ll exp, ll MOD = (1LL<<62)){
ll ans = 1;
while(exp){
if(exp & 1)
ans = (ans*base)%MOD;
exp >>= 1;
base = (base*base)%MOD;
}
return ans;
}
void sieve(int N) {
bool isPrime[1000000];
for(int i = 0; i <= N;++i) {
isPrime[i] = true;
}
isPrime[0] = false;
isPrime[1] = false;
for(int i = 2; i * i <= N; ++i) {
if(isPrime[i] == true) {
for(int j = i * i; j <= N; j += i)
isPrime[j] = false;
}}}
//=====================================================
// O((R−L+1)loglog(R)+(√R)loglog(√R)).
vector<bool> segmentedSieve(long long L, long long R) {
// generate all primes up to sqrt(R)
long long lim = sqrt(R);
vector<bool> mark(lim + 1, false);
vector<long long> primes;
for (long long i = 2; i <= lim; ++i) {
if (!mark[i]) {
primes.emplace_back(i);
for (long long j = i * i; j <= lim; j += i)
mark[j] = true;
}
}
vector<bool> isPrime(R - L + 1, true);
for (long long i : primes)
for (long long j = max(i * i, (L + i - 1) / i * i); j <= R; j += i)
isPrime[j - L] = false;
if (L == 1)
isPrime[0] = false;
return isPrime;
}
///======================================
ll minPrime[1000000];
void pre_factorize(ll n){
for (ll i = 2; i * i <= n; ++i) {
if (minPrime[i] == 0) { //if i is prime
for (ll j = i * i; j <= n; j += i) {
if (minPrime[j] == 0) {
minPrime[j] = i;
}}}}
for (ll i = 2; i <= n; ++i) {
if (minPrime[i] == 0) {
minPrime[i] = i;
}}
}
vector<ll> factorize(ll n) {
vector<ll> res;
while (n != 1) {
res.push_back(minPrime[n]);
n /= minPrime[n];}
return res;}
vector<ll> factorize_hh(ll n) {
vector<ll> res;
for (ll i = 2; i * i <= n; ++i) {
while (n % i == 0) {
res.push_back(i);
n /= i;}}
if (n != 1) {
res.push_back(n);}
return res;}
ll n;
int main(){
fast;
INFILE("../in.txt");
OUFILE("../out.txt");
cout<<pow(2,5,10);
// cout << nCr(100000000000000000,50);
// cout << miller(23);
// cout << factor(510).first << factor(510).second;
// For(i, 1, 10) cout << i << " " << (i & 1) << "\n";
// cout << (10<<1);
// ll a = 100000;
// DUMP(a);
// pre_factorize(1000000);
// vector<ll> x = factorize(a);
// for(auto i : x) cout << i << " ";
// vector<ll> x = factorize_hh(a);
// for(auto i : x) cout << i << " ";
// CURTIME();
}
// xc = ((a.x * a.x + a.y * a.y) * (b.y - c.y) + (b.x * b.x + b.y * b.y) * (c.y - a.y) + (c.x * c.x + c.y * c.y) * (a.y - b.y)) / d;
// yc = ((a.x * a.x + a.y * a.y) * (c.x - b.x) + (b.x * b.x + b.y * b.y) * (a.x - c.x) + (c.x * c.x + c.y * c.y) * (b.x - a.x)) / d;
| 26.583691
| 160
| 0.45092
|
HieuuuLeee
|
8d17a9708f7d382445bdde2d7b06c3fbb2d322ae
| 347
|
cpp
|
C++
|
test/compute/Main.cpp
|
craft095/sere
|
b7ce9aafe5390a0bf48ade7ebe0a1a09bf0396b9
|
[
"MIT"
] | null | null | null |
test/compute/Main.cpp
|
craft095/sere
|
b7ce9aafe5390a0bf48ade7ebe0a1a09bf0396b9
|
[
"MIT"
] | null | null | null |
test/compute/Main.cpp
|
craft095/sere
|
b7ce9aafe5390a0bf48ade7ebe0a1a09bf0396b9
|
[
"MIT"
] | null | null | null |
#ifdef GTEST
#include "gtest/gtest.h"
#endif
#define CATCH_CONFIG_RUNNER
#include "catch2/catch.hpp"
int main(int argc, char **argv) {
#ifdef GTEST
::testing::InitGoogleTest(&argc, argv);
int result = RUN_ALL_TESTS();
if (result != 0) {
return result;
}
#endif
int result = Catch::Session().run( argc, argv );
return result;
}
| 16.52381
| 50
| 0.668588
|
craft095
|
8d180d3c6da645841f0beecc34ec1e85de2879dc
| 18,738
|
hpp
|
C++
|
examples/experimental/nvshmem/matrix/grb_util.hpp
|
ge49nuk/BCLmatrix
|
f04368cc88ff9b2b652a403c69075a036b2b5586
|
[
"BSD-3-Clause"
] | null | null | null |
examples/experimental/nvshmem/matrix/grb_util.hpp
|
ge49nuk/BCLmatrix
|
f04368cc88ff9b2b652a403c69075a036b2b5586
|
[
"BSD-3-Clause"
] | 1
|
2021-05-21T20:27:02.000Z
|
2021-05-21T21:54:46.000Z
|
examples/experimental/nvshmem/matrix/grb_util.hpp
|
ge49nuk/BCLmatrix
|
f04368cc88ff9b2b652a403c69075a036b2b5586
|
[
"BSD-3-Clause"
] | null | null | null |
#pragma once
#include <matrix_sum.cuh>
namespace BCL {
template <typename T>
struct max {
T operator()(const T& a, const T& b) const {
if (a < b) {
return b;
} else {
return a;
}
}
};
template <typename T>
struct min {
T operator()(const T& a, const T& b) const {
if (a < b) {
return a;
} else {
return b;
}
}
};
namespace cuda {
graphblas::Descriptor* grb_desc_ = nullptr;
// TODO: Actually free matrix contents.
template <typename T>
void destroy_grb(graphblas::Matrix<T>* x, const std::string lbl = "hey") {
if (x == nullptr) {
return;
}
auto& m = x->matrix_.sparse_;
if (m.h_csrRowPtr_) free(m.h_csrRowPtr_);
if (m.h_csrColInd_) free(m.h_csrColInd_);
if (m.h_csrVal_ ) free(m.h_csrVal_);
if (BCL::cuda::__is_valid_cuda_gptr(m.d_csrRowPtr_)) {
BCL::cuda::dealloc(BCL::cuda::__to_cuda_gptr(m.d_csrRowPtr_));
} else {
/*
fprintf(stderr, "0x%p is not a valid BCL pointer, checking value for %s (valid segment is 0x%p -> 0x%p\n",
m.d_csrRowPtr_, lbl.c_str(), BCL::cuda::smem_base_ptr, BCL::cuda::smem_base_ptr + BCL::cuda::shared_segment_size);
*/
CUDA_CALL(cudaPeekAtLastError());
if (m.d_csrRowPtr_) CUDA_CALL(cudaFree(m.d_csrRowPtr_));
}
if (BCL::cuda::__is_valid_cuda_gptr(m.d_csrColInd_)) {
BCL::cuda::dealloc(BCL::cuda::__to_cuda_gptr(m.d_csrColInd_));
} else {
if (m.d_csrColInd_) CUDA_CALL(cudaFree(m.d_csrColInd_));
}
if (BCL::cuda::__is_valid_cuda_gptr(m.d_csrVal_ )) {
BCL::cuda::dealloc(BCL::cuda::__to_cuda_gptr(m.d_csrVal_));
} else {
if (m.d_csrVal_ ) CUDA_CALL(cudaFree(m.d_csrVal_ ));
}
if (m.format_ == graphblas::backend::GrB_SPARSE_MATRIX_CSRCSC) {
throw std::runtime_error("destroy_grb: Case not handled.");
}
}
template <typename T, typename Allocator>
graphblas::Matrix<T>* sum_tiles_yuxin(std::vector<graphblas::Matrix<T>*> imp) {
if (imp.size() == 0) {
return nullptr;
}
using index_type = graphblas::Index;
graphblas::Index m, n;
imp[0]->nrows(&m);
imp[0]->ncols(&n);
::cuda::SparseSPAAccumulator<T, index_type, Allocator> acc;
for (auto mat : imp) {
// convert mat into Yuxin's BCL::cuda::CSRMatrix
graphblas::Index nnz;
mat->nvals(&nnz);
::cuda::CSRMatrix<T, index_type, Allocator> cmat(m, n, nnz,
mat->matrix_.sparse_.d_csrVal_,
mat->matrix_.sparse_.d_csrRowPtr_,
mat->matrix_.sparse_.d_csrColInd_);
acc.accumulate(std::move(cmat), {0, 0});
}
acc.sort_mats();
acc.get_lbs();
// Assume a 1 GB memory limit for accumualtor.
size_t max_mem = 1*1000*1000*1000;
size_t max_mem_row = std::min<size_t>(m, max_mem/((sizeof(graphblas::Index)+sizeof(T))*n));
size_t block_size = 512;
auto result_mat = acc.get_matrix(m, n, max_mem_row, block_size);
graphblas::Matrix<T>* grb_result = new graphblas::Matrix<T>(result_mat.m_, result_mat.n_);
grb_result->build(result_mat.row_ptr_, result_mat.col_ind_, result_mat.vals_,
result_mat.nnz_);
return grb_result;
}
template <typename T, typename index_type>
auto get_coo(const std::vector<T>& values,
const std::vector<index_type>& row_indices,
const std::vector<index_type>& col_indices)
{
using coord_type = std::pair<index_type, index_type>;
using tuple_type = std::pair<coord_type, T>;
using coo_t = std::vector<tuple_type>;
coo_t coo_values(values.size());
for (size_t i = 0; i < values.size(); i++) {
coo_values[i] = {{row_indices[i], col_indices[i]}, values[i]};
}
std::sort(coo_values.begin(), coo_values.end(),
[](const auto& a, const auto& b) -> bool {
if (std::get<0>(a) != std::get<0>(b)) {
return std::get<0>(a) < std::get<0>(b);
} else {
return std::get<1>(a) < std::get<1>(b);
}
});
return coo_values;
}
template <typename T, typename index_type>
auto remove_zeros(const std::vector<std::pair<std::pair<index_type, index_type>, T>>& coo_values) {
using coord_type = std::pair<index_type, index_type>;
using tuple_type = std::pair<coord_type, T>;
using coo_t = std::vector<tuple_type>;
coo_t new_coo;
for (const auto& nz : coo_values) {
auto val = std::get<1>(nz);
if (val != 0.0) {
new_coo.push_back(nz);
}
}
return new_coo;
}
template <typename T>
void print_coo(const T& coo, size_t max_idx = std::numeric_limits<size_t>::max()) {
for (size_t i = 0; i < std::min(coo.size(), max_idx); i++) {
auto idx = std::get<0>(coo[i]);
auto val = std::get<1>(coo[i]);
printf("(%lu, %lu) %f\n", idx.first, idx.second, val);
}
}
template <typename T, typename index_type, typename Allocator>
graphblas::Matrix<T>*
get_graphblast_view(CudaCSRMatrix<T, index_type, Allocator>& a) {
graphblas::Matrix<T>* grb_matrix = new graphblas::Matrix<T>(a.m(), a.n());
grb_matrix->build(a.rowptr_data(), a.colind_data(), a.values_data(), a.nnz());
return grb_matrix;
}
template <typename T, typename index_type, typename Allocator>
CudaCSRMatrix<T, index_type, Allocator>
convert_to_csr(graphblas::Matrix<T>* a_grb) {
graphblas::Index m, n, nnz;
a_grb->nrows(&m);
a_grb->ncols(&n);
a_grb->nvals(&nnz);
T* values = a_grb->matrix_.sparse_.d_csrVal_;
index_type* rowptr = a_grb->matrix_.sparse_.d_csrRowPtr_;
index_type* colind = a_grb->matrix_.sparse_.d_csrColInd_;
return CudaCSRMatrix<T, index_type, Allocator>({m, n}, nnz, values, rowptr, colind);
}
template <typename T, typename index_type, typename Allocator>
CudaCSRMatrix<T, index_type, Allocator>
spgemm_graphblast(CudaCSRMatrix<T, index_type, Allocator>& a,
CudaCSRMatrix<T, index_type, Allocator>& b)
{
// static assert index_type is graphblas::Index
grb_desc_->descriptor_.debug_ = false;
if (a.nnz() == 0 || b.nnz() == 0) {
// return empty matrix
return CudaCSRMatrix<T, index_type, Allocator>({a.shape()[0], b.shape()[1]});
} else {
auto binary_op = GrB_NULL;
auto semiring = graphblas::PlusMultipliesSemiring<T>{};
auto a_grb = get_graphblast_view(a);
auto b_grb = get_graphblast_view(b);
auto* c_grb = new graphblas::Matrix<T>(a.shape()[0], b.shape()[1]);
graphblas::mxm<T, T, T, T, decltype(binary_op), decltype(semiring),
Allocator>
(c_grb, GrB_NULL,
binary_op, semiring,
a_grb, b_grb, grb_desc_);
auto c = convert_to_csr<T, index_type, Allocator>(c_grb);
free(a_grb);
free(b_grb);
free(c_grb);
return c;
}
}
template <typename T, typename index_type, typename Allocator>
CudaCSRMatrix<T, index_type, Allocator>
sum_cusparse(CudaCSRMatrix<T, index_type, Allocator>& a,
CudaCSRMatrix<T, index_type, Allocator>& b) {
// XXX: Do an element-wise add using cuSparse
// 'A' here is local_c, and 'B' here is result_c
//. At the end, the new accumulated matrix will be put in local_c.
// TODO: allocate handle elsewhere.
cusparseHandle_t handle;
cusparseStatus_t status =
cusparseCreate(&handle);
BCL::cuda::throw_cusparse(status);
status =
cusparseSetPointerMode(handle, CUSPARSE_POINTER_MODE_HOST);
BCL::cuda::throw_cusparse(status);
index_type arows = a.shape()[0];
index_type acols = a.shape()[1];
index_type brows = b.shape()[0];
index_type bcols = b.shape()[1];
assert(acols == bcols);
assert(arows == brows);
index_type m = arows;
index_type n = acols;
static_assert(std::is_same<int, index_type>::value);
cusparseMatDescr_t descr_a, descr_b, descr_c;
status =
cusparseCreateMatDescr(&descr_a);
BCL::cuda::throw_cusparse(status);
status =
cusparseCreateMatDescr(&descr_b);
BCL::cuda::throw_cusparse(status);
status =
cusparseCreateMatDescr(&descr_c);
BCL::cuda::throw_cusparse(status);
status =
cusparseSetMatType(descr_a, CUSPARSE_MATRIX_TYPE_GENERAL);
BCL::cuda::throw_cusparse(status);
status =
cusparseSetMatIndexBase(descr_a, CUSPARSE_INDEX_BASE_ZERO);
BCL::cuda::throw_cusparse(status);
status =
cusparseSetMatType(descr_b, CUSPARSE_MATRIX_TYPE_GENERAL);
BCL::cuda::throw_cusparse(status);
status =
cusparseSetMatIndexBase(descr_b, CUSPARSE_INDEX_BASE_ZERO);
BCL::cuda::throw_cusparse(status);
status =
cusparseSetMatType(descr_c, CUSPARSE_MATRIX_TYPE_GENERAL);
BCL::cuda::throw_cusparse(status);
status =
cusparseSetMatIndexBase(descr_c, CUSPARSE_INDEX_BASE_ZERO);
BCL::cuda::throw_cusparse(status);
index_type a_nnz = a.nnz();
index_type b_nnz = b.nnz();
index_type c_nnz;
index_type* nnzTotalDevHostPtr;
nnzTotalDevHostPtr = &c_nnz;
index_type* row_ptr_c;
row_ptr_c = rebind_allocator_t<Allocator, index_type>{}.allocate(m+1);
if (row_ptr_c == nullptr) {
throw std::runtime_error("Couldn't allocate C.");
}
index_type* a_row_ptr = a.rowptr_data();
index_type* a_col_ind = a.colind_data();
index_type* b_row_ptr = b.rowptr_data();
index_type* b_col_ind = b.colind_data();
status =
cusparseXcsrgeamNnz(handle,
m,
n,
descr_a,
a_nnz,
a_row_ptr,
a_col_ind,
descr_b,
b_nnz,
b_row_ptr,
b_col_ind,
descr_c,
row_ptr_c,
nnzTotalDevHostPtr);
BCL::cuda::throw_cusparse(status);
if (nnzTotalDevHostPtr == nullptr) {
throw std::runtime_error("Unhandled case: nnzTotalDevHostPtr is null.");
} else {
c_nnz = *nnzTotalDevHostPtr;
}
T alpha = 1.0;
T beta = 1.0;
index_type* col_ind_c;
T* values_c;
col_ind_c = rebind_allocator_t<Allocator, index_type>{}.allocate(c_nnz);
values_c = rebind_allocator_t<Allocator, T>{}.allocate(c_nnz);
if (col_ind_c == nullptr || values_c == nullptr) {
throw std::runtime_error("sum_tiles(): out of memory.");
}
status =
cusparseScsrgeam(handle,
m,
n,
&alpha,
descr_a,
a_nnz,
a.values_data(),
a.rowptr_data(),
a.colind_data(),
&beta,
descr_b,
b_nnz,
b.values_data(),
b.rowptr_data(),
b.colind_data(),
descr_c,
values_c,
row_ptr_c,
col_ind_c);
BCL::cuda::throw_cusparse(status);
cudaDeviceSynchronize();
return CudaCSRMatrix<T, index_type, Allocator>({m, n}, c_nnz, values_c, row_ptr_c, col_ind_c);
}
template <typename T, typename index_type, typename Allocator>
CudaCSRMatrix<T, index_type, Allocator>
sum_tiles_cusparse(std::vector<CudaCSRMatrix<T, index_type, Allocator>>& imp) {
using csr_type = CudaCSRMatrix<T, index_type, Allocator>;
if (imp.size() == 0) {
return csr_type({0, 0}, 0);
}
csr_type sum = std::move(imp[0]);
for (size_t i = 1; i < imp.size(); i++) {
csr_type comp = std::move(imp[i]);
csr_type result = sum_cusparse<T, index_type, Allocator>(sum, comp);
std::swap(sum, result);
}
return sum;
}
template <typename T, typename index_type, typename Allocator>
bool is_shared_seg(CudaCSRMatrix<T, index_type, Allocator>& mat) {
if (!__is_valid_cuda_gptr(mat.values_data())) {
return false;
} else if (!__is_valid_cuda_gptr(mat.rowptr_data())) {
return false;
} else if (!__is_valid_cuda_gptr(mat.colind_data())) {
return false;
} else {
return true;
}
}
template <typename T, typename index_type, typename Allocator>
CudaCSRMatrix<T, index_type, Allocator>
spgemm_cusparse(CudaCSRMatrix<T, index_type, Allocator>& a,
CudaCSRMatrix<T, index_type, Allocator>& b)
{
// static assert index_type is graphblas::Index
grb_desc_->descriptor_.debug_ = false;
if (a.nnz() == 0 || b.nnz() == 0) {
// return empty matrix
return CudaCSRMatrix<T, index_type, Allocator>({a.shape()[0], b.shape()[1]}, 0);
} else {
size_t m = a.m();
size_t n = b.n();
size_t k = a.n();
cusparseHandle_t handle;
cusparseStatus_t status = cusparseCreate(&handle);
BCL::cuda::throw_cusparse(status);
status = cusparseSetPointerMode(handle, CUSPARSE_POINTER_MODE_HOST);
BCL::cuda::throw_cusparse(status);
int baseC, nnzC;
csrgemm2Info_t info = nullptr;
size_t bufferSize;
char* buffer = nullptr;
// nnzTotalDevHostPtr points to host memory
int* nnzTotalDevHostPtr = &nnzC;
T alpha = 1;
T beta = 0;
cusparseSetPointerMode(handle, CUSPARSE_POINTER_MODE_HOST);
cusparseMatDescr_t descr;
cusparseCreateMatDescr(&descr);
cusparseSetMatType(descr, CUSPARSE_MATRIX_TYPE_GENERAL);
cusparseSetMatIndexBase(descr, CUSPARSE_INDEX_BASE_ZERO);
// step1: create an opaque structure
cusparseCreateCsrgemm2Info(&info);
status =
cusparseScsrgemm2_bufferSizeExt(handle, m, n, k, &alpha,
descr, a.nnz(), a.rowptr_data(), a.colind_data(),
descr, b.nnz(), b.rowptr_data(), b.colind_data(),
&beta,
descr, b.nnz(), b.rowptr_data(), b.colind_data(),
info,
&bufferSize);
BCL::cuda::throw_cusparse(status);
buffer = allocate_with<char, Allocator>(bufferSize);
// step 3: compute csrRowPtrC
index_type* csrRowPtrC = allocate_with<index_type, Allocator>(m+1);
status =
cusparseXcsrgemm2Nnz(handle, m, n, k,
descr, a.nnz(), a.rowptr_data(), a.colind_data(),
descr, b.nnz(), b.rowptr_data(), b.colind_data(),
descr, b.nnz(), b.rowptr_data(), b.colind_data(),
descr, csrRowPtrC, nnzTotalDevHostPtr, info, buffer);
BCL::cuda::throw_cusparse(status);
if (nnzTotalDevHostPtr != nullptr) {
nnzC = *nnzTotalDevHostPtr;
} else {
cudaMemcpy(&nnzC, csrRowPtrC+m, sizeof(index_type), cudaMemcpyDeviceToHost);
cudaMemcpy(&baseC, csrRowPtrC, sizeof(index_type), cudaMemcpyDeviceToHost);
nnzC -= baseC;
}
// step 4: finish sparsity pattern and value of C
index_type* csrColIndC = allocate_with<index_type, Allocator>(nnzC);
T* csrValC = allocate_with<T, Allocator>(nnzC);
// Remark: set csrValC to null if only sparsity pattern is required.
status =
cusparseScsrgemm2(handle, m, n, k, &alpha,
descr, a.nnz(), a.values_data(), a.rowptr_data(), a.colind_data(),
descr, b.nnz(), b.values_data(), b.rowptr_data(), b.colind_data(),
&beta,
descr, b.nnz(), b.values_data(), b.rowptr_data(), b.colind_data(),
descr, csrValC, csrRowPtrC, csrColIndC,
info, buffer);
BCL::cuda::throw_cusparse(status);
cudaDeviceSynchronize();
// step 5: destroy the opaque structure
cusparseDestroyCsrgemm2Info(info);
deallocate_with<char, Allocator>(buffer);
cusparseDestroy(handle);
return CudaCSRMatrix<T, index_type, Allocator>({m, n}, nnzC, csrValC, csrRowPtrC, csrColIndC);
}
}
template <typename AMatrixType, typename BMatrixType, typename CMatrixType>
void spmm_cusparse(AMatrixType& a,
BMatrixType& b,
CMatrixType& c)
{
using Allocator = typename AMatrixType::allocator_type;
if (a.nnz() == 0) {
return;
}
static_assert(std::is_same<typename AMatrixType::value_type, float>::value);
static_assert(std::is_same<typename BMatrixType::value_type, float>::value);
static_assert(std::is_same<typename CMatrixType::value_type, float>::value);
static_assert(std::is_same<typename AMatrixType::index_type, int32_t>::value);
cusparseHandle_t handle;
cusparseStatus_t status = cusparseCreate(&handle);
BCL::cuda::throw_cusparse(status);
cusparseSpMatDescr_t a_cusparse;
status =
cusparseCreateCsr(&a_cusparse, a.m(), a.n(), a.nnz(),
a.rowptr_data(), a.colind_data(), a.values_data(),
CUSPARSE_INDEX_32I, CUSPARSE_INDEX_32I,
CUSPARSE_INDEX_BASE_ZERO, CUDA_R_32F);
BCL::cuda::throw_cusparse(status);
cusparseDnMatDescr_t b_cusparse;
status =
cusparseCreateDnMat(&b_cusparse, b.m(), b.n(), b.ld(),
b.data(), CUDA_R_32F, CUSPARSE_ORDER_COL);
BCL::cuda::throw_cusparse(status);
cusparseDnMatDescr_t c_cusparse;
status =
cusparseCreateDnMat(&c_cusparse, c.m(), c.n(), c.ld(),
c.data(), CUDA_R_32F, CUSPARSE_ORDER_COL);
BCL::cuda::throw_cusparse(status);
T alpha = 1.0;
T beta = 1.0;
size_t bufferSize;
status =
cusparseSpMM_bufferSize(handle,
CUSPARSE_OPERATION_NON_TRANSPOSE,
CUSPARSE_OPERATION_NON_TRANSPOSE,
&alpha,
a_cusparse,
b_cusparse,
&beta,
c_cusparse,
CUDA_R_32F,
CUSPARSE_MM_ALG_DEFAULT,
&bufferSize);
BCL::cuda::throw_cusparse(status);
char* externalBuffer = allocate_with<char, Allocator>(bufferSize);
status =
cusparseSpMM(handle,
CUSPARSE_OPERATION_NON_TRANSPOSE,
CUSPARSE_OPERATION_NON_TRANSPOSE,
&alpha,
a_cusparse,
b_cusparse,
&beta,
c_cusparse,
CUDA_R_32F,
CUSPARSE_MM_ALG_DEFAULT,
externalBuffer);
BCL::cuda::throw_cusparse(status);
cudaDeviceSynchronize();
deallocate_with<char, Allocator>(externalBuffer);
cusparseDestroy(handle);
cusparseDestroySpMat(a_cusparse);
cusparseDestroyDnMat(b_cusparse);
cusparseDestroyDnMat(c_cusparse);
}
// TODO: Put this in another file
template <typename T, typename index_type, typename Allocator = BCL::bcl_allocator<T>>
CudaCSRMatrix<T, index_type, Allocator> to_gpu(CSRMatrix<T, index_type>& mat) {
CudaCSRMatrix<T, index_type, Allocator> mat_gpu({mat.m(), mat.n()}, mat.nnz());
cudaMemcpy(mat_gpu.values_data(), mat.values_data(), sizeof(T)*mat.nnz(), cudaMemcpyHostToDevice);
cudaMemcpy(mat_gpu.rowptr_data(), mat.rowptr_data(), sizeof(index_type)*(mat.m()+1), cudaMemcpyHostToDevice);
cudaMemcpy(mat_gpu.colind_data(), mat.colind_data(), sizeof(index_type)*mat.nnz(), cudaMemcpyHostToDevice);
return mat_gpu;
}
} // end cuda
} // end BCL
| 33.223404
| 126
| 0.631871
|
ge49nuk
|
8d1a59c4632d463f2ba79946c7d246130b41d12c
| 57,743
|
cpp
|
C++
|
fsck/source/modes/ModeCheckFS.cpp
|
TomatoYoung/beegfs
|
edf287940175ecded493183209719d2d90d45374
|
[
"BSD-3-Clause"
] | null | null | null |
fsck/source/modes/ModeCheckFS.cpp
|
TomatoYoung/beegfs
|
edf287940175ecded493183209719d2d90d45374
|
[
"BSD-3-Clause"
] | null | null | null |
fsck/source/modes/ModeCheckFS.cpp
|
TomatoYoung/beegfs
|
edf287940175ecded493183209719d2d90d45374
|
[
"BSD-3-Clause"
] | null | null | null |
#include "ModeCheckFS.h"
#include <common/toolkit/DisposalCleaner.h>
#include <common/toolkit/ListTk.h>
#include <common/toolkit/UnitTk.h>
#include <common/toolkit/UiTk.h>
#include <common/toolkit/ZipIterator.h>
#include <components/DataFetcher.h>
#include <components/worker/RetrieveChunksWork.h>
#include <net/msghelpers/MsgHelperRepair.h>
#include <toolkit/DatabaseTk.h>
#include <toolkit/FsckTkEx.h>
#include <program/Program.h>
#include <ftw.h>
#include <boost/lexical_cast.hpp>
template<unsigned Actions>
UserPrompter::UserPrompter(const FsckRepairAction (&possibleActions)[Actions],
FsckRepairAction defaultRepairAction)
: askForAction(true), possibleActions(possibleActions, possibleActions + Actions),
repairAction(FsckRepairAction_UNDEFINED)
{
if(Program::getApp()->getConfig()->getReadOnly() )
askForAction = false;
else
if(Program::getApp()->getConfig()->getAutomatic() )
{
askForAction = false;
repairAction = defaultRepairAction;
}
}
FsckRepairAction UserPrompter::chooseAction(const std::string& prompt)
{
if(askForAction)
FsckTkEx::fsckOutput("> " + prompt, OutputOptions_LINEBREAK | OutputOptions_NOLOG);
FsckTkEx::fsckOutput("> " + prompt, OutputOptions_NOSTDOUT);
while(askForAction)
{
for(size_t i = 0; i < possibleActions.size(); i++)
{
FsckTkEx::fsckOutput(
" " + StringTk::uintToStr(i + 1) + ") "
+ FsckTkEx::getRepairActionDesc(possibleActions[i]), OutputOptions_NOLOG |
OutputOptions_LINEBREAK);
}
for(size_t i = 0; i < possibleActions.size(); i++)
{
FsckTkEx::fsckOutput(
" " + StringTk::uintToStr(i + possibleActions.size() + 1) + ") "
+ FsckTkEx::getRepairActionDesc(possibleActions[i]) + " (apply for all)",
OutputOptions_NOLOG | OutputOptions_LINEBREAK);
}
std::string inputStr;
getline(std::cin, inputStr);
unsigned input = StringTk::strToUInt(inputStr);
if( (input > 0) && (input <= possibleActions.size() ) )
{
// user chose for this error
repairAction = possibleActions[input - 1];
break;
}
if( (input > possibleActions.size() ) && (input <= possibleActions.size() * 2) )
{
// user chose for all errors => do not ask again
askForAction = false;
repairAction = possibleActions[input - possibleActions.size() - 1];
break;
}
}
FsckTkEx::fsckOutput(" - [ra: " + FsckTkEx::getRepairActionDesc(repairAction, true) + "]",
OutputOptions_LINEBREAK | OutputOptions_NOSTDOUT);
return repairAction;
}
static FhgfsOpsErr handleDisposalItem(Node& owner, const std::string& entryID,
const bool isMirrored)
{
FhgfsOpsErr err = DisposalCleaner::unlinkFile(owner, entryID, isMirrored);
if (err == FhgfsOpsErr_INUSE)
return FhgfsOpsErr_SUCCESS;
else
return err;
}
ModeCheckFS::ModeCheckFS()
: log("ModeCheckFS")
{
}
ModeCheckFS::~ModeCheckFS()
{
}
void ModeCheckFS::printHelp()
{
std::cout <<
"MODE ARGUMENTS:\n"
" Optional:\n"
" --readOnly Check only, skip repairs.\n"
" --runOffline Run in offline mode, which disables the modification\n"
" logging. Use this only if you are sure there is no user\n"
" access to the file system while the check is running.\n"
" --automatic Do not prompt for repair actions and automatically use\n"
" reasonable default actions.\n"
" --noFetch Do not build a new database from the servers and\n"
" instead work on an existing database (e.g. from a\n"
" previous read-only run).\n"
" --quotaEnabled Enable checks for quota support.\n"
" --databasePath=<path> Path to store for the database files. On systems with \n"
" many files, the database can grow to a size of several \n"
" 100 GB.\n"
" (Default: " CONFIG_DEFAULT_DBPATH ")\n"
" --overwriteDbFile Overwrite an existing database file without prompt.\n"
" --ignoreDBDiskSpace Ignore free disk space check for database file.\n"
" --logOutFile=<path> Path to the fsck output file, which contains a copy of\n"
" the console output.\n"
" (Default: " CONFIG_DEFAULT_OUTFILE ")\n"
" --logStdFile=<path> Path to the program error log file, which contains e.g.\n"
" network error messages.\n"
" (Default: " CONFIG_DEFAULT_LOGFILE ")\n"
" --forceRestart Restart check even though another instance seems to be running.\n"
" Use only if a previous run was aborted, and make sure no other\n"
" fsck is running on the same file system at the same time.\n"
"\n"
"USAGE:\n"
" This mode performs a full check and optional repair of a BeeGFS file system\n"
" instance by building a database of the current file system contents on the\n"
" local machine.\n"
"\n"
" The fsck gathers information from all BeeGFS server daemons in parallel through\n"
" their configured network interfaces. All server components of the file\n"
" system have to be running to start a check.\n"
"\n"
" If the fsck is running with the \"--runoffline\" argument, users may not\n"
" access the file system during a run (otherwise false errors might be reported).\n"
"\n"
" Example: Check for errors, but skip repairs\n"
" $ beegfs-fsck --checkfs --readonly\n";
std::cout << std::flush;
}
int ModeCheckFS::execute()
{
App* app = Program::getApp();
Config *cfg = app->getConfig();
std::string databasePath = cfg->getDatabasePath();
if ( this->checkInvalidArgs(cfg->getUnknownConfigArgs()) )
return APPCODE_INVALID_CONFIG;
FsckTkEx::printVersionHeader(false);
printHeaderInformation();
if (cfg->getNoFetch() && !Program::getApp()->getConfig()->getReadOnly()) {
FsckTkEx::fsckOutput(
" WARNING: RISK OF DATA LOSS!\n"
" NEVER USE THE SAME DATABASE TWICE!\n\n"
"After running fsck, any database obtained previously no longer matches the state\n"
"of the filesystem. A new database MUST be obtained before running fsck again.\n\n"
"You are seeing this warning because you are using the option --nofetch.",
OutputOptions_DOUBLELINEBREAK | OutputOptions_ADDLINEBREAKBEFORE);
if (!uitk::userYNQuestion("Do you wish to continue?"))
return APPCODE_USER_ABORTED;
}
if ( !FsckTkEx::checkReachability() )
return APPCODE_COMMUNICATION_ERROR;
if (!FsckTkEx::checkConsistencyStates())
{
FsckTkEx::fsckOutput("At least one meta or storage target is in NEEDS_RESYNC state. "
"To prevent interference between fsck and resync operations, fsck will abort now. "
"Please make sure that no resyncs are currently pending or running.",
OutputOptions_DOUBLELINEBREAK | OutputOptions_ADDLINEBREAKBEFORE);
return APPCODE_RUNTIME_ERROR;
}
if(cfg->getNoFetch() )
{
try {
this->database.reset(new FsckDB(databasePath + "/fsckdb", cfg->getTuneDbFragmentSize(),
cfg->getTuneDentryCacheSize(), false) );
} catch (const FragmentDoesNotExist& e) {
std::string err = "Database was found to be incomplete in path " + databasePath;
log.logErr(err);
FsckTkEx::fsckOutput(err);
return APPCODE_RUNTIME_ERROR;
}
}
else
{
int initDBRes = initDatabase();
if (initDBRes)
return initDBRes;
disposeUnusedFiles();
boost::scoped_ptr<ModificationEventHandler> modificationEventHandler;
if (!cfg->getRunOffline())
{
modificationEventHandler.reset(
new ModificationEventHandler(*this->database->getModificationEventsTable() ) );
modificationEventHandler->start();
Program::getApp()->setModificationEventHandler(modificationEventHandler.get() );
// start modification logging
auto startLogRes = FsckTkEx::startModificationLogging(app->getMetaNodes(),
app->getLocalNode(), cfg->getForceRestart());
if (startLogRes != FhgfsOpsErr_SUCCESS)
{
std::string errStr;
switch (startLogRes)
{
case FhgfsOpsErr_INUSE:
errStr = "Another instance of beegfs-fsck is still running or was aborted. "
"Cannot start a new one unless --forceRestart command line switch is used. "
"Do this only after making sure there is no other instance of beefs-fsck "
"running.";
// stop the modification event handler
Program::getApp()->setModificationEventHandler(NULL);
modificationEventHandler->selfTerminate();
modificationEventHandler->join();
break;
default:
errStr = "Unable to start file system modification logging. "
"Fsck cannot proceed.";
}
log.logErr(errStr);
FsckTkEx::fsckOutput(errStr);
return APPCODE_RUNTIME_ERROR;
}
}
FhgfsOpsErr gatherDataRes = gatherData(cfg->getForceRestart());
if (!cfg->getRunOffline())
{
// stop modification logging
bool eventLoggingOK = FsckTkEx::stopModificationLogging(app->getMetaNodes());
// stop mod event handler (to make it flush for the last time
Program::getApp()->setModificationEventHandler(NULL);
modificationEventHandler->selfTerminate();
modificationEventHandler->join();
// if event logging is not OK (i.e. that not all events might have been processed), go
// into read-only mode
if ( !eventLoggingOK )
{
Program::getApp()->getConfig()->disableAutomaticRepairMode();
Program::getApp()->getConfig()->setReadOnly();
FsckTkEx::fsckOutput("-----",
OutputOptions_ADDLINEBREAKBEFORE | OutputOptions_FLUSH | OutputOptions_LINEBREAK);
FsckTkEx::fsckOutput(
"WARNING: Fsck did not get all modification events from metadata servers.",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
FsckTkEx::fsckOutput(
"For instance, this might have happened due to network timeouts.",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
FsckTkEx::fsckOutput(
"This means beegfs-fsck is not aware of all changes in the filesystem and it is "
"not safe to execute repair actions. "
"In the worst case executing repair actions can result in data loss.",
OutputOptions_FLUSH | OutputOptions_DOUBLELINEBREAK);
FsckTkEx::fsckOutput(
"Thus, read-only mode was automatically enabled. "
"You can still force repair by running beegfs-fsck again on the existing "
"database with the -noFetch option.",
OutputOptions_FLUSH | OutputOptions_DOUBLELINEBREAK);
FsckTkEx::fsckOutput("Please press any key to continue.",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
FsckTkEx::fsckOutput("-----", OutputOptions_FLUSH | OutputOptions_DOUBLELINEBREAK);
std::cin.get();
}
}
if (gatherDataRes != FhgfsOpsErr_SUCCESS)
{
std::string errStr;
switch (gatherDataRes)
{
case FhgfsOpsErr_INUSE:
errStr = "Another instance of beegfs-fsck is still running or was aborted. "
"Cannot start a new one unless --forceRestart command line switch is used. "
"Do this only after making sure there is no other instance of beefs-fsck "
"running.";
break;
default:
errStr = "An error occured while fetching data from servers. Fsck cannot proceed. "
"Please see log file for more information.";
}
log.logErr(errStr);
FsckTkEx::fsckOutput(errStr);
return APPCODE_RUNTIME_ERROR;
}
}
checkAndRepair();
return APPCODE_NO_ERROR;
}
/*
* initializes the database, this is done here and not inside the main app, because we do not want
* it to effect the help modes; DB file shall only be created if user really runs a check
*
* @return integer value symbolizing an appcode
*/
int ModeCheckFS::initDatabase()
{
Config* cfg = Program::getApp()->getConfig();
// create the database path
Path dbPath(cfg->getDatabasePath() + "/fsckdb");
if ( !StorageTk::createPathOnDisk(dbPath, false) )
{
FsckTkEx::fsckOutput("Could not create path for database files: " +
dbPath.str());
return APPCODE_INITIALIZATION_ERROR;
}
// check disk space
if ( !FsckTkEx::checkDiskSpace(dbPath) )
return APPCODE_INITIALIZATION_ERROR;
// check if DB file path already exists and is not empty
if ( StorageTk::pathExists(dbPath.str())
&& StorageTk::pathHasChildren(dbPath.str()) && (!cfg->getOverwriteDbFile()) )
{
FsckTkEx::fsckOutput("The database path already exists: " + dbPath.str());
FsckTkEx::fsckOutput("If you continue now any existing database files in that path will be "
"deleted.");
std::string input;
while (input.size() != 1 || !strchr("YyNn", input[0]))
{
FsckTkEx::fsckOutput("Do you want to continue? (Y/N)");
std::getline(std::cin, input);
}
switch (input[0])
{
case 'Y':
case 'y':
break; // just do nothing and go ahead
case 'N':
case 'n':
default:
// abort here
return APPCODE_USER_ABORTED;
}
}
struct ops
{
static int visit(const char* path, const struct stat*, int type, struct FTW* state)
{
if(state->level == 0)
return 0;
else
if(type == FTW_F || type == FTW_SL)
return ::unlink(path);
else
return ::rmdir(path);
}
};
int ftwRes = ::nftw(dbPath.str().c_str(), ops::visit, 10, FTW_DEPTH | FTW_PHYS);
if(ftwRes)
{
FsckTkEx::fsckOutput("Could not empty path for database files: " + dbPath.str() );
return APPCODE_INITIALIZATION_ERROR;
}
try {
this->database.reset(
new FsckDB(dbPath.str(), cfg->getTuneDbFragmentSize(),
cfg->getTuneDentryCacheSize(), true) );
} catch (const std::runtime_error& e) {
FsckTkEx::fsckOutput("Database " + dbPath.str() + " is corrupt");
return APPCODE_RUNTIME_ERROR;
}
return 0;
}
void ModeCheckFS::printHeaderInformation()
{
Config* cfg = Program::getApp()->getConfig();
// get the current time and create some nice output, so the user can see at which time the run
// was started (especially nice to find older runs in the log file)
time_t t;
time(&t);
std::string timeStr = std::string(ctime(&t));
FsckTkEx::fsckOutput(
"Started BeeGFS fsck in forward check mode [" + timeStr.substr(0, timeStr.length() - 1)
+ "]\nLog will be written to " + cfg->getLogStdFile() + "\nDatabase will be saved in "
+ cfg->getDatabasePath(), OutputOptions_LINEBREAK | OutputOptions_HEADLINE);
if (Program::getApp()->getMetaMirrorBuddyGroupMapper()->getSize() > 0)
{
FsckTkEx::fsckOutput(
"IMPORTANT NOTICE: The initiation of a repair action on a metadata mirror group "
"will temporarily set the consistency state of the secondary node to bad to prevent "
"interaction during the repair. After fsck finishes, it will set the states "
"of all affected nodes to needs-resync, so the repaired data will be synced from their "
"primary. \n\nIf beegfs-fsck is aborted prematurely, a resync needs to be initiated "
"manually so all targets are consistent (good) again." ,
OutputOptions_DOUBLELINEBREAK | OutputOptions_HEADLINE);
}
}
void ModeCheckFS::disposeUnusedFiles()
{
Config* cfg = Program::getApp()->getConfig();
if (cfg->getReadOnly() || cfg->getNoFetch())
return;
FsckTkEx::fsckOutput("Step 2: Delete unused files from disposal: ", OutputOptions_NONE);
using namespace std::placeholders;
uint64_t errors = 0;
DisposalCleaner dc(*Program::getApp()->getMetaMirrorBuddyGroupMapper());
dc.run(Program::getApp()->getMetaNodes()->referenceAllNodes(),
handleDisposalItem,
[&] (const auto&, const auto&) { errors += 1; });
if (errors > 0)
FsckTkEx::fsckOutput("Some files could not be deleted.");
else
FsckTkEx::fsckOutput("Finished.");
}
FhgfsOpsErr ModeCheckFS::gatherData(bool forceRestart)
{
FsckTkEx::fsckOutput("Step 3: Gather data from nodes: ", OutputOptions_DOUBLELINEBREAK);
DataFetcher dataFetcher(*this->database, forceRestart);
const FhgfsOpsErr retVal = dataFetcher.execute();
FsckTkEx::fsckOutput("", OutputOptions_LINEBREAK);
return retVal;
}
template<typename Obj, typename State>
int64_t ModeCheckFS::checkAndRepairGeneric(Cursor<Obj> cursor,
void (ModeCheckFS::*repair)(Obj&, State&), State& state)
{
int64_t errorCount = 0;
while(cursor.step() )
{
Obj* entry = cursor.get();
(this->*repair)(*entry, state);
errorCount++;
}
if(errorCount)
{
database->getDentryTable()->commitChanges();
database->getFileInodesTable()->commitChanges();
database->getDirInodesTable()->commitChanges();
database->getChunksTable()->commitChanges();
database->getContDirsTable()->commitChanges();
database->getFsIDsTable()->commitChanges();
FsckTkEx::fsckOutput(">>> Found " + StringTk::int64ToStr(errorCount)
+ " errors. Detailed information can also be found in "
+ Program::getApp()->getConfig()->getLogOutFile() + ".",
OutputOptions_DOUBLELINEBREAK);
}
else
{
FsckTkEx::fsckOutput(">>> None found", OutputOptions_FLUSH | OutputOptions_LINEBREAK);
}
return errorCount;
}
int64_t ModeCheckFS::checkAndRepairDanglingDentry()
{
FsckRepairAction fileActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_DELETEDENTRY,
};
FsckRepairAction dirActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_DELETEDENTRY,
FsckRepairAction_CREATEDEFAULTDIRINODE,
};
UserPrompter forFiles(fileActions, FsckRepairAction_DELETEDENTRY);
UserPrompter forDirs(dirActions, FsckRepairAction_CREATEDEFAULTDIRINODE);
std::pair<UserPrompter*, UserPrompter*> prompt(&forFiles, &forDirs);
FsckTkEx::fsckOutput("* Checking: Dangling directory entry ...",
OutputOptions_FLUSH |OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findDanglingDirEntries(),
&ModeCheckFS::repairDanglingDirEntry, prompt);
}
int64_t ModeCheckFS::checkAndRepairWrongInodeOwner()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_CORRECTOWNER,
};
UserPrompter prompt(possibleActions, FsckRepairAction_CORRECTOWNER);
FsckTkEx::fsckOutput("* Checking: Wrong owner node saved in inode ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findInodesWithWrongOwner(),
&ModeCheckFS::repairWrongInodeOwner, prompt);
}
int64_t ModeCheckFS::checkAndRepairWrongOwnerInDentry()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_CORRECTOWNER,
};
UserPrompter prompt(possibleActions, FsckRepairAction_CORRECTOWNER);
FsckTkEx::fsckOutput("* Checking: Dentry points to inode on wrong node ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findDirEntriesWithWrongOwner(),
&ModeCheckFS::repairWrongInodeOwnerInDentry, prompt);
}
int64_t ModeCheckFS::checkAndRepairOrphanedContDir()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_CREATEDEFAULTDIRINODE,
};
UserPrompter prompt(possibleActions, FsckRepairAction_CREATEDEFAULTDIRINODE);
FsckTkEx::fsckOutput("* Checking: Content directory without an inode ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findOrphanedContDirs(),
&ModeCheckFS::repairOrphanedContDir, prompt);
}
int64_t ModeCheckFS::checkAndRepairOrphanedDirInode()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_LOSTANDFOUND,
};
UserPrompter prompt(possibleActions, FsckRepairAction_LOSTANDFOUND);
FsckTkEx::fsckOutput("* Checking: Dir inode without a dentry pointing to it (orphaned inode) ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
bool result = checkAndRepairGeneric(this->database->findOrphanedDirInodes(),
&ModeCheckFS::repairOrphanedDirInode, prompt);
releaseLostAndFound();
return result;
}
int64_t ModeCheckFS::checkAndRepairOrphanedFileInode()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_DELETEINODE,
//FsckRepairAction_LOSTANDFOUND,
};
UserPrompter prompt(possibleActions, FsckRepairAction_DELETEINODE);
FsckTkEx::fsckOutput("* Checking: File inode without a dentry pointing to it (orphaned inode) ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findOrphanedFileInodes(),
&ModeCheckFS::repairOrphanedFileInode, prompt);
}
int64_t ModeCheckFS::checkAndRepairOrphanedChunk()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
};
UserPrompter prompt(possibleActions, FsckRepairAction_NOTHING);
RepairChunkState state = { &prompt, "", FsckRepairAction_UNDEFINED };
FsckTkEx::fsckOutput("* Checking: Chunk without an inode pointing to it (orphaned chunk) ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findOrphanedChunks(),
&ModeCheckFS::repairOrphanedChunk, state);
}
int64_t ModeCheckFS::checkAndRepairMissingContDir()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_CREATECONTDIR,
};
UserPrompter prompt(possibleActions, FsckRepairAction_CREATECONTDIR);
FsckTkEx::fsckOutput("* Checking: Directory inode without a content directory ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findInodesWithoutContDir(),
&ModeCheckFS::repairMissingContDir, prompt);
}
int64_t ModeCheckFS::checkAndRepairWrongFileAttribs()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_UPDATEATTRIBS,
};
UserPrompter prompt(possibleActions, FsckRepairAction_UPDATEATTRIBS);
FsckTkEx::fsckOutput("* Checking: Attributes of file inode are wrong ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findWrongInodeFileAttribs(),
&ModeCheckFS::repairWrongFileAttribs, prompt);
}
int64_t ModeCheckFS::checkAndRepairWrongDirAttribs()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_UPDATEATTRIBS,
};
UserPrompter prompt(possibleActions, FsckRepairAction_UPDATEATTRIBS);
FsckTkEx::fsckOutput("* Checking: Attributes of dir inode are wrong ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findWrongInodeDirAttribs(),
&ModeCheckFS::repairWrongDirAttribs, prompt);
}
int64_t ModeCheckFS::checkAndRepairFilesWithMissingTargets()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_DELETEFILE,
};
UserPrompter prompt(possibleActions, FsckRepairAction_NOTHING);
FsckTkEx::fsckOutput("* Checking: File has a missing target in stripe pattern ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(
this->database->findFilesWithMissingStripeTargets(
Program::getApp()->getTargetMapper(), Program::getApp()->getMirrorBuddyGroupMapper() ),
&ModeCheckFS::repairFileWithMissingTargets, prompt);
}
int64_t ModeCheckFS::checkAndRepairDirEntriesWithBrokeByIDFile()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_RECREATEFSID,
};
UserPrompter prompt(possibleActions, FsckRepairAction_RECREATEFSID);
FsckTkEx::fsckOutput("* Checking: Dentry-by-ID file is broken or missing ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findDirEntriesWithBrokenByIDFile(),
&ModeCheckFS::repairDirEntryWithBrokenByIDFile, prompt);
}
int64_t ModeCheckFS::checkAndRepairOrphanedDentryByIDFiles()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_RECREATEDENTRY,
};
UserPrompter prompt(possibleActions, FsckRepairAction_RECREATEDENTRY);
FsckTkEx::fsckOutput("* Checking: Dentry-by-ID file is present, but no corresponding dentry ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findOrphanedFsIDFiles(),
&ModeCheckFS::repairOrphanedDentryByIDFile, prompt);
}
int64_t ModeCheckFS::checkAndRepairChunksWithWrongPermissions()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_FIXPERMISSIONS,
};
UserPrompter prompt(possibleActions, FsckRepairAction_FIXPERMISSIONS);
FsckTkEx::fsckOutput("* Checking: Chunk has wrong permissions ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findChunksWithWrongPermissions(),
&ModeCheckFS::repairChunkWithWrongPermissions, prompt);
}
// no repair at the moment
int64_t ModeCheckFS::checkAndRepairChunksInWrongPath()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_MOVECHUNK,
};
UserPrompter prompt(possibleActions, FsckRepairAction_MOVECHUNK);
FsckTkEx::fsckOutput("* Checking: Chunk is saved in wrong path ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findChunksInWrongPath(),
&ModeCheckFS::repairWrongChunkPath, prompt);
}
int64_t ModeCheckFS::checkDuplicateInodeIDs()
{
FsckTkEx::fsckOutput("* Checking: Duplicated inode IDs ... ",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
int dummy = 0;
return checkAndRepairGeneric(this->database->findDuplicateInodeIDs(),
&ModeCheckFS::logDuplicateInodeID, dummy);
}
void ModeCheckFS::logDuplicateInodeID(checks::DuplicatedInode& dups, int&)
{
FsckTkEx::fsckOutput(">>> Found duplicated ID " + dups.first.str(),
OutputOptions_LINEBREAK | OutputOptions_NOSTDOUT);
for(const auto& it : dups.second)
{
FsckTkEx::fsckOutput(" * Found on " + std::string(it.second ? "buddy group " : "node ")
+ StringTk::uintToStr(it.first), OutputOptions_LINEBREAK | OutputOptions_NOSTDOUT);
}
}
int64_t ModeCheckFS::checkDuplicateChunks()
{
FsckTkEx::fsckOutput("* Checking: Duplicated chunks ...", OutputOptions_FLUSH | OutputOptions_LINEBREAK);
int dummy = 0;
return checkAndRepairGeneric(this->database->findDuplicateChunks(),
&ModeCheckFS::logDuplicateChunk, dummy);
}
void ModeCheckFS::logDuplicateChunk(std::list<FsckChunk>& dups, int&)
{
FsckTkEx::fsckOutput(">>> Found duplicated Chunks for ID " + dups.begin()->getID(),
OutputOptions_LINEBREAK | OutputOptions_NOSTDOUT);
for(std::list<FsckChunk>::iterator it = dups.begin(), end = dups.end();
it != end; ++it)
{
FsckTkEx::fsckOutput(" * Found on target " + StringTk::uintToStr(it->getTargetID() )
+ (it->getBuddyGroupID()
? ", buddy group " + StringTk::uintToStr(it->getBuddyGroupID() )
: "")
+ " in path " + it->getSavedPath()->str(),
OutputOptions_LINEBREAK | OutputOptions_NOSTDOUT);
}
}
int64_t ModeCheckFS::checkDuplicateContDirs()
{
FsckTkEx::fsckOutput("* Checking: Duplicated content directores ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
int dummy = 0;
return checkAndRepairGeneric(this->database->findDuplicateContDirs(),
&ModeCheckFS::logDuplicateContDir, dummy);
}
void ModeCheckFS::logDuplicateContDir(std::list<db::ContDir>& dups, int&)
{
FsckTkEx::fsckOutput(">>> Found duplicated content directories for ID " + dups.front().id.str(),
OutputOptions_LINEBREAK | OutputOptions_NOSTDOUT);
for (auto it = dups.begin(), end = dups.end(); it != end; ++it)
{
FsckTkEx::fsckOutput(" * Found on " +
std::string(it->isBuddyMirrored ? "buddy group " : "node ") +
StringTk::uintToStr(it->saveNodeID),
OutputOptions_LINEBREAK | OutputOptions_NOSTDOUT);
}
}
int64_t ModeCheckFS::checkMismirroredDentries()
{
FsckTkEx::fsckOutput("* Checking: Bad target mirror information in dentry ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
int dummy = 0;
return checkAndRepairGeneric(this->database->findMismirroredDentries(),
&ModeCheckFS::logMismirroredDentry, dummy);
}
void ModeCheckFS::logMismirroredDentry(db::DirEntry& entry, int&)
{
FsckTkEx::fsckOutput(">>> Found mismirrored dentry " +
database->getDentryTable()->getNameOf(entry) + " on " +
(entry.isBuddyMirrored ? "buddy group " : "node ") +
StringTk::uintToStr(entry.saveNodeID) + " " + StringTk::uintToStr(entry.entryOwnerNodeID));
}
int64_t ModeCheckFS::checkMismirroredDirectories()
{
FsckTkEx::fsckOutput("* Checking: Bad content mirror information in dir inode ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
int dummy = 0;
return checkAndRepairGeneric(this->database->findMismirroredDirectories(),
&ModeCheckFS::logMismirroredDirectory, dummy);
}
void ModeCheckFS::logMismirroredDirectory(db::DirInode& dir, int&)
{
FsckTkEx::fsckOutput(">>> Found mismirrored directory " + dir.id.str() + " on " +
(dir.isBuddyMirrored ? "buddy group " : "node ") +
StringTk::uintToStr(dir.saveNodeID));
;
}
int64_t ModeCheckFS::checkMismirroredFiles()
{
FsckTkEx::fsckOutput("* Checking: Bad content mirror information in file inode ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
int dummy = 0;
return checkAndRepairGeneric(this->database->findMismirroredFiles(),
&ModeCheckFS::logMismirroredFile, dummy);
}
void ModeCheckFS::logMismirroredFile(db::FileInode& file, int&)
{
FsckTkEx::fsckOutput(">>> Found mismirrored file " + file.id.str() + " on " +
std::string(file.isBuddyMirrored ? "buddy group " : "node ") +
StringTk::uintToStr(file.saveNodeID));
}
int64_t ModeCheckFS::checkAndRepairMalformedChunk()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_DELETECHUNK,
};
UserPrompter prompt(possibleActions, FsckRepairAction_DELETECHUNK);
FsckTkEx::fsckOutput("* Checking: Malformed chunk ...", OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(Cursor<FsckChunk>(database->getMalformedChunksList()->cursor()),
&ModeCheckFS::repairMalformedChunk, prompt);
}
void ModeCheckFS::repairMalformedChunk(FsckChunk& chunk, UserPrompter& prompt)
{
FsckRepairAction action = prompt.chooseAction("Chunk ID: " + chunk.getID() + " on " +
(chunk.getBuddyGroupID()
? "buddy group " + StringTk::uintToStr(chunk.getBuddyGroupID())
: "target " + StringTk::uintToStr(chunk.getTargetID())));
switch (action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_DELETECHUNK: {
FhgfsOpsErr refErr;
NodeStore* storageNodeStore = Program::getApp()->getStorageNodes();
auto node = storageNodeStore->referenceNodeByTargetID(chunk.getTargetID(),
Program::getApp()->getTargetMapper(), &refErr);
if(!node)
{
FsckTkEx::fsckOutput("could not get storage target "
+ StringTk::uintToStr(chunk.getTargetID() ), OutputOptions_LINEBREAK);
return;
}
FsckChunkList chunks(1, chunk);
FsckChunkList failed;
MsgHelperRepair::deleteChunks(*node, &chunks, &failed);
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::checkAndRepair()
{
FsckTkEx::fsckOutput("Step 4: Check for errors... ", OutputOptions_DOUBLELINEBREAK);
Config* cfg = Program::getApp()->getConfig();
int64_t errorCount = 0;
errorCount += checkDuplicateInodeIDs();
errorCount += checkDuplicateChunks();
errorCount += checkDuplicateContDirs();
errorCount += checkMismirroredDentries();
errorCount += checkMismirroredDirectories();
errorCount += checkMismirroredFiles();
if(errorCount)
{
FsckTkEx::fsckOutput("Found errors beegfs-fsck cannot fix. Please consult the log for "
"more information.", OutputOptions_LINEBREAK);
return;
}
errorCount += checkAndRepairMalformedChunk();
errorCount += checkAndRepairFilesWithMissingTargets();
errorCount += checkAndRepairOrphanedDentryByIDFiles();
errorCount += checkAndRepairDirEntriesWithBrokeByIDFile();
errorCount += checkAndRepairOrphanedChunk();
errorCount += checkAndRepairChunksInWrongPath();
errorCount += checkAndRepairWrongInodeOwner();
errorCount += checkAndRepairWrongOwnerInDentry();
errorCount += checkAndRepairOrphanedContDir();
errorCount += checkAndRepairOrphanedDirInode();
errorCount += checkAndRepairOrphanedFileInode();
errorCount += checkAndRepairDanglingDentry();
errorCount += checkAndRepairMissingContDir();
errorCount += checkAndRepairWrongFileAttribs();
errorCount += checkAndRepairWrongDirAttribs();
if ( cfg->getQuotaEnabled())
{
errorCount += checkAndRepairChunksWithWrongPermissions();
}
if ( cfg->getReadOnly() )
{
FsckTkEx::fsckOutput(
"Found " + StringTk::int64ToStr(errorCount)
+ " errors. Detailed information can also be found in "
+ Program::getApp()->getConfig()->getLogOutFile() + ".",
OutputOptions_ADDLINEBREAKBEFORE | OutputOptions_LINEBREAK);
return;
}
for (auto it = secondariesSetBad.begin(); it != secondariesSetBad.end(); ++it)
{
auto secondary = *it;
FsckTkEx::fsckOutput(">>> Setting metadata node " + StringTk::intToStr(secondary.val())
+ " to needs-resync", OutputOptions_LINEBREAK);
auto setRes = MsgHelperRepair::setNodeState(secondary, TargetConsistencyState_NEEDS_RESYNC);
if (setRes != FhgfsOpsErr_SUCCESS)
FsckTkEx::fsckOutput("Failed: " + boost::lexical_cast<std::string>(setRes),
OutputOptions_LINEBREAK);
}
if(errorCount > 0)
FsckTkEx::fsckOutput(">>> Found " + StringTk::int64ToStr(errorCount) + " errors <<< ",
OutputOptions_ADDLINEBREAKBEFORE | OutputOptions_LINEBREAK);
}
//////////////////////////
// internals ///////
/////////////////////////
void ModeCheckFS::repairDanglingDirEntry(db::DirEntry& entry,
std::pair<UserPrompter*, UserPrompter*>& prompt)
{
FsckDirEntry fsckEntry = entry;
FsckRepairAction action;
std::string promptText = "Entry ID: " + fsckEntry.getID() + "; Path: " +
this->database->getDentryTable()->getPathOf(entry) + "; " +
(entry.isBuddyMirrored ? "Buddy group: " : "Node: ") +
StringTk::uintToStr(entry.saveNodeID);
if(fsckEntry.getEntryType() == FsckDirEntryType_DIRECTORY)
action = prompt.second->chooseAction(promptText);
else
action = prompt.first->chooseAction(promptText);
fsckEntry.setName(this->database->getDentryTable()->getNameOf(entry) );
FsckDirEntryList entries(1, fsckEntry);
FsckDirEntryList failedEntries;
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_DELETEDENTRY: {
MsgHelperRepair::deleteDanglingDirEntries(fsckEntry.getSaveNodeID(),
fsckEntry.getIsBuddyMirrored(), &entries, &failedEntries,
secondariesSetBad);
if(failedEntries.empty() )
{
this->database->getDentryTable()->remove(entries);
this->deleteFsIDsFromDB(entries);
}
break;
}
case FsckRepairAction_CREATEDEFAULTDIRINODE: {
FsckDirInodeList createdInodes;
// create mirrored inodes iff the dentry was mirrored. if a contdir with the same id exists,
// a previous check will have created an inode for it, leaving this dentry not dangling.
MsgHelperRepair::createDefDirInodes(fsckEntry.getSaveNodeID(), fsckEntry.getIsBuddyMirrored(),
{std::make_tuple(fsckEntry.getID(), fsckEntry.getIsBuddyMirrored())}, &createdInodes,
secondariesSetBad);
this->database->getDirInodesTable()->insert(createdInodes);
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairWrongInodeOwner(FsckDirInode& inode, UserPrompter& prompt)
{
FsckRepairAction action = prompt.chooseAction("Entry ID: " + inode.getID()
+ "; Path: "
+ this->database->getDentryTable()->getPathOf(db::EntryID::fromStr(inode.getID() ) ) );
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_CORRECTOWNER: {
inode.setOwnerNodeID(inode.getSaveNodeID() );
FsckDirInodeList inodes(1, inode);
FsckDirInodeList failed;
MsgHelperRepair::correctInodeOwners(inode.getSaveNodeID(), inode.getIsBuddyMirrored(),
&inodes, &failed, secondariesSetBad);
if(failed.empty() )
this->database->getDirInodesTable()->update(inodes);
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairWrongInodeOwnerInDentry(std::pair<db::DirEntry, NumNodeID>& error,
UserPrompter& prompt)
{
FsckDirEntry fsckEntry = error.first;
FsckRepairAction action = prompt.chooseAction("File ID: " + fsckEntry.getID()
+ "; Path: " + this->database->getDentryTable()->getPathOf(error.first) );
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_CORRECTOWNER: {
fsckEntry.setName(this->database->getDentryTable()->getNameOf(error.first) );
FsckDirEntryList dentries(1, fsckEntry);
NumNodeIDList owners(1, NumNodeID(error.second) );
FsckDirEntryList failed;
MsgHelperRepair::correctInodeOwnersInDentry(fsckEntry.getSaveNodeID(),
fsckEntry.getIsBuddyMirrored(), &dentries, &owners, &failed,
secondariesSetBad);
if(failed.empty() )
this->database->getDentryTable()->updateFieldsExceptParent(dentries);
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairOrphanedDirInode(FsckDirInode& inode, UserPrompter& prompt)
{
FsckRepairAction action = prompt.chooseAction("Directory ID: " + inode.getID() + "; " +
(inode.getIsBuddyMirrored() ? "Buddy group: " : "Node: ") + inode.getSaveNodeID().str());
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_LOSTANDFOUND: {
if(!ensureLostAndFoundExists() )
{
log.logErr("Orphaned dir inodes could not be linked to lost+found, because lost+found "
"directory could not be created");
return;
}
FsckDirInodeList inodes(1, inode);
FsckDirEntryList created;
FsckDirInodeList failed;
MsgHelperRepair::linkToLostAndFound(*this->lostAndFoundNode, &this->lostAndFoundInfo, &inodes,
&failed, &created, secondariesSetBad);
if(failed.empty() )
this->database->getDentryTable()->insert(created);
// on server side, each dentry also created a dentry-by-ID file
FsckFsIDList createdFsIDs;
for(FsckDirEntryListIter iter = created.begin(); iter != created.end(); iter++)
{
FsckFsID fsID(iter->getID(), iter->getParentDirID(), iter->getSaveNodeID(),
iter->getSaveDevice(), iter->getSaveInode(), iter->getIsBuddyMirrored());
createdFsIDs.push_back(fsID);
}
this->database->getFsIDsTable()->insert(createdFsIDs);
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairOrphanedFileInode(FsckFileInode& inode, UserPrompter& prompt)
{
FsckRepairAction action = prompt.chooseAction("File ID: " + inode.getID() + "; " +
(inode.getIsBuddyMirrored() ? "Buddy group: " : "Node: ") + inode.getSaveNodeID().str());
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_DELETEINODE: {
FsckFileInodeList inodes(1, inode);
StringList failed;
MsgHelperRepair::deleteFileInodes(inode.getSaveNodeID(), inode.getIsBuddyMirrored(), inodes,
failed, secondariesSetBad);
if(failed.empty() )
this->database->getFileInodesTable()->remove(inodes);
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairOrphanedChunk(FsckChunk& chunk, RepairChunkState& state)
{
// ask for repair action only once per chunk id, not once per chunk id and node
if(state.lastID != chunk.getID() )
state.lastChunkAction = state.prompt->chooseAction("Chunk ID: " + chunk.getID() + " on " +
(chunk.getBuddyGroupID()
? "buddy group " + StringTk::uintToStr(chunk.getBuddyGroupID())
: "target " + StringTk::uintToStr(chunk.getTargetID())));
state.lastID = chunk.getID();
switch(state.lastChunkAction)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_DELETECHUNK: {
FhgfsOpsErr refErr;
NodeStore* storageNodeStore = Program::getApp()->getStorageNodes();
auto node = storageNodeStore->referenceNodeByTargetID(chunk.getTargetID(),
Program::getApp()->getTargetMapper(), &refErr);
if(!node)
{
FsckTkEx::fsckOutput("could not get storage target "
+ StringTk::uintToStr(chunk.getTargetID() ), OutputOptions_LINEBREAK);
return;
}
FsckChunkList chunks(1, chunk);
FsckChunkList failed;
MsgHelperRepair::deleteChunks(*node, &chunks, &failed);
if(failed.empty() )
this->database->getChunksTable()->remove(
{db::EntryID::fromStr(chunk.getID()), chunk.getTargetID(), chunk.getBuddyGroupID()});
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairMissingContDir(FsckDirInode& inode, UserPrompter& prompt)
{
FsckRepairAction action = prompt.chooseAction("Directory ID: " + inode.getID() +
"; Path: " +
this->database->getDentryTable()->getPathOf(db::EntryID::fromStr(inode.getID())) + "; " +
(inode.getIsBuddyMirrored() ? "Buddy group: " : "Node: ") + inode.getSaveNodeID().str());
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_CREATECONTDIR: {
FsckDirInodeList inodes(1, inode);
StringList failed;
MsgHelperRepair::createContDirs(inode.getSaveNodeID(), inode.getIsBuddyMirrored(), &inodes,
&failed, secondariesSetBad);
if(failed.empty() )
{
// create a list of cont dirs from dir inode
FsckContDirList contDirs(1,
FsckContDir(inode.getID(), inode.getSaveNodeID(), inode.getIsBuddyMirrored()));
this->database->getContDirsTable()->insert(contDirs);
}
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairOrphanedContDir(FsckContDir& dir, UserPrompter& prompt)
{
FsckRepairAction action = prompt.chooseAction("Directory ID: " + dir.getID() + "; " +
(dir.getIsBuddyMirrored() ? "Buddy group: " : "Node: ") + dir.getSaveNodeID().str());
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_CREATEDEFAULTDIRINODE: {
FsckDirInodeList createdInodes;
MsgHelperRepair::createDefDirInodes(dir.getSaveNodeID(), dir.getIsBuddyMirrored(),
{std::make_tuple(dir.getID(), dir.getIsBuddyMirrored())}, &createdInodes,
secondariesSetBad);
this->database->getDirInodesTable()->insert(createdInodes);
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairWrongFileAttribs(std::pair<FsckFileInode, checks::InodeAttribs>& error,
UserPrompter& prompt)
{
FsckRepairAction action = prompt.chooseAction("File ID: " + error.first.getID() + "; Path: " +
this->database->getDentryTable()->getPathOf(db::EntryID::fromStr(error.first.getID())) +
"; " + (error.first.getIsBuddyMirrored() ? "Buddy group: " : "Node: ") +
error.first.getSaveNodeID().str());
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_UPDATEATTRIBS: {
error.first.setFileSize(error.second.size);
error.first.setNumHardLinks(error.second.nlinks);
FsckFileInodeList inodes(1, error.first);
FsckFileInodeList failed;
MsgHelperRepair::updateFileAttribs(error.first.getSaveNodeID(),
error.first.getIsBuddyMirrored(), &inodes, &failed, secondariesSetBad);
if(failed.empty() )
this->database->getFileInodesTable()->update(inodes);
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairWrongDirAttribs(std::pair<FsckDirInode, checks::InodeAttribs>& error,
UserPrompter& prompt)
{
std::string filePath = this->database->getDentryTable()->getPathOf(
db::EntryID::fromStr(error.first.getID() ) );
FsckRepairAction action = prompt.chooseAction("Directory ID: " + error.first.getID() +
"; Path: " + filePath + "; " +
(error.first.getIsBuddyMirrored() ? "Buddy group: " : "Node: ") +
error.first.getSaveNodeID().str());
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_UPDATEATTRIBS: {
FsckDirInodeList inodes(1, error.first);
FsckDirInodeList failed;
// update the file attribs in the inode objects (even though they may not be used
// on the server side, we need updated values here to update the DB
error.first.setSize(error.second.size);
error.first.setNumHardLinks(error.second.nlinks);
MsgHelperRepair::updateDirAttribs(error.first.getSaveNodeID(),
error.first.getIsBuddyMirrored(), &inodes, &failed, secondariesSetBad);
if(failed.empty() )
this->database->getDirInodesTable()->update(inodes);
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairFileWithMissingTargets(db::DirEntry& entry, UserPrompter& prompt)
{
FsckDirEntry fsckEntry = entry;
FsckRepairAction action = prompt.chooseAction("Entry ID: " + fsckEntry.getID() +
"; Path: " + this->database->getDentryTable()->getPathOf(entry) + "; " +
(entry.isBuddyMirrored ? "Buddy group: " : "Node: ") +
StringTk::uintToStr(entry.entryOwnerNodeID));
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
return;
case FsckRepairAction_DELETEFILE: {
fsckEntry.setName(this->database->getDentryTable()->getNameOf(entry) );
FsckDirEntryList dentries(1, fsckEntry);
FsckDirEntryList failed;
MsgHelperRepair::deleteFiles(fsckEntry.getSaveNodeID(), fsckEntry.getIsBuddyMirrored(),
&dentries, &failed);
if(failed.empty() )
this->deleteFilesFromDB(dentries);
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairDirEntryWithBrokenByIDFile(db::DirEntry& entry, UserPrompter& prompt)
{
FsckDirEntry fsckEntry = entry;
FsckRepairAction action = prompt.chooseAction("Entry ID: " + fsckEntry.getID() +
"; Path: " + this->database->getDentryTable()->getPathOf(entry) + "; " +
(entry.isBuddyMirrored ? "Buddy group: " : "Node: ") +
StringTk::uintToStr(entry.entryOwnerNodeID));
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_RECREATEFSID: {
fsckEntry.setName(this->database->getDentryTable()->getNameOf(entry) );
FsckDirEntryList dentries(1, fsckEntry);
FsckDirEntryList failed;
MsgHelperRepair::recreateFsIDs(fsckEntry.getSaveNodeID(), fsckEntry.getIsBuddyMirrored(),
&dentries, &failed, secondariesSetBad);
if(failed.empty() )
{
// create a FsID list from the dentry
FsckFsIDList idList(1,
FsckFsID(fsckEntry.getID(), fsckEntry.getParentDirID(), fsckEntry.getSaveNodeID(),
fsckEntry.getSaveDevice(), fsckEntry.getSaveInode(),
fsckEntry.getIsBuddyMirrored()));
this->database->getFsIDsTable()->insert(idList);
}
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairOrphanedDentryByIDFile(FsckFsID& id, UserPrompter& prompt)
{
FsckRepairAction action = prompt.chooseAction(
"Entry ID: " + id.getID() +
"; Path: " +
this->database->getDentryTable()->getPathOf(db::EntryID::fromStr(id.getID())) + "; " +
(id.getIsBuddyMirrored() ? "Buddy group: " : "Node: ") + id.getSaveNodeID().str());
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_RECREATEDENTRY: {
FsckFsIDList fsIDs(1, id);
FsckFsIDList failed;
FsckDirEntryList createdDentries;
FsckFileInodeList createdInodes;
MsgHelperRepair::recreateDentries(id.getSaveNodeID(), id.getIsBuddyMirrored(), &fsIDs,
&failed, &createdDentries, &createdInodes, secondariesSetBad);
if(failed.empty() )
{
this->database->getDentryTable()->insert(createdDentries);
this->database->getFileInodesTable()->insert(createdInodes);
}
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairChunkWithWrongPermissions(std::pair<FsckChunk, FsckFileInode>& error,
UserPrompter& prompt)
{
FsckRepairAction action = prompt.chooseAction(
"Chunk ID: " + error.first.getID() + "; "
+ (error.first.getBuddyGroupID()
? "Buddy group: " + StringTk::uintToStr(error.first.getBuddyGroupID())
: "Target: " + StringTk::uintToStr(error.first.getTargetID()))
+ "; File path: "
+ this->database->getDentryTable()->getPathOf(db::EntryID::fromStr(error.first.getID())));
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_FIXPERMISSIONS: {
NodeStore* nodeStore = Program::getApp()->getStorageNodes();
TargetMapper* targetMapper = Program::getApp()->getTargetMapper();
// we will need the PathInfo later to send the SetAttr message and we don't have it in the
// chunk
PathInfoList pathInfoList(1, *error.second.getPathInfo() );
// set correct permissions
error.first.setUserID(error.second.getUserID() );
error.first.setGroupID(error.second.getGroupID() );
FsckChunkList chunkList(1, error.first);
FsckChunkList failed;
auto storageNode = nodeStore->referenceNode(
targetMapper->getNodeID(error.first.getTargetID() ) );
MsgHelperRepair::fixChunkPermissions(*storageNode, chunkList, pathInfoList, failed);
if(failed.empty() )
this->database->getChunksTable()->update(chunkList);
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairWrongChunkPath(std::pair<FsckChunk, FsckFileInode>& error,
UserPrompter& prompt)
{
FsckRepairAction action = prompt.chooseAction("Entry ID: " + error.first.getID()
+ "; " + (error.first.getBuddyGroupID()
? "Group: " + StringTk::uintToStr(error.first.getBuddyGroupID())
: "Target: " + StringTk::uintToStr(error.first.getTargetID()))
+ "; Chunk path: " + error.first.getSavedPath()->str()
+ "; File path: "
+ this->database->getDentryTable()->getPathOf(db::EntryID::fromStr(error.first.getID() ) ) );
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_MOVECHUNK: {
NodeStore* nodeStore = Program::getApp()->getStorageNodes();
TargetMapper* targetMapper = Program::getApp()->getTargetMapper();
auto storageNode = nodeStore->referenceNode(
targetMapper->getNodeID(error.first.getTargetID() ) );
std::string moveToPath = DatabaseTk::calculateExpectedChunkPath(error.first.getID(),
error.second.getPathInfo()->getOrigUID(),
error.second.getPathInfo()->getOrigParentEntryID(),
error.second.getPathInfo()->getFlags() );
if(MsgHelperRepair::moveChunk(*storageNode, error.first, moveToPath, false) )
{
FsckChunkList chunks(1, error.first);
this->database->getChunksTable()->update(chunks);
break;
}
// chunk file exists at the correct location
FsckTkEx::fsckOutput("Chunk file for " + error.first.getID()
+ " already exists at the correct location. ", OutputOptions_NONE);
if(Program::getApp()->getConfig()->getAutomatic() )
{
FsckTkEx::fsckOutput("Will not attempt automatic repair.", OutputOptions_LINEBREAK);
break;
}
char chosen = 0;
while(chosen != 'y' && chosen != 'n')
{
FsckTkEx::fsckOutput("Move anyway? (y/n) ", OutputOptions_NONE);
std::string line;
std::getline(std::cin, line);
if(line.size() == 1)
chosen = line[0];
}
if(chosen != 'y')
break;
if(MsgHelperRepair::moveChunk(*storageNode, error.first, moveToPath, true) )
{
FsckChunkList chunks(1, error.first);
this->database->getChunksTable()->update(chunks);
}
else
{
FsckTkEx::fsckOutput("Repair failed, see log file for more details.",
OutputOptions_LINEBREAK);
}
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::deleteFsIDsFromDB(FsckDirEntryList& dentries)
{
// create the fsID list
FsckFsIDList fsIDs;
for ( FsckDirEntryListIter iter = dentries.begin(); iter != dentries.end(); iter++ )
{
FsckFsID fsID(iter->getID(), iter->getParentDirID(), iter->getSaveNodeID(),
iter->getSaveDevice(), iter->getSaveInode(), iter->getIsBuddyMirrored());
fsIDs.push_back(fsID);
}
this->database->getFsIDsTable()->remove(fsIDs);
}
void ModeCheckFS::deleteFilesFromDB(FsckDirEntryList& dentries)
{
for ( FsckDirEntryListIter dentryIter = dentries.begin(); dentryIter != dentries.end();
dentryIter++ )
{
std::pair<bool, db::FileInode> inode = this->database->getFileInodesTable()->get(
dentryIter->getID() );
if(inode.first)
{
this->database->getFileInodesTable()->remove(inode.second.id);
this->database->getChunksTable()->remove(inode.second.id);
}
}
this->database->getDentryTable()->remove(dentries);
// delete the dentry-by-id files
this->deleteFsIDsFromDB(dentries);
}
bool ModeCheckFS::ensureLostAndFoundExists()
{
this->lostAndFoundNode = MsgHelperRepair::referenceLostAndFoundOwner(&this->lostAndFoundInfo);
if(!this->lostAndFoundNode)
{
if(!MsgHelperRepair::createLostAndFound(this->lostAndFoundNode, this->lostAndFoundInfo) )
return false;
}
std::pair<bool, FsckDirInode> dbLaF = this->database->getDirInodesTable()->get(
this->lostAndFoundInfo.getEntryID() );
if(dbLaF.first)
this->lostAndFoundInode.reset(new FsckDirInode(dbLaF.second) );
return true;
}
void ModeCheckFS::releaseLostAndFound()
{
if(!this->lostAndFoundNode)
return;
if(this->lostAndFoundInode)
{
FsckDirInodeList updates(1, *this->lostAndFoundInode);
this->database->getDirInodesTable()->update(updates);
}
this->lostAndFoundInode.reset();
}
| 33.319677
| 108
| 0.667423
|
TomatoYoung
|
8d1a7ec064dc8cea90086e0320845f0c256f8aa0
| 371
|
cpp
|
C++
|
LeetCode/Problems/Algorithms/#848_ShiftingLetters_sol2_suffix_sum_O(N)_time_O(1)_extra_space_193ms_68MB.cpp
|
Tudor67/Competitive-Programming
|
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
|
[
"MIT"
] | 1
|
2022-01-26T14:50:07.000Z
|
2022-01-26T14:50:07.000Z
|
LeetCode/Problems/Algorithms/#848_ShiftingLetters_sol2_suffix_sum_O(N)_time_O(1)_extra_space_193ms_68MB.cpp
|
Tudor67/Competitive-Programming
|
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
|
[
"MIT"
] | null | null | null |
LeetCode/Problems/Algorithms/#848_ShiftingLetters_sol2_suffix_sum_O(N)_time_O(1)_extra_space_193ms_68MB.cpp
|
Tudor67/Competitive-Programming
|
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
|
[
"MIT"
] | null | null | null |
class Solution {
public:
string shiftingLetters(string s, vector<int>& shifts) {
const int N = shifts.size();
int suffixShifts = 0;
for(int i = N - 1; i >= 0; --i){
suffixShifts += shifts[i];
suffixShifts %= 26;
s[i] = 'a' + (s[i] - 'a' + suffixShifts) % 26;
}
return s;
}
};
| 28.538462
| 60
| 0.455526
|
Tudor67
|
8d1e0ee582941eb03c4ad82eaea4a2f8c1bebe61
| 1,391
|
cpp
|
C++
|
BeanDogEngine/cVortex.cpp
|
RoyFilipchuk56/BeanDogEngine
|
189ff606b1568b8c2228602b545767bb827d3065
|
[
"MIT"
] | null | null | null |
BeanDogEngine/cVortex.cpp
|
RoyFilipchuk56/BeanDogEngine
|
189ff606b1568b8c2228602b545767bb827d3065
|
[
"MIT"
] | null | null | null |
BeanDogEngine/cVortex.cpp
|
RoyFilipchuk56/BeanDogEngine
|
189ff606b1568b8c2228602b545767bb827d3065
|
[
"MIT"
] | null | null | null |
#include "cFirework.h"
namespace nPhysics
{
cVortex::cVortex(float mass, const glm::vec3& position) : cFirework(mass, position)
{
}
cVortex::~cVortex()
{
}
void cVortex::GenerateChildren(std::vector<cFirework*>& childrenOut, glm::vec3 location)
{
//Genereate 50 new stage 2 particles
for (int i = 0; i < 50; i++)
{
nPhysics::cVortex* particle = new nPhysics::cVortex(1.0f, location);
particle->SetStageTwo();
childrenOut.push_back(particle);
}
}
void cVortex::Integrate(float deltaTime)
{
if (mInverseMass == 0.f)
{
return; // static things don't move!
}
//Set the new age
age += deltaTime;
mPosition += mVelocity * deltaTime;
// F*(1/m) = a
mVelocity += (mAcceleration + mAppliedForce * mInverseMass) * deltaTime;
// apply damping
mVelocity *= glm::pow(mDamping, deltaTime);
//Check if its still alive
if (mVelocity.y <= 0 && stage == 1)
{
isAlive = false;
}
if (age >= 1.5f && stage == 2)
{
isAlive = false;
}
// clear applied forces
ClearAppliedForces();
}
void cVortex::SetStageOne()
{
//set the stage
stage = 1;
//launch it in the air
this->SetVelocity(glm::vec3(0, getRandom(10, 15), 0));
}
void cVortex::SetStageTwo()
{
//set the stage
stage = 2;
//send them in a random direction
this->SetVelocity(getRandomVec3XZ(10));
this->SetAcceleration(glm::vec3(0.0f, 9.8f, 0.0f));
}
}
| 20.455882
| 89
| 0.640546
|
RoyFilipchuk56
|
8d22fb1052419774d27b3cbb4147b5040b5933f1
| 35,544
|
cpp
|
C++
|
src/superscalar.cpp
|
Teredic/DefyX
|
5d71a3e8076e850acfeb18ec3612a2ec2a5b1308
|
[
"BSD-3-Clause"
] | 2
|
2020-01-04T02:35:40.000Z
|
2021-11-29T19:11:27.000Z
|
src/superscalar.cpp
|
Teredic/DefyX
|
5d71a3e8076e850acfeb18ec3612a2ec2a5b1308
|
[
"BSD-3-Clause"
] | null | null | null |
src/superscalar.cpp
|
Teredic/DefyX
|
5d71a3e8076e850acfeb18ec3612a2ec2a5b1308
|
[
"BSD-3-Clause"
] | 2
|
2019-07-30T18:40:07.000Z
|
2019-12-22T11:01:13.000Z
|
/*
Copyright (c) 2018-2019, tevador <tevador@gmail.com>
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 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.
*/
#include "configuration.h"
#include "program.hpp"
#include "blake2/endian.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <iomanip>
#include "superscalar.hpp"
#include "intrin_portable.h"
#include "reciprocal.h"
#include "common.hpp"
namespace defyx {
static bool isMultiplication(SuperscalarInstructionType type) {
return type == SuperscalarInstructionType::IMUL_R || type == SuperscalarInstructionType::IMULH_R || type == SuperscalarInstructionType::ISMULH_R || type == SuperscalarInstructionType::IMUL_RCP;
}
//uOPs (micro-ops) are represented only by the execution port they can go to
namespace ExecutionPort {
using type = int;
constexpr type Null = 0;
constexpr type P0 = 1;
constexpr type P1 = 2;
constexpr type P5 = 4;
constexpr type P01 = P0 | P1;
constexpr type P05 = P0 | P5;
constexpr type P015 = P0 | P1 | P5;
}
//Macro-operation as output of the x86 decoder
//Usually one macro-op = one x86 instruction, but 2 instructions are sometimes fused into 1 macro-op
//Macro-op can consist of 1 or 2 uOPs.
class MacroOp {
public:
MacroOp(const char* name, int size)
: name_(name), size_(size), latency_(0), uop1_(ExecutionPort::Null), uop2_(ExecutionPort::Null) {}
MacroOp(const char* name, int size, int latency, ExecutionPort::type uop)
: name_(name), size_(size), latency_(latency), uop1_(uop), uop2_(ExecutionPort::Null) {}
MacroOp(const char* name, int size, int latency, ExecutionPort::type uop1, ExecutionPort::type uop2)
: name_(name), size_(size), latency_(latency), uop1_(uop1), uop2_(uop2) {}
MacroOp(const MacroOp& parent, bool dependent)
: name_(parent.name_), size_(parent.size_), latency_(parent.latency_), uop1_(parent.uop1_), uop2_(parent.uop2_), dependent_(dependent) {}
const char* getName() const {
return name_;
}
int getSize() const {
return size_;
}
int getLatency() const {
return latency_;
}
ExecutionPort::type getUop1() const {
return uop1_;
}
ExecutionPort::type getUop2() const {
return uop2_;
}
bool isSimple() const {
return uop2_ == ExecutionPort::Null;
}
bool isEliminated() const {
return uop1_ == ExecutionPort::Null;
}
bool isDependent() const {
return dependent_;
}
static const MacroOp Add_rr;
static const MacroOp Add_ri;
static const MacroOp Lea_sib;
static const MacroOp Sub_rr;
static const MacroOp Imul_rr;
static const MacroOp Imul_r;
static const MacroOp Mul_r;
static const MacroOp Mov_rr;
static const MacroOp Mov_ri64;
static const MacroOp Xor_rr;
static const MacroOp Xor_ri;
static const MacroOp Ror_rcl;
static const MacroOp Ror_ri;
static const MacroOp TestJz_fused;
static const MacroOp Xor_self;
static const MacroOp Cmp_ri;
static const MacroOp Setcc_r;
private:
const char* name_;
int size_;
int latency_;
ExecutionPort::type uop1_;
ExecutionPort::type uop2_;
bool dependent_ = false;
};
//Size: 3 bytes
const MacroOp MacroOp::Add_rr = MacroOp("add r,r", 3, 1, ExecutionPort::P015);
const MacroOp MacroOp::Sub_rr = MacroOp("sub r,r", 3, 1, ExecutionPort::P015);
const MacroOp MacroOp::Xor_rr = MacroOp("xor r,r", 3, 1, ExecutionPort::P015);
const MacroOp MacroOp::Imul_r = MacroOp("imul r", 3, 4, ExecutionPort::P1, ExecutionPort::P5);
const MacroOp MacroOp::Mul_r = MacroOp("mul r", 3, 4, ExecutionPort::P1, ExecutionPort::P5);
const MacroOp MacroOp::Mov_rr = MacroOp("mov r,r", 3);
//Size: 4 bytes
const MacroOp MacroOp::Lea_sib = MacroOp("lea r,r+r*s", 4, 1, ExecutionPort::P01);
const MacroOp MacroOp::Imul_rr = MacroOp("imul r,r", 4, 3, ExecutionPort::P1);
const MacroOp MacroOp::Ror_ri = MacroOp("ror r,i", 4, 1, ExecutionPort::P05);
//Size: 7 bytes (can be optionally padded with nop to 8 or 9 bytes)
const MacroOp MacroOp::Add_ri = MacroOp("add r,i", 7, 1, ExecutionPort::P015);
const MacroOp MacroOp::Xor_ri = MacroOp("xor r,i", 7, 1, ExecutionPort::P015);
//Size: 10 bytes
const MacroOp MacroOp::Mov_ri64 = MacroOp("mov rax,i64", 10, 1, ExecutionPort::P015);
//Unused:
const MacroOp MacroOp::Ror_rcl = MacroOp("ror r,cl", 3, 1, ExecutionPort::P0, ExecutionPort::P5);
const MacroOp MacroOp::Xor_self = MacroOp("xor rcx,rcx", 3);
const MacroOp MacroOp::Cmp_ri = MacroOp("cmp r,i", 7, 1, ExecutionPort::P015);
const MacroOp MacroOp::Setcc_r = MacroOp("setcc cl", 3, 1, ExecutionPort::P05);
const MacroOp MacroOp::TestJz_fused = MacroOp("testjz r,i", 13, 0, ExecutionPort::P5);
const MacroOp IMULH_R_ops_array[] = { MacroOp::Mov_rr, MacroOp::Mul_r, MacroOp::Mov_rr };
const MacroOp ISMULH_R_ops_array[] = { MacroOp::Mov_rr, MacroOp::Imul_r, MacroOp::Mov_rr };
const MacroOp IMUL_RCP_ops_array[] = { MacroOp::Mov_ri64, MacroOp(MacroOp::Imul_rr, true) };
class SuperscalarInstructionInfo {
public:
const char* getName() const {
return name_;
}
int getSize() const {
return ops_.size();
}
bool isSimple() const {
return getSize() == 1;
}
int getLatency() const {
return latency_;
}
const MacroOp& getOp(int index) const {
return ops_[index];
}
SuperscalarInstructionType getType() const {
return type_;
}
int getResultOp() const {
return resultOp_;
}
int getDstOp() const {
return dstOp_;
}
int getSrcOp() const {
return srcOp_;
}
static const SuperscalarInstructionInfo ISUB_R;
static const SuperscalarInstructionInfo IXOR_R;
static const SuperscalarInstructionInfo IADD_RS;
static const SuperscalarInstructionInfo IMUL_R;
static const SuperscalarInstructionInfo IROR_C;
static const SuperscalarInstructionInfo IADD_C7;
static const SuperscalarInstructionInfo IXOR_C7;
static const SuperscalarInstructionInfo IADD_C8;
static const SuperscalarInstructionInfo IXOR_C8;
static const SuperscalarInstructionInfo IADD_C9;
static const SuperscalarInstructionInfo IXOR_C9;
static const SuperscalarInstructionInfo IMULH_R;
static const SuperscalarInstructionInfo ISMULH_R;
static const SuperscalarInstructionInfo IMUL_RCP;
static const SuperscalarInstructionInfo NOP;
private:
const char* name_;
SuperscalarInstructionType type_;
std::vector<MacroOp> ops_;
int latency_;
int resultOp_ = 0;
int dstOp_ = 0;
int srcOp_;
SuperscalarInstructionInfo(const char* name)
: name_(name), type_(SuperscalarInstructionType::INVALID), latency_(0) {}
SuperscalarInstructionInfo(const char* name, SuperscalarInstructionType type, const MacroOp& op, int srcOp)
: name_(name), type_(type), latency_(op.getLatency()), srcOp_(srcOp) {
ops_.push_back(MacroOp(op));
}
template <size_t N>
SuperscalarInstructionInfo(const char* name, SuperscalarInstructionType type, const MacroOp(&arr)[N], int resultOp, int dstOp, int srcOp)
: name_(name), type_(type), latency_(0), resultOp_(resultOp), dstOp_(dstOp), srcOp_(srcOp) {
for (unsigned i = 0; i < N; ++i) {
ops_.push_back(MacroOp(arr[i]));
latency_ += ops_.back().getLatency();
}
static_assert(N > 1, "Invalid array size");
}
};
const SuperscalarInstructionInfo SuperscalarInstructionInfo::ISUB_R = SuperscalarInstructionInfo("ISUB_R", SuperscalarInstructionType::ISUB_R, MacroOp::Sub_rr, 0);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::IXOR_R = SuperscalarInstructionInfo("IXOR_R", SuperscalarInstructionType::IXOR_R, MacroOp::Xor_rr, 0);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::IADD_RS = SuperscalarInstructionInfo("IADD_RS", SuperscalarInstructionType::IADD_RS, MacroOp::Lea_sib, 0);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::IMUL_R = SuperscalarInstructionInfo("IMUL_R", SuperscalarInstructionType::IMUL_R, MacroOp::Imul_rr, 0);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::IROR_C = SuperscalarInstructionInfo("IROR_C", SuperscalarInstructionType::IROR_C, MacroOp::Ror_ri, -1);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::IADD_C7 = SuperscalarInstructionInfo("IADD_C7", SuperscalarInstructionType::IADD_C7, MacroOp::Add_ri, -1);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::IXOR_C7 = SuperscalarInstructionInfo("IXOR_C7", SuperscalarInstructionType::IXOR_C7, MacroOp::Xor_ri, -1);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::IADD_C8 = SuperscalarInstructionInfo("IADD_C8", SuperscalarInstructionType::IADD_C8, MacroOp::Add_ri, -1);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::IXOR_C8 = SuperscalarInstructionInfo("IXOR_C8", SuperscalarInstructionType::IXOR_C8, MacroOp::Xor_ri, -1);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::IADD_C9 = SuperscalarInstructionInfo("IADD_C9", SuperscalarInstructionType::IADD_C9, MacroOp::Add_ri, -1);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::IXOR_C9 = SuperscalarInstructionInfo("IXOR_C9", SuperscalarInstructionType::IXOR_C9, MacroOp::Xor_ri, -1);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::IMULH_R = SuperscalarInstructionInfo("IMULH_R", SuperscalarInstructionType::IMULH_R, IMULH_R_ops_array, 1, 0, 1);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::ISMULH_R = SuperscalarInstructionInfo("ISMULH_R", SuperscalarInstructionType::ISMULH_R, ISMULH_R_ops_array, 1, 0, 1);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::IMUL_RCP = SuperscalarInstructionInfo("IMUL_RCP", SuperscalarInstructionType::IMUL_RCP, IMUL_RCP_ops_array, 1, 1, -1);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::NOP = SuperscalarInstructionInfo("NOP");
//these are some of the options how to split a 16-byte window into 3 or 4 x86 instructions.
//DefyX uses instructions with a native size of 3 (sub, xor, mul, mov), 4 (lea, mul), 7 (xor, add immediate) or 10 bytes (mov 64-bit immediate).
//Slots with sizes of 8 or 9 bytes need to be padded with a nop instruction.
const int buffer0[] = { 4, 8, 4 };
const int buffer1[] = { 7, 3, 3, 3 };
const int buffer2[] = { 3, 7, 3, 3 };
const int buffer3[] = { 4, 9, 3 };
const int buffer4[] = { 4, 4, 4, 4 };
const int buffer5[] = { 3, 3, 10 };
class DecoderBuffer {
public:
static const DecoderBuffer Default;
template <size_t N>
DecoderBuffer(const char* name, int index, const int(&arr)[N])
: name_(name), index_(index), counts_(arr), opsCount_(N) {}
const int* getCounts() const {
return counts_;
}
int getSize() const {
return opsCount_;
}
int getIndex() const {
return index_;
}
const char* getName() const {
return name_;
}
const DecoderBuffer* fetchNext(SuperscalarInstructionType instrType, int cycle, int mulCount, Blake2Generator& gen) const {
//If the current DefyX instruction is "IMULH", the next fetch configuration must be 3-3-10
//because the full 128-bit multiplication instruction is 3 bytes long and decodes to 2 uOPs on Intel CPUs.
//Intel CPUs can decode at most 4 uOPs per cycle, so this requires a 2-1-1 configuration for a total of 3 macro ops.
if (instrType == SuperscalarInstructionType::IMULH_R || instrType == SuperscalarInstructionType::ISMULH_R)
return &decodeBuffer3310;
//To make sure that the multiplication port is saturated, a 4-4-4-4 configuration is generated if the number of multiplications
//is lower than the number of cycles.
if (mulCount < cycle + 1)
return &decodeBuffer4444;
//If the current DefyX instruction is "IMUL_RCP", the next buffer must begin with a 4-byte slot for multiplication.
if(instrType == SuperscalarInstructionType::IMUL_RCP)
return (gen.getByte() & 1) ? &decodeBuffer484 : &decodeBuffer493;
//Default: select a random fetch configuration.
return fetchNextDefault(gen);
}
private:
const char* name_;
int index_;
const int* counts_;
int opsCount_;
DecoderBuffer() : index_(-1) {}
static const DecoderBuffer decodeBuffer484;
static const DecoderBuffer decodeBuffer7333;
static const DecoderBuffer decodeBuffer3733;
static const DecoderBuffer decodeBuffer493;
static const DecoderBuffer decodeBuffer4444;
static const DecoderBuffer decodeBuffer3310;
static const DecoderBuffer* decodeBuffers[4];
const DecoderBuffer* fetchNextDefault(Blake2Generator& gen) const {
return decodeBuffers[gen.getByte() & 3];
}
};
const DecoderBuffer DecoderBuffer::decodeBuffer484 = DecoderBuffer("4,8,4", 0, buffer0);
const DecoderBuffer DecoderBuffer::decodeBuffer7333 = DecoderBuffer("7,3,3,3", 1, buffer1);
const DecoderBuffer DecoderBuffer::decodeBuffer3733 = DecoderBuffer("3,7,3,3", 2, buffer2);
const DecoderBuffer DecoderBuffer::decodeBuffer493 = DecoderBuffer("4,9,3", 3, buffer3);
const DecoderBuffer DecoderBuffer::decodeBuffer4444 = DecoderBuffer("4,4,4,4", 4, buffer4);
const DecoderBuffer DecoderBuffer::decodeBuffer3310 = DecoderBuffer("3,3,10", 5, buffer5);
const DecoderBuffer* DecoderBuffer::decodeBuffers[4] = {
&DecoderBuffer::decodeBuffer484,
&DecoderBuffer::decodeBuffer7333,
&DecoderBuffer::decodeBuffer3733,
&DecoderBuffer::decodeBuffer493,
};
const DecoderBuffer DecoderBuffer::Default = DecoderBuffer();
const SuperscalarInstructionInfo* slot_3[] = { &SuperscalarInstructionInfo::ISUB_R, &SuperscalarInstructionInfo::IXOR_R };
const SuperscalarInstructionInfo* slot_3L[] = { &SuperscalarInstructionInfo::ISUB_R, &SuperscalarInstructionInfo::IXOR_R, &SuperscalarInstructionInfo::IMULH_R, &SuperscalarInstructionInfo::ISMULH_R };
const SuperscalarInstructionInfo* slot_4[] = { &SuperscalarInstructionInfo::IROR_C, &SuperscalarInstructionInfo::IADD_RS };
const SuperscalarInstructionInfo* slot_7[] = { &SuperscalarInstructionInfo::IXOR_C7, &SuperscalarInstructionInfo::IADD_C7 };
const SuperscalarInstructionInfo* slot_8[] = { &SuperscalarInstructionInfo::IXOR_C8, &SuperscalarInstructionInfo::IADD_C8 };
const SuperscalarInstructionInfo* slot_9[] = { &SuperscalarInstructionInfo::IXOR_C9, &SuperscalarInstructionInfo::IADD_C9 };
const SuperscalarInstructionInfo* slot_10 = &SuperscalarInstructionInfo::IMUL_RCP;
static bool selectRegister(std::vector<int>& availableRegisters, Blake2Generator& gen, int& reg) {
int index;
if (availableRegisters.size() == 0)
return false;
if (availableRegisters.size() > 1) {
index = gen.getUInt32() % availableRegisters.size();
}
else {
index = 0;
}
reg = availableRegisters[index];
return true;
}
class RegisterInfo {
public:
RegisterInfo() : latency(0), lastOpGroup(SuperscalarInstructionType::INVALID), lastOpPar(-1), value(0) {}
int latency;
SuperscalarInstructionType lastOpGroup;
int lastOpPar;
int value;
};
//"SuperscalarInstruction" consists of one or more macro-ops
class SuperscalarInstruction {
public:
void toInstr(Instruction& instr) { //translate to a DefyX instruction format
instr.opcode = (int)getType();
instr.dst = dst_;
instr.src = src_ >= 0 ? src_ : dst_;
instr.setMod(mod_);
instr.setImm32(imm32_);
}
void createForSlot(Blake2Generator& gen, int slotSize, int fetchType, bool isLast, bool isFirst) {
switch (slotSize)
{
case 3:
//if this is the last slot, we can also select "IMULH" instructions
if (isLast) {
create(slot_3L[gen.getByte() & 3], gen);
}
else {
create(slot_3[gen.getByte() & 1], gen);
}
break;
case 4:
//if this is the 4-4-4-4 buffer, issue multiplications as the first 3 instructions
if (fetchType == 4 && !isLast) {
create(&SuperscalarInstructionInfo::IMUL_R, gen);
}
else {
create(slot_4[gen.getByte() & 1], gen);
}
break;
case 7:
create(slot_7[gen.getByte() & 1], gen);
break;
case 8:
create(slot_8[gen.getByte() & 1], gen);
break;
case 9:
create(slot_9[gen.getByte() & 1], gen);
break;
case 10:
create(slot_10, gen);
break;
default:
UNREACHABLE;
}
}
void create(const SuperscalarInstructionInfo* info, Blake2Generator& gen) {
info_ = info;
reset();
switch (info->getType())
{
case SuperscalarInstructionType::ISUB_R: {
mod_ = 0;
imm32_ = 0;
opGroup_ = SuperscalarInstructionType::IADD_RS;
groupParIsSource_ = true;
} break;
case SuperscalarInstructionType::IXOR_R: {
mod_ = 0;
imm32_ = 0;
opGroup_ = SuperscalarInstructionType::IXOR_R;
groupParIsSource_ = true;
} break;
case SuperscalarInstructionType::IADD_RS: {
mod_ = gen.getByte();
imm32_ = 0;
opGroup_ = SuperscalarInstructionType::IADD_RS;
groupParIsSource_ = true;
} break;
case SuperscalarInstructionType::IMUL_R: {
mod_ = 0;
imm32_ = 0;
opGroup_ = SuperscalarInstructionType::IMUL_R;
groupParIsSource_ = true;
} break;
case SuperscalarInstructionType::IROR_C: {
mod_ = 0;
do {
imm32_ = gen.getByte() & 63;
} while (imm32_ == 0);
opGroup_ = SuperscalarInstructionType::IROR_C;
opGroupPar_ = -1;
} break;
case SuperscalarInstructionType::IADD_C7:
case SuperscalarInstructionType::IADD_C8:
case SuperscalarInstructionType::IADD_C9: {
mod_ = 0;
imm32_ = gen.getUInt32();
opGroup_ = SuperscalarInstructionType::IADD_C7;
opGroupPar_ = -1;
} break;
case SuperscalarInstructionType::IXOR_C7:
case SuperscalarInstructionType::IXOR_C8:
case SuperscalarInstructionType::IXOR_C9: {
mod_ = 0;
imm32_ = gen.getUInt32();
opGroup_ = SuperscalarInstructionType::IXOR_C7;
opGroupPar_ = -1;
} break;
case SuperscalarInstructionType::IMULH_R: {
canReuse_ = true;
mod_ = 0;
imm32_ = 0;
opGroup_ = SuperscalarInstructionType::IMULH_R;
opGroupPar_ = gen.getUInt32();
} break;
case SuperscalarInstructionType::ISMULH_R: {
canReuse_ = true;
mod_ = 0;
imm32_ = 0;
opGroup_ = SuperscalarInstructionType::ISMULH_R;
opGroupPar_ = gen.getUInt32();
} break;
case SuperscalarInstructionType::IMUL_RCP: {
mod_ = 0;
do {
imm32_ = gen.getUInt32();
} while (isZeroOrPowerOf2(imm32_));
opGroup_ = SuperscalarInstructionType::IMUL_RCP;
opGroupPar_ = -1;
} break;
default:
break;
}
}
bool selectDestination(int cycle, bool allowChainedMul, RegisterInfo (®isters)[8], Blake2Generator& gen) {
/*if (allowChainedMultiplication && opGroup_ == SuperscalarInstructionType::IMUL_R)
std::cout << "Selecting destination with chained MUL enabled" << std::endl;*/
std::vector<int> availableRegisters;
//Conditions for the destination register:
// * value must be ready at the required cycle
// * cannot be the same as the source register unless the instruction allows it
// - this avoids optimizable instructions such as "xor r, r" or "sub r, r"
// * register cannot be multiplied twice in a row unless allowChainedMul is true
// - this avoids accumulation of trailing zeroes in registers due to excessive multiplication
// - allowChainedMul is set to true if an attempt to find source/destination registers failed (this is quite rare, but prevents a catastrophic failure of the generator)
// * either the last instruction applied to the register or its source must be different than this instruction
// - this avoids optimizable instruction sequences such as "xor r1, r2; xor r1, r2" or "ror r, C1; ror r, C2" or "add r, C1; add r, C2"
// * register r5 cannot be the destination of the IADD_RS instruction (limitation of the x86 lea instruction)
for (unsigned i = 0; i < 8; ++i) {
if (registers[i].latency <= cycle && (canReuse_ || i != src_) && (allowChainedMul || opGroup_ != SuperscalarInstructionType::IMUL_R || registers[i].lastOpGroup != SuperscalarInstructionType::IMUL_R) && (registers[i].lastOpGroup != opGroup_ || registers[i].lastOpPar != opGroupPar_) && (info_->getType() != SuperscalarInstructionType::IADD_RS || i != RegisterNeedsDisplacement))
availableRegisters.push_back(i);
}
return selectRegister(availableRegisters, gen, dst_);
}
bool selectSource(int cycle, RegisterInfo(®isters)[8], Blake2Generator& gen) {
std::vector<int> availableRegisters;
//all registers that are ready at the cycle
for (unsigned i = 0; i < 8; ++i) {
if (registers[i].latency <= cycle)
availableRegisters.push_back(i);
}
//if there are only 2 available registers for IADD_RS and one of them is r5, select it as the source because it cannot be the destination
if (availableRegisters.size() == 2 && info_->getType() == SuperscalarInstructionType::IADD_RS) {
if (availableRegisters[0] == RegisterNeedsDisplacement || availableRegisters[1] == RegisterNeedsDisplacement) {
opGroupPar_ = src_ = RegisterNeedsDisplacement;
return true;
}
}
if (selectRegister(availableRegisters, gen, src_)) {
if (groupParIsSource_)
opGroupPar_ = src_;
return true;
}
return false;
}
SuperscalarInstructionType getType() {
return info_->getType();
}
int getSource() {
return src_;
}
int getDestination() {
return dst_;
}
SuperscalarInstructionType getGroup() {
return opGroup_;
}
int getGroupPar() {
return opGroupPar_;
}
const SuperscalarInstructionInfo& getInfo() const {
return *info_;
}
static const SuperscalarInstruction Null;
private:
const SuperscalarInstructionInfo* info_;
int src_ = -1;
int dst_ = -1;
int mod_;
uint32_t imm32_;
SuperscalarInstructionType opGroup_;
int opGroupPar_;
bool canReuse_ = false;
bool groupParIsSource_ = false;
void reset() {
src_ = dst_ = -1;
canReuse_ = groupParIsSource_ = false;
}
SuperscalarInstruction(const SuperscalarInstructionInfo* info) : info_(info) {
}
};
const SuperscalarInstruction SuperscalarInstruction::Null = SuperscalarInstruction(&SuperscalarInstructionInfo::NOP);
constexpr int CYCLE_MAP_SIZE = RANDOMX_SUPERSCALAR_LATENCY + 4;
constexpr int LOOK_FORWARD_CYCLES = 4;
constexpr int MAX_THROWAWAY_COUNT = 256;
template<bool commit>
static int scheduleUop(ExecutionPort::type uop, ExecutionPort::type(&portBusy)[CYCLE_MAP_SIZE][3], int cycle) {
//The scheduling here is done optimistically by checking port availability in order P5 -> P0 -> P1 to not overload
//port P1 (multiplication) by instructions that can go to any port.
for (; cycle < CYCLE_MAP_SIZE; ++cycle) {
if ((uop & ExecutionPort::P5) != 0 && !portBusy[cycle][2]) {
if (commit) {
if (trace) std::cout << "; P5 at cycle " << cycle << std::endl;
portBusy[cycle][2] = uop;
}
return cycle;
}
if ((uop & ExecutionPort::P0) != 0 && !portBusy[cycle][0]) {
if (commit) {
if (trace) std::cout << "; P0 at cycle " << cycle << std::endl;
portBusy[cycle][0] = uop;
}
return cycle;
}
if ((uop & ExecutionPort::P1) != 0 && !portBusy[cycle][1]) {
if (commit) {
if (trace) std::cout << "; P1 at cycle " << cycle << std::endl;
portBusy[cycle][1] = uop;
}
return cycle;
}
}
return -1;
}
template<bool commit>
static int scheduleMop(const MacroOp& mop, ExecutionPort::type(&portBusy)[CYCLE_MAP_SIZE][3], int cycle, int depCycle) {
//if this macro-op depends on the previous one, increase the starting cycle if needed
//this handles an explicit dependency chain in IMUL_RCP
if (mop.isDependent()) {
cycle = std::max(cycle, depCycle);
}
//move instructions are eliminated and don't need an execution unit
if (mop.isEliminated()) {
if (commit)
if (trace) std::cout << "; (eliminated)" << std::endl;
return cycle;
}
else if (mop.isSimple()) {
//this macro-op has only one uOP
return scheduleUop<commit>(mop.getUop1(), portBusy, cycle);
}
else {
//macro-ops with 2 uOPs are scheduled conservatively by requiring both uOPs to execute in the same cycle
for (; cycle < CYCLE_MAP_SIZE; ++cycle) {
int cycle1 = scheduleUop<false>(mop.getUop1(), portBusy, cycle);
int cycle2 = scheduleUop<false>(mop.getUop2(), portBusy, cycle);
if (cycle1 == cycle2) {
if (commit) {
scheduleUop<true>(mop.getUop1(), portBusy, cycle1);
scheduleUop<true>(mop.getUop2(), portBusy, cycle2);
}
return cycle1;
}
}
}
return -1;
}
void generateSuperscalar(SuperscalarProgram& prog, Blake2Generator& gen) {
ExecutionPort::type portBusy[CYCLE_MAP_SIZE][3];
memset(portBusy, 0, sizeof(portBusy));
RegisterInfo registers[8];
const DecoderBuffer* decodeBuffer = &DecoderBuffer::Default;
SuperscalarInstruction currentInstruction = SuperscalarInstruction::Null;
int macroOpIndex = 0;
int codeSize = 0;
int macroOpCount = 0;
int cycle = 0;
int depCycle = 0;
int retireCycle = 0;
bool portsSaturated = false;
int programSize = 0;
int mulCount = 0;
int decodeCycle;
int throwAwayCount = 0;
//decode instructions for RANDOMX_SUPERSCALAR_LATENCY cycles or until an execution port is saturated.
//Each decode cycle decodes 16 bytes of x86 code.
//Since a decode cycle produces on average 3.45 macro-ops and there are only 3 ALU ports, execution ports are always
//saturated first. The cycle limit is present only to guarantee loop termination.
//Program size is limited to SuperscalarMaxSize instructions.
for (decodeCycle = 0; decodeCycle < RANDOMX_SUPERSCALAR_LATENCY && !portsSaturated && programSize < SuperscalarMaxSize; ++decodeCycle) {
//select a decode configuration
decodeBuffer = decodeBuffer->fetchNext(currentInstruction.getType(), decodeCycle, mulCount, gen);
if (trace) std::cout << "; ------------- fetch cycle " << cycle << " (" << decodeBuffer->getName() << ")" << std::endl;
int bufferIndex = 0;
//fill all instruction slots in the current decode buffer
while (bufferIndex < decodeBuffer->getSize()) {
int topCycle = cycle;
//if we have issued all macro-ops for the current DefyX instruction, create a new instruction
if (macroOpIndex >= currentInstruction.getInfo().getSize()) {
if (portsSaturated || programSize >= SuperscalarMaxSize)
break;
//select an instruction so that the first macro-op fits into the current slot
currentInstruction.createForSlot(gen, decodeBuffer->getCounts()[bufferIndex], decodeBuffer->getIndex(), decodeBuffer->getSize() == bufferIndex + 1, bufferIndex == 0);
macroOpIndex = 0;
if (trace) std::cout << "; " << currentInstruction.getInfo().getName() << std::endl;
}
const MacroOp& mop = currentInstruction.getInfo().getOp(macroOpIndex);
if (trace) std::cout << mop.getName() << " ";
//calculate the earliest cycle when this macro-op (all of its uOPs) can be scheduled for execution
int scheduleCycle = scheduleMop<false>(mop, portBusy, cycle, depCycle);
if (scheduleCycle < 0) {
if (trace) std::cout << "Unable to map operation '" << mop.getName() << "' to execution port (cycle " << cycle << ")" << std::endl;
//__debugbreak();
portsSaturated = true;
break;
}
//find a source register (if applicable) that will be ready when this instruction executes
if (macroOpIndex == currentInstruction.getInfo().getSrcOp()) {
int forward;
//if no suitable operand is ready, look up to LOOK_FORWARD_CYCLES forward
for (forward = 0; forward < LOOK_FORWARD_CYCLES && !currentInstruction.selectSource(scheduleCycle, registers, gen); ++forward) {
if (trace) std::cout << "; src STALL at cycle " << cycle << std::endl;
++scheduleCycle;
++cycle;
}
//if no register was found, throw the instruction away and try another one
if (forward == LOOK_FORWARD_CYCLES) {
if (throwAwayCount < MAX_THROWAWAY_COUNT) {
throwAwayCount++;
macroOpIndex = currentInstruction.getInfo().getSize();
if (trace) std::cout << "; THROW away " << currentInstruction.getInfo().getName() << std::endl;
//cycle = topCycle;
continue;
}
//abort this decode buffer
if (trace) std::cout << "Aborting at cycle " << cycle << " with decode buffer " << decodeBuffer->getName() << " - source registers not available for operation " << currentInstruction.getInfo().getName() << std::endl;
currentInstruction = SuperscalarInstruction::Null;
break;
}
if (trace) std::cout << "; src = r" << currentInstruction.getSource() << std::endl;
}
//find a destination register that will be ready when this instruction executes
if (macroOpIndex == currentInstruction.getInfo().getDstOp()) {
int forward;
for (forward = 0; forward < LOOK_FORWARD_CYCLES && !currentInstruction.selectDestination(scheduleCycle, throwAwayCount > 0, registers, gen); ++forward) {
if (trace) std::cout << "; dst STALL at cycle " << cycle << std::endl;
++scheduleCycle;
++cycle;
}
if (forward == LOOK_FORWARD_CYCLES) { //throw instruction away
if (throwAwayCount < MAX_THROWAWAY_COUNT) {
throwAwayCount++;
macroOpIndex = currentInstruction.getInfo().getSize();
if (trace) std::cout << "; THROW away " << currentInstruction.getInfo().getName() << std::endl;
//cycle = topCycle;
continue;
}
//abort this decode buffer
if (trace) std::cout << "Aborting at cycle " << cycle << " with decode buffer " << decodeBuffer->getName() << " - destination registers not available" << std::endl;
currentInstruction = SuperscalarInstruction::Null;
break;
}
if (trace) std::cout << "; dst = r" << currentInstruction.getDestination() << std::endl;
}
throwAwayCount = 0;
//recalculate when the instruction can be scheduled for execution based on operand availability
scheduleCycle = scheduleMop<true>(mop, portBusy, scheduleCycle, scheduleCycle);
//calculate when the result will be ready
depCycle = scheduleCycle + mop.getLatency();
//if this instruction writes the result, modify register information
// RegisterInfo.latency - which cycle the register will be ready
// RegisterInfo.lastOpGroup - the last operation that was applied to the register
// RegisterInfo.lastOpPar - the last operation source value (-1 = constant, 0-7 = register)
if (macroOpIndex == currentInstruction.getInfo().getResultOp()) {
int dst = currentInstruction.getDestination();
RegisterInfo& ri = registers[dst];
retireCycle = depCycle;
ri.latency = retireCycle;
ri.lastOpGroup = currentInstruction.getGroup();
ri.lastOpPar = currentInstruction.getGroupPar();
if (trace) std::cout << "; RETIRED at cycle " << retireCycle << std::endl;
}
codeSize += mop.getSize();
bufferIndex++;
macroOpIndex++;
macroOpCount++;
//terminating condition
if (scheduleCycle >= RANDOMX_SUPERSCALAR_LATENCY) {
portsSaturated = true;
}
cycle = topCycle;
//when all macro-ops of the current instruction have been issued, add the instruction into the program
if (macroOpIndex >= currentInstruction.getInfo().getSize()) {
currentInstruction.toInstr(prog(programSize++));
mulCount += isMultiplication(currentInstruction.getType());
}
}
++cycle;
}
double ipc = (macroOpCount / (double)retireCycle);
memset(prog.asicLatencies, 0, sizeof(prog.asicLatencies));
//Calculate ASIC latency:
//Assumes 1 cycle latency for all operations and unlimited parallelization.
for (int i = 0; i < programSize; ++i) {
Instruction& instr = prog(i);
int latDst = prog.asicLatencies[instr.dst] + 1;
int latSrc = instr.dst != instr.src ? prog.asicLatencies[instr.src] + 1 : 0;
prog.asicLatencies[instr.dst] = std::max(latDst, latSrc);
}
//address register is the register with the highest ASIC latency
int asicLatencyMax = 0;
int addressReg = 0;
for (int i = 0; i < 8; ++i) {
if (prog.asicLatencies[i] > asicLatencyMax) {
asicLatencyMax = prog.asicLatencies[i];
addressReg = i;
}
prog.cpuLatencies[i] = registers[i].latency;
}
prog.setSize(programSize);
prog.setAddressRegister(addressReg);
prog.cpuLatency = retireCycle;
prog.asicLatency = asicLatencyMax;
prog.codeSize = codeSize;
prog.macroOps = macroOpCount;
prog.decodeCycles = decodeCycle;
prog.ipc = ipc;
prog.mulCount = mulCount;
/*if(INFO) std::cout << "; ALU port utilization:" << std::endl;
if (INFO) std::cout << "; (* = in use, _ = idle)" << std::endl;
int portCycles = 0;
for (int i = 0; i < CYCLE_MAP_SIZE; ++i) {
std::cout << "; " << std::setw(3) << i << " ";
for (int j = 0; j < 3; ++j) {
std::cout << (portBusy[i][j] ? '*' : '_');
portCycles += !!portBusy[i][j];
}
std::cout << std::endl;
}*/
}
void executeSuperscalar(int_reg_t(&r)[8], SuperscalarProgram& prog, std::vector<uint64_t> *reciprocals) {
for (unsigned j = 0; j < prog.getSize(); ++j) {
Instruction& instr = prog(j);
switch ((SuperscalarInstructionType)instr.opcode)
{
case SuperscalarInstructionType::ISUB_R:
r[instr.dst] -= r[instr.src];
break;
case SuperscalarInstructionType::IXOR_R:
r[instr.dst] ^= r[instr.src];
break;
case SuperscalarInstructionType::IADD_RS:
r[instr.dst] += r[instr.src] << instr.getModShift();
break;
case SuperscalarInstructionType::IMUL_R:
r[instr.dst] *= r[instr.src];
break;
case SuperscalarInstructionType::IROR_C:
r[instr.dst] = rotr(r[instr.dst], instr.getImm32());
break;
case SuperscalarInstructionType::IADD_C7:
case SuperscalarInstructionType::IADD_C8:
case SuperscalarInstructionType::IADD_C9:
r[instr.dst] += signExtend2sCompl(instr.getImm32());
break;
case SuperscalarInstructionType::IXOR_C7:
case SuperscalarInstructionType::IXOR_C8:
case SuperscalarInstructionType::IXOR_C9:
r[instr.dst] ^= signExtend2sCompl(instr.getImm32());
break;
case SuperscalarInstructionType::IMULH_R:
r[instr.dst] = mulh(r[instr.dst], r[instr.src]);
break;
case SuperscalarInstructionType::ISMULH_R:
r[instr.dst] = smulh(r[instr.dst], r[instr.src]);
break;
case SuperscalarInstructionType::IMUL_RCP:
if (reciprocals != nullptr)
r[instr.dst] *= (*reciprocals)[instr.getImm32()];
else
r[instr.dst] *= defyx_reciprocal(instr.getImm32());
break;
default:
UNREACHABLE;
}
}
}
}
| 39.581292
| 381
| 0.71064
|
Teredic
|
8d23bd7fec398c47e83030a985c02a77263b4609
| 390
|
cpp
|
C++
|
all/native/datasources/components/VectorData.cpp
|
JianYT/mobile-sdk
|
1835603e6cb7994222fea681928dc90055816628
|
[
"BSD-3-Clause"
] | 155
|
2016-10-20T08:39:13.000Z
|
2022-02-27T14:08:32.000Z
|
all/native/datasources/components/VectorData.cpp
|
JianYT/mobile-sdk
|
1835603e6cb7994222fea681928dc90055816628
|
[
"BSD-3-Clause"
] | 448
|
2016-10-20T12:33:06.000Z
|
2022-03-22T14:42:58.000Z
|
all/native/datasources/components/VectorData.cpp
|
JianYT/mobile-sdk
|
1835603e6cb7994222fea681928dc90055816628
|
[
"BSD-3-Clause"
] | 64
|
2016-12-05T16:04:31.000Z
|
2022-02-07T09:36:22.000Z
|
#include "VectorData.h"
#include "vectorelements/VectorElement.h"
namespace carto {
VectorData::VectorData(std::vector<std::shared_ptr<VectorElement> > elements) :
_elements(std::move(elements))
{
}
VectorData::~VectorData() {
}
const std::vector<std::shared_ptr<VectorElement> >& VectorData::getElements() const {
return _elements;
}
}
| 20.526316
| 89
| 0.653846
|
JianYT
|
8d306544728dd80129b583599067b3b815bd7faf
| 11,675
|
cpp
|
C++
|
src/gateway/ocg_bss/virtual_ocg/ocg_encoder.cpp
|
liutongwei/ft
|
c75c1ea6b4e53128248113f9810b997d2f7ff236
|
[
"MIT"
] | null | null | null |
src/gateway/ocg_bss/virtual_ocg/ocg_encoder.cpp
|
liutongwei/ft
|
c75c1ea6b4e53128248113f9810b997d2f7ff236
|
[
"MIT"
] | null | null | null |
src/gateway/ocg_bss/virtual_ocg/ocg_encoder.cpp
|
liutongwei/ft
|
c75c1ea6b4e53128248113f9810b997d2f7ff236
|
[
"MIT"
] | null | null | null |
// Copyright [2020] <Copyright Kevin, kevin.lau.gd@gmail.com>
#include "virtual_ocg/ocg_encoder.h"
using namespace ft::bss;
void OcgEncoder::encode_msg(const ExecutionReport& report, MsgBuffer* buffer) {
buffer->size = 0;
cur_msg_buf_ = buffer;
auto header = encode_header(EXECUTION_REPORT);
header->body_fields_presence_map[0] = 0b11110011;
header->body_fields_presence_map[1] = 0b01000000;
header->body_fields_presence_map[2] = 0b00000111;
header->body_fields_presence_map[3] = 0b11000000;
encode(report.client_order_id);
encode(report.submitting_broker_id);
encode(report.security_id);
encode(report.security_id_source);
if (report.security_exchange[0] != 0) {
set_presence(header->body_fields_presence_map, 4);
encode(report.security_exchange);
}
if (report.broker_location_id[0] != 0) {
set_presence(header->body_fields_presence_map, 5);
encode(report.broker_location_id);
}
encode(report.transaction_time);
encode(report.side);
if (report.original_client_order_id[0] != 0) {
set_presence(header->body_fields_presence_map, 8);
encode(report.original_client_order_id);
}
encode(report.order_id);
if (report.owning_broker_id[0] != 0) {
set_presence(header->body_fields_presence_map, 10);
encode(report.owning_broker_id);
}
if (report.order_type != 0) {
set_presence(header->body_fields_presence_map, 11);
encode(report.order_type);
}
if (report.price != 0) {
set_presence(header->body_fields_presence_map, 12);
encode(report.price);
}
if (report.order_quantity != 0) {
set_presence(header->body_fields_presence_map, 13);
encode(report.order_quantity);
}
if (1) {
set_presence(header->body_fields_presence_map, 14);
encode(report.tif);
}
if (report.position_effect != 0) {
set_presence(header->body_fields_presence_map, 15);
encode(report.position_effect);
}
if (report.order_restrictions[0] != 0) {
set_presence(header->body_fields_presence_map, 16);
encode(report.order_restrictions);
}
if (report.max_price_levels != 0) {
set_presence(header->body_fields_presence_map, 17);
encode(report.max_price_levels);
}
if (report.order_capacity != 0) {
set_presence(header->body_fields_presence_map, 18);
encode(report.order_capacity);
}
if (report.text.len > 0) {
set_presence(header->body_fields_presence_map, 19);
encode(report.text);
}
if (report.reason.len > 0) {
set_presence(header->body_fields_presence_map, 20);
encode(report.reason);
}
encode(report.execution_id);
encode(report.order_status);
encode(report.exec_type);
encode(report.cumulative_quantity);
encode(report.leaves_quantity);
if (report.order_reject_code != 0) {
set_presence(header->body_fields_presence_map, 26);
encode(report.order_reject_code);
}
if (report.lot_type != 0) {
set_presence(header->body_fields_presence_map, 27);
encode(report.lot_type);
}
if (report.exec_restatement_reason != 0) {
set_presence(header->body_fields_presence_map, 28);
encode(report.exec_restatement_reason);
}
if (report.cancel_reject_code != 0) {
set_presence(header->body_fields_presence_map, 29);
encode(report.cancel_reject_code);
}
if (report.match_type != 0) {
set_presence(header->body_fields_presence_map, 30);
encode(report.match_type);
}
if (report.counterparty_broker_id[0] != 0) {
set_presence(header->body_fields_presence_map, 31);
encode(report.counterparty_broker_id);
}
if (report.execution_quantity != 0) {
set_presence(header->body_fields_presence_map, 32);
encode(report.execution_quantity);
}
if (report.execution_price != 0) {
set_presence(header->body_fields_presence_map, 33);
encode(report.execution_price);
}
if (report.reference_execution_id[0] != 0) {
set_presence(header->body_fields_presence_map, 34);
encode(report.reference_execution_id);
}
if (report.order_category != 0) {
set_presence(header->body_fields_presence_map, 35);
encode(report.order_category);
}
if (report.amend_reject_code != 0) {
set_presence(header->body_fields_presence_map, 36);
encode(report.amend_reject_code);
}
// 37 skip
if (report.trade_match_id[0] != 0) {
set_presence(header->body_fields_presence_map, 38);
encode(report.trade_match_id);
}
if (report.exchange_trade_type != 0) {
set_presence(header->body_fields_presence_map, 39);
encode(report.exchange_trade_type);
}
fill_header_and_trailer();
}
void OcgEncoder::encode_msg(const TradeCaptureReportAck& ack,
MsgBuffer* buffer) {
buffer->size = 0;
cur_msg_buf_ = buffer;
auto header = encode_header(EXECUTION_REPORT);
header->body_fields_presence_map[0] = 0b11101001;
header->body_fields_presence_map[1] = 0b10110000;
encode(ack.trade_report_id);
encode(ack.trade_report_trans_type); //
encode(ack.trade_report_type);
if (ack.trade_handling_instructions != 0) {
set_presence(header->body_fields_presence_map, 3);
encode(ack.trade_handling_instructions);
}
encode(ack.submitting_broker_id);
if (ack.counterparty_broker_id[0] != 0) {
set_presence(header->body_fields_presence_map, 5);
encode(ack.counterparty_broker_id);
}
if (ack.broker_location_id[0] != 0) {
set_presence(header->body_fields_presence_map, 6);
encode(ack.broker_location_id);
}
encode(ack.security_id);
encode(ack.security_id_source);
if (ack.security_exchange[0] != 0) {
set_presence(header->body_fields_presence_map, 9);
encode(ack.security_exchange);
}
encode(ack.side);
encode(ack.transaction_time);
if (ack.trade_id[0] != 0) {
set_presence(header->body_fields_presence_map, 12);
encode(ack.trade_id);
}
if (ack.trade_report_status != 0) {
set_presence(header->body_fields_presence_map, 13);
encode(ack.trade_report_status);
}
if (ack.trade_report_reject_code != 0) {
set_presence(header->body_fields_presence_map, 14);
encode(ack.trade_report_reject_code);
}
if (ack.reason.len > 0) {
set_presence(header->body_fields_presence_map, 15);
encode(ack.reason);
}
fill_header_and_trailer();
}
void OcgEncoder::encode_msg(const QuoteStatusReport& report,
MsgBuffer* buffer) {
buffer->size = 0;
cur_msg_buf_ = buffer;
auto header = encode_header(QUOTE_STATUS_REPORT);
header->body_fields_presence_map[0] = 0b10000000;
header->body_fields_presence_map[1] = 0b10000000;
encode(report.submitting_broker_id);
if (report.broker_location_id[0] != 0) {
set_presence(header->body_fields_presence_map, 1);
encode(report.broker_location_id);
}
if (report.security_id[0] != 0) {
set_presence(header->body_fields_presence_map, 2);
encode(report.security_id);
}
if (report.security_id_source != 0) {
set_presence(header->body_fields_presence_map, 3);
encode(report.security_id_source);
}
if (report.security_exchange[0] != 0) {
set_presence(header->body_fields_presence_map, 4);
encode(report.security_exchange);
}
if (report.quote_bid_id[0] != 0) {
set_presence(header->body_fields_presence_map, 5);
encode(report.quote_bid_id);
}
if (report.quote_offer_id[0] != 0) {
set_presence(header->body_fields_presence_map, 6);
encode(report.quote_offer_id);
}
if (report.quote_type != 0) {
set_presence(header->body_fields_presence_map, 7);
encode(report.quote_type);
}
encode(report.transaction_time);
if (report.quote_message_id[0] != 0) {
set_presence(header->body_fields_presence_map, 9);
encode(report.quote_message_id);
}
if (report.quote_cancel_type != 0) {
set_presence(header->body_fields_presence_map, 10);
encode(report.quote_cancel_type);
}
if (report.quote_status != 0) {
set_presence(header->body_fields_presence_map, 11);
encode(report.quote_status);
}
if (report.quote_reject_code != 0) {
set_presence(header->body_fields_presence_map, 12);
encode(report.quote_reject_code);
}
if (report.reason.len > 0) {
set_presence(header->body_fields_presence_map, 13);
encode(report.reason);
}
fill_header_and_trailer();
}
void OcgEncoder::encode_msg(const OrderMassCancelReport& report,
MsgBuffer* buffer) {
buffer->size = 0;
cur_msg_buf_ = buffer;
auto header = encode_header(ORDER_MASS_CANCEL_REPORT);
header->body_fields_presence_map[0] = 0b00000011;
header->body_fields_presence_map[1] = 0b01100000;
if (report.client_order_id[0] != 0) {
set_presence(header->body_fields_presence_map, 0);
encode(report.client_order_id);
}
if (report.submitting_broker_id[0] != 0) {
set_presence(header->body_fields_presence_map, 1);
encode(report.submitting_broker_id);
}
if (report.security_id[0] != 0) {
set_presence(header->body_fields_presence_map, 2);
encode(report.security_id);
}
if (report.security_id_source != 0) {
set_presence(header->body_fields_presence_map, 4);
encode(report.security_id_source);
}
if (report.security_exchange[0] != 0) {
set_presence(header->body_fields_presence_map, 5);
encode(report.security_exchange);
}
encode(report.transaction_time);
encode(report.mass_cancel_request_type);
if (report.owning_broker_id[0] != 0) {
set_presence(header->body_fields_presence_map, 8);
encode(report.owning_broker_id);
}
encode(report.mass_action_report_id);
encode(report.mass_cancel_response);
if (report.mass_cancel_reject_code != 0) {
set_presence(header->body_fields_presence_map, 11);
encode(report.mass_cancel_reject_code);
}
if (report.reason.len > 0) {
set_presence(header->body_fields_presence_map, 12);
encode(report.reason);
}
fill_header_and_trailer();
}
void OcgEncoder::encode_msg(const BusinessRejectMessage& msg,
MsgBuffer* buffer) {
buffer->size = 0;
cur_msg_buf_ = buffer;
auto header = encode_header(BUSINESS_MESSAGE_REJECT);
header->body_fields_presence_map[0] = 0b10100000;
encode(msg.business_reject_code);
if (msg.reason.len > 0) {
set_presence(header->body_fields_presence_map, 1);
encode(msg.reason);
}
encode(msg.reference_message_type);
if (msg.reference_field_name[0] != 0) {
set_presence(header->body_fields_presence_map, 3);
encode(msg.reference_field_name);
}
if (msg.reference_sequence_number > 0) {
set_presence(header->body_fields_presence_map, 4);
encode(msg.reference_sequence_number);
}
if (msg.business_reject_reference_id[0] != 0) {
set_presence(header->body_fields_presence_map, 5);
encode(msg.business_reject_reference_id);
}
fill_header_and_trailer();
}
void OcgEncoder::encode_msg(const LookupResponse& rsp, MsgBuffer* buffer) {
buffer->size = 0;
cur_msg_buf_ = buffer;
auto header = encode_header(LOOKUP_RESPONSE);
header->sequence_number = 1;
header->body_fields_presence_map[0] = 0b10000000;
encode(rsp.status);
if (rsp.status != LOOKUP_SERVICE_ACCEPTED) {
set_presence(header->body_fields_presence_map, 1);
encode(rsp.lookup_reject_code);
}
if (rsp.reason.len > 0) {
set_presence(header->body_fields_presence_map, 2);
encode(rsp.reason);
}
if (rsp.status == LOOKUP_SERVICE_ACCEPTED) {
set_presence(header->body_fields_presence_map, 3);
set_presence(header->body_fields_presence_map, 4);
set_presence(header->body_fields_presence_map, 5);
set_presence(header->body_fields_presence_map, 6);
encode(rsp.primary_ip);
encode(rsp.primary_port);
encode(rsp.secondary_ip);
encode(rsp.secondary_port);
}
fill_header_and_trailer();
}
| 32.34072
| 79
| 0.719572
|
liutongwei
|
8d31fe997730fd6090d6480468af8a0edfcd27e4
| 4,788
|
cpp
|
C++
|
GerchbergSaxton/test.cpp
|
daelsepara/hipSLM
|
bb85cc24413e2bb7517b85e9cca45dd42fd2baf7
|
[
"MIT"
] | 1
|
2021-08-30T15:26:22.000Z
|
2021-08-30T15:26:22.000Z
|
GerchbergSaxton/test.cpp
|
daelsepara/hipSLM
|
bb85cc24413e2bb7517b85e9cca45dd42fd2baf7
|
[
"MIT"
] | 1
|
2021-09-30T19:23:14.000Z
|
2021-09-30T19:23:22.000Z
|
GerchbergSaxton/test.cpp
|
daelsepara/hipSLM
|
bb85cc24413e2bb7517b85e9cca45dd42fd2baf7
|
[
"MIT"
] | null | null | null |
#define _USE_MATH_DEFINES
#include "../Includes/lodepng.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <dlfcn.h>
#include <stdexcept>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif // !M_PI
#undef min
#undef max
// Allocate double array on host
double* Double(int Length, double val)
{
auto host = (double*)malloc(Length * sizeof(double));
if (host != NULL)
{
for (auto x = 0; x < Length; x++)
{
host[x] = val;
}
}
return host;
}
void phasepng(const char* filename, double* data, int gray, int xdim, int ydim)
{
unsigned char* buffer = (unsigned char*)malloc(xdim * ydim);
for (int index = 0; index < xdim * ydim; index++)
{
unsigned char c = (unsigned char)((double)gray * (data[index]) / (2.0 * M_PI));
buffer[index] = c;
}
unsigned error = lodepng_encode_file(filename, buffer, xdim, ydim, LCT_GREY, 8);
if (error)
{
fprintf(stderr, "error %u: %s\n", error, lodepng_error_text(error));
}
free(buffer);
}
void amppng(const char* filename, double* data, int xdim, int ydim, double scale = 1.0)
{
unsigned char* buffer = (unsigned char*)malloc(xdim * ydim);
for (int index = 0; index < xdim * ydim; index++)
{
unsigned char c = (unsigned char)(data[index] * scale);
buffer[index] = c;
}
unsigned error = lodepng_encode_file(filename, buffer, xdim, ydim, LCT_GREY, 8);
if (error)
{
fprintf(stderr, "error %u: %s\n", error, lodepng_error_text(error));
}
free(buffer);
}
inline double Mod(double a, double m)
{
return a - m * floor(a / m);
}
double* loadpng(const char* filename, int& xdim, int& ydim, double scale = 1.0)
{
unsigned error;
unsigned char* image;
unsigned w, h;
// load PNG
error = lodepng_decode24_file(&image, &w, &h, filename);
// exit on error
if (error)
{
fprintf(stderr, "decoder error %u: %s\n", error, lodepng_error_text(error));
exit(1);
}
// allocate w x h double image
int memsize = w * h * sizeof(double);
auto png = (double*)malloc(memsize);
if (!png)
{
fprintf(stderr, "unable to allocate %u bytes for image\n", memsize);
exit(1);
}
for (int index = 0; index < (int)(w * h); index++)
{
unsigned char r, g, b;
r = image[3 * index + 0]; // red
g = image[3 * index + 1]; // green
b = image[3 * index + 2]; // blue
// convert RGB to grey
auto val = (0.299 * (double)r + 0.587 * (double)g + 0.114 * (double)b) * scale;
png[index] = val;
}
xdim = w;
ydim = h;
free(image);
return png;
}
void ParseInt(std::string arg, const char* str, const char* var, int& dst)
{
auto len = strlen(str);
if (len > 0)
{
if (!arg.compare(0, len, str) && arg.length() > len)
{
try
{
auto val = stoi(arg.substr(len));
fprintf(stderr, "... %s = %d\n", var, val);
dst = val;
}
catch (const std::invalid_argument& ia)
{
fprintf(stderr, "... %s = NaN %s\n", var, ia.what());
exit(1);
}
}
}
}
int main(int argc, char** argv)
{
auto M = 800; // SLM width in # of pixels
auto N = 600; // SLM height in # of pixels
auto Ngs = 1000; // Ngs
auto gpu = false;
char InputFile[200];
InputFile[0] = '\0';
for (int i = 0; i < argc; i++)
{
std::string arg = argv[i];
std::transform(arg.begin(), arg.end(), arg.begin(), ::tolower);
ParseInt(arg, "/m=", "SLM Width", M);
ParseInt(arg, "/n=", "SLM Height", N);
ParseInt(arg, "/i=", "GS Iterations", Ngs);
if (!arg.compare(0, 8, "/target=") && arg.length() > 8)
{
strncpy(InputFile, &argv[i][8], sizeof(InputFile));
}
if (!arg.compare("/gpu"))
{
gpu = true;
fprintf(stderr, "... use GPU\n");
}
}
if (strlen(InputFile) > 0)
{
int targetw;
int targeth;
double* target = loadpng(InputFile, targetw, targeth, 1.0);
double h = 20e-6; // hologram pixel size
bool gaussian = false;
double r = 960e-6; // input gaussian beam waist
// No aperture
int aperture = 0;
int aperturew = targetw;
int apertureh = targeth;
char Libname[200];
void *lib_handle;
void (*Calculate)(int, void**);
char *error;
sprintf(Libname, "./GerchbergSaxton.so");
lib_handle = dlopen(Libname, RTLD_LAZY);
if (!lib_handle)
{
fprintf(stderr, "%s\n", dlerror());
exit(1);
}
Calculate = (void (*)(int, void**)) dlsym(lib_handle, "Calculate");
if ((error = dlerror()) != NULL)
{
fprintf(stderr, "%s\n", error);
exit(1);
}
double *GerchbergSaxtonPhase = Double(M * N, 0.0);
// Gerchberg-Saxton
void* Params[] = { GerchbergSaxtonPhase, &M, &N, &Ngs, &h, &gaussian, &r, &aperture, &aperturew, &apertureh, target, &targetw, &targeth, &gpu };
(*Calculate)(14, Params);
phasepng("phase-gs.png", GerchbergSaxtonPhase, 255, M, N);
free(GerchbergSaxtonPhase);
free(target);
}
return 0;
}
| 19.703704
| 146
| 0.606099
|
daelsepara
|
8d33cce301e5c6bec2ee950e812d8b47ca6892c8
| 12,594
|
cpp
|
C++
|
test/window/comoment_suite.cpp
|
breese/trial.online
|
d28f8025082682ce10d9eb97c63ed0d4e62c7511
|
[
"BSL-1.0"
] | 6
|
2017-11-19T15:12:33.000Z
|
2021-12-18T08:21:45.000Z
|
test/window/comoment_suite.cpp
|
breese/trial.online
|
d28f8025082682ce10d9eb97c63ed0d4e62c7511
|
[
"BSL-1.0"
] | 1
|
2019-02-20T11:28:49.000Z
|
2019-02-20T11:28:49.000Z
|
test/window/comoment_suite.cpp
|
breese/trial.online
|
d28f8025082682ce10d9eb97c63ed0d4e62c7511
|
[
"BSL-1.0"
] | 2
|
2019-02-19T16:00:03.000Z
|
2020-10-29T08:26:44.000Z
|
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2018 Bjorn Reese <breese@users.sourceforge.net>
//
// 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 <trial/online/detail/lightweight_test.hpp>
#include <trial/online/detail/functional.hpp>
#include <trial/online/window/moment.hpp>
#include <trial/online/window/comoment.hpp>
using namespace trial::online;
//-----------------------------------------------------------------------------
namespace properties_suite
{
void test_constant()
{
// Cov(X, a) = 0
const double a = 0.0;
window::covariance<double, 32> filter;
filter.push(0.0, a);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
filter.push(1.0, a);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
filter.push(10.0, a);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
filter.push(100.0, a);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
}
void test_same()
{
// Cov(X, X) = Var(X)
const auto tolerance = detail::close_to<double>(1e-6);
window::covariance<double, 32> filter;
window::moment_variance<double, 32> average;
{
double x = 0.0;
filter.push(x, x);
TRIAL_TEST_WITH(filter.unbiased_variance(), 0.0, tolerance);
TRIAL_TEST_WITH(filter.variance(), 0.0, tolerance);
average.push(x);
TRIAL_TEST_WITH(filter.variance(), average.variance(), tolerance);
}
{
double x = 1.0;
filter.push(x, x);
average.push(x);
TRIAL_TEST_WITH(filter.unbiased_variance(), 0.5, tolerance);
TRIAL_TEST_WITH(filter.variance(), 0.25, tolerance);
TRIAL_TEST_WITH(filter.variance(), average.variance(), tolerance);
}
{
double x = 10.0;
filter.push(x, x);
average.push(x);
TRIAL_TEST_WITH(filter.unbiased_variance(), 30.333333, tolerance);
TRIAL_TEST_WITH(filter.variance(), 20.222222, tolerance);
TRIAL_TEST_WITH(filter.variance(), average.variance(), tolerance);
}
{
double x = 100.0;
filter.push(x, x);
average.push(x);
TRIAL_TEST_WITH(filter.unbiased_variance(), 2340.25, tolerance);
TRIAL_TEST_WITH(filter.variance(), 1755.1875, tolerance);
TRIAL_TEST_WITH(filter.variance(), average.variance(), tolerance);
}
}
void test_commutative()
{
// Cov(X, Y) = Cov(Y, X)
const auto tolerance = detail::close_to<double>(1e-6);
window::covariance<double, 32> lhs;
window::covariance<double, 32> rhs;
{
const double x = 0.0;
const double y = 0.0;
lhs.push(x, y);
rhs.push(y, x);
TRIAL_TEST_WITH(lhs.unbiased_variance(), rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), rhs.variance(), tolerance);
}
{
const double x = -1.0;
const double y = 1.0;
lhs.push(x, y);
rhs.push(y, x);
TRIAL_TEST_WITH(lhs.unbiased_variance(), rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), rhs.variance(), tolerance);
}
{
const double x = -2.0;
const double y = 10.0;
lhs.push(x, y);
rhs.push(y, x);
TRIAL_TEST_WITH(lhs.unbiased_variance(), rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), rhs.variance(), tolerance);
}
{
const double x = -3.0;
const double y = 100.0;
lhs.push(x, y);
rhs.push(y, x);
TRIAL_TEST_WITH(lhs.unbiased_variance(), rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), rhs.variance(), tolerance);
}
{
const double x = -4.0;
const double y = 1000.0;
lhs.push(x, y);
rhs.push(y, x);
TRIAL_TEST_WITH(lhs.unbiased_variance(), rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), rhs.variance(), tolerance);
}
}
void test_distributive()
{
// Cov(aX, bY) = ab Cov(Y, X)
const auto tolerance = detail::close_to<double>(1e-6);
window::covariance<double, 32> lhs;
window::covariance<double, 32> rhs;
const double a = 0.5;
const double b = 2.0;
{
const double x = 0.0;
const double y = 0.0;
lhs.push(a * x, b * y);
rhs.push(x, y);
TRIAL_TEST_WITH(lhs.unbiased_variance(), a * b * rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), a * b * rhs.variance(), tolerance);
}
{
const double x = -1.0;
const double y = 1.0;
lhs.push(a * x, b * y);
rhs.push(x, y);
TRIAL_TEST_WITH(lhs.unbiased_variance(), a * b * rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), a * b * rhs.variance(), tolerance);
}
{
const double x = -2.0;
const double y = 10.0;
lhs.push(a * x, b * y);
rhs.push(x, y);
TRIAL_TEST_WITH(lhs.unbiased_variance(), a * b * rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), a * b * rhs.variance(), tolerance);
}
{
const double x = -3.0;
const double y = 100.0;
lhs.push(a * x, b * y);
rhs.push(x, y);
TRIAL_TEST_WITH(lhs.unbiased_variance(), a * b * rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), a * b * rhs.variance(), tolerance);
}
{
const double x = -4.0;
const double y = 1000.0;
lhs.push(a * x, b * y);
rhs.push(x, y);
TRIAL_TEST_WITH(lhs.unbiased_variance(), a * b * rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), a * b * rhs.variance(), tolerance);
}
}
void test_shift_invariant()
{
// Cov(X + a, Y + b) = Cov(X, Y)
const auto tolerance = detail::close_to<double>(1e-6);
window::covariance<double, 32> lhs;
window::covariance<double, 32> rhs;
const double a = 0.5;
const double b = 2.0;
{
const double x = 0.0;
const double y = 0.0;
lhs.push(x + a, y + b);
rhs.push(x, y);
TRIAL_TEST_WITH(lhs.unbiased_variance(), rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), rhs.variance(), tolerance);
}
{
const double x = -1.0;
const double y = 1.0;
lhs.push(x + a, y + b);
rhs.push(x, y);
TRIAL_TEST_WITH(lhs.unbiased_variance(), rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), rhs.variance(), tolerance);
}
{
const double x = -2.0;
const double y = 10.0;
lhs.push(x + a, y + b);
rhs.push(x, y);
TRIAL_TEST_WITH(lhs.unbiased_variance(), rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), rhs.variance(), tolerance);
}
{
const double x = -3.0;
const double y = 100.0;
lhs.push(x + a, y + b);
rhs.push(x, y);
TRIAL_TEST_WITH(lhs.unbiased_variance(), rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), rhs.variance(), tolerance);
}
{
const double x = -4.0;
const double y = 1000.0;
lhs.push(x + a, y + b);
rhs.push(x, y);
TRIAL_TEST_WITH(lhs.unbiased_variance(), rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), rhs.variance(), tolerance);
}
}
void run()
{
test_constant();
test_same();
test_commutative();
test_distributive();
test_shift_invariant();
}
} // namespace properties_suite
//-----------------------------------------------------------------------------
namespace double_suite
{
void test_empty()
{
window::covariance<double, 4> filter;
TRIAL_TEST_EQ(filter.size(), 0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
}
void test_same_no_increment()
{
window::covariance<double, 4> filter;
filter.push(2.0, 2.0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
filter.push(2.0, 2.0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
filter.push(2.0, 2.0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
filter.push(2.0, 2.0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
filter.push(2.0, 2.0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
}
void test_same_increment_by_one()
{
const auto tolerance = detail::close_to<double>(1e-6);
window::covariance<double, 4> filter;
filter.push(1.0, 1.0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
filter.push(2.0, 2.0);
TRIAL_TEST_WITH(filter.variance(), 0.25, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 0.5, tolerance);
filter.push(3.0, 3.0);
TRIAL_TEST_WITH(filter.variance(), 0.666667, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 1.0, tolerance);
filter.push(4.0, 4.0);
TRIAL_TEST_WITH(filter.variance(), 1.25, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 1.666667, tolerance);
// Window full
filter.push(5.0, 5.0);
TRIAL_TEST_WITH(filter.variance(), 1.25, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 1.666667, tolerance);
}
void test_same_increment_by_half()
{
const auto tolerance = detail::close_to<double>(1e-6);
window::covariance<double, 4> filter;
filter.push(1.0, 1.0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
filter.push(1.5, 1.5);
TRIAL_TEST_WITH(filter.variance(), 0.0625, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 0.125, tolerance);
filter.push(2.0, 2.0);
TRIAL_TEST_WITH(filter.variance(), 0.1666667, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 0.25, tolerance);
filter.push(2.5, 2.5);
TRIAL_TEST_WITH(filter.variance(), 0.3125, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 0.416667, tolerance);
// Window full
filter.push(3.0, 3.0);
TRIAL_TEST_WITH(filter.variance(), 0.3125, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 0.416667, tolerance);
}
void test_exponential_increase()
{
const auto tolerance = detail::close_to<double>(1e-5);
window::covariance<double, 4> filter;
filter.push(1e0, 1e0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
filter.push(1e1, 1e1);
TRIAL_TEST_WITH(filter.variance(), 20.25, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 40.5, tolerance);
filter.push(1e2, 1e2);
TRIAL_TEST_WITH(filter.variance(), 1998.0, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 2997.0, tolerance);
filter.push(1e3, 1e3);
TRIAL_TEST_WITH(filter.variance(), 1.7538e5, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 2.3384e5, tolerance);
filter.push(1e4, 1e4);
TRIAL_TEST_WITH(filter.variance(), 1.7538e7, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 2.3384e7, tolerance);
filter.push(1e5, 1e5);
TRIAL_TEST_WITH(filter.variance(), 1.7538e9, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 2.3384e9, tolerance);
filter.push(1e6, 1e6);
TRIAL_TEST_WITH(filter.variance(), 1.7538e11, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 2.3384e11, tolerance);
}
void test_clear()
{
window::covariance<double, 4> filter;
TRIAL_TEST_EQ(filter.size(), 0);
filter.push(0.0, 0.0);
TRIAL_TEST_EQ(filter.size(), 1);
filter.clear();
TRIAL_TEST_EQ(filter.size(), 0);
}
void run()
{
test_empty();
test_clear();
test_same_no_increment();
test_same_increment_by_one();
test_same_increment_by_half();
test_exponential_increase();
}
} // namespace double_suite
//-----------------------------------------------------------------------------
// main
//-----------------------------------------------------------------------------
int main()
{
properties_suite::run();
double_suite::run();
return boost::report_errors();
}
| 33.31746
| 93
| 0.607035
|
breese
|
8d34c7bae19e7362e8219977ccad3b3ffe386c1c
| 468
|
cpp
|
C++
|
map/extra features.cpp
|
FirdausJawed/DSA
|
caf72a4606746009bc4616bfe11cdcb6ca103dcd
|
[
"MIT"
] | 2
|
2021-08-31T11:20:29.000Z
|
2021-09-05T10:51:36.000Z
|
map/extra features.cpp
|
FirdausJawed/DSA
|
caf72a4606746009bc4616bfe11cdcb6ca103dcd
|
[
"MIT"
] | null | null | null |
map/extra features.cpp
|
FirdausJawed/DSA
|
caf72a4606746009bc4616bfe11cdcb6ca103dcd
|
[
"MIT"
] | 1
|
2021-09-01T14:30:49.000Z
|
2021-09-01T14:30:49.000Z
|
#include<bits/stdc++.h>
using namespace std;
void print (map<int,string>&m){
cout<<m.size()<<endl;
for(auto pr:m){
cout<<pr.first<<" "<<pr.second<<endl;
}
}
int main(){
map<int,string>m;
m[1]="fj";
m[5]="fird";
m[3]="muskan";
m[2]="tgb";
m[7]="firdaus";
m.insert({4,"the great fj"});
int x;
cin>>x;
auto it = m.find(x);
if (it != m.end())
{
cout<<"yes "<<m[x]<<endl;
}
else{
cout<<"no"<<endl;
}
//print(m);
return 0;
}
| 14.625
| 45
| 0.510684
|
FirdausJawed
|
8d3983fdcc301d428f164a2773dacad7b52f6844
| 742
|
hpp
|
C++
|
src/hash_map.hpp
|
ecnerwala/cp-book
|
89ba206e1d65ab48819d956d76073057fb43434e
|
[
"CC0-1.0"
] | 351
|
2019-11-26T14:56:22.000Z
|
2022-03-30T10:40:13.000Z
|
src/hash_map.hpp
|
Mastermind-git/cp-book
|
53d97ec192a60e2956c2b4fbe17840ab74c066d6
|
[
"CC0-1.0"
] | 8
|
2019-12-24T21:37:19.000Z
|
2021-05-17T07:33:55.000Z
|
src/hash_map.hpp
|
Mastermind-git/cp-book
|
53d97ec192a60e2956c2b4fbe17840ab74c066d6
|
[
"CC0-1.0"
] | 57
|
2020-04-28T09:20:17.000Z
|
2022-02-13T09:35:31.000Z
|
#pragma once
#include<bits/stdc++.h>
#include<bits/extc++.h>
struct splitmix64_hash {
static uint64_t splitmix64(uint64_t x) {
// http://xorshift.di.unimi.it/splitmix64.c
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}
size_t operator()(uint64_t x) const {
static const uint64_t FIXED_RANDOM = std::chrono::steady_clock::now().time_since_epoch().count();
return splitmix64(x + FIXED_RANDOM);
}
};
template <typename K, typename V, typename Hash = splitmix64_hash>
using hash_map = __gnu_pbds::gp_hash_table<K, V, Hash>;
template <typename K, typename Hash = splitmix64_hash>
using hash_set = hash_map<K, __gnu_pbds::null_type, Hash>;
| 28.538462
| 99
| 0.700809
|
ecnerwala
|
8d3d220db6678fa822eb0358f6a79288b9a21f3f
| 624
|
cpp
|
C++
|
Nmeetings.cpp
|
KaranKaira/Questions-Algorithms
|
c6416592d335be94656f3d58a01c972059d41528
|
[
"MIT"
] | null | null | null |
Nmeetings.cpp
|
KaranKaira/Questions-Algorithms
|
c6416592d335be94656f3d58a01c972059d41528
|
[
"MIT"
] | null | null | null |
Nmeetings.cpp
|
KaranKaira/Questions-Algorithms
|
c6416592d335be94656f3d58a01c972059d41528
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
struct job{
int st, end,ind;
};
bool comp(job a,job b)
{
return a.end < b.end;
}
int main() {
int t;cin>>t;while(t--)
{
int n;cin>>n;
job a[n];
for(int i=0;i<n;i++) cin>>a[i].st;
for(int i=0;i<n;i++) {cin>>a[i].end;a[i].ind = i+1;}
sort(a,a+n,comp);
int k=0;
cout<<a[k].ind<<" ";
for(int i=1;i<n;i++)
{
if(a[i].st >= a[k].end) {
cout<<a[i].ind<<" ";
k = i;
}
}
cout<<endl;
}
return 0;
}
| 18.909091
| 60
| 0.375
|
KaranKaira
|
8d3d9425d2a317b010def452cc92830e97ca601e
| 18,622
|
cpp
|
C++
|
Plugins/Main/mcplugin_main.cpp
|
alexanderoster/AutodeskMachineControlFramework
|
17aec986c2cb3c9ea46bbe583bdc0e766e6f980b
|
[
"BSD-3-Clause"
] | null | null | null |
Plugins/Main/mcplugin_main.cpp
|
alexanderoster/AutodeskMachineControlFramework
|
17aec986c2cb3c9ea46bbe583bdc0e766e6f980b
|
[
"BSD-3-Clause"
] | null | null | null |
Plugins/Main/mcplugin_main.cpp
|
alexanderoster/AutodeskMachineControlFramework
|
17aec986c2cb3c9ea46bbe583bdc0e766e6f980b
|
[
"BSD-3-Clause"
] | null | null | null |
/*++
Copyright (C) 2020 Autodesk Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Autodesk Inc. nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL AUTODESK INC. BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "libmcplugin_statefactory.hpp"
#include "libmcplugin_interfaceexception.hpp"
#include "libmcplugin_state.hpp"
using namespace LibMCPlugin::Impl;
#include "libmcenv_drivercast.hpp"
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4250)
#endif
/*************************************************************************************************************************
Class definition of CMainData
**************************************************************************************************************************/
class CMainData : public virtual CPluginData {
protected:
public:
};
/*************************************************************************************************************************
Class definition of CMainState
**************************************************************************************************************************/
typedef CState<CMainData> CMainState;
/*************************************************************************************************************************
Class definition of CMainState_Init
**************************************************************************************************************************/
class CMainState_Init : public virtual CMainState {
public:
CMainState_Init(const std::string& sStateName, PPluginData pPluginData)
: CMainState (getStateName (), sStateName, pPluginData)
{
}
static const std::string getStateName()
{
return "init";
}
void Execute(LibMCEnv::PStateEnvironment pStateEnvironment)
{
pStateEnvironment->LogMessage("Initializing...");
pStateEnvironment->SetIntegerParameter("jobinfo", "layercount", 0);
pStateEnvironment->SetIntegerParameter("jobinfo", "currentlayer", 0);
pStateEnvironment->SetBoolParameter("jobinfo", "printinprogress", false);
pStateEnvironment->SetNextState("idle");
}
};
/*************************************************************************************************************************
Class definition of CMainState_Idle
**************************************************************************************************************************/
class CMainState_Idle : public virtual CMainState {
public:
CMainState_Idle(const std::string& sStateName, PPluginData pPluginData)
: CMainState(getStateName(), sStateName, pPluginData)
{
}
static const std::string getStateName()
{
return "idle";
}
void Execute(LibMCEnv::PStateEnvironment pStateEnvironment)
{
LibMCEnv::PSignalHandler pSignalHandler;
double targetO2 = pStateEnvironment->GetDoubleParameter("processsettings", "targeto2");
pStateEnvironment->SetDoubleParameter("processsettings", "targeto2", targetO2 + 1.0);
pStateEnvironment->SetBoolParameter("ui", "preparebuilddisabled", !pStateEnvironment->GetBoolParameter("ui", "preparebuilddisabled"));
pStateEnvironment->LogMessage ("Waiting for user input...");
if (pStateEnvironment->WaitForSignal("signal_preparebuildjob", 100, pSignalHandler)) {
auto sJobUUID = pSignalHandler->GetUUID("jobuuid");
pStateEnvironment->SetStringParameter("jobinfo", "jobuuid", sJobUUID);
pSignalHandler->SignalHandled();
pStateEnvironment->LogMessage("Preparing job " + sJobUUID);
pStateEnvironment->SetNextState("preparebuild");
}
else if (pStateEnvironment->WaitForSignal("signal_changeprocesssettings", 100, pSignalHandler)) {
double dTargetO2 = pSignalHandler->GetDouble("targeto2");
double dRecoaterSpeed = pSignalHandler->GetDouble("recoaterspeed");
double dGasFlowSpeed = pSignalHandler->GetDouble("gasflowspeed");
pSignalHandler->SignalHandled();
pStateEnvironment->SetDoubleParameter("processsettings", "targeto2", dTargetO2);
pStateEnvironment->SetDoubleParameter("processsettings", "recoaterspeed", dRecoaterSpeed);
pStateEnvironment->SetDoubleParameter("processsettings", "gasflowspeed", dGasFlowSpeed);
pStateEnvironment->LogMessage("Updated process Parameters!");
pStateEnvironment->SetNextState("idle");
}
else {
pStateEnvironment->SetNextState("idle");
}
}
};
/*************************************************************************************************************************
Class definition of CMainState_PrepareBuild
**************************************************************************************************************************/
class CMainState_PrepareBuild : public virtual CMainState {
public:
CMainState_PrepareBuild(const std::string& sStateName, PPluginData pPluginData)
: CMainState(getStateName(), sStateName, pPluginData)
{
}
static const std::string getStateName()
{
return "preparebuild";
}
void Execute(LibMCEnv::PStateEnvironment pStateEnvironment)
{
pStateEnvironment->LogMessage("Waiting for build preparation...");
LibMCEnv::PSignalHandler pSignalHandler;
if (pStateEnvironment->WaitForSignal("signal_cancelbuildpreparation", 100, pSignalHandler)) {
pStateEnvironment->SetStringParameter("jobinfo", "jobuuid", "00000000-0000-0000-0000-000000000000");
pSignalHandler->SignalHandled();
pStateEnvironment->SetNextState("idle");
}
else if (pStateEnvironment->WaitForSignal("signal_startbuild", 100, pSignalHandler)) {
pSignalHandler->SignalHandled();
pStateEnvironment->SetNextState("initbuild");
}
else {
pStateEnvironment->SetNextState("preparebuild");
}
}
};
/*************************************************************************************************************************
Class definition of CMainState_InitBuild
**************************************************************************************************************************/
class CMainState_InitBuild : public virtual CMainState {
public:
CMainState_InitBuild(const std::string& sStateName, PPluginData pPluginData)
: CMainState(getStateName(), sStateName, pPluginData)
{
}
static const std::string getStateName()
{
return "initbuild";
}
void Execute(LibMCEnv::PStateEnvironment pStateEnvironment)
{
pStateEnvironment->LogMessage("Initializing build...");
auto sJobUUID = pStateEnvironment->GetUUIDParameter("jobinfo", "jobuuid");
pStateEnvironment->LogMessage("Loading Toolpath...");
auto pBuildJob = pStateEnvironment->GetBuildJob (sJobUUID);
pBuildJob->LoadToolpath();
auto sJobName = pBuildJob->GetName();
auto nLayerCount = pBuildJob->GetLayerCount();
pStateEnvironment->LogMessage("Job Name: " + sJobName);
pStateEnvironment->LogMessage("Layer Count: " + std::to_string (nLayerCount));
pStateEnvironment->SetIntegerParameter("jobinfo", "currentlayer", 0);
pStateEnvironment->SetIntegerParameter("jobinfo", "layercount", nLayerCount);
pStateEnvironment->Sleep(1000);
pStateEnvironment->LogMessage("Waiting for atmosphere...");
pStateEnvironment->Sleep(3000);
pStateEnvironment->SetNextState("beginlayer");
}
};
/*************************************************************************************************************************
Class definition of CMainState_BeginLayer
**************************************************************************************************************************/
class CMainState_BeginLayer : public virtual CMainState {
public:
CMainState_BeginLayer(const std::string& sStateName, PPluginData pPluginData)
: CMainState(getStateName(), sStateName, pPluginData)
{
}
static const std::string getStateName()
{
return "beginlayer";
}
void Execute(LibMCEnv::PStateEnvironment pStateEnvironment)
{
auto nLayer = pStateEnvironment->GetIntegerParameter("jobinfo", "currentlayer");
pStateEnvironment->LogMessage("Starting layer " + std::to_string (nLayer));
pStateEnvironment->SetNextState("recoatlayer");
}
};
/*************************************************************************************************************************
Class definition of CMainState_BeginLayer
**************************************************************************************************************************/
class CMainState_RecoatLayer : public virtual CMainState {
public:
CMainState_RecoatLayer(const std::string& sStateName, PPluginData pPluginData)
: CMainState(getStateName(), sStateName, pPluginData)
{
}
static const std::string getStateName()
{
return "recoatlayer";
}
void Execute(LibMCEnv::PStateEnvironment pStateEnvironment)
{
pStateEnvironment->LogMessage("Recoating layer...");
auto nRecoatingTimeOut = pStateEnvironment->GetIntegerParameter("jobinfo", "recoatingtimeout");
auto pSignal = pStateEnvironment->PrepareSignal("plc", "signal_recoatlayer");
pSignal->Trigger();
if (pSignal->WaitForHandling((uint32_t)nRecoatingTimeOut)) {
if (pSignal->GetBoolResult("success")) {
pStateEnvironment->LogMessage("Recoating successful...");
pStateEnvironment->SetNextState("exposelayer");
}
else {
pStateEnvironment->LogMessage("Recoating failed...");
pStateEnvironment->SetNextState("fatalerror");
}
}
else {
pStateEnvironment->LogMessage("Recoating timeout...");
pStateEnvironment->SetNextState("fatalerror");
}
}
};
/*************************************************************************************************************************
Class definition of CMainState_ExposeLayer
**************************************************************************************************************************/
class CMainState_ExposeLayer : public virtual CMainState {
public:
CMainState_ExposeLayer(const std::string& sStateName, PPluginData pPluginData)
: CMainState(getStateName(), sStateName, pPluginData)
{
}
static const std::string getStateName()
{
return "exposelayer";
}
void Execute(LibMCEnv::PStateEnvironment pStateEnvironment)
{
pStateEnvironment->LogMessage("Exposing layer...");
auto sJobUUID = pStateEnvironment->GetStringParameter("jobinfo", "jobuuid");
auto nCurrentLayer = pStateEnvironment->GetIntegerParameter("jobinfo", "currentlayer");
auto nExposureTimeOut = pStateEnvironment->GetIntegerParameter("jobinfo", "exposuretimeout");
auto pSignal = pStateEnvironment->PrepareSignal("laser", "signal_exposure");
pSignal->SetString("jobuuid", sJobUUID);
pSignal->SetInteger("layerindex", nCurrentLayer);
pSignal->SetInteger("timeout", nExposureTimeOut);
pSignal->Trigger();
if (pSignal->WaitForHandling((uint32_t)nExposureTimeOut)) {
pStateEnvironment->LogMessage("Layer successfully exposed...");
pStateEnvironment->SetNextState("finishlayer");
}
else {
pStateEnvironment->LogMessage("Layer exposure failed...");
pStateEnvironment->SetNextState("fatalerror");
}
}
};
/*************************************************************************************************************************
Class definition of CMainState_FinishLayer
**************************************************************************************************************************/
class CMainState_FinishLayer : public virtual CMainState {
public:
CMainState_FinishLayer(const std::string& sStateName, PPluginData pPluginData)
: CMainState(getStateName(), sStateName, pPluginData)
{
}
static const std::string getStateName()
{
return "finishlayer";
}
void Execute(LibMCEnv::PStateEnvironment pStateEnvironment)
{
auto nLayer = pStateEnvironment->GetIntegerParameter("jobinfo", "currentlayer");
auto nLayerCount = pStateEnvironment->GetIntegerParameter("jobinfo", "layercount");
pStateEnvironment->LogMessage("Finished layer " + std::to_string (nLayer));
nLayer++;
pStateEnvironment->SetIntegerParameter("jobinfo", "currentlayer", nLayer);
if (nLayer < nLayerCount) {
pStateEnvironment->SetNextState("beginlayer");
}
else {
pStateEnvironment->SetNextState("finishbuild");
}
}
};
/*************************************************************************************************************************
Class definition of CMainState_FinishBuild
**************************************************************************************************************************/
class CMainState_FinishBuild : public virtual CMainState {
public:
CMainState_FinishBuild(const std::string& sStateName, PPluginData pPluginData)
: CMainState(getStateName(), sStateName, pPluginData)
{
}
static const std::string getStateName()
{
return "finishbuild";
}
void Execute(LibMCEnv::PStateEnvironment pStateEnvironment)
{
pStateEnvironment->LogMessage("Finishing Build...");
pStateEnvironment->LogMessage("Turning laser off...");
pStateEnvironment->Sleep(1000);
pStateEnvironment->SetNextState("idle");
}
};
/*************************************************************************************************************************
Class definition of CMainState_PauseBuild
**************************************************************************************************************************/
class CMainState_PauseBuild : public virtual CMainState {
public:
CMainState_PauseBuild(const std::string& sStateName, PPluginData pPluginData)
: CMainState(getStateName(), sStateName, pPluginData)
{
}
static const std::string getStateName()
{
return "pausebuild";
}
void Execute(LibMCEnv::PStateEnvironment pStateEnvironment)
{
pStateEnvironment->LogMessage("Build paused");
pStateEnvironment->Sleep(3000);
pStateEnvironment->SetNextState("pausebuild");
}
};
/*************************************************************************************************************************
Class definition of CMainState_FatalError
**************************************************************************************************************************/
class CMainState_FatalError : public virtual CMainState {
public:
CMainState_FatalError(const std::string& sStateName, PPluginData pPluginData)
: CMainState(getStateName(), sStateName, pPluginData)
{
}
static const std::string getStateName()
{
return "fatalerror";
}
void Execute(LibMCEnv::PStateEnvironment pStateEnvironment)
{
// Unload all toolpathes that might be in memory
pStateEnvironment->UnloadAllToolpathes();
pStateEnvironment->SetNextState("fatalerror");
}
};
/*************************************************************************************************************************
Class definition of CMainState_CancelBuild
**************************************************************************************************************************/
class CMainState_CancelBuild : public virtual CMainState {
public:
CMainState_CancelBuild(const std::string& sStateName, PPluginData pPluginData)
: CMainState(getStateName(), sStateName, pPluginData)
{
}
static const std::string getStateName()
{
return "cancelbuild";
}
void Execute(LibMCEnv::PStateEnvironment pStateEnvironment)
{
pStateEnvironment->LogMessage("Canceling Build...");
pStateEnvironment->LogMessage("Turning laser off...");
pStateEnvironment->Sleep(1000);
pStateEnvironment->SetNextState("idle");
}
};
/*************************************************************************************************************************
Class definition of CStateFactory
**************************************************************************************************************************/
CStateFactory::CStateFactory(const std::string& sInstanceName)
{
m_pPluginData = std::make_shared<CMainData>();
}
IState * CStateFactory::CreateState(const std::string & sStateName)
{
IState* pStateInstance = nullptr;
if (createStateInstanceByName<CMainState_Init>(sStateName, pStateInstance, m_pPluginData))
return pStateInstance;
if (createStateInstanceByName<CMainState_Idle>(sStateName, pStateInstance, m_pPluginData))
return pStateInstance;
if (createStateInstanceByName<CMainState_FatalError>(sStateName, pStateInstance, m_pPluginData))
return pStateInstance;
if (createStateInstanceByName<CMainState_PrepareBuild>(sStateName, pStateInstance, m_pPluginData))
return pStateInstance;
if (createStateInstanceByName<CMainState_InitBuild>(sStateName, pStateInstance, m_pPluginData))
return pStateInstance;
if (createStateInstanceByName<CMainState_BeginLayer>(sStateName, pStateInstance, m_pPluginData))
return pStateInstance;
if (createStateInstanceByName<CMainState_RecoatLayer>(sStateName, pStateInstance, m_pPluginData))
return pStateInstance;
if (createStateInstanceByName<CMainState_ExposeLayer>(sStateName, pStateInstance, m_pPluginData))
return pStateInstance;
if (createStateInstanceByName<CMainState_FinishLayer>(sStateName, pStateInstance, m_pPluginData))
return pStateInstance;
if (createStateInstanceByName<CMainState_FinishBuild>(sStateName, pStateInstance, m_pPluginData))
return pStateInstance;
if (createStateInstanceByName<CMainState_PauseBuild>(sStateName, pStateInstance, m_pPluginData))
return pStateInstance;
if (createStateInstanceByName<CMainState_CancelBuild>(sStateName, pStateInstance, m_pPluginData))
return pStateInstance;
throw ELibMCPluginInterfaceException(LIBMCPLUGIN_ERROR_INVALIDSTATENAME);
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
| 31.509306
| 136
| 0.619106
|
alexanderoster
|
8d408677d1cfba6b8bae0aa9395cf5ca37691f5c
| 4,016
|
cpp
|
C++
|
14.image_text_glut/text.cpp
|
JackeyLea/OpenGL_Freshman
|
d17468d7f2faf752c9a0ccb8f12a2ca4cb8e3a91
|
[
"MIT"
] | 1
|
2022-02-08T01:24:50.000Z
|
2022-02-08T01:24:50.000Z
|
14.image_text_glut/text.cpp
|
JackeyLea/OpenGL_Beginner
|
d17468d7f2faf752c9a0ccb8f12a2ca4cb8e3a91
|
[
"MIT"
] | null | null | null |
14.image_text_glut/text.cpp
|
JackeyLea/OpenGL_Beginner
|
d17468d7f2faf752c9a0ccb8f12a2ca4cb8e3a91
|
[
"MIT"
] | null | null | null |
///
/// \note 加载字体并显示文字
///
#include <GL/gl.h>
#include <GL/glut.h>
#include <GL/glx.h>
#include <unistd.h>//延时
#include <cmath>
#include <iostream>
#include <string>
#include <cstring>
#define ESCAPE 27//esc键ASCII码值
int window; //glut窗口标识号
GLuint base;//字体集的基本显示列表
GLfloat cnt1;//用于移动文字和颜色的计数器
GLfloat cnt2;//同上
void buildFont(){
Display *dpy;
XFontStruct *fontInfo;//存储字体
base = glGenLists(96);//存储96个字符
/*
加载字体。
你拥有什么字体由操作系统决定,
我的系统中字体位于/usr/X11R6/lib/X11/fonts/*,
同时包含fonts.alias和fonts.dir文件来说明.pcf.gz文件中是什么字体。
在任何情况下,你的系统应该至少包含一种字体,否则你将看不见任何文字
获取当前显示。
这将根据环境变量打开与显示服务的第二个连接,并且至少持续到加载完字体为止。
*/
dpy = XOpenDisplay(NULL);//默认为环境变量值
fontInfo = XLoadQueryFont(dpy,"-adobe-helvetica-medium-r-normal--18-*-*-*-p-*-iso8859-1");
if(fontInfo==NULL){
fontInfo = XLoadQueryFont(dpy,"fixed");
if(fontInfo==NULL){
std::cout<<"No X font found.\n"<<std::endl;
}
}
/*
加载字体信息之后,可以处理(旋转、缩放等)字体
*/
/*
从32(空格)开始,获取96个字符(z之后的一些字符),将其存储在base中
*/
glXUseXFont(fontInfo->fid,32,96,base);
//获取完显示列表后缩放内存
XFreeFont(dpy,fontInfo);
//关闭与显示服务器的连接
XCloseDisplay(dpy);
}
void killFont(){
glDeleteLists(base,96);//删除全部96个字符
}
//自定义显示方法
void glPrint(char *text){
if(text==NULL){//没有东西显示就退出
return ;
}
glPushAttrib(GL_LIST_BIT);//我们将通过glListBase偏移显示列表
glListBase(base-32);//设置基准字符为32
glCallLists(strlen(text),GL_UNSIGNED_BYTE,text);//绘制显示文本
glPopAttrib();//取消glPushAtrrib的功能
}
//初始化函数,设置所有初始化值
void initGL(int width, int height)
{
glClearColor(0.0f, 0.0f, 0.0f, 0.0f); //将界面背景清空为红绿蓝alpha值对应的颜色
glClearDepth(1.0);//设置清空深度缓冲区(depth buffer)
glDepthFunc(GL_LESS);//设置深度测试的类型
glEnable(GL_DEPTH_TEST);//设置进行深度测试(depth test)
glShadeModel(GL_SMOOTH);//栅格化模式为平滑,只有平滑和两种模式
glMatrixMode(GL_PROJECTION);//矩阵模式为投影模式
glLoadIdentity();//重置投影矩阵
gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);//计算窗口的显示比例
glMatrixMode(GL_MODELVIEW);//
buildFont();
}
//OpenGL的主要绘图函数,绘制什么显示什么。
void displayGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);//清空界面和depth缓冲区
glLoadIdentity();//调整视场
glTranslatef(0.0f,0.0f,-1.0f);//平移
//基于文本位置的颜色
glColor3f(1.0f*((float)(cos(cnt1))),1.0f*((float)(sin(cnt2))),1.0f-0.5f*((float)(cos(cnt1+cnt2))));
//文本在屏幕的位置
glRasterPos2f(-0.2f+0.35f*((float)(cos(cnt1))),0.35f*((float)(sin(cnt2))));
glPrint("My name is JackeyLea");//显示文本
cnt1+=0.001f;
cnt2+=0.0081f;
//双缓冲技术,交换缓冲区以显示刚刚绘制的图像
glutSwapBuffers();
}
// 窗口大小变化回调函数
void reshapeGL(int w, int h)
{
if(h==0){//防止出现长度为0的情况,尤其是下面还将h用作除数
h=1;
}
glViewport(0, 0, w, h);//重置当前窗口的视场和角度
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, static_cast<GLfloat>(w/h),0.1f,100.0f); //设置长宽视景
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
//如果有按键按下调用此函数
void keyboard(unsigned char key, int x, int y)
{
usleep(100);//稍微延时以免干扰
if (key == ESCAPE)//如果是escape键
{
glutDestroyWindow(window); //销毁窗口
exit(0);//正常退出程序
}
}
int main(int argc,char **argv)
{
//初始化glut状态,并且接管所有传给程序的参数
glutInit(&argc, argv);
//设置显示模式:双缓冲、RGBA颜色、alpha支持、depth缓冲支持
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH);
// 初始化窗口
glutInitWindowSize(640, 480); //初始界面大小
glutInitWindowPosition(100, 100); //界面初始位置,相对于屏幕左上角的像素值
//创建界面,界面标题为argv[0],即程序名称,也可以以字符串进行指定
//同时获取创建的窗口ID号,销毁时使用
window = glutCreateWindow(argv[0]);
glutIdleFunc(&displayGL);//即使没有任何事件,也重绘场景
glutReshapeFunc(&reshapeGL);//注册调整窗口大小回调函数
glutDisplayFunc(&displayGL);//注册主要绘图回调函数
glutKeyboardFunc(&keyboard);//注册键盘回调函数
initGL(640,480);//初始化窗口
glutMainLoop();//开始事件处理引擎
return 0;
}
| 23.213873
| 104
| 0.630976
|
JackeyLea
|
8d42dc7dba9c7cc3254acac2957982f28f1dec98
| 3,075
|
cpp
|
C++
|
src/game/localization.cpp
|
ftk/XXLDDRace
|
68ae75092f4483f003e165d93e6334524015dfec
|
[
"Zlib"
] | 2
|
2015-04-23T16:38:41.000Z
|
2016-05-24T00:59:25.000Z
|
src/game/localization.cpp
|
ftk/XXLDDRace
|
68ae75092f4483f003e165d93e6334524015dfec
|
[
"Zlib"
] | null | null | null |
src/game/localization.cpp
|
ftk/XXLDDRace
|
68ae75092f4483f003e165d93e6334524015dfec
|
[
"Zlib"
] | 1
|
2019-10-21T23:12:12.000Z
|
2019-10-21T23:12:12.000Z
|
/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com. */
#include "localization.h"
#include <base/tl/algorithm.h>
#include <engine/shared/linereader.h>
#include <engine/console.h>
#include <engine/storage.h>
#include <unordered_map>
static std::unordered_map<const char*, const char*> loc;
const char *Localize(const char *pStr)
{
//dbg_msg("localize", "searching for %s", pStr);
auto it = loc.find(pStr);
if(it != loc.end())
return it->second;
const char *pNewStr = g_Localization.FindString(str_quickhash(pStr));
pNewStr = pNewStr ? pNewStr : pStr;
//dbg_msg("localize", "%s -> %s", pStr, pNewStr);
loc[pStr] = pNewStr;
return pNewStr;
}
CLocConstString::CLocConstString(const char *pStr)
{
m_pDefaultStr = pStr;
m_Hash = str_quickhash(m_pDefaultStr);
m_Version = -1;
}
void CLocConstString::Reload()
{
m_Version = g_Localization.Version();
const char *pNewStr = g_Localization.FindString(m_Hash);
m_pCurrentStr = pNewStr;
if(!m_pCurrentStr)
m_pCurrentStr = m_pDefaultStr;
}
CLocalizationDatabase::CLocalizationDatabase()
{
m_VersionCounter = 0;
m_CurrentVersion = 0;
}
void CLocalizationDatabase::AddString(const char *pOrgStr, const char *pNewStr)
{
CString s;
s.m_Hash = str_quickhash(pOrgStr);
s.m_Replacement = *pNewStr ? pNewStr : pOrgStr;
m_Strings.add(s);
}
bool CLocalizationDatabase::Load(const char *pFilename, IStorage *pStorage, IConsole *pConsole)
{
// empty string means unload
if(pFilename[0] == 0)
{
m_Strings.clear();
m_CurrentVersion = 0;
return true;
}
IOHANDLE IoHandle = pStorage->OpenFile(pFilename, IOFLAG_READ, IStorage::TYPE_ALL);
if(!IoHandle)
return false;
char aBuf[256];
str_format(aBuf, sizeof(aBuf), "loaded '%s'", pFilename);
pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "localization", aBuf);
m_Strings.clear();
loc.clear();
char aOrigin[512];
CLineReader LineReader;
LineReader.Init(IoHandle);
char *pLine;
while((pLine = LineReader.Get()))
{
if(!str_length(pLine))
continue;
if(pLine[0] == '#') // skip comments
continue;
str_copy(aOrigin, pLine, sizeof(aOrigin));
char *pReplacement = LineReader.Get();
if(!pReplacement)
{
pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "localization", "unexpected end of file");
break;
}
if(pReplacement[0] != '=' || pReplacement[1] != '=' || pReplacement[2] != ' ')
{
str_format(aBuf, sizeof(aBuf), "malform replacement line for '%s'", aOrigin);
pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "localization", aBuf);
continue;
}
pReplacement += 3;
AddString(aOrigin, pReplacement);
}
io_close(IoHandle);
m_CurrentVersion = ++m_VersionCounter;
return true;
}
const char *CLocalizationDatabase::FindString(unsigned Hash)
{
CString String;
String.m_Hash = Hash;
sorted_array<CString>::range r = ::find_binary(m_Strings.all(), String);
if(r.empty())
return 0;
return r.front().m_Replacement;
}
CLocalizationDatabase g_Localization;
| 23.837209
| 95
| 0.708618
|
ftk
|
1d26a58741cb817f07b0c97e73cfc5dc972dbd2f
| 1,428
|
cpp
|
C++
|
BAC_2nd/ch6/UVa12657.cpp
|
Anyrainel/aoapc-code
|
e787a01380698fb9236d933462052f97b20e6132
|
[
"Apache-2.0"
] | 3
|
2017-08-15T06:00:01.000Z
|
2018-12-10T09:05:53.000Z
|
BAC_2nd/ch6/UVa12657.cpp
|
Anyrainel/aoapc-related-code
|
e787a01380698fb9236d933462052f97b20e6132
|
[
"Apache-2.0"
] | null | null | null |
BAC_2nd/ch6/UVa12657.cpp
|
Anyrainel/aoapc-related-code
|
e787a01380698fb9236d933462052f97b20e6132
|
[
"Apache-2.0"
] | 2
|
2017-09-16T18:46:27.000Z
|
2018-05-22T05:42:03.000Z
|
// UVa12657 Boxes in a Line
// Rujia Liu
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 100000 + 5;
int n, left[maxn], right[maxn];
inline void link(int L, int R) {
right[L] = R; left[R] = L;
}
int main() {
int m, kase = 0;
while(scanf("%d%d", &n, &m) == 2) {
for(int i = 1; i <= n; i++) {
left[i] = i-1;
right[i] = (i+1) % (n+1);
}
right[0] = 1; left[0] = n;
int op, X, Y, inv = 0;
while(m--) {
scanf("%d", &op);
if(op == 4) inv = !inv;
else {
scanf("%d%d", &X, &Y);
if(op == 3 && right[Y] == X) swap(X, Y);
if(op != 3 && inv) op = 3 - op;
if(op == 1 && X == left[Y]) continue;
if(op == 2 && X == right[Y]) continue;
int LX = left[X], RX = right[X], LY = left[Y], RY = right[Y];
if(op == 1) {
link(LX, RX); link(LY, X); link(X, Y);
}
else if(op == 2) {
link(LX, RX); link(Y, X); link(X, RY);
}
else if(op == 3) {
if(right[X] == Y) { link(LX, Y); link(Y, X); link(X, RY); }
else { link(LX, Y); link(Y, RX); link(LY, X); link(X, RY); }
}
}
}
int b = 0;
long long ans = 0;
for(int i = 1; i <= n; i++) {
b = right[b];
if(i % 2 == 1) ans += b;
}
if(inv && n % 2 == 0) ans = (long long)n*(n+1)/2 - ans;
printf("Case %d: %lld\n", ++kase, ans);
}
return 0;
}
| 24.20339
| 70
| 0.418768
|
Anyrainel
|
1d28926caaf9e51f33d11cdb62bc7da6eb24f800
| 919
|
cpp
|
C++
|
Day 03/day3.cpp
|
holaguz/AdventOfCode2021
|
349b7a33ab1128264dceb7aaf604030b0df842df
|
[
"Unlicense"
] | null | null | null |
Day 03/day3.cpp
|
holaguz/AdventOfCode2021
|
349b7a33ab1128264dceb7aaf604030b0df842df
|
[
"Unlicense"
] | null | null | null |
Day 03/day3.cpp
|
holaguz/AdventOfCode2021
|
349b7a33ab1128264dceb7aaf604030b0df842df
|
[
"Unlicense"
] | null | null | null |
/* https://adventofcode.com/2021/day/3 */
#include <iostream>
#include <bitset>
#include <vector>
int main(){
int n;
int gamma = 0, epsilon = 0;
std::cin >> n;
std::vector<int> count(64);
std::vector<long long> input(n);
long long max = 0;
for(auto& v: input){
std::cin >> v;
max = v > max ? v : max;
}
int msb = 0;
while(max){
std::cerr << max << std::endl;
max /= 10;
msb++;
}
std::cerr << msb << std::endl;
for (int i = 0; i < n; ++i)
for (int j = 0; j < msb; ++j)
{
count[j] += (input[i] & 1);
input[i] /= 10;
}
for (int i = 0; i < msb; ++i)
{
epsilon |= (2 * count[i] < n ? (1 << i) : 0);
}
gamma = (1 << msb) - epsilon - 1;
std::cerr << epsilon << ' ' << gamma << std::endl;
std::cout << gamma * epsilon << std::endl;
}
| 21.880952
| 57
| 0.425462
|
holaguz
|
1d2b2781fd183efc7741f9e3b155a1647c395c0c
| 6,361
|
cpp
|
C++
|
src/discovery/window.cpp
|
amin-amani/QtNetDiscovery
|
cdc09ddd4813536c45944b388772f7afc8472d80
|
[
"MIT"
] | null | null | null |
src/discovery/window.cpp
|
amin-amani/QtNetDiscovery
|
cdc09ddd4813536c45944b388772f7afc8472d80
|
[
"MIT"
] | null | null | null |
src/discovery/window.cpp
|
amin-amani/QtNetDiscovery
|
cdc09ddd4813536c45944b388772f7afc8472d80
|
[
"MIT"
] | null | null | null |
/**************************************************************************************************
---------------------------------------------------------------------------------------------------
Copyright (C) 2015 Jonathan Bagg
This file is part of QtZeroConf.
QtZeroConf is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QtZeroConf 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 QtZeroConf. If not, see <http://www.gnu.org/licenses/>.
---------------------------------------------------------------------------------------------------
Project name : QtZeroConf Example
File name : window.cpp
Created : 3 November 2015
Author(s) : Jonathan Bagg
---------------------------------------------------------------------------------------------------
Example app to demonstrate service publishing and service discovery
---------------------------------------------------------------------------------------------------
**************************************************************************************************/
#include <QGuiApplication>
#include <QVBoxLayout>
#include <QPushButton>
#include <QTableWidgetItem>
#include <QNetworkInterface>
#include <QHeaderView>
#include <QDebug>
#include "window.h"
#ifdef Q_OS_IOS
#define OS_NAME "iOS"
#elif defined(Q_OS_MAC)
#define OS_NAME "Mac"
#elif defined(Q_OS_ANDROID)
#define OS_NAME "Android"
#elif defined(Q_OS_LINUX)
#define OS_NAME "Linux"
#elif defined(Q_OS_WIN)
#define OS_NAME "Windows"
#elif defined(Q_OS_FREEBSD)
#define OS_NAME "FreeBSD"
#else
#define OS_NAME "Some OS"
#endif
mainWindow::mainWindow()
{
publishEnabled = 0;
buildGUI();
if (!zeroConf.browserExists())
zeroConf.startBrowser("_qtzeroconf_test._tcp");
connect(&zeroConf, &QZeroConf::serviceAdded, this, &mainWindow::addService);
// connect(&zeroConf, &QZeroConf::serviceRemoved, this, &mainWindow::removeService);
// connect(&zeroConf, &QZeroConf::serviceUpdated, this, &mainWindow::updateService);
// connect(qGuiApp, SIGNAL(applicationStateChanged(Qt::ApplicationState)), this, SLOT(appStateChanged(Qt::ApplicationState)));
// publishEnabled = 1;
}
void mainWindow::buildGUI()
{
QPushButton *button;
QVBoxLayout *layout = new QVBoxLayout;
button = new QPushButton(tr(" Enable Publish "));
button->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(button);
layout->setAlignment(button, Qt::AlignHCenter);
connect(button, &QPushButton::clicked, this, &mainWindow::startPublishClicked);
button = new QPushButton(tr(" Disable Publish "));
button->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(button);
layout->setAlignment(button, Qt::AlignHCenter);
connect(button, &QPushButton::clicked, this, &mainWindow::stopPublishClicked);
table.verticalHeader()->hide();
table.horizontalHeader()->hide();
table.setColumnCount(2);
layout->addWidget(&table);
//table.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
QWidget *widget = new QWidget;
widget->setLayout(layout);
setCentralWidget(widget);
show();
}
QString mainWindow::buildName(void)
{
QString name;
QList<QNetworkInterface> list = QNetworkInterface::allInterfaces(); // now you have interfaces list
name = list.last().hardwareAddress();
name.remove(":");
name.remove(0, 6);
name+= ')';
name.prepend("Qt ZeroConf Test - " OS_NAME " (");
return name;
}
void mainWindow::appStateChanged(Qt::ApplicationState state)
{qDebug()<<"changed"<<state;
if (state == Qt::ApplicationSuspended) {
zeroConf.stopServicePublish();
zeroConf.stopBrowser();
}
else if (state == Qt::ApplicationActive) {
if (publishEnabled && !zeroConf.publishExists())
startPublish();
if (!zeroConf.browserExists())
zeroConf.startBrowser("_qtzeroconf_test._tcp");
}
}
// ---------- Service Publish ----------
void mainWindow::startPublish()
{
zeroConf.clearServiceTxtRecords();
zeroConf.addServiceTxtRecord("Qt", "the best!");
zeroConf.addServiceTxtRecord("ZeroConf is nice too");
zeroConf.startServicePublish(buildName().toUtf8(), "_qtzeroconf_test._tcp", "local", 11437);
}
void mainWindow::startPublishClicked()
{
if (publishEnabled)
return;
publishEnabled = 1;
startPublish();
}
void mainWindow::stopPublishClicked()
{
if (!publishEnabled)
return;
publishEnabled = 0;
zeroConf.stopServicePublish();
}
// ---------- Discovery Callbacks ----------
void mainWindow::addService(QZeroConfService zcs)
{
qint32 row;
QTableWidgetItem *cell;
qDebug() << "Added service: " << zcs;
row = table.rowCount();
table.insertRow(row);
cell = new QTableWidgetItem(zcs->name());
table.setItem(row, 0, cell);
cell = new QTableWidgetItem(zcs->ip().toString());
table.setItem(row, 1, cell);
table.resizeColumnsToContents();
#if !(defined(Q_OS_IOS) || defined(Q_OS_ANDROID))
setFixedSize(table.horizontalHeader()->length() + 60, table.verticalHeader()->length() + 100);
#endif
}
void mainWindow::removeService(QZeroConfService zcs)
{
qint32 i, row;
QTableWidgetItem *nameItem, *ipItem;
qDebug() << "Removed service: " << zcs;
QList <QTableWidgetItem*> search = table.findItems(zcs->name(), Qt::MatchExactly);
for (i=0; i<search.size(); i++) {
nameItem = search.at(i);
row = nameItem->row();
ipItem = table.item(row, 1);
if (table.item(row, 1)->text() == zcs->ip().toString()) { // match ip address in case of dual homed systems
delete nameItem;
delete ipItem;
table.removeRow(row);
}
}
}
void mainWindow::updateService(QZeroConfService zcs)
{
qDebug() << "Service updated: " << zcs;
}
| 33.130208
| 130
| 0.617513
|
amin-amani
|
1d30a0ad65cde45076d2fd379cc9cab1a93619ae
| 145
|
cpp
|
C++
|
Source/FSD/Private/SchematicSave.cpp
|
Dr-Turtle/DRG_ModPresetManager
|
abd7ff98a820969504491a1fe68cf2f9302410dc
|
[
"MIT"
] | 8
|
2021-07-10T20:06:05.000Z
|
2022-03-04T19:03:50.000Z
|
Source/FSD/Private/SchematicSave.cpp
|
Dr-Turtle/DRG_ModPresetManager
|
abd7ff98a820969504491a1fe68cf2f9302410dc
|
[
"MIT"
] | 9
|
2022-01-13T20:49:44.000Z
|
2022-03-27T22:56:48.000Z
|
Source/FSD/Private/SchematicSave.cpp
|
Dr-Turtle/DRG_ModPresetManager
|
abd7ff98a820969504491a1fe68cf2f9302410dc
|
[
"MIT"
] | 2
|
2021-07-10T20:05:42.000Z
|
2022-03-14T17:05:35.000Z
|
#include "SchematicSave.h"
FSchematicSave::FSchematicSave() {
this->SkinFixupCounter = 0;
this->bFirstSchematicMessageShown = false;
}
| 18.125
| 46
| 0.731034
|
Dr-Turtle
|
1d31480315eafacec7b9f2a2c70652e55b7f128c
| 544
|
cpp
|
C++
|
OGMM/gui/MenuItem.cpp
|
Moneyl/OGMM
|
52a4bcc051fab160c55f0cc7228bd99de3ff5c47
|
[
"MIT"
] | 3
|
2020-08-26T17:53:47.000Z
|
2020-09-13T07:48:40.000Z
|
OGMM/gui/MenuItem.cpp
|
Moneyl/OGMM
|
52a4bcc051fab160c55f0cc7228bd99de3ff5c47
|
[
"MIT"
] | 2
|
2020-09-01T06:08:28.000Z
|
2020-11-14T02:14:41.000Z
|
OGMM/gui/MenuItem.cpp
|
Moneyl/OGMM
|
52a4bcc051fab160c55f0cc7228bd99de3ff5c47
|
[
"MIT"
] | null | null | null |
#include "MenuItem.h"
#include "IGuiPanel.h"
#include <string_view>
#include <imgui.h>
MenuItem* MenuItem::GetItem(std::string_view text)
{
for (auto& item : Items)
{
if (item.Text == text)
return &item;
}
return nullptr;
}
void MenuItem::Draw()
{
if (panel)
{
ImGui::MenuItem(Text.c_str(), "", &panel->Open);
return;
}
if (ImGui::BeginMenu(Text.c_str()))
{
for (auto& item : Items)
{
item.Draw();
}
ImGui::EndMenu();
}
}
| 17
| 56
| 0.512868
|
Moneyl
|
1d31b033e30bcb077e3621fc38a330a885a47ff4
| 2,971
|
cpp
|
C++
|
test/molch-init-test.cpp
|
1984not-GmbH/molch
|
c7f1f646c800ef3388f36e8805a3b94d33d85b12
|
[
"MIT"
] | 15
|
2016-04-12T17:12:19.000Z
|
2019-08-14T17:46:17.000Z
|
test/molch-init-test.cpp
|
1984not-GmbH/molch
|
c7f1f646c800ef3388f36e8805a3b94d33d85b12
|
[
"MIT"
] | 63
|
2016-03-22T14:35:31.000Z
|
2018-07-04T22:17:07.000Z
|
test/molch-init-test.cpp
|
1984not-GmbH/molch
|
c7f1f646c800ef3388f36e8805a3b94d33d85b12
|
[
"MIT"
] | 1
|
2017-08-17T09:27:30.000Z
|
2017-08-17T09:27:30.000Z
|
/*
* Molch, an implementation of the axolotl ratchet based on libsodium
*
* ISC License
*
* Copyright (C) 2015-2016 1984not Security GmbH
* Author: Max Bruckner (FSMaxB)
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sodium.h>
#include <cstring>
#include <iostream>
#include <string>
#include "molch.h"
#include "integration-utils.hpp"
#include "inline-utils.hpp"
int main(int argc, char *args[]) noexcept {
try {
auto recreate{false};
if (argc == 2) {
if (strcmp(args[1], "--recreate") == 0) {
recreate = true;
}
}
if (::sodium_init() != 0) {
throw ::Exception("Failed to initialize libsodium.");
}
BackupKeyArray backup_key;
if (!recreate) {
//load the backup from a file
auto backup_file{read_file("test-data/molch-init.backup")};
//load the backup key from a file
auto backup_key_file{read_file("test-data/molch-init-backup.key")};
if (backup_key_file.size() not_eq backup_key.size()) {
throw ::Exception("Backup key from file has an incorrect length.");
}
//try to import the backup
{
auto status{molch_import(
backup_key.data(),
backup_key.size(),
backup_file.data(),
backup_file.size(),
backup_key_file.data(),
backup_key_file.size())};
if (status.status != status_type::SUCCESS) {
throw ::Exception("Failed to import backup.");
}
}
//destroy again
molch_destroy_all_users();
}
//create a new user
AutoFreeBuffer backup;
AutoFreeBuffer prekey_list;
PublicIdentity user_id;
{
auto status{molch_create_user(
user_id.data(),
user_id.size(),
&prekey_list.pointer,
&prekey_list.length,
backup_key.data(),
backup_key.size(),
&backup.pointer,
&backup.length,
char_to_uchar("random"),
sizeof("random"))};
if (status.status != status_type::SUCCESS) {
throw ::Exception("Failed to create user.");
}
}
if (backup.pointer == nullptr) {
throw ::Exception("Failed to export backup.");
}
//print the backup to a file
write_to_file(backup, "molch-init.backup");
write_to_file(backup_key, "molch-init-backup.key");
} catch (const std::exception& exception) {
std::cerr << exception.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 27.509259
| 75
| 0.682262
|
1984not-GmbH
|
1d3395e3d9d641245b8029878dc07a1013fc5aae
| 3,215
|
hpp
|
C++
|
hpx/performance_counters/stubs/performance_counter.hpp
|
bremerm31/hpx
|
a9d22b8eb2e443d2e95991da9b1a621f94d4ebaa
|
[
"BSL-1.0"
] | 1
|
2019-07-04T10:18:01.000Z
|
2019-07-04T10:18:01.000Z
|
hpx/performance_counters/stubs/performance_counter.hpp
|
bremerm31/hpx
|
a9d22b8eb2e443d2e95991da9b1a621f94d4ebaa
|
[
"BSL-1.0"
] | 1
|
2017-07-24T07:16:26.000Z
|
2017-07-24T08:03:33.000Z
|
hpx/performance_counters/stubs/performance_counter.hpp
|
biddisco/hpx
|
2d244e1e27c6e014189a6cd59c474643b31fad4b
|
[
"BSL-1.0"
] | null | null | null |
// Copyright (c) 2007-2018 Hartmut Kaiser
//
// 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(HPX_PERFORMANCE_COUNTERS_STUBS_COUNTER_MAR_03_2009_0745M)
#define HPX_PERFORMANCE_COUNTERS_STUBS_COUNTER_MAR_03_2009_0745M
#include <hpx/config.hpp>
#include <hpx/performance_counters/server/base_performance_counter.hpp>
#include <hpx/runtime/components/stubs/stub_base.hpp>
#include <hpx/runtime/launch_policy.hpp>
///////////////////////////////////////////////////////////////////////////////
namespace hpx { namespace performance_counters { namespace stubs
{
///////////////////////////////////////////////////////////////////////////
struct HPX_EXPORT performance_counter
: components::stub_base<
performance_counters::server::base_performance_counter>
{
///////////////////////////////////////////////////////////////////////
static counter_info get_info(launch::sync_policy,
naming::id_type const& targetid, error_code& ec = throws);
static counter_value get_value(launch::sync_policy,
naming::id_type const& targetid, bool reset = false,
error_code& ec = throws);
static counter_values_array get_values_array(launch::sync_policy,
naming::id_type const& targetid,
bool reset = false, error_code& ec = throws);
static lcos::future<counter_info> get_info(launch::async_policy,
naming::id_type const& targetid);
static lcos::future<counter_value> get_value(launch::async_policy,
naming::id_type const& targetid, bool reset = false);
static lcos::future<counter_values_array> get_values_array(
launch::async_policy, naming::id_type const& targetid,
bool reset = false);
///////////////////////////////////////////////////////////////////////
static lcos::future<bool> start(launch::async_policy,
naming::id_type const& targetid);
static lcos::future<bool> stop(launch::async_policy,
naming::id_type const& targetid);
static lcos::future<void> reset(launch::async_policy,
naming::id_type const& targetid);
static lcos::future<void> reinit(launch::async_policy,
naming::id_type const& targetid, bool reset);
static bool start(launch::sync_policy, naming::id_type const& targetid,
error_code& ec = throws);
static bool stop(launch::sync_policy, naming::id_type const& targetid,
error_code& ec = throws);
static void reset(launch::sync_policy, naming::id_type const& targetid,
error_code& ec = throws);
static void reinit(launch::sync_policy, naming::id_type const& targetid,
bool reset, error_code& ec = throws);
template <typename T>
static T
get_typed_value(naming::id_type const& targetid, bool reset = false,
error_code& ec = throws)
{
counter_value value = get_value(launch::sync, targetid, reset);
return value.get_value<T>(ec);
}
};
}}}
#endif
| 45.28169
| 80
| 0.609642
|
bremerm31
|
1d36e90b89b62099851d1cb7c07dbf2a0fbb5f7b
| 5,555
|
cpp
|
C++
|
src/network/ChannelSocketClient.cpp
|
vitorjna/LoggerClient
|
b447f36224e98919045138bb08a849df211e5491
|
[
"MIT"
] | null | null | null |
src/network/ChannelSocketClient.cpp
|
vitorjna/LoggerClient
|
b447f36224e98919045138bb08a849df211e5491
|
[
"MIT"
] | null | null | null |
src/network/ChannelSocketClient.cpp
|
vitorjna/LoggerClient
|
b447f36224e98919045138bb08a849df211e5491
|
[
"MIT"
] | null | null | null |
#include "ChannelSocketClient.h"
#include "network/TcpSocketThreadable.h"
#include "util/MemoryUtils.h"
#include "util/NetworkUtils.h"
#include "util/TimeUtils.h"
ChannelSocketClient::ChannelSocketClient(QObject *parent)
: QObject(parent)
, bKeepRetrying(false)
, nPort(0)
, mySocket(new TcpSocketThreadable(parent))
{
setupSignalsAndSlots();
mySocket->moveToThread(&myWorkerThread);
QObject::connect(&myWorkerThread, SIGNAL(finished()), this, SLOT(deleteLater()));
myWorkerThread.start();
}
ChannelSocketClient::~ChannelSocketClient()
{
bKeepRetrying = false;
disconnectSocket();
MemoryUtils::deletePointer(mySocket);
myWorkerThread.quit();
myWorkerThread.wait(200);
}
bool ChannelSocketClient::connect(const QString &szIpAddress, const QString &szPort)
{
qDebug() << "Connecting to" << szIpAddress << ":" << szPort;
if (NetworkUtils::isIpV4Address(szIpAddress) == false
|| NetworkUtils::isValidPort(szPort) == false) {
return false;
} else {
this->szIpAddress = NetworkUtils::cleanupIpV4Address(szIpAddress);
this->nPort = szPort.toUShort();
emit connectSocket(this->szIpAddress, this->nPort);
return true;
}
}
void ChannelSocketClient::setNeverDies(bool bNeverDies)
{
this->bKeepRetrying = bNeverDies;
}
void ChannelSocketClient::disconnectAndStopRetries()
{
bKeepRetrying = false;
clearIpAndPort(true);
emit disconnectSocket();
}
void ChannelSocketClient::clearIpAndPort(bool bForce)
{
if (bForce == true
|| bKeepRetrying == false) {
szIpAddress.clear();
nPort = 0;
}
}
void ChannelSocketClient::setupSignalsAndSlots()
{
QObject::connect(mySocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
QObject::connect(mySocket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(socketError(QAbstractSocket::SocketError)));
QObject::connect(mySocket, SIGNAL(newMessage(QString)),
this, SLOT(newMessageOnSocket(QString)));
QObject::connect(this, SIGNAL(connectSocket(QString, quint16)),
mySocket, SLOT(connectSocket(QString, quint16)));
QObject::connect(this, SIGNAL(disconnectSocket()),
mySocket, SLOT(disconnectSocket()));
}
void ChannelSocketClient::reconnectSocket()
{
if (bKeepRetrying == true) {
emit connectSocket(this->szIpAddress, this->nPort);
}
}
void ChannelSocketClient::newMessageOnSocket(const QString &szMessage)
{
//check if there was a disconnect requested, ignore message
if (nPort == 0) {
return;
}
emit newMessageReceived(szMessage);
}
void ChannelSocketClient::socketStateChanged(QAbstractSocket::SocketState eSocketState)
{
if (nPort == 0) {
//socket was trying to connect when a disconnect was requested
if (eSocketState == QAbstractSocket::ConnectedState) {
emit disconnectSocket();
}
return;
}
#ifdef DEBUG_STUFF
QMetaEnum myMetaEnum = QMetaEnum::fromType<QAbstractSocket::SocketState>();
qDebug() << "socketStateChanged" << myMetaEnum.valueToKey(eSocketState);
#endif
switch (eSocketState) {
case QAbstractSocket::UnconnectedState:
reconnectSocket();
break;
case QAbstractSocket::HostLookupState:
break;
case QAbstractSocket::ConnectingState:
emit connectionInProgress();
break;
case QAbstractSocket::ConnectedState:
emit connectionSuccess();
break;
case QAbstractSocket::BoundState:
break;
case QAbstractSocket::ListeningState:
break;
case QAbstractSocket::ClosingState:
reconnectSocket();
break;
}
}
void ChannelSocketClient::socketError(QAbstractSocket::SocketError eSocketError)
{
if (nPort == 0) {
return;
}
emit connectionError(mySocket->error(), mySocket->errorString());
switch (eSocketError) {
case QAbstractSocket::ConnectionRefusedError:
case QAbstractSocket::RemoteHostClosedError:
case QAbstractSocket::HostNotFoundError:
case QAbstractSocket::SocketAccessError:
case QAbstractSocket::SocketResourceError:
case QAbstractSocket::SocketTimeoutError:
case QAbstractSocket::DatagramTooLargeError:
case QAbstractSocket::NetworkError:
case QAbstractSocket::AddressInUseError:
case QAbstractSocket::SocketAddressNotAvailableError:
case QAbstractSocket::UnsupportedSocketOperationError:
case QAbstractSocket::UnfinishedSocketOperationError:
case QAbstractSocket::ProxyAuthenticationRequiredError:
case QAbstractSocket::SslHandshakeFailedError:
case QAbstractSocket::ProxyConnectionRefusedError:
case QAbstractSocket::ProxyConnectionClosedError:
case QAbstractSocket::ProxyConnectionTimeoutError:
case QAbstractSocket::ProxyNotFoundError:
case QAbstractSocket::ProxyProtocolError:
case QAbstractSocket::OperationError:
case QAbstractSocket::SslInternalError:
case QAbstractSocket::SslInvalidUserDataError:
case QAbstractSocket::TemporaryError:
case QAbstractSocket::UnknownSocketError:
reconnectSocket();
break;
}
}
| 29.08377
| 92
| 0.672367
|
vitorjna
|
1d384e0091b3dbbc6d71ea5629b8e16111aff5e9
| 1,359
|
hpp
|
C++
|
include/Taus88.hpp
|
michaeldzjap/MDAudio
|
70f9b75eeb39062fe9483fa4240274dcbfce68e3
|
[
"MIT"
] | null | null | null |
include/Taus88.hpp
|
michaeldzjap/MDAudio
|
70f9b75eeb39062fe9483fa4240274dcbfce68e3
|
[
"MIT"
] | null | null | null |
include/Taus88.hpp
|
michaeldzjap/MDAudio
|
70f9b75eeb39062fe9483fa4240274dcbfce68e3
|
[
"MIT"
] | null | null | null |
#ifndef MD_AUDIO_TAUS_88_HPP
#define MD_AUDIO_TAUS_88_HPP
#include <cstdint>
namespace md_audio {
// Original source: https://github.com/supercollider/supercollider/blob/develop/include/plugin_interface/SC_RGen.h
class Taus88 {
public:
explicit Taus88();
explicit Taus88(std::int32_t);
void initialise(std::int32_t) noexcept;
double generate() noexcept;
private:
std::uint32_t m_s1;
std::uint32_t m_s2;
std::uint32_t m_s3;
static constexpr std::int32_t Hash(std::int32_t in_key) noexcept {
auto hash = static_cast<std::uint32_t>(in_key);
hash += ~(hash << 15);
hash ^= hash >> 10;
hash += hash << 3;
hash ^= hash >> 6;
hash += ~(hash << 11);
hash ^= hash >> 16;
return static_cast<std::int32_t>(hash);
}
std::uint32_t trand(std::uint32_t& s1, std::uint32_t& s2, std::uint32_t& s3) noexcept {
s1 = ((s1 & static_cast<std::uint32_t>(-2)) << 12) ^ (((s1 << 13) ^ s1) >> 19);
s2 = ((s2 & static_cast<std::uint32_t>(-8)) << 4) ^ (((s2 << 2) ^ s2) >> 25);
s3 = ((s3 & static_cast<std::uint32_t>(-16)) << 17) ^ (((s3 << 3) ^ s3) >> 11);
return s1 ^ s2 ^ s3;
}
};
}
#endif /* MD_AUDIO_TAUS_88_HPP */
| 27.18
| 118
| 0.534952
|
michaeldzjap
|
1d3a7864125a9f8653c1e33370a551b3b100b823
| 1,401
|
hpp
|
C++
|
external/boost_1_60_0/qsboost/type_traits/decay.hpp
|
wouterboomsma/quickstep
|
a33447562eca1350c626883f21c68125bd9f776c
|
[
"MIT"
] | 1
|
2019-06-27T17:54:13.000Z
|
2019-06-27T17:54:13.000Z
|
external/boost_1_60_0/qsboost/type_traits/decay.hpp
|
wouterboomsma/quickstep
|
a33447562eca1350c626883f21c68125bd9f776c
|
[
"MIT"
] | null | null | null |
external/boost_1_60_0/qsboost/type_traits/decay.hpp
|
wouterboomsma/quickstep
|
a33447562eca1350c626883f21c68125bd9f776c
|
[
"MIT"
] | null | null | null |
// (C) Copyright John Maddock & Thorsten Ottosen 2005.
// Use, modification and distribution are subject to 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/type_traits for most recent version including documentation.
#ifndef QSBOOST_TT_DECAY_HPP_INCLUDED
#define QSBOOST_TT_DECAY_HPP_INCLUDED
#include <qsboost/type_traits/is_array.hpp>
#include <qsboost/type_traits/is_function.hpp>
#include <qsboost/type_traits/remove_bounds.hpp>
#include <qsboost/type_traits/add_pointer.hpp>
#include <qsboost/type_traits/remove_reference.hpp>
#include <qsboost/type_traits/remove_cv.hpp>
namespace qsboost
{
namespace detail
{
template <class T, bool Array, bool Function> struct decay_imp { typedef typename remove_cv<T>::type type; };
template <class T> struct decay_imp<T, true, false> { typedef typename remove_bounds<T>::type* type; };
template <class T> struct decay_imp<T, false, true> { typedef T* type; };
}
template< class T >
struct decay
{
private:
typedef typename remove_reference<T>::type Ty;
public:
typedef typename qsboost::detail::decay_imp<Ty, qsboost::is_array<Ty>::value, qsboost::is_function<Ty>::value>::type type;
};
} // namespace boost
#endif // BOOST_TT_DECAY_HPP_INCLUDED
| 31.840909
| 129
| 0.729479
|
wouterboomsma
|
1d44e69ebf330562f5585661a267f67a4e94c7b1
| 10,210
|
cpp
|
C++
|
CrazyCanvas/Source/ECS/Systems/Player/WeaponSystemClient.cpp
|
IbexOmega/CrazyCanvas
|
f60f01aaf9c988e4da8990dc1ef3caac20cecf7e
|
[
"MIT"
] | 18
|
2020-09-04T08:00:54.000Z
|
2021-08-29T23:04:45.000Z
|
CrazyCanvas/Source/ECS/Systems/Player/WeaponSystemClient.cpp
|
IbexOmega/LambdaEngine
|
f60f01aaf9c988e4da8990dc1ef3caac20cecf7e
|
[
"MIT"
] | 32
|
2020-09-12T19:24:50.000Z
|
2020-12-11T14:29:44.000Z
|
CrazyCanvas/Source/ECS/Systems/Player/WeaponSystemClient.cpp
|
IbexOmega/LambdaEngine
|
f60f01aaf9c988e4da8990dc1ef3caac20cecf7e
|
[
"MIT"
] | 2
|
2020-12-15T15:36:13.000Z
|
2021-03-27T14:27:02.000Z
|
#include "ECS/Systems/Player/WeaponSystemClient.h"
#include "ECS/Components/Player/Player.h"
#include "ECS/ECSCore.h"
#include "Application/API/Events/EventQueue.h"
#include "Resources/Material.h"
#include "Resources/ResourceManager.h"
#include "Input/API/InputActionSystem.h"
#include "Math/Random.h"
#include "Lobby/PlayerManagerClient.h"
#include "Match/Match.h"
#include "Resources/ResourceCatalog.h"
/*
* WeaponSystemClients
*/
WeaponSystemClient::WeaponSystemClient()
{
LambdaEngine::EventQueue::RegisterEventHandler<PlayerAliveUpdatedEvent>(this, &WeaponSystemClient::OnPlayerAliveUpdated);
}
WeaponSystemClient::~WeaponSystemClient()
{
LambdaEngine::EventQueue::UnregisterEventHandler<PlayerAliveUpdatedEvent>(this, &WeaponSystemClient::OnPlayerAliveUpdated);
}
void WeaponSystemClient::Tick(LambdaEngine::Timestamp deltaTime)
{
using namespace LambdaEngine;
UNREFERENCED_VARIABLE(deltaTime);
ECSCore* pECS = ECSCore::GetInstance();
const ComponentArray<WeaponComponent>* pWeaponComponents = pECS->GetComponentArray<WeaponComponent>();
ComponentArray<PositionComponent>* pPositionComponents = pECS->GetComponentArray<PositionComponent>();
ComponentArray<RotationComponent>* pRotationComponents = pECS->GetComponentArray<RotationComponent>();
ComponentArray<ScaleComponent>* pScaleComponent = pECS->GetComponentArray<ScaleComponent>();
for (Entity weaponEntity : m_WeaponEntities)
{
const WeaponComponent& weaponComponent = pWeaponComponents->GetConstData(weaponEntity);
PositionComponent& weaponPositionComponent = pPositionComponents->GetData(weaponEntity);
RotationComponent& weaponRotationComponent = pRotationComponents->GetData(weaponEntity);
ScaleComponent& weaponScaleComponent = pScaleComponent->GetData(weaponEntity);
PositionComponent playerPositionComponent;
RotationComponent playerRotationComponent;
ScaleComponent playerScaleComponent;
if (pPositionComponents->GetConstIf(weaponComponent.WeaponOwner, playerPositionComponent) &&
pRotationComponents->GetConstIf(weaponComponent.WeaponOwner, playerRotationComponent) &&
pScaleComponent->GetConstIf(weaponComponent.WeaponOwner, playerScaleComponent))
{
weaponPositionComponent.Position = playerPositionComponent.Position;
weaponRotationComponent.Quaternion = playerRotationComponent.Quaternion;
weaponScaleComponent.Scale = playerScaleComponent.Scale;
}
}
}
void WeaponSystemClient::FixedTick(LambdaEngine::Timestamp deltaTime)
{
using namespace LambdaEngine;
const float32 dt = (float32)deltaTime.AsSeconds();
ECSCore* pECS = ECSCore::GetInstance();
ComponentArray<PacketComponent<PacketPlayerAction>>* pPlayerActionPackets = pECS->GetComponentArray<PacketComponent<PacketPlayerAction>>();
ComponentArray<PacketComponent<PacketPlayerActionResponse>>* pPlayerResponsePackets = pECS->GetComponentArray<PacketComponent<PacketPlayerActionResponse>>();
ComponentArray<WeaponComponent>* pWeaponComponents = pECS->GetComponentArray<WeaponComponent>();
const ComponentArray<TeamComponent>* pTeamComponents = pECS->GetComponentArray<TeamComponent>();
// TODO: Check local response and maybe roll back
for (Entity weaponEntity : m_WeaponEntities)
{
WeaponComponent& weaponComponent = pWeaponComponents->GetData(weaponEntity);
Entity playerEntity = weaponComponent.WeaponOwner;
TeamComponent teamComponent;
if (pTeamComponents->GetConstIf(playerEntity, teamComponent))
{
// Foreign Players
if (m_ForeignPlayerEntities.HasElement(playerEntity))
{
PacketComponent<PacketPlayerActionResponse>& packets = pPlayerResponsePackets->GetData(playerEntity);
const TArray<PacketPlayerActionResponse>& receivedPackets = packets.GetPacketsReceived();
for (const PacketPlayerActionResponse& response : receivedPackets)
{
if (response.FiredAmmo != EAmmoType::AMMO_TYPE_NONE)
{
Fire(weaponEntity,
weaponComponent,
response.FiredAmmo,
response.WeaponPosition,
response.WeaponVelocity,
teamComponent.TeamIndex,
response.Angle);
}
}
continue;
}
// Local Player
PacketComponent<PacketPlayerAction>& playerActions = pPlayerActionPackets->GetData(playerEntity);
auto waterAmmo = weaponComponent.WeaponTypeAmmo.find(EAmmoType::AMMO_TYPE_WATER);
VALIDATE(waterAmmo != weaponComponent.WeaponTypeAmmo.end())
auto paintAmmo = weaponComponent.WeaponTypeAmmo.find(EAmmoType::AMMO_TYPE_PAINT);
VALIDATE(paintAmmo != weaponComponent.WeaponTypeAmmo.end())
const bool hasNoAmmo = (waterAmmo->second.first <= 0) || (paintAmmo->second.first <= 0);
const bool hasFullAmmo = (waterAmmo->second.first >= waterAmmo->second.second) && (paintAmmo->second.first >= paintAmmo->second.second);
const bool isReloading = weaponComponent.ReloadClock > 0.0f;
const bool onCooldown = weaponComponent.CurrentCooldown > 0.0f;
if (hasNoAmmo && !isReloading)
{
StartReload(weaponComponent, playerActions);
}
if (!PlayerManagerClient::GetPlayerLocal()->IsDead())
{
// Reload if we are not reloading
if (InputActionSystem::IsActive(EAction::ACTION_ATTACK_RELOAD) && !isReloading && !hasFullAmmo)
{
StartReload(weaponComponent, playerActions);
}
else if (!onCooldown) // If we did not hit the reload try and shoot
{
if (InputActionSystem::IsActive(EAction::ACTION_ATTACK_PRIMARY))
{
TryFire(EAmmoType::AMMO_TYPE_PAINT, weaponEntity);
}
else if (InputActionSystem::IsActive(EAction::ACTION_ATTACK_SECONDARY))
{
TryFire(EAmmoType::AMMO_TYPE_WATER, weaponEntity);
}
}
}
// Update reload and cooldown timers
UpdateWeapon(weaponComponent, dt);
}
}
}
void WeaponSystemClient::Fire(LambdaEngine::Entity weaponEntity, WeaponComponent& weaponComponent, EAmmoType ammoType, const glm::vec3& position, const glm::vec3& velocity, uint8 playerTeam, uint32 angle)
{
using namespace LambdaEngine;
WeaponSystem::Fire(weaponEntity, weaponComponent, ammoType, position, velocity, playerTeam, angle);
// Play gun fire and spawn particles
ECSCore* pECS = ECSCore::GetInstance();
const auto* pWeaponLocalComponents = pECS->GetComponentArray<WeaponLocalComponent>();
// Play 2D sound if local player shooting else play 3D sound
if (pWeaponLocalComponents != nullptr && pWeaponLocalComponents->HasComponent(weaponEntity))
{
ISoundEffect2D* pSound = ResourceManager::GetSoundEffect2D(ResourceCatalog::WEAPON_SOUND_GUNFIRE_2D_GUID);
pSound->PlayOnce(0.5f);
}
else
{
ISoundEffect3D* pSound = ResourceManager::GetSoundEffect3D(ResourceCatalog::WEAPON_SOUND_GUNFIRE_3D_GUID);
pSound->PlayOnceAt(position, velocity, 0.25f, 1.0f);
}
}
bool WeaponSystemClient::OnPlayerAliveUpdated(const PlayerAliveUpdatedEvent& event)
{
using namespace LambdaEngine;
const Player* pPlayer = PlayerManagerClient::GetPlayerLocal();
if (event.pPlayer == pPlayer)
{
ECSCore* pECS = ECSCore::GetInstance();
ComponentArray<WeaponComponent>* pWeaponComponents = pECS->GetComponentArray<WeaponComponent>();
for (Entity weaponEntity : m_WeaponEntities)
{
WeaponComponent& weaponComponent = pWeaponComponents->GetData(weaponEntity);
if (weaponComponent.WeaponOwner == pPlayer->GetEntity())
{
for (auto& ammo : weaponComponent.WeaponTypeAmmo)
{
ammo.second.first = AMMO_CAPACITY;
}
}
}
}
return false;
}
bool WeaponSystemClient::InitInternal()
{
using namespace LambdaEngine;
// Register system
{
PlayerGroup playerGroup;
playerGroup.Position.Permissions = R;
playerGroup.Scale.Permissions = R;
playerGroup.Rotation.Permissions = R;
playerGroup.Velocity.Permissions = R;
SystemRegistration systemReg = {};
WeaponSystem::CreateBaseSystemRegistration(systemReg);
systemReg.SubscriberRegistration.EntitySubscriptionRegistrations.PushBack(
{
.pSubscriber = &m_ForeignPlayerEntities,
.ComponentAccesses =
{
{ NDA, PlayerForeignComponent::Type() },
{ RW, PacketComponent<PacketPlayerActionResponse>::Type() }
},
.ComponentGroups = { &playerGroup }
}
);
systemReg.SubscriberRegistration.EntitySubscriptionRegistrations.PushBack(
{
.pSubscriber = &m_LocalPlayerEntities,
.ComponentAccesses =
{
{ NDA, PlayerLocalComponent::Type() },
{ RW, PacketComponent<PacketPlayerAction>::Type() }
},
.ComponentGroups = { &playerGroup }
}
);
RegisterSystem(TYPE_NAME(WeaponSystemClient), systemReg);
}
return true;
}
bool WeaponSystemClient::TryFire(EAmmoType ammoType, LambdaEngine::Entity weaponEntity)
{
using namespace LambdaEngine;
// Add cooldown
ECSCore* pECS = ECSCore::GetInstance();
WeaponComponent& weaponComponent = pECS->GetComponent<WeaponComponent>(weaponEntity);
weaponComponent.CurrentCooldown = 1.0f / weaponComponent.FireRate;
auto ammoState = weaponComponent.WeaponTypeAmmo.find(ammoType);
VALIDATE(ammoState != weaponComponent.WeaponTypeAmmo.end());
const bool hasAmmo = (ammoState->second.first > 0);
if (Match::HasBegun() && hasAmmo)
{
// If we try to shoot when reloading we abort the reload
const bool isReloading = weaponComponent.ReloadClock > 0.0f;
if (isReloading)
{
AbortReload(weaponComponent);
}
//Calculate Weapon Fire Properties (Position, Velocity and Team)
glm::vec3 firePosition;
glm::vec3 fireVelocity;
uint8 playerTeam;
CalculateWeaponFireProperties(weaponEntity, firePosition, fireVelocity, playerTeam);
uint32 angle = Random::UInt32(0, 360);
// For creating entity
Fire(weaponEntity, weaponComponent, ammoType, firePosition, fireVelocity, playerTeam, angle);
// Send action to server
PacketComponent<PacketPlayerAction>& packets = pECS->GetComponent<PacketComponent<PacketPlayerAction>>(weaponComponent.WeaponOwner);
TQueue<PacketPlayerAction>& actions = packets.GetPacketsToSend();
if (!actions.empty())
{
actions.back().FiredAmmo = ammoType;
actions.back().Angle = angle;
}
return true;
}
else
{
// Play out of ammo
ISoundEffect2D* pSound = ResourceManager::GetSoundEffect2D(ResourceCatalog::WEAPON_SOUND_OUTOFAMMO_2D_GUID);
pSound->PlayOnce(1.0f, 1.0f);
return false;
}
}
| 33.47541
| 204
| 0.760333
|
IbexOmega
|
1d490289541c1f9a95e8a96554b9e424bf3d146d
| 5,187
|
cpp
|
C++
|
test/Math/Test_Statistics.cpp
|
petiaccja/DSPBB
|
405d43c4458adfc16ffad68dac4bcd7e1735407f
|
[
"MIT"
] | 2
|
2021-03-11T13:34:33.000Z
|
2022-02-08T20:25:20.000Z
|
test/Math/Test_Statistics.cpp
|
MoeSzyslak98/DSPBB
|
405d43c4458adfc16ffad68dac4bcd7e1735407f
|
[
"MIT"
] | 56
|
2021-08-14T11:02:23.000Z
|
2022-02-25T15:41:31.000Z
|
test/Math/Test_Statistics.cpp
|
MoeSzyslak98/DSPBB
|
405d43c4458adfc16ffad68dac4bcd7e1735407f
|
[
"MIT"
] | 2
|
2021-03-29T14:32:16.000Z
|
2022-02-08T20:25:15.000Z
|
#include <dspbb/Math/Statistics.hpp>
#include <dspbb/Primitives/Signal.hpp>
#include <catch2/catch.hpp>
#include <complex>
using namespace dspbb;
using namespace std::complex_literals;
TEST_CASE("CentralMoment #0 and #1", "[Statistics]") {
Signal<float> s = { 2, 4, 4, 4, 5, 5, 7, 9 };
REQUIRE(0 == CentralMoment(s, 0));
REQUIRE(0 == CentralMoment(s, 1));
}
TEST_CASE("CentralMoment #2", "[Statistics]") {
Signal<float> s = { 2, 4, 4, 4, 5, 5, 7, 9 };
REQUIRE(Approx(4) == CentralMoment(s, 2));
}
TEST_CASE("CentralMoment #3", "[Statistics]") {
Signal<float> s = { 2, 4, 4, 4, 5, 5, 7, 9 };
REQUIRE(Approx(5.25) == CentralMoment(s, 3));
}
TEST_CASE("CentralMoment #4", "[Statistics]") {
Signal<float> s = { 2, 4, 4, 4, 5, 5, 7, 9 };
REQUIRE(Approx(44.5) == CentralMoment(s, 4));
}
TEST_CASE("CentralMoment #5", "[Statistics]") {
Signal<float> s = { 2, 4, 4, 4, 5, 5, 7, 9 };
REQUIRE(Approx(101.25) == CentralMoment(s, 5));
}
TEST_CASE("StandardizedMoment #1", "[Statistics]") {
Signal<float> s = { 2, 4, 4, 4, 5, 5, 7, 9 };
REQUIRE(Approx(0) == StandardizedMoment(s, 1));
}
TEST_CASE("StandardizedMoment #2", "[Statistics]") {
Signal<float> s = { 2, 4, 4, 4, 5, 5, 7, 9 };
REQUIRE(Approx(1) == StandardizedMoment(s, 2));
}
TEST_CASE("Standard deviation", "[Statistics]") {
Signal<float> s = { 2, 4, 4, 4, 5, 5, 7, 9 };
REQUIRE(Approx(2) == StandardDeviation(s));
}
TEST_CASE("Variance", "[Statistics]") {
Signal<float> s = { 2, 4, 4, 4, 5, 5, 7, 9 };
REQUIRE(Approx(4) == Variance(s));
}
TEST_CASE("Skewness", "[Statistics]") {
Signal<float> s = { 2, 4, 4, 4, 5, 5, 7, 9 };
REQUIRE(Approx(5.25f / 8.f) == Skewness(s));
}
TEST_CASE("Kurtosis", "[Statistics]") {
Signal<float> s = { 2, 4, 4, 4, 5, 5, 7, 9 };
REQUIRE(Approx(44.5f / 16.f) == Kurtosis(s));
}
TEST_CASE("Corrected standard deviation", "[Statistics]") {
Signal<float> s = { 2, 4, 4, 4, 5, 5, 7, 9 };
REQUIRE(Approx(2.138089935) == CorrectedStandardDeviation(s));
}
TEST_CASE("Corrected variance", "[Statistics]") {
Signal<float> s = { 2, 4, 4, 4, 5, 5, 7, 9 };
REQUIRE(Approx(4.571428571) == CorrectedVariance(s));
}
TEST_CASE("Corrected skewness", "[Statistics]") {
Signal<float> s = { 2, 4, 4, 4, 5, 5, 7, 9 };
REQUIRE(Approx(0.818487553) == CorrectedSkewness(s));
}
TEST_CASE("Corrected kurtosis", "[Statistics]") {
Signal<float> s(1000000);
std::mt19937 rne(762375);
std::normal_distribution<float> rng;
for (auto& v : s) {
v = rng(rne);
}
// Kurtosis of normal distribution should be 3.
REQUIRE(Approx(3.0f).epsilon(0.01f) == CorrectedKurtosis(s));
}
TEST_CASE("Sum", "[Statistics]") {
Signal<float> s = { 1, 3, 2, 4, 5, 6, 7, 8, 9, 10 };
REQUIRE(Approx(55) == Sum(s));
}
TEST_CASE("Mean", "[Statistics]") {
Signal<float> s = { 1, 3, 2, 4, 5, 6, 7, 8, 9, 10 };
REQUIRE(Approx(5.5f) == Mean(s));
}
TEST_CASE("SumSquare", "[Statistics]") {
Signal<float> s = { 1, 3, 2, 4, 5, 6, 7, 8, 9, 10 };
REQUIRE(Approx(385) == SumSquare(s));
}
TEST_CASE("MeanSquare", "[Statistics]") {
Signal<float> s = { 1, 3, 2, 4, 5, 6, 7, 8, 9, 10 };
REQUIRE(Approx(38.5f) == MeanSquare(s));
}
TEST_CASE("RootMeanSquare", "[Statistics]") {
Signal<float> s = { 1, 3, 2, 4, 5, 6, 7, 8, 9, 10 };
REQUIRE(Approx(std::sqrt(38.5f)) == RootMeanSquare(s));
}
TEST_CASE("Norm", "[Statistics]") {
Signal<float> s = { 1, 3, 2, 4, 5, 6, 7, 8, 9, 10 };
REQUIRE(Approx(std::sqrt(385.f)) == Norm(s));
}
TEST_CASE("Max", "[Statistics]") {
Signal<float> s = { 1, 3, 2, 4, 8, 9, 10, 5, 6, 7 };
REQUIRE(Approx(10) == Max(s));
}
TEST_CASE("Min", "[Statistics]") {
Signal<float> s = { 1, 3, 2, 4, 8, 9, 10, 5, 6, 7 };
REQUIRE(Approx(1) == Min(s));
}
TEST_CASE("Covariance self", "[Statistics]") {
Signal<float> s = { 1, 3, 2, 4, 8, 9, 10, 5, 6, 7 };
Signal<float> t = { 1, 3, 2, 4, 8, 9, 10, 5, 6, 7 };
REQUIRE(Approx(Variance(s)) == Covariance(s, t));
}
TEST_CASE("Covariance anti", "[Statistics]") {
Signal<float> base = { 1, 3, 2, 4, 8, 9, 10, 5, 6, 7 };
Signal<float> s = base - Mean(base);
Signal<float> t = Mean(base) - base;
REQUIRE(Approx(-Variance(s)) == Covariance(s, t));
}
TEST_CASE("Covariance middle", "[Statistics]") {
Signal<float> s = { 1, 3, 2, 4, 8, 9, 10, 5, 6, 7 };
Signal<float> t = { 3, 4, 5, 6, 3, 7, 3, 7, 4, 5 };
REQUIRE(Approx(0.15f) == Covariance(s, t));
}
TEST_CASE("Corrected covariance self", "[Statistics]") {
Signal<float> s = { 1, 3, 2, 4, 8, 9, 10, 5, 6, 7 };
Signal<float> t = { 1, 3, 2, 4, 8, 9, 10, 5, 6, 7 };
REQUIRE(Approx(CorrectedVariance(s)) == CorrectedCovariance(s, t));
}
TEST_CASE("Correlation self", "[Statistics]") {
Signal<float> s = { 1, 3, 2, 4, 8, 9, 10, 5, 6, 7 };
Signal<float> t = { 1, 3, 2, 4, 8, 9, 10, 5, 6, 7 };
REQUIRE(Approx(1) == Correlation(s, t));
}
TEST_CASE("Correlation anti", "[Statistics]") {
Signal<float> base = { 1, 3, 2, 4, 8, 9, 10, 5, 6, 7 };
Signal<float> s = base - Mean(base);
Signal<float> t = Mean(base) - base;
REQUIRE(Approx(-1) == Correlation(s, t));
}
TEST_CASE("Correlation middle", "[Statistics]") {
Signal<float> s = { 1, 3, 2, 4, 8, 9, 10, 5, 6, 7 };
Signal<float> t = { 3, 4, 5, 6, 3, 7, 3, 7, 4, 5 };
REQUIRE(Approx(0.15f / 4.27f) == Correlation(s, t));
}
| 27.887097
| 68
| 0.585117
|
petiaccja
|
1d4b0293cf006e7061b39800d8f7c57d62a36701
| 17,122
|
cpp
|
C++
|
libs/leaf/test/error_code_test.cpp
|
armdevvel/boost
|
30d0930951181ef5bc5aad2231ebac8575db0720
|
[
"BSL-1.0"
] | 1
|
2020-04-28T15:15:28.000Z
|
2020-04-28T15:15:28.000Z
|
libs/leaf/test/error_code_test.cpp
|
armdevvel/boost
|
30d0930951181ef5bc5aad2231ebac8575db0720
|
[
"BSL-1.0"
] | 2
|
2017-05-23T08:01:11.000Z
|
2019-09-06T20:49:05.000Z
|
libs/leaf/test/error_code_test.cpp
|
armdevvel/boost
|
30d0930951181ef5bc5aad2231ebac8575db0720
|
[
"BSL-1.0"
] | 8
|
2015-11-03T14:12:19.000Z
|
2020-09-22T19:20:54.000Z
|
// Copyright (c) 2018-2020 Emil Dotchevski and Reverge Studios, Inc.
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/leaf/handle_errors.hpp>
#include <boost/leaf/pred.hpp>
#include <boost/leaf/result.hpp>
#include "_test_res.hpp"
#include "lightweight_test.hpp"
namespace leaf = boost::leaf;
struct e_wrapped_error_code { std::error_code value; };
template <class R>
void test()
{
#if __cplusplus >= 201703L
{
int r = leaf::try_handle_all(
[]() -> R
{
return make_error_code(errc_a::a0);
},
[]( leaf::match<std::error_code, leaf::category<errc_a>, leaf::category<errc_b>> code )
{
std::error_code const & ec = code.matched;
BOOST_TEST_EQ(&ec.category(), &cat_errc_a());
BOOST_TEST_EQ(ec, errc_a::a0);
return 42;
},
[]
{
return -42;
} );
BOOST_TEST_EQ(r, 42);
}
{
int r = leaf::try_handle_all(
[]() -> R
{
return make_error_code(errc_b::b0);
},
[]( leaf::match<std::error_code, leaf::category<errc_a>, leaf::category<errc_b>> code )
{
std::error_code const & ec = code.matched;
BOOST_TEST_EQ(&ec.category(), &cat_errc_b());
BOOST_TEST_EQ(ec, errc_b::b0);
return 42;
},
[]
{
return -42;
} );
BOOST_TEST_EQ(r, 42);
}
{
int r = leaf::try_handle_all(
[]() -> R
{
return make_error_code(errc_b::b0);
},
[]( leaf::match<std::error_code, leaf::category<errc_a>, errc_b::b0> code )
{
std::error_code const & ec = code.matched;
BOOST_TEST_EQ(&ec.category(), &cat_errc_b());
BOOST_TEST_EQ(ec, errc_b::b0);
return 42;
},
[]
{
return -42;
} );
BOOST_TEST_EQ(r, 42);
}
#endif
{
int r = leaf::try_handle_all(
[]() -> R
{
return errc_a::a0; // testing without make_error_code
},
[]( std::error_code const & ec )
{
BOOST_TEST(!leaf::is_error_id(ec));
BOOST_TEST_EQ(ec, errc_a::a0);
return 42;
},
[]
{
return -42;
} );
BOOST_TEST_EQ(r, 42);
}
{
int r = leaf::try_handle_all(
[]() -> R
{
return make_error_code(errc_a::a0);
},
[]( leaf::match<leaf::condition<errc_a>, errc_a::a0> code )
{
std::error_code const & ec = code.matched;
BOOST_TEST_EQ(ec, errc_a::a0);
return 42;
},
[]
{
return -42;
} );
BOOST_TEST_EQ(r, 42);
}
#if __cplusplus >= 201703L
{
int r = leaf::try_handle_all(
[]() -> R
{
return make_error_code(errc_a::a0);
},
[]( leaf::match<std::error_code, errc_a::a0> code )
{
std::error_code const & ec = code.matched;
BOOST_TEST_EQ(ec, errc_a::a0);
return 42;
},
[]
{
return -42;
} );
BOOST_TEST_EQ(r, 42);
}
#endif
{
int r = leaf::try_handle_all(
[]() -> R
{
return make_error_code(errc_a::a0);
},
[]( leaf::match<leaf::condition<errc_a>, errc_a::a0> code )
{
std::error_code const & ec = code.matched;
BOOST_TEST_EQ(ec, errc_a::a0);
return 42;
},
[]
{
return -42;
} );
BOOST_TEST_EQ(r, 42);
}
{
int r = leaf::try_handle_all(
[]() -> R
{
return make_error_code(errc_a::a0);
},
[]( leaf::match<leaf::condition<cond_x>, cond_x::x00> cond )
{
std::error_code const & ec = cond.matched;
BOOST_TEST_EQ(ec, errc_a::a0);
BOOST_TEST(ec==make_error_condition(cond_x::x00));
return 42;
},
[]
{
return -42;
} );
BOOST_TEST_EQ(r, 42);
}
#if __cplusplus >= 201703L
{
int r = leaf::try_handle_all(
[]() -> R
{
return make_error_code(errc_a::a0);
},
[]( leaf::match<std::error_code, cond_x::x00> cond )
{
std::error_code const & ec = cond.matched;
BOOST_TEST_EQ(ec, errc_a::a0);
BOOST_TEST(ec==make_error_condition(cond_x::x00));
return 42;
},
[]
{
return -42;
} );
BOOST_TEST_EQ(r, 42);
}
#endif
{
int r = leaf::try_handle_all(
[]() -> R
{
return leaf::new_error( e_wrapped_error_code { make_error_code(errc_a::a0) } ).to_error_code();
},
[]( e_wrapped_error_code const & wec )
{
std::error_code const & ec = wec.value;
BOOST_TEST_EQ(ec, errc_a::a0);
return 42;
},
[]
{
return -42;
} );
BOOST_TEST_EQ(r, 42);
}
{
int r = leaf::try_handle_all(
[]() -> R
{
return leaf::new_error( e_wrapped_error_code { make_error_code(errc_a::a0) } ).to_error_code();
},
[]( leaf::match_value<leaf::condition<e_wrapped_error_code, errc_a>, errc_a::a0> code )
{
e_wrapped_error_code const & wec = code.matched;
std::error_code const & ec = wec.value;
BOOST_TEST_EQ(ec, errc_a::a0);
return 42;
},
[]
{
return -42;
} );
BOOST_TEST_EQ(r, 42);
}
#if __cplusplus >= 201703L
{
int r = leaf::try_handle_all(
[]() -> R
{
return leaf::new_error( e_wrapped_error_code { make_error_code(errc_a::a0) } ).to_error_code();
},
[]( leaf::match_value<e_wrapped_error_code, errc_a::a0> code )
{
e_wrapped_error_code const & wec = code.matched;
std::error_code const & ec = wec.value;
BOOST_TEST_EQ(ec, errc_a::a0);
return 42;
},
[]
{
return -42;
} );
BOOST_TEST_EQ(r, 42);
}
#endif
{
int r = leaf::try_handle_all(
[]() -> R
{
return leaf::new_error( e_wrapped_error_code { make_error_code(errc_a::a0) } ).to_error_code();
},
[]( leaf::match_value<leaf::condition<e_wrapped_error_code, cond_x>, cond_x::x00> cond )
{
e_wrapped_error_code const & wec = cond.matched;
std::error_code const & ec = wec.value;
BOOST_TEST_EQ(ec, errc_a::a0);
BOOST_TEST(ec==make_error_condition(cond_x::x00));
return 42;
},
[]
{
return -42;
} );
BOOST_TEST_EQ(r, 42);
}
#if __cplusplus >= 201703L
{
int r = leaf::try_handle_all(
[]() -> R
{
return leaf::new_error( e_wrapped_error_code { make_error_code(errc_a::a0) } ).to_error_code();
},
[]( leaf::match_value<e_wrapped_error_code, cond_x::x00> cond )
{
e_wrapped_error_code const & wec = cond.matched;
std::error_code const & ec = wec.value;
BOOST_TEST_EQ(ec, errc_a::a0);
BOOST_TEST(ec==make_error_condition(cond_x::x00));
return 42;
},
[]
{
return -42;
} );
BOOST_TEST_EQ(r, 42);
}
#endif
}
template <class R>
void test_void()
{
#if __cplusplus >= 201703L
{
int r = 0;
leaf::try_handle_all(
[]() -> R
{
return make_error_code(errc_a::a0);
},
[&]( leaf::match<std::error_code, leaf::category<errc_a>, leaf::category<errc_b>> code )
{
std::error_code const & ec = code.matched;
BOOST_TEST_EQ(&ec.category(), &cat_errc_a());
BOOST_TEST_EQ(ec, errc_a::a0);
r = 42;
},
[&]
{
r = -42;
} );
BOOST_TEST_EQ(r, 42);
}
{
int r = 0;
leaf::try_handle_all(
[]() -> R
{
return make_error_code(errc_b::b0);
},
[&]( leaf::match<std::error_code, leaf::category<errc_a>, leaf::category<errc_b>> code )
{
std::error_code const & ec = code.matched;
BOOST_TEST_EQ(&ec.category(), &cat_errc_b());
BOOST_TEST_EQ(ec, errc_b::b0);
r = 42;
},
[&]
{
r = -42;
} );
BOOST_TEST_EQ(r, 42);
}
{
int r = 0;
leaf::try_handle_all(
[]() -> R
{
return make_error_code(errc_b::b0);
},
[&]( leaf::match<std::error_code, leaf::category<errc_a>, errc_b::b0> code )
{
std::error_code const & ec = code.matched;
BOOST_TEST_EQ(&ec.category(), &cat_errc_b());
BOOST_TEST_EQ(ec, errc_b::b0);
r = 42;
},
[&]
{
r = -42;
} );
BOOST_TEST_EQ(r, 42);
}
#endif
{
int r = 0;
leaf::try_handle_all(
[&]() -> R
{
return errc_a::a0; // testing without make_error_code
},
[&]( std::error_code const & ec )
{
BOOST_TEST(!leaf::is_error_id(ec));
BOOST_TEST_EQ(ec, errc_a::a0);
r = 42;
},
[&]
{
r = -42;
} );
BOOST_TEST_EQ(r, 42);
}
{
int r = 0;
leaf::try_handle_all(
[]() -> R
{
return make_error_code(errc_a::a0);
},
[&]( leaf::match<leaf::condition<errc_a>, errc_a::a0> code )
{
std::error_code const & ec = code.matched;
BOOST_TEST_EQ(ec, errc_a::a0);
r = 42;
},
[&]
{
r = -42;
} );
BOOST_TEST_EQ(r, 42);
}
#if __cplusplus >= 201703L
{
int r = 0;
leaf::try_handle_all(
[]() -> R
{
return make_error_code(errc_a::a0);
},
[&]( leaf::match<std::error_code, errc_a::a0> code )
{
std::error_code const & ec = code.matched;
BOOST_TEST_EQ(ec, errc_a::a0);
r = 42;
},
[&]
{
r = -42;
} );
BOOST_TEST_EQ(r, 42);
}
#endif
{
int r = 0;
leaf::try_handle_all(
[]() -> R
{
return make_error_code(errc_a::a0);
},
[&]( leaf::match<leaf::condition<errc_a>, errc_a::a0> code )
{
std::error_code const & ec = code.matched;
BOOST_TEST_EQ(ec, errc_a::a0);
r = 42;
},
[&]
{
r = -42;
} );
BOOST_TEST_EQ(r, 42);
}
{
int r = 0;
leaf::try_handle_all(
[]() -> R
{
return make_error_code(errc_a::a0);
},
[&]( leaf::match<leaf::condition<cond_x>, cond_x::x00> cond )
{
std::error_code const & ec = cond.matched;
BOOST_TEST_EQ(ec, errc_a::a0);
BOOST_TEST(ec==make_error_condition(cond_x::x00));
r = 42;
},
[&]
{
r = -42;
} );
BOOST_TEST_EQ(r, 42);
}
#if __cplusplus >= 201703L
{
int r = 0;
leaf::try_handle_all(
[]() -> R
{
return make_error_code(errc_a::a0);
},
[&]( leaf::match<std::error_code, cond_x::x00> cond )
{
std::error_code const & ec = cond.matched;
BOOST_TEST_EQ(ec, errc_a::a0);
BOOST_TEST(ec==make_error_condition(cond_x::x00));
r = 42;
},
[&]
{
r = -42;
} );
BOOST_TEST_EQ(r, 42);
}
#endif
{
int r = 0;
leaf::try_handle_all(
[]() -> R
{
return leaf::new_error( e_wrapped_error_code { make_error_code(errc_a::a0) } ).to_error_code();
},
[&]( e_wrapped_error_code const & wec )
{
std::error_code const & ec = wec.value;
BOOST_TEST_EQ(ec, errc_a::a0);
r = 42;
},
[&]
{
r = -42;
} );
BOOST_TEST_EQ(r, 42);
}
{
int r = 0;
leaf::try_handle_all(
[]() -> R
{
return leaf::new_error( e_wrapped_error_code { make_error_code(errc_a::a0) } ).to_error_code();
},
[&]( leaf::match_value<leaf::condition<e_wrapped_error_code, errc_a>, errc_a::a0> code )
{
e_wrapped_error_code const & wec = code.matched;
std::error_code const & ec = wec.value;
BOOST_TEST_EQ(ec, errc_a::a0);
r = 42;
},
[&]
{
r = -42;
} );
BOOST_TEST_EQ(r, 42);
}
#if __cplusplus >= 201703L
{
int r = 0;
leaf::try_handle_all(
[]() -> R
{
return leaf::new_error( e_wrapped_error_code { make_error_code(errc_a::a0) } ).to_error_code();
},
[&]( leaf::match_value<e_wrapped_error_code, errc_a::a0> code )
{
e_wrapped_error_code const & wec = code.matched;
std::error_code const & ec = wec.value;
BOOST_TEST_EQ(ec, errc_a::a0);
r = 42;
},
[&]
{
r = -42;
} );
BOOST_TEST_EQ(r, 42);
}
#endif
{
int r = 0;
leaf::try_handle_all(
[]() -> R
{
return leaf::new_error( e_wrapped_error_code { make_error_code(errc_a::a0) } ).to_error_code();
},
[&]( leaf::match_value<leaf::condition<e_wrapped_error_code, cond_x>, cond_x::x00> cond )
{
e_wrapped_error_code const & wec = cond.matched;
std::error_code const & ec = wec.value;
BOOST_TEST_EQ(ec, errc_a::a0);
BOOST_TEST(ec==make_error_condition(cond_x::x00));
r = 42;
},
[&]
{
r = -42;
} );
BOOST_TEST_EQ(r, 42);
}
#if __cplusplus >= 201703L
{
int r = 0;
leaf::try_handle_all(
[]() -> R
{
return leaf::new_error( e_wrapped_error_code { make_error_code(errc_a::a0) } ).to_error_code();
},
[&]( leaf::match_value<e_wrapped_error_code, cond_x::x00> cond )
{
e_wrapped_error_code const & wec = cond.matched;
std::error_code const & ec = wec.value;
BOOST_TEST_EQ(ec, errc_a::a0);
BOOST_TEST(ec==make_error_condition(cond_x::x00));
r = 42;
},
[&]
{
r = -42;
} );
BOOST_TEST_EQ(r, 42);
}
#endif
}
int main()
{
test<leaf::result<int>>();
test<test_res<int, std::error_code>>();
test_void<leaf::result<void>>();
test_void<test_res<void, std::error_code>>();
return boost::report_errors();
}
| 28.632107
| 111
| 0.414846
|
armdevvel
|
1d4d7f8023f673b3f184d1aed3d450aa2550d4ca
| 1,797
|
cpp
|
C++
|
DNS with Benefits/main.cpp
|
SFaghihi/DNSWithBenefits
|
2553866c0a634313eab00f1a6eb485fa3eb7ab14
|
[
"Apache-2.0"
] | null | null | null |
DNS with Benefits/main.cpp
|
SFaghihi/DNSWithBenefits
|
2553866c0a634313eab00f1a6eb485fa3eb7ab14
|
[
"Apache-2.0"
] | null | null | null |
DNS with Benefits/main.cpp
|
SFaghihi/DNSWithBenefits
|
2553866c0a634313eab00f1a6eb485fa3eb7ab14
|
[
"Apache-2.0"
] | null | null | null |
//
// main.cpp
// DNS with Benefits
//
// Created by Soroush Faghihi on 5/26/18.
// Copyright © 2018 sorco. All rights reserved.
//
#include <iostream>
#include <arpa/inet.h>
#include <sys/time.h>
#include "cxxopts.hpp"
#include "DBRoutingSystem.hpp"
#include "DBDNSHypervisor.hpp"
// Cammand line options structure
struct CMDOpt {
public:
const char *listen_host;
int listen_port;
bool verbose;
const char *conf_file;
CMDOpt(int argc, const char *argv[])
: listen_host("127.0.0.1"), listen_port(53), verbose(false), conf_file("")
{
}
void usage()
{
}
};
int main(int argc, char * argv[])
{
// Parse the command line options
cxxopts::Options options("DNS With Benefits", "DNS Resolver Server With Filtering Capabilities.");
options.add_options()
("a,addr", "IP Address to listen on", cxxopts::value<std::string>()->default_value("127.0.0.1"))
("f,conf", "Routing Config File name", cxxopts::value<std::string>()->default_value(""))
("p,port", "Routing Config File name", cxxopts::value<uint16_t>()->default_value("53"))
("v,verbose", "Verbose Logging")
;
auto result = options.parse(argc, argv);
// Setup the networking configurations
in_addr listen_host;
inet_aton(result["addr"].as<std::string>().c_str(), &listen_host);
sockaddr_in addr = {sizeof(sockaddr_in), AF_INET, htons(result["port"].as<uint16_t>()), listen_host, 0};
// Construct the routing system
DBRoutingSystem routing_system(result["conf"].as<std::string>());
// Construct the DNS hypervisor
DBDNSHypervisor dns_hypervisor((sockaddr *)&addr, &routing_system);
// Start the threads
dns_hypervisor.start_threads();
for (;;)
sleep(1);
return 0;
}
| 26.043478
| 108
| 0.64552
|
SFaghihi
|
1d4e88fb7edf1f44f945bbe7d41d4cdab68cec8d
| 1,662
|
cpp
|
C++
|
BlockChain.cpp
|
tryingsomestuff/blockchain
|
c3fb445d4e3512282dc05f59159d17e531c16eaa
|
[
"MIT"
] | null | null | null |
BlockChain.cpp
|
tryingsomestuff/blockchain
|
c3fb445d4e3512282dc05f59159d17e531c16eaa
|
[
"MIT"
] | null | null | null |
BlockChain.cpp
|
tryingsomestuff/blockchain
|
c3fb445d4e3512282dc05f59159d17e531c16eaa
|
[
"MIT"
] | null | null | null |
#include "BlockChain.h"
#include <cassert>
#include <iostream>
BlockChain::BlockChain(const uint32_t difficulty): difficulty(difficulty > 0 ? difficulty : defaultDifficulty_) {
Block b0(0, "Zero!");
b0.prevHash = std::string(64,'0');
b0.mine(BlockChain::difficulty);
chain_.push_back(b0);
}
void BlockChain::addBlock(Block&& b) {
b.prevHash = last_().hash;
b.mine(difficulty);
chain_.push_back(b);
}
Block BlockChain::last_() const { return chain_.back(); }
Block& BlockChain::operator[](const size_t index) {
assert(index < chain_.size());
return chain_[index];
}
const Block& BlockChain::operator[](const size_t index) const {
assert(index < chain_.size());
return chain_[index];
}
bool BlockChain::isValidBlock(const size_t index) const {
assert(index < chain_.size());
return chain_[index].isValid(difficulty);
}
bool BlockChain::isValidChain() const {
bool ret = true;
for (size_t i = 0; i < chain_.size(); ++i) {
ret &= chain_[i].isValid(difficulty);
if (i > 0) { ret &= chain_[i].prevHash == chain_[i - 1].computeHash(); }
if (!ret) std::cout << "Invalid block in chain at position " << i << std::endl;
}
return ret;
}
void BlockChain::dump(std::ostream & os)const{
std::cout << "Dumping chain" << std::endl;
writeIt(os, chain_.size());
for(const auto & b : chain_){
b.dump(os);
}
}
void BlockChain::load(std::istream & is){
std::cout << "Loading chain" << std::endl;
chain_.clear();
size_t s = 0;
readIt(is, s);
for(size_t i = 0; i < s; ++i){
Block b(-1,"");
b.load(is);
if(b.isValid(difficulty)) chain_.push_back(b);
}
}
| 25.96875
| 113
| 0.628761
|
tryingsomestuff
|
1d563649559e46343699dff0a1ae835fef984928
| 141,826
|
cpp
|
C++
|
src/gmatutil/util/FileManager.cpp
|
saichikine/GMAT
|
80bde040e12946a61dae90d9fc3538f16df34190
|
[
"Apache-2.0"
] | null | null | null |
src/gmatutil/util/FileManager.cpp
|
saichikine/GMAT
|
80bde040e12946a61dae90d9fc3538f16df34190
|
[
"Apache-2.0"
] | null | null | null |
src/gmatutil/util/FileManager.cpp
|
saichikine/GMAT
|
80bde040e12946a61dae90d9fc3538f16df34190
|
[
"Apache-2.0"
] | 1
|
2021-12-05T05:40:15.000Z
|
2021-12-05T05:40:15.000Z
|
//$Id$
//------------------------------------------------------------------------------
// FileManager
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool
//
// Copyright (c) 2002 - 2018 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other 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.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract
// number S-67573-G
//
// Author: Linda Jun, NASA/GSFC
// Created: 2004/04/02
/**
* Implements FileManager class. This is singleton class which manages
* list of file paths and names.
*/
//------------------------------------------------------------------------------
#include "FileManager.hpp"
#include "MessageInterface.hpp"
#include "UtilityException.hpp"
#include "StringUtil.hpp"
#include "FileTypes.hpp" // for GmatFile::MAX_PATH_LEN
#include "FileUtil.hpp" // for GmatFileUtil::
#include "StringTokenizer.hpp" // for StringTokenizer()
#include "GmatGlobal.hpp" // for SetTestingMode()
#include <fstream>
#include <sstream>
#include <iomanip>
#include <algorithm> // Required for GCC 4.3
#ifndef _MSC_VER // if not Microsoft Visual C++
#include <dirent.h>
#endif
// For adding default input path and files
//#define __FM_ADD_DEFAULT_INPUT__
//#define DEBUG_FILE_MANAGER
//#define DEBUG_GMAT_PATH
//#define DEBUG_ADD_FILETYPE
//#define DEBUG_ABS_PATH
//#define DEBUG_FILE_PATH
//#define DEBUG_SET_PATH
//#define DEBUG_READ_STARTUP_FILE
//#define DEBUG_WRITE_STARTUP_FILE
//#define DEBUG_PLUGIN_DETECTION
//#define DEBUG_FILE_RENAME
//#define DEBUG_MAPPING
//#define DEBUG_STARTUP_WITH_ABSOLUTE_PATH
//#define DEBUG_BIN_DIR
//#define DEBUG_TEXTURE_FILE
//#define DEBUG_3DMODEL_FILE
//#define DEBUG_FIND_PATH
//#define DEBUG_FIND_INPUT_PATH
//#define DEBUG_FIND_OUTPUT_PATH
//#define DEBUG_REFRESH_FILES
//---------------------------------
// static data
//---------------------------------
const std::string
FileManager::FILE_TYPE_STRING[FileTypeCount] =
{
// File path
"BEGIN_OF_PATH",
"ROOT_PATH",
// Input path
"TIME_PATH",
"PLANETARY_COEFF_PATH",
"PLANETARY_EPHEM_DE_PATH",
"PLANETARY_EPHEM_SPK_PATH",
"VEHICLE_EPHEM_PATH",
"VEHICLE_EPHEM_SPK_PATH",
"VEHICLE_EPHEM_CCSDS_PATH",
"EARTH_POT_PATH",
"LUNA_POT_PATH",
"VENUS_POT_PATH",
"MARS_POT_PATH",
"OTHER_POT_PATH",
"TEXTURE_PATH",
"BODY_3D_MODEL_PATH",
"MEASUREMENT_PATH",
"GUI_CONFIG_PATH",
"SPLASH_PATH",
"ICON_PATH",
"STAR_PATH",
"VEHICLE_MODEL_PATH",
"SPAD_PATH",
"ATMOSPHERE_PATH",
"FILE_UPDATE_PATH",
// Output path
"OUTPUT_PATH",
"END_OF_PATH",
// General file name
"LOG_FILE",
"REPORT_FILE",
"EPHEM_OUTPUT_FILE",
"SPLASH_FILE",
"TIME_COEFF_FILE",
// Specific file name
"DE405_FILE",
"DE421_FILE",
"DE424_FILE",
"DE430_FILE",
"IAUSOFA_FILE",
"ICRF_FILE",
"PLANETARY_SPK_FILE",
"JGM2_FILE",
"JGM3_FILE",
"EGM96_FILE",
"LP165P_FILE",
"MGNP180U_FILE",
"MARS50C_FILE",
"EOP_FILE",
"PLANETARY_COEFF_FILE",
"NUTATION_COEFF_FILE",
"PLANETARY_PCK_FILE",
"EARTH_LATEST_PCK_FILE",
"EARTH_PCK_PREDICTED_FILE",
"EARTH_PCK_CURRENT_FILE",
"LUNA_PCK_CURRENT_FILE",
"LUNA_FRAME_KERNEL_FILE",
"LEAP_SECS_FILE",
"LSK_FILE",
"PERSONALIZATION_FILE",
"MAIN_ICON_FILE",
"STAR_FILE",
"CONSTELLATION_FILE",
"SPACECRAFT_MODEL_FILE",
"SPAD_SRP_FILE",
"CSSI_FLUX_FILE",
"SCHATTEN_FILE",
"MARINI_TROPO_FILE",
"HELP_FILE",};
FileManager* FileManager::theInstance = NULL;
//---------------------------------
// public methods
//---------------------------------
//------------------------------------------------------------------------------
// FileManager* Instance(const std::string &appName = "GMAT.exe")
//------------------------------------------------------------------------------
FileManager* FileManager::Instance(const std::string &appName)
{
if (theInstance == NULL)
theInstance = new FileManager(appName);
return theInstance;
}
//------------------------------------------------------------------------------
// ~FileManager()
//------------------------------------------------------------------------------
FileManager::~FileManager()
{
for (std::map<std::string, FileInfo*>::iterator pos = mFileMap.begin();
pos != mFileMap.end(); ++pos)
{
if (pos->second)
{
#ifdef DEBUG_FILE_MANAGER
MessageInterface::ShowMessage
("FileManager::~FileManager deleting %s\n", pos->first.c_str());
#endif
delete pos->second;
}
}
}
//------------------------------------------------------------------------------
// std::string GetBinDirectory(const std::string &appName = "GMAT.exe")
//------------------------------------------------------------------------------
std::string FileManager::GetBinDirectory(const std::string &appName)
{
#ifdef DEBUG_BIN_DIR
MessageInterface::ShowMessage
("FileManager::GetBinDirectory() entered, appName = %s, mAbsBinDir = '%s'\n",
appName.c_str(), mAbsBinDir.c_str());
#endif
if (mAbsBinDir == "")
SetBinDirectory(appName);
#ifdef DEBUG_BIN_DIR
MessageInterface::ShowMessage
("FileManager::GetBinDirectory() returning '%s'\n", mAbsBinDir.c_str());
#endif
return mAbsBinDir;
}
//------------------------------------------------------------------------------
// bool SetBinDirectory(const std::string &appName = "GMAT.exe",
// const std::string &binDir = "")
//------------------------------------------------------------------------------
/**
* Sets bin directory where GMAT.exe reside. It sets only once when GMAT.exe
* found in the directory. If input binDir is blank, it will try with
* GmatFileUtil::GetApplicationPath().
*/
//------------------------------------------------------------------------------
bool FileManager::SetBinDirectory(const std::string &appName, const std::string &binDir)
{
#ifdef DEBUG_BIN_DIR
MessageInterface::ShowMessage
("FileManager::SetBinDirectory() entered, appName = '%s', binDir = '%s', mAbsBinDir = '%s'\n",
appName.c_str(), binDir.c_str(), mAbsBinDir.c_str());
#endif
if (mAbsBinDir == "")
{
std::string appFullPath = binDir;
if (binDir == "")
appFullPath = GmatFileUtil::GetApplicationPath();
#ifdef DEBUG_BIN_DIR
MessageInterface::ShowMessage(" appFullPath = '%s'\n", appFullPath.c_str());
#endif
// Set absolute bin directory if it is not relative path and appName found
if (appFullPath[0] != '.')
{
std::string appPath = GmatFileUtil::ParsePathName(appFullPath);
std::string newPath = appPath + appName;
if (GmatFileUtil::DoesFileExist(newPath))
{
mAbsBinDir = appPath;
#ifdef DEBUG_BIN_DIR
MessageInterface::ShowMessage
("FileManager::SetBinDirectory() returning true, bin directory set to '%s'\n",
mAbsBinDir.c_str());
#endif
return true;
}
else
{
#ifdef DEBUG_BIN_DIR
MessageInterface::ShowMessage
(" The file '%s' does not exist\n", newPath.c_str());
#endif
}
}
}
else
{
#ifdef DEBUG_BIN_DIR
MessageInterface::ShowMessage
(" The bin directory already set to '%s'\n", mAbsBinDir.c_str());
#endif
}
#ifdef DEBUG_BIN_DIR
MessageInterface::ShowMessage
("FileManager::SetBinDirectory() returning false, mAbsBinDir = '%s'\n", mAbsBinDir.c_str());
#endif
return false;
}
//------------------------------------------------------------------------------
// std::string GetGmatWorkingDirectory()
//------------------------------------------------------------------------------
/**
* Returns GMAT working directory. This is the directory where script is passed
* to GMAT from the command line.
*/
//------------------------------------------------------------------------------
std::string FileManager::GetGmatWorkingDirectory()
{
return mGmatWorkingDir;
}
//------------------------------------------------------------------------------
// bool SetGmatWorkingDirectory(const std::string &newDir = "")
//------------------------------------------------------------------------------
/**
* Sets GMAT working directory. This is the directory where script resides.
*/
//------------------------------------------------------------------------------
bool FileManager::SetGmatWorkingDirectory(const std::string &newDir)
{
// Allow resetting on purpose
if (newDir == "")
{
mGmatWorkingDir = newDir;
}
else
{
if (DoesDirectoryExist(newDir))
{
mGmatWorkingDir = newDir;
AddGmatIncludePath(newDir);
// Add GMAT working directory to MATLAB search path so that this directory
// will have higher priority in search path for the new file path implementation.
// (LOJ: 2014.07.09)
AddMatlabFunctionPath(newDir);
// Also add it to GmatFunction path (LOJ: 2015.09.18)
AddGmatFunctionPath(newDir);
// //Python
// AddPythonModulePath(newDir);
}
else
return false;
}
return true;
}
//------------------------------------------------------------------------------
// std::string GetCurrentWorkingDirectory()
//------------------------------------------------------------------------------
/**
* @return System's current working directory of the process
*/
//------------------------------------------------------------------------------
std::string FileManager::GetCurrentWorkingDirectory()
{
return GmatFileUtil::GetCurrentWorkingDirectory();
}
//------------------------------------------------------------------------------
// bool SetCurrentWorkingDirectory(const std::string &newDir = "")
//------------------------------------------------------------------------------
/**
* Sets system's current working directory of the process.
*/
//------------------------------------------------------------------------------
bool FileManager::SetCurrentWorkingDirectory(const std::string &newDir)
{
return GmatFileUtil::SetCurrentWorkingDirectory(newDir);
}
//------------------------------------------------------------------------------
// std::string FindPath(const std::string &fileName, const FileType type,
// bool forInput, bool writeWarning = false, bool writeInfo = false,
// const std::string &objName)
//------------------------------------------------------------------------------
/**
* Finds path for requested fileName using the file path search order.
* This method calls FindPath() taking type name.
*
* @return path found using search order
*/
//------------------------------------------------------------------------------
std::string FileManager::FindPath(const std::string &fileName, const FileType type,
bool forInput, bool writeWarning, bool writeInfo,
const std::string &objName)
{
#ifdef DEBUG_FIND_PATH
MessageInterface::ShowMessage
("FileManager::FindPath() entered, fileName = '%s', type = %d, forInput = %d, "
"writeWarning = %d, writeInfo = %d\n", fileName.c_str(), type, forInput,
writeWarning, writeInfo);
#endif
std::string typeName;
if (type >=0 && type < FileTypeCount)
{
typeName = FILE_TYPE_STRING[type];
}
else
{
std::stringstream ss("");
ss << "*** INTERNAL ERROR *** FileManager::FindPath() enum type: " << type
<< " is out of bounds\n";
throw UtilityException(ss.str());
}
return FindPath(fileName, typeName, forInput, writeWarning, writeInfo, objName);
}
//------------------------------------------------------------------------------
// std::string FindPath(const std::string &fileName, const std::string &fileType,
// bool forInput, bool writeWarning = false, bool writeInfo = false,
// const std::string &objName = "")
//------------------------------------------------------------------------------
/**
* Finds path for requested fileName. If fileName has a absolute path, it will
* return fileName or blank if path not found. If fileName has a relative path or
* no path, it will find path using the following file path search order.
* For Input:
* 1) Current GMAT working directory
* 2) Directory from the startup file in the application directory
* For Output:
* 1) Current GMAT working directory if it has relative path
* 2) Directory from the startup file in the application directory
* if no path found
* 3) Application directory
*
* It returns blank if filename is blank
* It returns blank if path not found for input file.
* If input fileName is blank, it uses default filename using the type
*
* @param fileName The requested filename to be searched
* Enter blank name if default name to be used for the type
* @param fileType The file type name of the input file
* @param forInput Set to true if filename is for input
* @param writeWarning Set to true if warning should be written when no path found
* @param writeInfo Set to true if information should be written for output path (currently not used)
* @param objName The name of the calling object to be written to informational message
*
* @return full path name using search order
*/
//------------------------------------------------------------------------------
std::string FileManager::FindPath(const std::string &fileName, const std::string &fileType,
bool forInput, bool writeWarning, bool writeInfo,
const std::string &objName)
{
#ifdef DEBUG_FIND_PATH
MessageInterface::ShowMessage
("FileManager::FindPath() entered\n fileName = '%s'\n fileType = '%s', forInput = %d, "
"writeWarning = %d, writeInfo = %d, objName = '%s'\n", fileName.c_str(), fileType.c_str(),
forInput, writeWarning, writeInfo, objName.c_str());
#endif
mLastFilePathMessage = "";
std::string fullname = fileName;
bool writeFilePathInfo = GmatGlobal::Instance()->IsWritingFilePathInfo();
#ifdef DEBUG_FIND_PATH
MessageInterface::ShowMessage(" writeFilePathInfo = %d\n", writeFilePathInfo);
#endif
// If input filename is blank, get default name using type
try
{
if (fileName == "")
fullname = GetFilename(fileType);
}
catch (BaseException &be)
{
#ifdef DEBUG_FIND_PATH
MessageInterface::ShowMessage(be.GetFullMessage());
#endif
}
// Cannot handle blank, return blank
if (fullname == "")
{
#ifdef DEBUG_FIND_PATH
MessageInterface::ShowMessage
("FileManager::FindPath() cannot find default filename for type '%s', "
"so just returning blank\n", fileType.c_str());
#endif
return "";
}
fullname = GmatFileUtil::ConvertToOsFileName(fullname);
std::string pathOnly = GmatFileUtil::ParsePathName(fullname);
std::string fileOnly = GmatFileUtil::ParseFileName(fullname);
std::string gmatPath = GmatFileUtil::ConvertToOsFileName(mGmatWorkingDir);
// Get default path for file type
std::string defaultPath;
try
{
defaultPath = GmatFileUtil::ConvertToOsFileName(GetPathname(fileType));
}
catch (BaseException &be)
{
#ifdef DEBUG_FIND_PATH
MessageInterface::ShowMessage("*** WARNING *** %s\n", be.GetFullMessage().c_str());
#endif
// If *_POT_PATH, try OTHER_POT_PATH
std::string::size_type potLoc = fileType.find("_POT_PATH");
if (potLoc != fileType.npos)
{
#ifdef DEBUG_FIND_PATH
MessageInterface::ShowMessage("Trying OTHER_POT_PATH\n");
#endif
std::string oldPot = fileType.substr(0, potLoc+1);
std::string newPotPath = GmatStringUtil::Replace(fileType, oldPot, "OTHER_");
defaultPath = GmatFileUtil::ConvertToOsFileName(GetPathname(newPotPath));
}
}
std::string tempPath1, tempPath2;
std::string pathToReturn;
#ifdef DEBUG_FIND_PATH
MessageInterface::ShowMessage
(" fullname = '%s'\n pathOnly = '%s'\n fileOnly = '%s'\n gmatpath = '%s'\n"
" defaultpath = '%s'\n", fullname.c_str(), pathOnly.c_str(), fileOnly.c_str(),
gmatPath.c_str(), defaultPath.c_str());
#endif
if (GmatFileUtil::IsPathAbsolute(fullname))
{
#ifdef DEBUG_FIND_PATH
MessageInterface::ShowMessage(" The filename has absolute path\n");
#endif
if (GmatFileUtil::DoesFileExist(fullname))
{
pathToReturn = fullname;
}
else
{
#ifdef DEBUG_FIND_PATH
MessageInterface::ShowMessage(" The filename does not exist\n");
#endif
if (forInput)
{
pathToReturn = "";
if (writeWarning && gmatPath != "" && writeFilePathInfo)
{
MessageInterface::ShowMessage
("The input file '%s' does not exist\n", fullname.c_str());
}
}
else // for output
{
#ifdef DEBUG_FIND_PATH
MessageInterface::ShowMessage
(" It is for output, so checking if directory '%s' exist\n",
pathOnly.c_str());
#endif
if (DoesDirectoryExist(pathOnly, false))
{
#ifdef DEBUG_FIND_PATH
MessageInterface::ShowMessage(" The directory exist\n");
#endif
pathToReturn = fullname;
}
else
{
pathToReturn = "";
if (writeWarning && gmatPath != "" && writeFilePathInfo)
{
mLastFilePathMessage = "Cannot open output file '" + fullname +
"', the path '" + pathOnly + "' does not exist.";
MessageInterface::ShowMessage(mLastFilePathMessage + "\n");
}
}
}
}
}
else // filename without absolute path
{
#ifdef DEBUG_FIND_PATH
MessageInterface::ShowMessage(" The filename does not have absolute path\n");
#endif
if (forInput)
{
// First search in GMAT working directory.
// If GMAT directory is blank give some dummy name so that it can be failed to search
if (gmatPath == "")
tempPath1 = "__000_gmat_working_dir_is_blank_000__" + fullname;
else
tempPath1 = gmatPath + fullname;
#ifdef DEBUG_FIND_INPUT_PATH
MessageInterface::ShowMessage(" => first search Path = '%s'\n", tempPath1.c_str());
#endif
if (GmatFileUtil::DoesFileExist(tempPath1))
{
pathToReturn = tempPath1;
}
else
{
#ifdef DEBUG_FIND_INPUT_PATH
MessageInterface::ShowMessage
(" '%s' does not exist, so search in default path\n", tempPath1.c_str());
MessageInterface::ShowMessage
(" BinDirectory = '%s'\n", mAbsBinDir.c_str());
MessageInterface::ShowMessage
(" CurrentWorkingDirectory = '%s'\n", GetCurrentWorkingDirectory().c_str());
#endif
if (GmatFileUtil::IsPathRelative(fullname))
tempPath2 = mAbsBinDir + fullname;
else
tempPath2 = defaultPath + fullname;
#ifdef DEBUG_FIND_INPUT_PATH
MessageInterface::ShowMessage
(" => next search path = '%s' \n", tempPath2.c_str());
#endif
if (writeWarning && gmatPath != "" && writeFilePathInfo)
MessageInterface::ShowMessage
("The input file '%s' does not exist in GMAT "
"working directory\n '%s', so trying default path from the "
"startup file\n '%s'\n", fullname.c_str(), tempPath1.c_str(),
tempPath2.c_str());
if (GmatFileUtil::DoesFileExist(tempPath2))
{
pathToReturn = tempPath2;
}
else
{
pathToReturn = "";
if (writeWarning && gmatPath != "" && writeFilePathInfo)
MessageInterface::ShowMessage
("*** WARNING *** The input file '%s' does not exist in default "
"path from the startup file '%s'\n", fullname.c_str(), tempPath2.c_str());
}
}
}
else // for output
{
if (GmatFileUtil::IsPathRelative(fullname))
{
#ifdef DEBUG_FIND_OUTPUT_PATH
MessageInterface::ShowMessage(" The output filename has relative path\n");
#endif
// Check GMAT working (script) directory
std::string tempPath = gmatPath + fullname;
std::string outPath1 = GmatFileUtil::ParsePathName(tempPath);
#ifdef DEBUG_FIND_OUTPUT_PATH
MessageInterface::ShowMessage(" Checking if '%s' exist...\n", outPath1.c_str());
#endif
if (DoesDirectoryExist(outPath1, false))
{
pathToReturn = tempPath;
}
else
{
tempPath = defaultPath + fullname;
std::string outPath2 = GmatFileUtil::ParsePathName(tempPath);
#ifdef DEBUG_FIND_OUTPUT_PATH
MessageInterface::ShowMessage
(" '%s' does not exist.\n So checking if '%s' exist ...\n",
outPath1.c_str(), outPath2.c_str());
#endif
if (DoesDirectoryExist(outPath2, false))
{
pathToReturn = tempPath;
}
else
{
pathToReturn = mAbsBinDir + fileOnly;
#ifdef DEBUG_FIND_OUTPUT_PATH
MessageInterface::ShowMessage
(" '%s' does not exist.\n So set to use bin directory '%s'\n",
outPath2.c_str(), mAbsBinDir.c_str());
#endif
}
}
}
else // filename without any path
{
if (DoesDirectoryExist(defaultPath, false))
pathToReturn = defaultPath + fullname;
else
pathToReturn = mAbsBinDir + fullname;
}
}
}
// Write info only if file path debug is on from the startup file (LOJ: 2014.09.22)
// Write information about file location if file path debug mode is on
std::string ioType = "output";
std::string fType = "";
std::string rwType = "written to";
std::string oName = "";
if (fileType.find("_FILE") != fileType.npos)
fType = fileType + " ";
if (forInput)
{
ioType = "input";
rwType = "read from";
}
if (objName != "")
oName = " for the object '" + objName + "'";
// Write message where output goes or input from
if (pathToReturn != "")
{
if (writeFilePathInfo)
MessageInterface::ShowMessage
("*** The %s %sfile '%s'%s will be %s \n '%s'\n",
ioType.c_str(), fType.c_str(), fullname.c_str(), oName.c_str(),
rwType.c_str(), pathToReturn.c_str());
}
else
{
mLastFilePathMessage = "Cannot open " + ioType + " " + fType +
"'" + fullname + "'";
if (writeFilePathInfo)
MessageInterface::ShowMessage(mLastFilePathMessage + "\n");
}
#ifdef DEBUG_FIND_PATH
MessageInterface::ShowMessage
("FileManager::FindPath() returning '%s'\n", pathToReturn.c_str());
#endif
return pathToReturn;
} // FindPath()
//------------------------------------------------------------------------------
// std::string FindMainIconFile(bool writeInfo = true)
//------------------------------------------------------------------------------
std::string FileManager::FindMainIconFile(bool writeInfo)
{
// Changed not to write warning per GMAT session (LOJ: 2014.10.29)
#ifdef __WRITE_WARNING_PER_SESSION_
static bool writeWarning = true;
std::string fullpath = FindPath("", MAIN_ICON_FILE, true, writeWarning, writeInfo);
if (mGmatWorkingDir != "")
writeWarning = false;
#else
std::string fullpath = FindPath("", MAIN_ICON_FILE, true, false, writeInfo);
#endif
return fullpath;
}
//------------------------------------------------------------------------------
// std::string GetPathSeparator()
//------------------------------------------------------------------------------
/**
* @return path separator; "/" or "\\" dependends on the platform
*/
//------------------------------------------------------------------------------
std::string FileManager::GetPathSeparator()
{
// Changed back to return FileUtil::GetPathSeparator(); (LOJ: 2014.06.09)
// Just return "/" for all operating system for consistency (LOJ: 2011.03.18)
//return "/";
return GmatFileUtil::GetPathSeparator();
}
//------------------------------------------------------------------------------
// bool DoesDirectoryExist(const std::string &dirPath, bool isBlankOk = true)
//------------------------------------------------------------------------------
/*
* @return true If directory exist, false otherwise
*/
//------------------------------------------------------------------------------
bool FileManager::DoesDirectoryExist(const std::string &dirPath, bool isBlankOk)
{
return GmatFileUtil::DoesDirectoryExist(dirPath, isBlankOk);
}
//------------------------------------------------------------------------------
// bool DoesFileExist(const std::string &filename)
//------------------------------------------------------------------------------
bool FileManager::DoesFileExist(const std::string &filename)
{
return GmatFileUtil::DoesFileExist(filename);
}
//------------------------------------------------------------------------------
// bool RenameFile(const std::string &oldName, const std::string &newName,
// Integer &retCode, bool overwriteIfExists = false)
//------------------------------------------------------------------------------
bool FileManager::RenameFile(const std::string &oldName,
const std::string &newName,
Integer &retCode, bool overwriteIfExists)
{
retCode = 0;
bool oldExists = DoesFileExist(oldName);
bool newExists = DoesFileExist(newName);
#ifdef DEBUG_FILE_RENAME
MessageInterface::ShowMessage("FM::Rename, old file (%s) exists = %s\n",
oldName.c_str(), (oldExists? "true" : "false"));
MessageInterface::ShowMessage("FM::Rename, new file (%s) exists = %s\n",
newName.c_str(), (newExists? "true" : "false"));
#endif
// if a file with the old name does not exist, we cannot do anything
if (!oldExists)
{
std::string errmsg = "Error renaming file \"";
errmsg += oldName + "\" to \"";
errmsg += newName + "\": file \"";
errmsg += oldName + "\" does not exist.\n";
throw UtilityException(errmsg);
}
// if a file with the new name does not exist, or exists but we are
// supposed to overwrite it, try to do the rename
if ((!newExists) || (newExists && overwriteIfExists))
{
#ifdef DEBUG_FILE_RENAME
MessageInterface::ShowMessage("FM::Rename, attempting to rename %s to %s\n",
oldName.c_str(), newName.c_str());
#endif
retCode = rename(oldName.c_str(), newName.c_str()); // overwriting is platform-dependent!!!!
if (retCode == 0)
{
return true;
}
else
{
return false;
}
}
else // it exists but we are not to overwrite it
return false;
}
//------------------------------------------------------------------------------
// bool CopyFile(const std::string &oldName, const std::string &newName,
// Integer &retCode, bool overwriteIfExists = false)
//------------------------------------------------------------------------------
bool FileManager::CopyFile(const std::string &oldName,
const std::string &newName,
Integer &retCode, bool overwriteIfExists)
{
retCode = 0;
if (oldName == newName) return true;
bool oldExists = DoesFileExist(oldName);
bool newExists = DoesFileExist(newName);
#ifdef DEBUG_FILE_RENAME
MessageInterface::ShowMessage("FM::Copy, old file (%s) exists = %s\n",
oldName.c_str(), (oldExists? "true" : "false"));
MessageInterface::ShowMessage("FM::Copy, new file (%s) exists = %s\n",
newName.c_str(), (newExists? "true" : "false"));
#endif
// if a file with the old name does not exist, we cannot do anything
if (!oldExists)
{
std::string errmsg = "Error copying file \"";
errmsg += oldName + "\" to \"";
errmsg += newName + "\": file \"";
errmsg += oldName + "\" does not exist.\n";
throw UtilityException(errmsg);
}
// if a file with the new name does not exist, or exists but we are
// supposed to overwrite it, try to do the rename
if ((!newExists) || (newExists && overwriteIfExists))
{
#ifdef DEBUG_FILE_RENAME
MessageInterface::ShowMessage("FM::Copy, attempting to copy %s to %s\n",
oldName.c_str(), newName.c_str());
#endif
std::ifstream src(oldName.c_str(), std::ios::binary);
std::ofstream dest(newName.c_str(), std::ios::binary);
dest << src.rdbuf();
retCode = src && dest;
return retCode == 1;
}
else // it exists but we are not to overwrite it
return false;
}
//------------------------------------------------------------------------------
// std::string GetStartupFileDir()
//------------------------------------------------------------------------------
/*
* Returns startup file directory without name.
*/
//------------------------------------------------------------------------------
std::string FileManager::GetStartupFileDir()
{
return mStartupFileDir;
}
//------------------------------------------------------------------------------
// std::string GetStartupFileName()
//------------------------------------------------------------------------------
/*
* Returns startup file name without directory.
*/
//------------------------------------------------------------------------------
std::string FileManager::GetStartupFileName()
{
return mStartupFileName;
}
//------------------------------------------------------------------------------
// std::string GetFullStartupFilePath()
//------------------------------------------------------------------------------
/*
* Returns startup file directory and name
*/
//------------------------------------------------------------------------------
std::string FileManager::GetFullStartupFilePath()
{
#ifdef DEBUG_STARTUP_FILE
MessageInterface::ShowMessage
("FileManager::GetFullStartupFilePath() mStartupFileDir='%s', "
"mStartupFileName='%s'\n", mStartupFileDir.c_str(), mStartupFileName.c_str());
#endif
if (mStartupFileDir == "")
return mStartupFileName;
else
{
mStartupFileDir = GmatFileUtil::GetCurrentWorkingDirectory() + mPathSeparator;
return mStartupFileDir + mStartupFileName;
}
}
//void FileManager::ReadStartupFile(const char *fileName)
//{
// ReadStartupFile(std::string(fileName));
//}
//------------------------------------------------------------------------------
// void ReadStartupFile(const std::string &fileName = "")
//------------------------------------------------------------------------------
/**
* Reads GMAT startup file.
*
* @param <fileName> startup file name.
*
*/
//------------------------------------------------------------------------------
void FileManager::ReadStartupFile(const std::string &fileName)
{
#ifdef DEBUG_READ_STARTUP_FILE
MessageInterface::ShowMessage
("FileManager::ReadStartupFile() entered, fileName='%s'\n", fileName.c_str());
#endif
RefreshFiles();
// Set bin directory
SetBinDirectory();
// get current path and application path
std::string currPath = GmatFileUtil::GetCurrentWorkingDirectory();
std::string appFullPath = GmatFileUtil::GetApplicationPath();
#ifdef DEBUG_READ_STARTUP_FILE
MessageInterface::ShowMessage(" currPath = '%s'\n", currPath.c_str());
MessageInterface::ShowMessage(" appFullPath = '%s'\n", appFullPath.c_str());
#endif
std::string line;
mSavedComments.clear();
std::string tmpStartupDir;
std::string tmpStartupFile;
std::string tmpStartupFilePath;
if (GmatFileUtil::DoesFileExist(fileName))
{
#ifdef DEBUG_READ_STARTUP_FILE
MessageInterface::ShowMessage(" startup file '%s' exist.\n", fileName.c_str());
#endif
tmpStartupFilePath = fileName;
}
else
{
#ifdef DEBUG_READ_STARTUP_FILE
MessageInterface::ShowMessage
(" startup file '%s' does not exist, \n so look in bin directory '%s'\n",
fileName.c_str(), appFullPath.c_str());
#endif
// Search application directory for startup file
std::string appPath = GmatFileUtil::ParsePathName(appFullPath);
std::string newPath = appPath + "gmat_startup_file.txt";
#ifdef DEBUG_READ_STARTUP_FILE
MessageInterface::ShowMessage(" appPath = '%s'\n", appPath.c_str());
MessageInterface::ShowMessage(" new startup file path = '%s'\n", newPath.c_str());
#endif
if (GmatFileUtil::DoesFileExist(newPath))
{
tmpStartupFilePath = newPath;
// set current directory to new path
if (SetCurrentWorkingDirectory(appPath))
{
MessageInterface::ShowMessage
("GMAT working directory set to '%s'\n", appPath.c_str());
}
else
{
UtilityException ue;
ue.SetDetails("FileManager::ReadStartupFile() cannot set working "
"directory to: \"%s\"", appPath.c_str());
throw ue;
}
}
else
{
tmpStartupFilePath = newPath;
}
}
tmpStartupDir = GmatFileUtil::ParsePathName(tmpStartupFilePath);
tmpStartupFile = GmatFileUtil::ParseFileName(tmpStartupFilePath);
#ifdef DEBUG_READ_STARTUP_FILE
MessageInterface::ShowMessage(" tmpStartupDir = '%s'\n", tmpStartupDir.c_str());
MessageInterface::ShowMessage(" tmpStartupFile = '%s'\n", tmpStartupFile.c_str());
#endif
if (tmpStartupDir == "")
tmpStartupFilePath = tmpStartupFile;
else
tmpStartupFilePath = tmpStartupDir + mPathSeparator + tmpStartupFile;
// // Reworked this part above so removed(LOJ: 2011.12.14)
// #if 0
// if (fileName == "")
// {
// tmpStartupDir = "";
// tmpStartupFile = mStartupFileName;
// tmpStartupFilePath = mStartupFileName;
// }
// else
// {
// tmpStartupDir = GmatFileUtil::ParsePathName(fileName);
// tmpStartupFile = GmatFileUtil::ParseFileName(fileName);
//
// if (tmpStartupDir == "")
// tmpStartupFilePath = tmpStartupFile;
// else
// tmpStartupFilePath = tmpStartupDir + mPathSeparator + tmpStartupFile;
// }
// #endif
#ifdef DEBUG_READ_STARTUP_FILE
MessageInterface::ShowMessage
("FileManager::ReadStartupFile() reading '%s'\n", tmpStartupFilePath.c_str());
#endif
std::ifstream mInStream(tmpStartupFilePath.c_str());
if (!mInStream)
{
UtilityException ue;
ue.SetDetails("FileManager::ReadStartupFile() cannot open GMAT startup "
"file: \"%s\"", tmpStartupFilePath.c_str());
throw ue;
}
// Read startup file
while (!mInStream.eof())
{
// Use cross-platform GetLine
GmatFileUtil::GetLine(&mInStream, line);
#ifdef DEBUG_READ_STARTUP_FILE
MessageInterface::ShowMessage("line=%s\n", line.c_str());
#endif
// Skip empty line or comment line
if (line.length() > 0) // Crashes in VS 2010 debugger without this
{
if (line[0] == '\0' || line[0] == '#')
{
// save line with ## in the first col
if (line.size() > 1 && line[1] == '#')
mSavedComments.push_back(line);
continue;
}
}
else
continue;
std::string type, equal, name;
std::stringstream ss("");
ss << line;
ss >> type >> equal;
if (equal != "=")
{
mInStream.close();
throw UtilityException
("FileManager::ReadStartupFile() expecting '=' at line:\n" +
std::string(line) + "\n");
}
// To fix bug 1916 (LOJ: 2010.10.08)
// Since >> uses space as deliminter, we cannot use it.
// So use GmatStringUtil::DecomposeBy() instead.
//ss >> name;
StringArray parts = GmatStringUtil::DecomposeBy(line, "=");
name = parts[1];
name = GmatStringUtil::Trim(name);
#ifdef DEBUG_READ_STARTUP_FILE
MessageInterface::ShowMessage("type=%s, name=%s\n", type.c_str(), name.c_str());
#endif
if (type == "RUN_MODE")
{
mRunMode = name;
if (name == "TESTING")
GmatGlobal::Instance()->SetRunMode(GmatGlobal::TESTING);
else if (name == "TESTING_NO_PLOTS")
GmatGlobal::Instance()->SetRunMode(GmatGlobal::TESTING_NO_PLOTS);
else if (name == "EXIT_AFTER_RUN")
GmatGlobal::Instance()->SetRunMode(GmatGlobal::EXIT_AFTER_RUN);
}
else if (type == "PLOT_MODE")
{
mPlotMode = name;
if (name == "TILE")
GmatGlobal::Instance()->SetPlotMode(GmatGlobal::TILED_PLOT);
}
else if (type == "MATLAB_MODE")
{
mMatlabMode = name;
if (name == "SINGLE")
GmatGlobal::Instance()->SetMatlabMode(GmatGlobal::SINGLE_USE);
else if (name == "SHARED")
GmatGlobal::Instance()->SetMatlabMode(GmatGlobal::SHARED);
else if (name == "NO_MATLAB")
GmatGlobal::Instance()->SetMatlabMode(GmatGlobal::NO_MATLAB);
}
else if (type == "DEBUG_MATLAB")
{
if (name == "ON")
{
mDebugMatlab = name;
GmatGlobal::Instance()->SetMatlabDebug(true);
}
}
else if (type == "DEBUG_MISSION_TREE")
{
if (name == "ON")
{
mDebugMissionTree = name;
GmatGlobal::Instance()->SetMissionTreeDebug(true);
}
}
else if (type == "DEBUG_PARAMETERS")
{
if (name == "ON")
{
mWriteParameterInfo = name;
GmatGlobal::Instance()->SetWriteParameterInfo(true);
}
}
else if (type == "DEBUG_FILE_PATH")
{
if (name == "ON")
{
mWriteFilePathInfo = name;
GmatGlobal::Instance()->SetWriteFilePathInfo(true);
}
}
else if (type == "WRITE_GMAT_KEYWORD")
{
if (name == "OFF")
{
mWriteGmatKeyword = name;
GmatGlobal::Instance()->SetWriteGmatKeyword(false);
}
}
else if (type == "WRITE_PERSONALIZATION_FILE")
{
if (name == "ON")
GmatGlobal::Instance()->SetWritePersonalizationFile(true);
else
GmatGlobal::Instance()->SetWritePersonalizationFile(false);
}
else if (type == "HIDE_SAVEMISSION")
{
if (name == "TRUE")
GmatGlobal::Instance()->AddHiddenCommand("SaveMission");
else
GmatGlobal::Instance()->RemoveHiddenCommand("SaveMission");
}
else if (type == "ECHO_COMMANDS")
{
if (name == "TRUE")
GmatGlobal::Instance()->SetCommandEchoMode(true);
else
GmatGlobal::Instance()->SetCommandEchoMode(false);
}
else if (type == "NO_SPLASH")
{
if (name == "TRUE")
GmatGlobal::Instance()->SetSkipSplashMode(true);
else
GmatGlobal::Instance()->SetSkipSplashMode(false);
}
else
{
// Ignore old VERSION specification (2011.03.18)
if (type != "VERSION")
AddFileType(type, name);
}
} // end While()
// Since we set all output to ./ as default, we don't need this (LOJ: 2011.03.17)
// Set VEHICLE_EPHEM_CCSDS_PATH to OUTPUT_PATH from the startup file if not set
// so that ./output directory is not required when writing the ephemeris file.
// if (mPathMap["VEHICLE_EPHEM_CCSDS_PATH"] == "./output/" &&
// mPathMap["OUTPUT_PATH"] != "./files/output/")
// {
// mPathMap["VEHICLE_EPHEM_CCSDS_PATH"] = mPathMap["OUTPUT_PATH"];
// #ifdef DEBUG_READ_STARTUP_FILE
// MessageInterface::ShowMessage
// ("==> VEHICLE_EPHEM_CCSDS_PATH set to '%s'\n", mPathMap["VEHICLE_EPHEM_CCSDS_PATH"].c_str());
// #endif
// }
// add potential files by type names
AddAvailablePotentialFiles();
// save good startup file
mStartupFileDir = tmpStartupDir;
mStartupFileName = tmpStartupFile;
// Check first to see if the user has set a log file on the command line -
// that would take prcedence over a log file specified in the startup
// file. Also, check to see if the command-line-specified file exists and
// if so, make sure it is a log file (i.e. starts with the correct text).
// TBD
// now use log file from the startup file if applicable
std::string startupLog = GetAbsPathname("LOG_FILE");
GmatGlobal *gmatGlobal = GmatGlobal::Instance();
gmatGlobal->SetLogfileName(GmatGlobal::STARTUP, startupLog);
Integer logSrc = gmatGlobal->GetLogfileSource();
if (logSrc == GmatGlobal::CMD_LINE)
{
std::string cmdLineLog = gmatGlobal->GetLogfileName(GmatGlobal::CMD_LINE);
MessageInterface::SetLogFile(cmdLineLog);
}
else // can't be SCRIPT yet since startup is read before scripts are parsed
{
MessageInterface::SetLogFile(startupLog);
}
MessageInterface::SetLogEnable(true);
mInStream.close();
/// @todo This code replaces relative paths with absolute. It was implemented to
/// address an issue in R2014a, but the side effects were to severe for
/// the release. It is commented out so that post release, we can asses how
/// to proceed addressing path issues in GMAT.
// SetPathsAbsolute();
// Validate PATHs
ValidatePaths();
#ifdef DEBUG_MAPPING
ShowMaps("In ReadStartupFile()");
#endif
}
//void FileManager::WriteStartupFile(const char *fileName)
//{
// WriteStartupFile(std::string(fileName));
//}
//------------------------------------------------------------------------------
// void WriteStartupFile(const std::string &fileName = "")
//------------------------------------------------------------------------------
/**
* Reads GMAT startup file.
*
* @param <fileName> startup file name.
*
* @exception UtilityException thrown if file cannot be opened
*/
//------------------------------------------------------------------------------
void FileManager::WriteStartupFile(const std::string &fileName)
{
std::string outFileName = "gmat_startup_file.new.txt";
mPathWrittenOuts.clear();
mFileWrittenOuts.clear();
if (fileName != "")
outFileName = fileName;
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage
("FileManager::WriteStartupFile() entered, outFileName = %s\n",
outFileName.c_str());
#endif
std::ofstream outStream(outFileName.c_str());
if (!outStream)
throw UtilityException
("FileManager::WriteStartupFile() cannot open:" + fileName);
//---------------------------------------------
// write header
//---------------------------------------------
WriteHeader(outStream);
// set left justified
outStream.setf(std::ios::left);
// don't write CURRENT_PATH
mPathWrittenOuts.push_back("CURRENT_PATH");
//---------------------------------------------
// write RUN_MODE if not blank
//---------------------------------------------
if (mRunMode != "")
{
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing RUN_MODE\n");
#endif
outStream << std::setw(22) << "RUN_MODE" << " = " << mRunMode << "\n";
}
// Write other option as comments
outStream << std::setw(22) << "#RUN_MODE" << " = TESTING\n";
outStream << std::setw(22) << "#RUN_MODE" << " = TESTING_NO_PLOTS\n";
outStream << std::setw(22) << "#RUN_MODE" << " = EXIT_AFTER_RUN\n";
//---------------------------------------------
// write PLOT_MODE if not blank
//---------------------------------------------
if (mPlotMode != "")
{
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing PLOT_MODE\n");
#endif
outStream << std::setw(22) << "PLOT_MODE" << " = " << mRunMode << "\n";
}
// Write other option as comments
// There are no other options implemented for now
//outStream << std::setw(22) << "#PLOT_MODE" << " = TILE\n";
//---------------------------------------------
// write MATLAB_MODE if not blank
//---------------------------------------------
if (mMatlabMode != "")
{
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing MATLAB_MODE\n");
#endif
outStream << std::setw(22) << "MATLAB_MODE" << " = " << mMatlabMode << "\n";
}
// Write other option as comments
outStream << std::setw(22) << "#MATLAB_MODE" << " = SINGLE\n";
outStream << std::setw(22) << "#MATLAB_MODE" << " = SHARED\n";
outStream << std::setw(22) << "#MATLAB_MODE" << " = NO_MATLAB\n";
//---------------------------------------------
// write DEBUG_MATLAB if not blank
//---------------------------------------------
if (mDebugMatlab != "")
{
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing DEBUG_MATLAB\n");
#endif
outStream << std::setw(22) << "DEBUG_MATLAB" << " = " << mDebugMatlab << "\n";
}
//---------------------------------------------
// write DEBUG_MISSION_TREE if not blank
//---------------------------------------------
if (mDebugMissionTree != "")
{
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing DEBUG_MISSION_TREE\n");
#endif
outStream << std::setw(22) << "DEBUG_MISSION_TREE" << " = " << mDebugMissionTree << "\n";
}
if (mRunMode != "" || mPlotMode != "" || mMatlabMode != "" ||
mDebugMatlab != "" || mDebugMissionTree != "")
outStream << "#-----------------------------------------------------------\n";
//---------------------------------------------
// write DEBUG_PARAMETERS if not blank
//---------------------------------------------
if (mWriteParameterInfo != "")
{
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing PARAMETER_INFO\n");
#endif
outStream << std::setw(22) << "DEBUG_PARAMETERS" << " = " << mWriteParameterInfo << "\n";
}
if (mRunMode != "" || mPlotMode != "" || mMatlabMode != "" ||
mDebugMatlab != "" || mDebugMissionTree != "" || mWriteParameterInfo != "")
outStream << "#-----------------------------------------------------------\n";
//---------------------------------------------
// write DEBUG_FILE_PATH if not blank
//---------------------------------------------
if (mWriteFilePathInfo != "")
{
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing FILE_PATH_INFO\n");
#endif
outStream << std::setw(22) << "DEBUG_FILE_PATH" << " = " << mWriteFilePathInfo << "\n";
}
if (mRunMode != "" || mPlotMode != "" || mMatlabMode != "" ||
mDebugMatlab != "" || mDebugMissionTree != "" || mWriteParameterInfo != "" ||
mWriteFilePathInfo != "")
outStream << "#-----------------------------------------------------------\n";
//---------------------------------------------
// write WRITE_GMAT_KEYWORD if not blank
//---------------------------------------------
if (mWriteGmatKeyword != "")
{
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing GMAT_KEYWORD_INFO\n");
#endif
outStream << std::setw(22) << "WRITE_GMAT_KEYWORD" << " = " << mWriteGmatKeyword << "\n";
}
if (mRunMode != "" || mPlotMode != "" || mMatlabMode != "" ||
mDebugMatlab != "" || mDebugMissionTree != "" || mWriteParameterInfo != "" ||
mWriteFilePathInfo != "" || mWriteGmatKeyword != "" )
outStream << "#-----------------------------------------------------------\n";
//---------------------------------------------
// write ROOT_PATH next
//---------------------------------------------
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing ROOT_PATH path\n");
#endif
outStream << std::setw(22) << "ROOT_PATH" << " = " << mPathMap["ROOT_PATH"]
<< "\n";
outStream << "#-----------------------------------------------------------\n";
mPathWrittenOuts.push_back("ROOT_PATH");
//---------------------------------------------
// write PLUGIN next
//---------------------------------------------
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing PLUGIN\n");
#endif
if (mPluginList.size() > 0)
{
for (UnsignedInt i = 0; i < mPluginList.size(); ++i)
{
outStream << std::setw(22) << "PLUGIN" << " = " << mPluginList[i]
<< "\n";
}
outStream << "#-----------------------------------------------------------\n";
}
//---------------------------------------------
// write OUTPUT_PATH and output files next
//---------------------------------------------
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing OUTPUT_PATH paths\n");
#endif
outStream << std::setw(22) << "OUTPUT_PATH" << " = "
<< mPathMap["OUTPUT_PATH"] << "\n";
WriteFiles(outStream, "LOG_");
WriteFiles(outStream, "REPORT_");
WriteFiles(outStream, "SCREENSHOT_");
outStream << "#-----------------------------------------------------------\n";
mPathWrittenOuts.push_back("OUTPUT_PATH");
//---------------------------------------------
// write MEASUREMENT_PATH next
//---------------------------------------------
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing MEASUREMENT_PATH paths\n");
#endif
outStream << std::setw(22) << "MEASUREMENT_PATH" << " = "
<< mPathMap["MEASUREMENT_PATH"] << "\n";
outStream << "#-----------------------------------------------------------\n";
mPathWrittenOuts.push_back("MEASUREMENT_PATH");
//---------------------------------------------
// write the VEHICLE_EPHEM_CCSDS_PATH next if set
//---------------------------------------------
if (mPathMap["VEHICLE_EPHEM_CCSDS_PATH"] != "./output/")
{
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing VEHICLE_EPHEM_CCSDS_PATH path\n");
#endif
outStream << std::setw(22) << "VEHICLE_EPHEM_CCSDS_PATH" << " = "
<< mPathMap["VEHICLE_EPHEM_CCSDS_PATH"];
outStream << "\n#---------------------------------------------"
"--------------\n";
mPathWrittenOuts.push_back("VEHICLE_EPHEM_CCSDS_PATH");
}
//---------------------------------------------
// write GMAT_INCLUDE_PATH next
//---------------------------------------------
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing GMAT_INCLUDE_PATH paths\n");
#endif
bool isEmptyPath = true;
for (std::map<std::string, std::string>::iterator pos = mPathMap.begin();
pos != mPathMap.end(); ++pos)
{
if (pos->first == "GMAT_INCLUDE_PATH")
{
// Write all GmatInclude paths
std::list<std::string>::iterator listpos = mGmatIncludePaths.begin();
while (listpos != mGmatIncludePaths.end())
{
outStream << std::setw(22) << pos->first << " = "
<< *listpos << "\n";
++listpos;
}
isEmptyPath = false;
break;
}
}
if (isEmptyPath)
outStream << std::setw(22) << "#GMAT_INCLUDE_PATH " << " = " << "\n";
outStream << "#-----------------------------------------------------------\n";
mPathWrittenOuts.push_back("GMAT_INCLUDE_PATH");
//---------------------------------------------
// write GMAT_FUNCTION_PATH next
//---------------------------------------------
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing GMAT_FUNCTION_PATH paths\n");
#endif
isEmptyPath = true;
for (std::map<std::string, std::string>::iterator pos = mPathMap.begin();
pos != mPathMap.end(); ++pos)
{
if (pos->first == "GMAT_FUNCTION_PATH")
{
// Write all GmatFunction paths
std::list<std::string>::iterator listpos = mGmatFunctionPaths.begin();
while (listpos != mGmatFunctionPaths.end())
{
outStream << std::setw(22) << pos->first << " = "
<< *listpos << "\n";
++listpos;
}
isEmptyPath = false;
break;
}
}
if (isEmptyPath)
outStream << std::setw(22) << "#GMAT_FUNCTION_PATH " << " = " << "\n";
outStream << "#-----------------------------------------------------------\n";
mPathWrittenOuts.push_back("GMAT_FUNCTION_PATH");
//---------------------------------------------
// write MATLAB_FUNCTION_PATH next
//---------------------------------------------
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing MATLAB_FUNCTION_PATH paths\n");
#endif
isEmptyPath = true;
for (std::map<std::string, std::string>::iterator pos = mPathMap.begin();
pos != mPathMap.end(); ++pos)
{
if (pos->first == "MATLAB_FUNCTION_PATH")
{
// Write all GmatFunction paths
std::list<std::string>::iterator listpos = mMatlabFunctionPaths.begin();
while (listpos != mMatlabFunctionPaths.end())
{
outStream << std::setw(22) << pos->first << " = " << *listpos << "\n";
++listpos;
}
break;
}
}
if (isEmptyPath)
outStream << std::setw(22) << "#MATLAB_FUNCTION_PATH " << " = " << "\n";
outStream << "#-----------------------------------------------------------\n";
mPathWrittenOuts.push_back("MATLAB_FUNCTION_PATH");
//---------------------------------------------
// write DATA_PATH next
//---------------------------------------------
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing DATA_PATH path\n");
#endif
outStream << std::setw(22) << "DATA_PATH" << " = " << mPathMap["DATA_PATH"]
<< "\n";
outStream << "#-----------------------------------------------------------\n";
mPathWrittenOuts.push_back("DATA_PATH");
//---------------------------------------------
// write any relative path used in PLANETARY_EPHEM_SPK_PATH
//---------------------------------------------
std::string spkPath = mPathMap["PLANETARY_EPHEM_SPK_PATH"];
if (spkPath.find("_PATH") != spkPath.npos)
{
std::string relPath = GmatFileUtil::ParseFirstPathName(spkPath, false);
if (find(mPathWrittenOuts.begin(), mPathWrittenOuts.end(), relPath) ==
mPathWrittenOuts.end())
{
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing %s\n", relPath.c_str());
#endif
outStream << std::setw(22) << relPath << " = " << mPathMap[relPath] << "\n";
outStream << "#-----------------------------------------------------------\n";
mPathWrittenOuts.push_back(relPath);
}
}
//---------------------------------------------
// write the PLANETARY_EPHEM_SPK_PATH and SPK file next
//---------------------------------------------
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing SPK path\n");
#endif
outStream << std::setw(22) << "PLANETARY_EPHEM_SPK_PATH" << " = "
<< mPathMap["PLANETARY_EPHEM_SPK_PATH"] << "\n";
WriteFiles(outStream, "PLANETARY SPK");
outStream << "#-----------------------------------------------------------\n";
mPathWrittenOuts.push_back("PLANETARY_EPHEM_SPK_PATH");
//---------------------------------------------
// write the PLANETARY_EPHEM_DE_PATH and DE file next
//---------------------------------------------
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing DE path\n");
#endif
outStream << std::setw(22) << "PLANETARY_EPHEM_DE_PATH" << " = "
<< mPathMap["PLANETARY_EPHEM_DE_PATH"] << "\n";
WriteFiles(outStream, "DE405");
outStream << "#-----------------------------------------------------------\n";
mPathWrittenOuts.push_back("PLANETARY_EPHEM_DE_PATH");
//---------------------------------------------
// write the PLANETARY_COEFF_PATH and files next
//---------------------------------------------
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing PLANETARY_COEFF_PATH path\n");
#endif
outStream << std::setw(22) << "PLANETARY_COEFF_PATH" << " = "
<< mPathMap["PLANETARY_COEFF_PATH"] << "\n";
WriteFiles(outStream, "EOP_FILE");
WriteFiles(outStream, "PLANETARY_COEFF_FILE");
WriteFiles(outStream, "NUTATION_COEFF_FILE");
WriteFiles(outStream, "PLANETARY_PCK_FILE");
WriteFiles(outStream, "EARTH_LATEST_PCK_FILE");
WriteFiles(outStream, "EARTH_PCK_PREDICTED_FILE");
WriteFiles(outStream, "EARTH_PCK_CURRENT_FILE");
WriteFiles(outStream, "LUNA_PCK_CURRENT_FILE");
WriteFiles(outStream, "LUNA_FRAME_KERNEL_FILE");
outStream << "#-----------------------------------------------------------\n";
mPathWrittenOuts.push_back("PLANETARY_COEFF_PATH");
//---------------------------------------------
// write the TIME_PATH and TIME file next
//---------------------------------------------
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing TIME path\n");
#endif
outStream << std::setw(22) << "TIME_PATH" << " = " << mPathMap["TIME_PATH"] << "\n";
WriteFiles(outStream, "LEAP_");
WriteFiles(outStream, "LSK_");
outStream << "#-----------------------------------------------------------\n";
mPathWrittenOuts.push_back("TIME_PATH");
//---------------------------------------------
// write the ATMOSPHERE_PATH and CSSI FLUX file next
//---------------------------------------------
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing ATMOSPHERE path\n");
#endif
outStream << std::setw(22) << "ATMOSPHERE_PATH" << " = " << mPathMap["ATMOSPHERE_PATH"] << "\n";
WriteFiles(outStream, "CSSI_FLUX_");
WriteFiles(outStream, "SCHATTEN_");
outStream << "#-----------------------------------------------------------\n";
mPathWrittenOuts.push_back("ATMOSPHERE_PATH");
//---------------------------------------------
// write *_POT_PATH and files next
//---------------------------------------------
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing *_POT_PATH paths\n");
#endif
for (std::map<std::string, std::string>::iterator pos = mPathMap.begin();
pos != mPathMap.end(); ++pos)
{
if (pos->first.find("_POT_") != std::string::npos)
{
outStream << std::setw(22) << pos->first << " = "
<< pos->second << "\n";
mPathWrittenOuts.push_back(pos->first);
}
}
outStream << "#-----------------------------------------------------------\n";
WriteFiles(outStream, "POT_FILE");
WriteFiles(outStream, "EGM96");
WriteFiles(outStream, "JGM");
WriteFiles(outStream, "MARS50C");
WriteFiles(outStream, "MGNP180U");
WriteFiles(outStream, "LP165P");
outStream << "#-----------------------------------------------------------\n";
//---------------------------------------------
// write the GUI_CONFIG_PATH and files next
//---------------------------------------------
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing GUI_CONFIG_PATH path\n");
#endif
outStream << std::setw(22) << "GUI_CONFIG_PATH" << " = "
<< mPathMap["GUI_CONFIG_PATH"] << "\n";
WriteFiles(outStream, "PERSONALIZATION_FILE");
outStream << "#-----------------------------------------------------------\n";
mPathWrittenOuts.push_back("GUI_CONFIG_PATH");
//---------------------------------------------
// write the ICON_PATH and files next
//---------------------------------------------
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing ICON_PATH path\n");
#endif
outStream << std::setw(22) << "ICON_PATH" << " = "
<< mPathMap["ICON_PATH"] << "\n";
WriteFiles(outStream, "ICON_FILE");
outStream << "#-----------------------------------------------------------\n";
mPathWrittenOuts.push_back("ICON_PATH");
//---------------------------------------------
// write the SPLASH_PATH and files next
//---------------------------------------------
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing SPLASH_PATH path\n");
#endif
outStream << std::setw(22) << "SPLASH_PATH" << " = "
<< mPathMap["SPLASH_PATH"] << "\n";
WriteFiles(outStream, "SPLASH_FILE");
outStream << "#-----------------------------------------------------------\n";
mPathWrittenOuts.push_back("SPLASH_PATH");
//---------------------------------------------
// write the TEXTURE_PATH and files next
//---------------------------------------------
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing TEXTURE_PATH path\n");
#endif
outStream << std::setw(22) << "TEXTURE_PATH" << " = "
<< mPathMap["TEXTURE_PATH"] << "\n";
WriteFiles(outStream, "TEXTURE_FILE");
outStream << "#-----------------------------------------------------------\n";
mPathWrittenOuts.push_back("TEXTURE_PATH");
//---------------------------------------------
// write the STAR_PATH and files next
//---------------------------------------------
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing STAR_PATH path\n");
#endif
outStream << std::setw(22) << "STAR_PATH" << " = "
<< mPathMap["STAR_PATH"] << "\n";
WriteFiles(outStream, "STAR_FILE");
WriteFiles(outStream, "CONSTELLATION_FILE");
outStream << "#-----------------------------------------------------------\n";
mPathWrittenOuts.push_back("STAR_PATH");
//---------------------------------------------
// write the VEHICLE_EPHEM_SPK_PATH and files next
//---------------------------------------------
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing VEHICLE_EPHEM_SPK_PATH path\n");
#endif
outStream << std::setw(22) << "VEHICLE_EPHEM_SPK_PATH" << " = "
<< mPathMap["VEHICLE_EPHEM_SPK_PATH"] << "\n";
outStream << "#-----------------------------------------------------------\n";
mPathWrittenOuts.push_back("VEHICLE_EPHEM_SPK_PATH");
//---------------------------------------------
// write the VEHICLE_MODEL_PATH and files next
//---------------------------------------------
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing VEHICLE_MODEL_PATH path\n");
#endif
outStream << std::setw(22) << "VEHICLE_MODEL_PATH" << " = "
<< mPathMap["VEHICLE_MODEL_PATH"] << "\n";
WriteFiles(outStream, "SPACECRAFT_MODEL_FILE");
outStream << "#-----------------------------------------------------------\n";
mPathWrittenOuts.push_back("VEHICLE_MODEL_PATH");
//---------------------------------------------
// write the HELP_FILE next
//---------------------------------------------
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing HELP_FILE\n");
#endif
if (GetFilename("HELP_FILE") == "")
outStream << std::setw(22) << "#HELP_FILE " << " = " << "\n";
else
WriteFiles(outStream, "HELP_FILE");
outStream << "#-----------------------------------------------------------\n";
mFileWrittenOuts.push_back("HELP_FILE");
//---------------------------------------------
// write rest of paths and files
//---------------------------------------------
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing rest of paths and files\n");
#endif
WriteFiles(outStream, "-OTHER-PATH-");
WriteFiles(outStream, "-OTHER-");
outStream << "#-----------------------------------------------------------\n";
//---------------------------------------------
// write saved comments
//---------------------------------------------
if (!mSavedComments.empty())
{
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing saved comments\n");
#endif
outStream << "# Saved Comments\n";
outStream << "#-----------------------------------------------------------\n";
for (UnsignedInt i=0; i<mSavedComments.size(); i++)
outStream << mSavedComments[i] << "\n";
outStream << "#-----------------------------------------------------------\n";
}
outStream << "\n";
outStream.close();
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage("FileManager::WriteStartupFile() exiting\n");
#endif
}
//------------------------------------------------------------------------------
// std::string GetRootPath()
//------------------------------------------------------------------------------
/**
* Retrives root pathname.
*
* @return file pathname if path type found.
*/
//------------------------------------------------------------------------------
std::string FileManager::GetRootPath()
{
return mPathMap["ROOT_PATH"];
}
//------------------------------------------------------------------------------
// bool GetTextureMapFile(const std::string &inFileName, const std::string &bodyName,
// const std::string &objName, std::string &outFileName,
// std::string &outFullPathName, bool writeWarning)
//------------------------------------------------------------------------------
bool FileManager::GetTextureMapFile(const std::string &inFileName, const std::string &bodyName,
const std::string &objName, std::string &outFileName,
std::string &outFullPathName, bool writeWarning)
{
#ifdef DEBUG_TEXTURE_FILE
MessageInterface::ShowMessage
("\nFileManager::GetTextureMapFile() entered\n inFileName = '%s'\n "
"bodyName = '%s', objName = '%s', writeWarning = %d\n", inFileName.c_str(),
bodyName.c_str(), objName.c_str(), writeWarning);
#endif
bool retval = true;
std::string actualFile = inFileName;
std::string fullPath;
std::string mapFileType = GmatStringUtil::ToUpper(bodyName) + "_TEXTURE_FILE";
mLastFilePathMessage = "";
bool writeInfo = false;
outFileName = inFileName;
#ifdef DEBUG_TEXTURE_FILE
MessageInterface::ShowMessage(" actualFile = '%s'\n", actualFile.c_str());
MessageInterface::ShowMessage(" mapFileType = '%s'\n", mapFileType.c_str());
#endif
try
{
if (inFileName == "")
actualFile = GetFilename(mapFileType);
fullPath =
FindPath(actualFile, mapFileType, true, writeWarning, writeInfo, objName);
#ifdef DEBUG_TEXTURE_FILE
MessageInterface::ShowMessage(" actualFile = '%s'\n", actualFile.c_str());
MessageInterface::ShowMessage(" fullPath = '%s'\n", fullPath.c_str());
#endif
// If fullPath is blank, try with TEXTURE_PATH since non-standard bodies'
// texture map file may not be available such as SOMECOMET1_TEXTURE_FILE
if (fullPath == "")
{
fullPath =
FindPath(actualFile, "TEXTURE_PATH", true, false, writeInfo, objName);
}
if (fullPath == "")
{
if (inFileName == "")
{
mLastFilePathMessage = GetLastFilePathMessage() + ", so using " + actualFile + ".";
}
else
{
mLastFilePathMessage = GetLastFilePathMessage();
retval = false;
}
}
else if (inFileName == "")
{
outFileName = actualFile;
std::string msg = "*** WARNING *** There is no texture map file "
"specified for " + objName + ", so using " + actualFile;
mLastFilePathMessage = msg;
if (writeWarning)
MessageInterface::ShowMessage(msg + "\n");
}
outFullPathName = fullPath;
}
catch (BaseException &be)
{
#ifdef DEBUG_TEXTURE_FILE
MessageInterface::ShowMessage("%s\n", be.GetFullMessage().c_str());
#endif
if (inFileName == "")
{
actualFile = "GenericCelestialBody.jpg";
std::string msg = "*** WARNING *** There is no texture map file "
"specified for " + objName + ", so using " + actualFile;
mLastFilePathMessage = msg;
if (writeWarning)
MessageInterface::ShowMessage(msg + "\n");
fullPath =
FileManager::Instance()->FindPath(actualFile, "TEXTURE_PATH", true, false,
writeInfo, objName);
outFileName = actualFile;
outFullPathName = fullPath;
}
else
{
outFullPathName = "";
retval = false;
}
}
#ifdef DEBUG_TEXTURE_FILE
MessageInterface::ShowMessage
(" outFileName = '%s'\n outFullPathName = '%s'\n mLastFilePathMessage = '%s'\n",
outFileName.c_str(), outFullPathName.c_str(), mLastFilePathMessage.c_str());
MessageInterface::ShowMessage("FileManager::GetTextureMapFile() returnng %d\n\n", retval);
#endif
return retval;
}
//------------------------------------------------------------------------------
// bool GetBody3dModelFile(const std::string &inFileName, const std::string &bodyName,
// const std::string &objName, std::string &outFileName,
// std::string &outFullPathName, bool writeWarning)
//------------------------------------------------------------------------------
bool FileManager::GetBody3dModelFile(const std::string &inFileName, const std::string &bodyName,
const std::string &objName, std::string &outFileName,
std::string &outFullPathName, bool writeWarning)
{
#ifdef DEBUG_3DMODEL_FILE
MessageInterface::ShowMessage
("\nFileManager::GetBody3dModelFile() entered\n inFileName = '%s'\n "
"bodyName = '%s', objName = '%s', writeWarning = %d\n", inFileName.c_str(),
bodyName.c_str(), objName.c_str(), writeWarning);
#endif
bool retval = true;
std::string actualFile = inFileName;
std::string fullPath;
std::string modelFileType = GmatStringUtil::ToUpper(bodyName) + "3D_MODEL_FILE";
mLastFilePathMessage = "";
bool writeInfo = false;
outFileName = inFileName;
#ifdef DEBUG_3DMODEL_FILE
MessageInterface::ShowMessage(" actualFile = '%s'\n", actualFile.c_str());
MessageInterface::ShowMessage(" modelFileType = '%s'\n", modelFileType.c_str());
#endif
try
{
if (inFileName == "")
actualFile = GetFilename(modelFileType);
fullPath =
FindPath(actualFile, modelFileType, true, writeWarning, writeInfo, objName);
#ifdef DEBUG_3DMODEL_FILE
MessageInterface::ShowMessage(" actualFile = '%s'\n", actualFile.c_str());
MessageInterface::ShowMessage(" fullPath = '%s'\n", fullPath.c_str());
#endif
// If fullPath is blank, try with BODY_3D_MODEL_PATH since non-standard bodies'
// 3d file may not be available such as SOMECOMET1_3D_MODEL_FILE
if (fullPath == "")
{
fullPath =
FindPath(actualFile, "BODY_3D_MODEL_PATH", true, false, writeInfo, objName);
}
if (fullPath == "")
{
if (inFileName == "")
{
mLastFilePathMessage = GetLastFilePathMessage() + ", so using " + actualFile + ".";
}
else
{
mLastFilePathMessage = GetLastFilePathMessage();
retval = false;
}
}
else if (inFileName == "")
{
outFileName = actualFile;
std::string msg = "*** WARNING *** There is no 3D model file "
"specified for " + objName + ", so using " + actualFile;
mLastFilePathMessage = msg;
if (writeWarning)
MessageInterface::ShowMessage(msg + "\n");
}
outFullPathName = fullPath;
}
catch (BaseException &be)
{
#ifdef DEBUG_3DMODEL_FILE
MessageInterface::ShowMessage("%s\n", be.GetFullMessage().c_str());
#endif
if (inFileName == "")
{
actualFile = "";
std::string msg = "*** WARNING *** There is no 3d model file "
"specified for " + objName + ", so using " + actualFile;
mLastFilePathMessage = msg;
if (writeWarning)
MessageInterface::ShowMessage(msg + "\n");
fullPath =
FileManager::Instance()->FindPath(actualFile, "BODY_3D_MODEL_PATH", true, false,
writeInfo, objName);
outFileName = actualFile;
outFullPathName = fullPath;
}
else
{
outFullPathName = "";
retval = false;
}
}
#ifdef DEBUG_3DMODEL_FILE
MessageInterface::ShowMessage
(" outFileName = '%s'\n outFullPathName = '%s'\n mLastFilePathMessage = '%s'\n",
outFileName.c_str(), outFullPathName.c_str(), mLastFilePathMessage.c_str());
MessageInterface::ShowMessage("FileManager::GetBody3dModelFile() returnng %d\n\n", retval);
#endif
return retval;
}
//------------------------------------------------------------------------------
// std::string GetPathname(const FileType type)
//------------------------------------------------------------------------------
/**
* Retrives absolute path for the type without filename.
*
* @param <type> enum file type of which path to be returned.
*
* @return file pathname if path type found.
* @exception thrown if enum type is out of bounds.
*/
//------------------------------------------------------------------------------
std::string FileManager::GetPathname(const FileType type)
{
if (type >=0 && type < FileTypeCount)
return GetPathname(FILE_TYPE_STRING[type]);
std::stringstream ss("");
ss << "FileManager::GetPathname() enum type: " << type
<< " is out of bounds\n";
throw UtilityException(ss.str());
}
//------------------------------------------------------------------------------
// std::string GetPathname(const std::string &typeName)
//------------------------------------------------------------------------------
/**
* Retrives absolute pathname for the type name without filename.
*
* @param <typeName> file type name of which pathname to be returned.
*
* @return pathname if type found.
* @exception thrown if type cannot be found.
*/
//------------------------------------------------------------------------------
std::string FileManager::GetPathname(const std::string &typeName)
{
std::string fileType = GmatStringUtil::ToUpper(typeName);
#ifdef DEBUG_FILE_PATH
MessageInterface::ShowMessage
("FileManager::GetPathname() entered, flleType='%s'\n", fileType.c_str());
#endif
std::string pathname;
bool nameFound = false;
// if typeName contains _PATH
if (fileType.find("_PATH") != fileType.npos)
{
if (mPathMap.find(fileType) != mPathMap.end())
{
pathname = mPathMap[fileType];
nameFound = true;
}
}
else
{
// typeName contains _FILE
if (mFileMap.find(fileType) != mFileMap.end())
{
pathname = mFileMap[fileType]->mPath;
nameFound = true;
}
}
if (nameFound)
{
#ifdef DEBUG_FILE_PATH
MessageInterface::ShowMessage(" pathname = '%s'\n", pathname.c_str());
#endif
// Replace relative path with absolute path
std::string abspath = ConvertToAbsPath(pathname);
#ifdef DEBUG_FILE_PATH
MessageInterface::ShowMessage
("FileManager::GetPathname() returning '%s'\n", abspath.c_str());
#endif
return abspath;
}
else
{
throw UtilityException("FileManager::GetPathname() file type: " + typeName +
" is unknown\n");
}
}
//------------------------------------------------------------------------------
// std::string GetFilename(const FileType type)
//------------------------------------------------------------------------------
/**
* Retrives filename for the type without path.
*
* @param <type> enum file type of which filename to be returned.
*
* @return file filename if file type found
* @exception thrown if enum type is out of bounds
*/
//------------------------------------------------------------------------------
std::string FileManager::GetFilename(const FileType type)
{
bool nameFound = false;
std::string name;
if (type >=0 && type < FileTypeCount)
{
name = GetFilename(FILE_TYPE_STRING[type]);
nameFound = true;
}
if (nameFound)
{
name = GmatFileUtil::ParseFileName(name);
return name;
}
std::stringstream ss("");
ss << "FileManager::GetFilename() enum type: " << type
<< " is out of bounds\n";
throw UtilityException(ss.str());
}
//------------------------------------------------------------------------------
// std::string GetFilename(const std::string &typeName)
//------------------------------------------------------------------------------
/**
* Retrives filename for the type name without path.
*
* @param <type> file type name of which filename to be returned.
*
* @return file filename if file type found
* @exception thrown if type cannot be found.
*/
//------------------------------------------------------------------------------
std::string FileManager::GetFilename(const std::string &typeName)
{
#ifdef DEBUG_GET_FILENAME
MessageInterface::ShowMessage
("FileManager::GetFilename() entered, typeName = '%s'\n", typeName.c_str());
#endif
bool nameFound = false;
std::string name;
if (mFileMap.find(typeName) != mFileMap.end())
{
name = mFileMap[typeName]->mFile;
nameFound = true;
}
if (nameFound)
{
name = GmatFileUtil::ParseFileName(name);
#ifdef DEBUG_GET_FILENAME
MessageInterface::ShowMessage
("FileManager::GetFilename() returning '%s'\n", name.c_str());
#endif
return name;
}
throw UtilityException("FileManager::GetFilename() file type: " + typeName +
" is unknown\n");
}
//------------------------------------------------------------------------------
// std::string GetFullPathname(const FileType type)
//------------------------------------------------------------------------------
/**
* Retrieves full pathname for the type.
*
* @param <type> file type of which filename to be returned.
*
* @return file pathname if file type found
* @exception thrown if enum type is out of bounds
*/
//------------------------------------------------------------------------------
std::string FileManager::GetFullPathname(const FileType type)
{
return GetAbsPathname(type);
}
//------------------------------------------------------------------------------
// std::string GetFullPathname(const std::string &typeName)
//------------------------------------------------------------------------------
/**
* Retrives full pathname for the type name.
*
* @param <type> file type name of which filename to be returned.
*
* @return file pathname if file type name found
* @exception thrown if type cannot be found.
*/
//------------------------------------------------------------------------------
std::string FileManager::GetFullPathname(const std::string &typeName)
{
return GetAbsPathname(typeName);
}
//------------------------------------------------------------------------------
// std::string GetAbsPathname(const FileType type)
//------------------------------------------------------------------------------
/**
* Retrieves full pathname for the type.
*
* @param <type> file type of which filename to be returned.
*
* @return file pathname if file type found
* @exception thrown if enum type is out of bounds
*/
//------------------------------------------------------------------------------
std::string FileManager::GetAbsPathname(const FileType type)
{
if (type >=0 && type < FileTypeCount)
return GetAbsPathname(FILE_TYPE_STRING[type]);
std::stringstream ss("");
ss << "FileManager::GetAbsPathname() enum type: " << type <<
" is out of bounds\n";
throw UtilityException(ss.str());
}
//------------------------------------------------------------------------------
// std::string GetAbsPathname(const std::string &typeName)
//------------------------------------------------------------------------------
/**
* Retrieves full pathname for the type name.
*
* @param <type> file type name of which filename to be returned.
*
* @return file pathname if file type name found
* @exception thrown if type cannot be found.
*/
//------------------------------------------------------------------------------
std::string FileManager::GetAbsPathname(const std::string &typeName)
{
std::string fileType = GmatStringUtil::ToUpper(typeName);
std::string absPath;
#ifdef DEBUG_ABS_PATH
MessageInterface::ShowMessage
("FileManager::GetAbsPathname() typeName='%s', fileType='%s'\n",
typeName.c_str(), fileType.c_str());
#endif
// typeName contains _PATH
if (fileType.find("_PATH") != fileType.npos)
{
if (mPathMap.find(fileType) != mPathMap.end())
{
absPath = ConvertToAbsPath(fileType);
#ifdef DEBUG_ABS_PATH
MessageInterface::ShowMessage
("FileManager::GetAbsPathname() with _PATH returning '%s'\n", absPath.c_str());
#endif
return absPath;
}
}
else
{
if (mFileMap.find(fileType) != mFileMap.end())
{
std::string path = GetPathname(fileType);
absPath = path + mFileMap[fileType]->mFile;
}
else if (mFileMap.find(fileType + "_ABS") != mFileMap.end())
{
absPath = mFileMap[typeName]->mFile;
}
#ifdef DEBUG_ABS_PATH
MessageInterface::ShowMessage
("FileManager::GetAbsPathname() without _PATH returning '%s'\n", absPath.c_str());
#endif
return absPath;
}
throw UtilityException
(GmatStringUtil::ToUpper(typeName) + " not in the gmat_startup_file\n");
}
//------------------------------------------------------------------------------
// std::string ConvertToAbsPath(const std::string &relPath, bool appendPathSep = true)
//------------------------------------------------------------------------------
/**
* Converts relative path to absolute path
*/
//------------------------------------------------------------------------------
std::string FileManager::ConvertToAbsPath(const std::string &relPath, bool appendPathSep)
{
#ifdef DEBUG_FILE_PATH
MessageInterface::ShowMessage
("FileManager::ConvertToAbsPath() relPath='%s'\n", relPath.c_str());
#endif
//std::string absPath = relPath;
std::string absPath;
bool startsWithSeparator = false;
if ((relPath[0] == '\\') || (relPath[0] == '/'))
startsWithSeparator = true;
StringTokenizer st(relPath, "/\\");
StringArray allNames = st.GetAllTokens();
StringArray pathNames;
#ifdef DEBUG_FILE_PATH
Integer numNames = allNames.size();
MessageInterface::ShowMessage("There are %d names in relPath\n", numNames);
for (int i = 0; i < numNames; i++)
MessageInterface::ShowMessage(" allNames[%d] = '%s'\n", i, allNames[i].c_str());
#endif
for (UnsignedInt i = 0; i < allNames.size(); i++)
{
std::string name = allNames[i];
#ifdef DEBUG_FILE_PATH
MessageInterface::ShowMessage(" allNames[%d] = '%s'\n", i, name.c_str());
#endif
absPath = name;
if (GmatStringUtil::EndsWith(name, "_PATH"))
{
#ifdef DEBUG_FILE_PATH
MessageInterface::ShowMessage(" _PATH found\n");
#endif
if (mPathMap.find(name) != mPathMap.end())
absPath = mPathMap[name];
#ifdef DEBUG_FILE_PATH
MessageInterface::ShowMessage(" 1st absPath = '%s'\n", absPath.c_str());
#endif
// If _PATH found and it is not the same as original name,
// Call ConvertToAbsPath() again
if (absPath.find("_PATH") != absPath.npos && absPath != name)
absPath = ConvertToAbsPath(absPath);
#ifdef DEBUG_FILE_PATH
MessageInterface::ShowMessage(" 2nd absPath = '%s'\n", absPath.c_str());
#endif
pathNames.push_back(absPath);
}
else
{
#ifdef DEBUG_FILE_PATH
MessageInterface::ShowMessage(" _PATH not found\n");
MessageInterface::ShowMessage(" absPath = '%s'\n", absPath.c_str());
#endif
pathNames.push_back(absPath);
}
}
absPath = "";
// For paths that already started with the separator (were already absolute paths)
if (startsWithSeparator)
absPath += mPathSeparator;
for (UnsignedInt i = 0; i < pathNames.size(); i++)
{
if (i < pathNames.size() - 1)
{
if (GmatStringUtil::EndsWithPathSeparator(pathNames[i]))
absPath = absPath + pathNames[i];
else
absPath = absPath + pathNames[i] + "/";
}
else
{
if (GmatStringUtil::EndsWithPathSeparator(pathNames[i]))
absPath = absPath + pathNames[i];
else
{
if (appendPathSep)
absPath = absPath + pathNames[i] + "/";
else
absPath = absPath + pathNames[i];
}
}
}
// Convert path to absolute by prepending bin dir (LOJ: 2014.06.18)
if (absPath != "" && absPath[0] == '.')
absPath = mAbsBinDir + absPath;
// Conver to OS path name
absPath = GmatFileUtil::ConvertToOsFileName(absPath);
#ifdef DEBUG_FILE_PATH
MessageInterface::ShowMessage
("FileManager::ConvertToAbsPath() returning '%s'\n", absPath.c_str());
#endif
return absPath;
}
//------------------------------------------------------------------------------
// void SetAbsPathname(const FileType type, const char *newpath)
//------------------------------------------------------------------------------
/**
* Sets absoulute pathname for the type.
*
* @param <type> file type of which path to be set.
* @param <newpath> new pathname.
*
* @exception thrown if enum type is out of bounds
*/
//------------------------------------------------------------------------------
void FileManager::SetAbsPathname(const FileType type, const char *newpath)
{
SetAbsPathname(type, std::string(newpath));
}
//------------------------------------------------------------------------------
// void SetAbsPathname(const FileType type, const std::string &newpath)
//------------------------------------------------------------------------------
/**
* Sets absoulute pathname for the type.
*
* @param <type> file type of which path to be set.
* @param <newpath> new pathname.
*
* @exception thrown if enum type is out of bounds
*/
//------------------------------------------------------------------------------
void FileManager::SetAbsPathname(const FileType type, const std::string &newpath)
{
if (type >= BEGIN_OF_PATH && type <= END_OF_PATH)
{
SetAbsPathname(FILE_TYPE_STRING[type], newpath);
}
else
{
std::stringstream ss("");
ss << "FileManager::SetAbsPathname() enum type: " << type <<
" is out of bounds of file path\n";
throw UtilityException(ss.str());
}
}
//------------------------------------------------------------------------------
// void SetAbsPathname(const std::string &type, const char *newpath)
//------------------------------------------------------------------------------
/**
* Sets absolute pathname for the type.
*
* @param <type> type name of which path to be set.
* @param <newpath> new pathname.
*
* @exception thrown if enum type is out of bounds
*/
//------------------------------------------------------------------------------
void FileManager::SetAbsPathname(const std::string &type, const char *newpath)
{
SetAbsPathname(type, std::string(newpath));
}
//------------------------------------------------------------------------------
// void SetAbsPathname(const std::string &type, const std::string &newpath)
//------------------------------------------------------------------------------
/**
* Sets absolute pathname for the type.
*
* @param <type> type name of which path to be set.
* @param <newpath> new pathname.
*
* @exception thrown if enum type is out of bounds
*/
//------------------------------------------------------------------------------
void FileManager::SetAbsPathname(const std::string &type, const std::string &newpath)
{
if (mPathMap.find(type) != mPathMap.end())
{
if (type.find("_PATH") != type.npos)
{
std::string str2 = newpath;
// append '/' if not there
std::string::size_type index = str2.find_last_of("/\\");
if (index != str2.length() - 1)
{
str2 = str2 + mPathSeparator;
}
else
{
index = str2.find_last_not_of("/\\");
str2 = str2.substr(0, index+1) + mPathSeparator;
}
mPathMap[type] = str2;
#ifdef DEBUG_SET_PATH
MessageInterface::ShowMessage
("FileManager::SetAbsPathname() %s set to %s\n", type.c_str(),
str2.c_str());
#endif
}
else
{
throw UtilityException
("FileManager::SetAbsPathname() type doesn't contain _PATH");
}
}
}
//------------------------------------------------------------------------------
// void ClearGmatIncludePath()
//------------------------------------------------------------------------------
void FileManager::ClearGmatIncludePath()
{
mGmatIncludePaths.clear();
}
//------------------------------------------------------------------------------
// void AddGmatIncludePath(const char *path, bool addFront)
//------------------------------------------------------------------------------
void FileManager::AddGmatIncludePath(const char *path, bool addFront)
{
return AddGmatIncludePath(std::string(path), addFront);
}
//------------------------------------------------------------------------------
// void AddGmatIncludePath(const std::string &path, bool addFront, bool addFront)
//------------------------------------------------------------------------------
/*
* If new path it adds to the GmatInclude path list.
* If path already exist, it moves to the front or back of the list, depends on
* addFront flag.
*
* @param path path name to be added
* @param addFront if set to true, it adds to the front, else adds to the back (true)
*/
//------------------------------------------------------------------------------
void FileManager::AddGmatIncludePath(const std::string &path, bool addFront)
{
#ifdef DEBUG_GMAT_PATH
MessageInterface::ShowMessage
("FileManager::AddGmatIncludePath() Adding %s to GmatIncludePath\n "
"addFront=%d\n", path.c_str(), addFront);
#endif
std::string pathname = path;
// if path has full pathname (directory and filename), remove filename first
if (path.find(".") != path.npos)
pathname = GmatFileUtil::ParsePathName(path);
std::list<std::string>::iterator pos =
find(mGmatIncludePaths.begin(), mGmatIncludePaths.end(), pathname);
if (pos == mGmatIncludePaths.end())
{
#ifdef DEBUG_GMAT_PATH
MessageInterface::ShowMessage
(" the pathname <%s> is new, so adding to %s\n", pathname.c_str(),
addFront ? "front" : "back");
#endif
// if new pathname, add to front or back of the list
if (addFront)
mGmatIncludePaths.push_front(pathname);
else
mGmatIncludePaths.push_back(pathname);
}
else
{
// if existing pathname remove and add front or back of the list
#ifdef DEBUG_GMAT_PATH
MessageInterface::ShowMessage
(" the pathname <%s> already exists, so moving to %s\n", pathname.c_str(),
addFront ? "front" : "back");
#endif
std::string oldPath = *pos;
mGmatIncludePaths.erase(pos);
if (addFront)
mGmatIncludePaths.push_front(oldPath);
else
mGmatIncludePaths.push_back(oldPath);
}
#ifdef DEBUG_GMAT_PATH
pos = mGmatIncludePaths.begin();
while (pos != mGmatIncludePaths.end())
{
MessageInterface::ShowMessage
("------ mGmatIncludePaths = %s\n", (*pos).c_str());
++pos;
}
#endif
}
//------------------------------------------------------------------------------
// std::string GetGmatIncludePath(const char *incName)
//------------------------------------------------------------------------------
std::string FileManager::GetGmatIncludePath(const char *incName)
{
return GetGmatPath(GMAT_INCLUDE, mGmatIncludePaths, std::string(incName));
}
//------------------------------------------------------------------------------
// std::string GetGmatIncludePath(const std::string &incName)
//------------------------------------------------------------------------------
/*
* Returns the absolute path that has Include filename.
* It searches in the most recently added path first which is at the top of
* the list.
*
* @param incName Include filename to be located
* @return Path Path that has Include filename
*/
//------------------------------------------------------------------------------
std::string FileManager::GetGmatIncludePath(const std::string &incName)
{
return GetGmatPath(GMAT_INCLUDE, mGmatIncludePaths, incName);
}
//------------------------------------------------------------------------------
// const StringArray& GetAllGmatIncludePaths()
//------------------------------------------------------------------------------
const StringArray& FileManager::GetAllGmatIncludePaths()
{
mGmatIncludeFullPaths.clear();
std::list<std::string>::iterator listpos = mGmatIncludePaths.begin();
while (listpos != mGmatIncludePaths.end())
{
mGmatIncludeFullPaths.push_back(ConvertToAbsPath(*listpos));
++listpos;
}
return mGmatIncludeFullPaths;
}
//------------------------------------------------------------------------------
// void ClearGmatFunctionPath()
//------------------------------------------------------------------------------
void FileManager::ClearGmatFunctionPath()
{
mGmatFunctionPaths.clear();
}
//------------------------------------------------------------------------------
// void AddGmatFunctionPath(const char *path, bool addFront)
//------------------------------------------------------------------------------
void FileManager::AddGmatFunctionPath(const char *path, bool addFront)
{
return AddGmatFunctionPath(std::string(path), addFront);
}
//------------------------------------------------------------------------------
// void AddGmatFunctionPath(const std::string &path, bool addFront, bool addFront)
//------------------------------------------------------------------------------
/*
* If new path it adds to the GmatFunction path list.
* If path already exist, it moves to the front or back of the list, depends on
* addFront flag.
*
* @param path path name to be added
* @param addFront if set to true, it adds to the front, else adds to the back (true)
*/
//------------------------------------------------------------------------------
void FileManager::AddGmatFunctionPath(const std::string &path, bool addFront)
{
#ifdef DEBUG_GMAT_PATH
MessageInterface::ShowMessage
("FileManager::AddGmatFunctionPath() Adding %s to GmatFunctionPath\n "
"addFront=%d\n", path.c_str(), addFront);
#endif
std::string pathname = path;
// if path has full pathname (directory and filename), remove filename first
if (path.find(".") != path.npos)
pathname = GmatFileUtil::ParsePathName(path);
std::list<std::string>::iterator pos =
find(mGmatFunctionPaths.begin(), mGmatFunctionPaths.end(), pathname);
if (pos == mGmatFunctionPaths.end())
{
#ifdef DEBUG_GMAT_PATH
MessageInterface::ShowMessage
(" the pathname <%s> is new, so adding to %s\n", pathname.c_str(),
addFront ? "front" : "back");
#endif
// if new pathname, add to front or back of the list
if (addFront)
mGmatFunctionPaths.push_front(pathname);
else
mGmatFunctionPaths.push_back(pathname);
}
else
{
// if existing pathname remove and add front or back of the list
#ifdef DEBUG_GMAT_PATH
MessageInterface::ShowMessage
(" the pathname <%s> already exists, so moving to %s\n", pathname.c_str(),
addFront ? "front" : "back");
#endif
std::string oldPath = *pos;
mGmatFunctionPaths.erase(pos);
if (addFront)
mGmatFunctionPaths.push_front(oldPath);
else
mGmatFunctionPaths.push_back(oldPath);
}
#ifdef DEBUG_GMAT_PATH
pos = mGmatFunctionPaths.begin();
while (pos != mGmatFunctionPaths.end())
{
MessageInterface::ShowMessage
("------ mGmatFunctionPaths = %s\n", (*pos).c_str());
++pos;
}
#endif
}
//------------------------------------------------------------------------------
// std::string GetGmatFunctionPath(const char *funcName)
//------------------------------------------------------------------------------
std::string FileManager::GetGmatFunctionPath(const char *funcName)
{
return GetGmatPath(GMAT_FUNCTION, mGmatFunctionPaths, std::string(funcName));
}
//------------------------------------------------------------------------------
// std::string GetGmatFunctionPath(const std::string &funcName)
//------------------------------------------------------------------------------
/*
* Returns the absolute path that has GmatFunction name.
* It searches in the most recently added path first which is at the top of
* the list.
*
* @param funcName Name of the GmatFunction to be located
* @return Path that has GmatFunction name
*/
//------------------------------------------------------------------------------
std::string FileManager::GetGmatFunctionPath(const std::string &funcName)
{
return GetGmatPath(GMAT_FUNCTION, mGmatFunctionPaths, funcName);
}
//------------------------------------------------------------------------------
// const StringArray& GetAllGmatFunctionPaths()
//------------------------------------------------------------------------------
const StringArray& FileManager::GetAllGmatFunctionPaths()
{
mGmatFunctionFullPaths.clear();
std::list<std::string>::iterator listpos = mGmatFunctionPaths.begin();
while (listpos != mGmatFunctionPaths.end())
{
mGmatFunctionFullPaths.push_back(ConvertToAbsPath(*listpos));
++listpos;
}
return mGmatFunctionFullPaths;
}
//------------------------------------------------------------------------------
// void ClearMatlabFunctionPath()
//------------------------------------------------------------------------------
void FileManager::ClearMatlabFunctionPath()
{
mMatlabFunctionPaths.clear();
}
void FileManager::AddMatlabFunctionPath(const char *path, bool addFront)
{
return AddMatlabFunctionPath(std::string(path), addFront);
}
//------------------------------------------------------------------------------
// void AddMatlabFunctionPath(const std::string &path, bool addFront = true)
//------------------------------------------------------------------------------
/*
* If new path it adds to the MatlabFunction path list.
* If path already exist, it moves to the front or back of the list, depends on
* addFront flag.
*
* @param path path name to be added
* @param addFront if set to true, it adds to the front, else adds to the back [true]
*/
//------------------------------------------------------------------------------
void FileManager::AddMatlabFunctionPath(const std::string &path, bool addFront)
{
#ifdef DEBUG_GMAT_PATH
MessageInterface::ShowMessage
("FileManager::AddMatlabFunctionPath() Adding %s to MatlabFunctionPath\n",
path.c_str());
#endif
std::list<std::string>::iterator pos =
find(mMatlabFunctionPaths.begin(), mMatlabFunctionPaths.end(), path);
if (pos == mMatlabFunctionPaths.end())
{
// if new path, add to front or back of the list
if (addFront)
mMatlabFunctionPaths.push_front(path);
else
mMatlabFunctionPaths.push_back(path);
}
else
{
// if existing path remove and add front or back of the list
std::string oldPath = *pos;
mMatlabFunctionPaths.erase(pos);
if (addFront)
mMatlabFunctionPaths.push_front(oldPath);
else
mMatlabFunctionPaths.push_back(oldPath);
}
#ifdef DEBUG_GMAT_PATH
pos = mMatlabFunctionPaths.begin();
while (pos != mMatlabFunctionPaths.end())
{
MessageInterface::ShowMessage
(" mMatlabFunctionPaths=%s\n",(*pos).c_str());
++pos;
}
#endif
}
std::string FileManager::GetMatlabFunctionPath(const char *funcName)
{
return GetMatlabFunctionPath(std::string(funcName));
}
//------------------------------------------------------------------------------
// std::string GetMatlabFunctionPath(const std::string &funcName)
//------------------------------------------------------------------------------
/*
* Returns the absolute path that has MatlabFunction name.
* It searches in the most recently added path first which is at the top of
* the list.
*
* @param funcName Name of the MatlabFunction to be located
* @return Path that has MatlabFunction name
*/
//------------------------------------------------------------------------------
std::string FileManager::GetMatlabFunctionPath(const std::string &funcName)
{
std::string path = GetGmatPath(MATLAB_FUNCTION, mMatlabFunctionPaths, funcName);
// Write informational message if debug is turned on from the startup file
if (mWriteFilePathInfo == "ON")
{
if (path == "")
MessageInterface::ShowMessage
("*** Using MATLAB built-in function '%s'\n", funcName.c_str());
else
MessageInterface::ShowMessage
("*** Using MATLAB function '%s' from '%s'\n", funcName.c_str(), path.c_str());
}
return path;
}
//------------------------------------------------------------------------------
// const StringArray& GetAllMatlabFunctionPaths()
//------------------------------------------------------------------------------
const StringArray& FileManager::GetAllMatlabFunctionPaths()
{
mMatlabFunctionFullPaths.clear();
std::list<std::string>::iterator listpos = mMatlabFunctionPaths.begin();
while (listpos != mMatlabFunctionPaths.end())
{
mMatlabFunctionFullPaths.push_back(ConvertToAbsPath(*listpos));
++listpos;
}
return mMatlabFunctionFullPaths;
}
//------------------------------------------------------------------------------
// void AddPythonModulePath(const std::string& path)
//------------------------------------------------------------------------------
/**
* Adds a folder to the buffer for the Python search path
*
* @param path The new folder that may contain Python modules
*/
//------------------------------------------------------------------------------
void FileManager::AddPythonModulePath(const std::string& path)
{
#ifdef DEBUG_GMAT_PATH
MessageInterface::ShowMessage
("FileManager::AddPythonModulePath() Adding %s to PythonModulePath\n",
path.c_str());
#endif
std::list<std::string>::iterator pos =
find(mPythonModulePaths.begin(), mPythonModulePaths.end(), path);
if (pos == mPythonModulePaths.end())
{
mPythonModulePaths.push_back(path);
}
#ifdef DEBUG_GMAT_PATH
pos = mPythonModulePaths.begin();
while (pos != mPythonModulePaths.end())
{
MessageInterface::ShowMessage
(" mPythonModulePaths=%s\n", (*pos).c_str());
++pos;
}
#endif
}
// ------------------------------------------------------------------------------
// const StringArray& GetAllPythonModulePaths()
//------------------------------------------------------------------------------
const StringArray& FileManager::GetAllPythonModulePaths()
{
mPythonModuleFullPaths.clear();
std::list<std::string>::iterator listpos = mPythonModulePaths.begin();
while (listpos != mPythonModulePaths.end())
{
mPythonModuleFullPaths.push_back(ConvertToAbsPath(*listpos));
++listpos;
}
return mPythonModuleFullPaths;
}
//------------------------------------------------------------------------------
// std::string GetLastFilePathMessage()
//------------------------------------------------------------------------------
/**
* Returns the last file path message set from FindPath().
*/
//------------------------------------------------------------------------------
std::string FileManager::GetLastFilePathMessage()
{
return mLastFilePathMessage;
}
//------------------------------------------------------------------------------
// const StringArray& GetPluginList()
//------------------------------------------------------------------------------
/**
* Accesses the list of plug-in libraries parsed from the startup file.
*
* @return The list of plug-in libraries
*/
//------------------------------------------------------------------------------
const StringArray& FileManager::GetPluginList()
{
return mPluginList;
}
//------------------------------------------------------------------------------
// void AdjustSettings(const std::string &suffix, const StringArray &forEntries)
//------------------------------------------------------------------------------
/**
* Appends a suffix to a list of settings stored in the file manager
*
* @param suffix The suffix to be appended to the setting
* @param forEntries A list of entries that receive the suffix
*/
//------------------------------------------------------------------------------
void FileManager::AdjustSettings(const std::string &suffix,
const StringArray &forEntries)
{
std::string temp;
for (UnsignedInt i = 0; i < forEntries.size(); ++i)
{
// Adjust if path
temp = mPathMap[forEntries[i]];
if (temp != "")
{
std::string trailingSlash = "";
if ((temp[temp.length()-1] == '/') || (temp[temp.length()-1] == '\\'))
{
trailingSlash = temp.substr(temp.length()-1);
temp = temp.substr(0, temp.length()-1);
}
temp += suffix;
temp += trailingSlash;
mPathMap[forEntries[i]] = temp;
}
else // Adjust if file
{
FileInfo *tempFI = mFileMap[forEntries[i]];
temp = tempFI->mFile;
std::string extension = "";
if (temp.find(".") != std::string::npos)
{
extension = temp.substr(temp.find("."));
temp = temp.substr(0, temp.find("."));
}
if (temp != "")
{
temp += suffix + extension;
tempFI->mFile = temp;
}
}
}
}
//---------------------------------
// private methods
//---------------------------------
//------------------------------------------------------------------------------
// std::string GetGmatPath(GmatPathType type, const std::list<std::string> &pathList
// const std::string &name)
//------------------------------------------------------------------------------
/*
* Searches proper GMAT path list from the top and return first path found.
*
* @param type type of function (MATLAB_FUNCTION, GMAT_FUNCTION)
* @param pathList function path list to use in search
* @param name name of the function to search
*/
//------------------------------------------------------------------------------
std::string FileManager::GetGmatPath(GmatPathType type,
std::list<std::string> &pathList,
const std::string &name)
{
#ifdef DEBUG_GMAT_PATH
MessageInterface::ShowMessage
("FileManager::GetGmatPath(%s) with type %d entered\n",
name.c_str(), type);
#endif
std::string name1 = name;
if (type == GMAT_FUNCTION)
{
if (name.find(".gmf") == name.npos)
name1 = name1 + ".gmf";
}
else if (type == MATLAB_FUNCTION)
{
if (name.find(".m") == name.npos)
name1 = name1 + ".m";
}
else if (type == GMAT_INCLUDE)
{
// GMAT include file can be any extension
name1 = name;
// If include name contains absolute path, just return the blank path
if (GmatFileUtil::IsPathAbsolute(name1))
{
std::string blankPath;
#ifdef DEBUG_GMAT_PATH
MessageInterface::ShowMessage
("FileManager::GetGmatPath(%s) returning '%s'\n", name.c_str(),
path.c_str());
#endif
return blankPath;
}
}
else
{
UtilityException ue;
ue.SetDetails("*** INTERNAL ERROR *** FileManager::GetGmatPath() The path "
"type %d is undefined\n", type);
throw ue;
}
// Search through pathList
// The most recent path added to the last, so search backwards
std::string pathName, fullPath;
bool fileFound = false;
// Search from the top of the list, which is the most recently added path
// The search order goes from top to bottom. (loj: 2008.10.02)
std::list<std::string>::iterator pos = pathList.begin();
while (pos != pathList.end())
{
pathName = *pos;
fullPath = ConvertToAbsPath(pathName) + name1;
#ifdef DEBUG_GMAT_PATH
MessageInterface::ShowMessage(" pathName='%s'\n", pathName.c_str());
MessageInterface::ShowMessage(" fullPath='%s'\n", fullPath.c_str());
#endif
if (GmatFileUtil::DoesFileExist(fullPath))
{
fileFound = true;
break;
}
pos++;
}
if (fileFound)
fullPath = GmatFileUtil::ParsePathName(fullPath);
else
fullPath = "";
#ifdef DEBUG_GMAT_PATH
MessageInterface::ShowMessage
("FileManager::GetGmatPath(%s) returning '%s'\n", name.c_str(),
fullPath.c_str());
#endif
return fullPath;
}
//------------------------------------------------------------------------------
// void AddFileType(const std::string &type, const std::string &name)
//------------------------------------------------------------------------------
/**
* Adds file type, path, name to the list. If typeName ends with _PATH, it is
* added to path map. If typeName ends with _FILE, it is added to file map, an
* exception is throw otherwise.
*
* @param <type> file type
* @param <name> file path or name
*
* @excepton thrown if typeName does not end with _PATH or _FILE
*/
//------------------------------------------------------------------------------
void FileManager::AddFileType(const std::string &type, const std::string &name)
{
#ifdef DEBUG_ADD_FILETYPE
MessageInterface::ShowMessage
("FileManager::AddFileType() entered, type=%s, name=%s\n", type.c_str(), name.c_str());
#endif
if (type.find("_PATH") != type.npos)
{
std::string str2 = name;
// append '/' if '\\' or '/' not there
if (!GmatStringUtil::EndsWithPathSeparator(str2))
str2 = str2 + mPathSeparator;
mPathMap[type] = str2;
#ifdef DEBUG_ADD_FILETYPE
MessageInterface::ShowMessage
(" Adding %s = %s to mPathMap\n", type.c_str(), str2.c_str());
#endif
// Handle Gmat and Matlab Function path
if (type == "GMAT_FUNCTION_PATH")
AddGmatFunctionPath(str2, false);
else if (type == "MATLAB_FUNCTION_PATH")
AddMatlabFunctionPath(str2, false);
else if (type == "PYTHON_MODULE_PATH")
AddPythonModulePath(str2);
}
else if (type.find("_FILE_ABS") != type.npos)
{
mFileMap[type] = new FileInfo("", name);
}
else if (type.find("_FILE") != type.npos)
{
std::string pathName;
std::string fileName;
// file name
std::string::size_type pos = name.find_last_of("/");
if (pos == name.npos)
pos = name.find_last_of("\\");
if (pos != name.npos)
{
std::string pathName = name.substr(0, pos);
std::string fileName = name.substr(pos+1, name.npos);
mFileMap[type] = new FileInfo(pathName, fileName);
#ifdef DEBUG_ADD_FILETYPE
MessageInterface::ShowMessage
(" Adding %s and %s to mFileMap\n", pathName.c_str(), fileName.c_str());
#endif
}
else
{
//loj: Should we add current path?
std::string pathName = "CURRENT_PATH";
mPathMap[pathName] = "./";
std::string fileName = name;
mFileMap[type] = new FileInfo(pathName, fileName);
#ifdef DEBUG_ADD_FILETYPE
MessageInterface::ShowMessage
(" Adding %s and %s to mFileMap\n", pathName.c_str(), fileName.c_str());
MessageInterface::ShowMessage
(" 'PATH/' not found in line:\n %s = %s\n So adding CURRENT_PATH = ./\n",
type.c_str(), name.c_str());
#endif
//loj: Should we just throw an exception?
//mInStream.close();
//throw UtilityException
// ("FileManager::AddFileType() expecting 'PATH/' in line:\n" +
// type + " = " + name);
}
}
else if (type == "PLUGIN")
{
#ifdef DEBUG_PLUGIN_DETECTION
MessageInterface::ShowMessage("Adding plug-in %s to plugin list\n",
name.c_str());
#endif
mPluginList.push_back(name);
}
else
{
throw UtilityException
("FileManager::AddFileType() file type should have '_PATH' or '_FILE'"
" in:\n" + type);
}
#ifdef DEBUG_ADD_FILETYPE
MessageInterface::ShowMessage("FileManager::AddFileType() leaving\n");
#endif
}
//------------------------------------------------------------------------------
// void AddAvailablePotentialFiles()
//------------------------------------------------------------------------------
void FileManager::AddAvailablePotentialFiles()
{
// add available potential files
// earth gravity files
if (mFileMap.find("JGM2_FILE") == mFileMap.end())
AddFileType("JGM2_FILE", "EARTH_POT_PATH/JGM2.cof");
if (mFileMap.find("JGM3_FILE") == mFileMap.end())
AddFileType("JGM3_FILE", "EARTH_POT_PATH/JGM3.cof");
if (mFileMap.find("EGM96_FILE") == mFileMap.end())
AddFileType("EGM96_FILE", "EARTH_POT_PATH/EGM96low.cof");
// luna gravity files
if (mFileMap.find("LP165P_FILE") == mFileMap.end())
AddFileType("LP165P_FILE", "LUNA_POT_PATH/LP165P.cof");
// venus gravity files
if (mFileMap.find("MGNP180U_FILE") == mFileMap.end())
AddFileType("MGNP180U_FILE", "VENUS_POT_PATH/MGNP180U.cof");
// mars gravity files
if (mFileMap.find("MARS50C_FILE") == mFileMap.end())
AddFileType("MARS50C_FILE", "MARS_POT_PATH/Mars50c.cof");
}
//------------------------------------------------------------------------------
// void WriteHeader(std::ofstream &outStream)
//------------------------------------------------------------------------------
void FileManager::WriteHeader(std::ofstream &outStream)
{
outStream << "#-------------------------------------------------------------------------------\n";
outStream << "# General Mission Analysis Tool (GMAT) startup file\n";
outStream << "#-------------------------------------------------------------------------------\n";
outStream << "# Comment line starts with #\n";
outStream << "# Comment line starting with ## will be saved when saving startup file.\n";
outStream << "#\n";
outStream << "# Path/File naming convention:\n";
outStream << "# - Path name should end with _PATH\n";
outStream << "# - File name should end with _FILE\n";
outStream << "# - Path/File names are case sensative\n";
outStream << "#\n";
outStream << "# You can add potential and texture files by following the naming convention.\n";
outStream << "# - Potential file should begin with planet name and end with _POT_FILE\n";
outStream << "# - Texture file should begin with planet name and end with _TEXTURE_FILE\n";
outStream << "#\n";
outStream << "# If same _FILE is specified multiple times, it will use the last one.\n";
outStream << "#\n";
outStream << "# You can have more than one line containing GMAT_FUNCTION_PATH. GMAT will store \n";
outStream << "# the multiple paths you specify and scan for GMAT Functions using the paths \n";
outStream << "# in top to bottom order and use the first function found from the search paths.\n";
outStream << "#\n";
outStream << "# In order for an object plugin to work inside GMAT, the plugin dynamic link libraries; \n";
outStream << "# Windows(.dll), Linux(.so) and Mac(.dylib), must be placed in the folder containing\n";
outStream << "# the GMAT executable or application. Once placed in the correct folder \n";
outStream << "# the PLUGIN line below must be set equal to the plugin name without the dynamic link \n";
outStream << "# library extension with the comment (#) removed from the front of the line.\n";
outStream << "#\n";
outStream << "# Some available PLUGINs are:\n";
outStream << "# PLUGIN = libMatlabInterface\n";
outStream << "# PLUGIN = libFminconOptimizer\n";
outStream << "# PLUGIN = libVF13Optimizer\n";
outStream << "# PLUGIN = libDataFile\n";
outStream << "# PLUGIN = libCcsdsEphemerisFile\n";
outStream << "# PLUGIN = libGmatEstimation\n";
outStream << "#\n";
outStream << "#===============================================================================\n";
}
//------------------------------------------------------------------------------
// void WriteFiles(std::ofstream &outStream, const std::string &type)
//------------------------------------------------------------------------------
void FileManager::WriteFiles(std::ofstream &outStream, const std::string &type)
{
#ifdef DEBUG_WRITE_STARTUP_FILE
MessageInterface::ShowMessage(" .....Writing %s file\n", type.c_str());
#endif
std::string realPath;
// Write remainder of path
if (type == "-OTHER-PATH-")
{
for (std::map<std::string, std::string>::iterator pos = mPathMap.begin();
pos != mPathMap.end(); ++pos)
{
// if name not found in already written out list, then write
if (find(mPathWrittenOuts.begin(), mPathWrittenOuts.end(), pos->first) ==
mPathWrittenOuts.end())
{
if (pos->second != "")
{
realPath = pos->second;
mPathWrittenOuts.push_back(pos->first);
outStream << std::setw(22) << pos->first << " = "
<< realPath << "\n";
}
}
}
return;
}
// Write remainder of files
if (type == "-OTHER-")
{
for (std::map<std::string, FileInfo*>::iterator pos = mFileMap.begin();
pos != mFileMap.end(); ++pos)
{
// if name not found in already written out list, then write
if (find(mFileWrittenOuts.begin(), mFileWrittenOuts.end(), pos->first) ==
mFileWrittenOuts.end())
{
if (pos->second)
{
realPath = pos->second->mPath;
if (realPath == "CURRENT_PATH")
realPath = "";
else
realPath = realPath + mPathSeparator;
mFileWrittenOuts.push_back(pos->first);
outStream << std::setw(22) << pos->first << " = "
<< realPath << pos->second->mFile << "\n";
}
}
}
return;
}
for (std::map<std::string, FileInfo*>::iterator pos = mFileMap.begin();
pos != mFileMap.end(); ++pos)
{
if (pos->first.find(type) != std::string::npos)
{
if (pos->second)
{
realPath = pos->second->mPath;
if (realPath == "CURRENT_PATH")
realPath = "";
else
realPath = realPath + mPathSeparator;
mFileWrittenOuts.push_back(pos->first);
outStream << std::setw(22) << pos->first << " = "
<< realPath << pos->second->mFile << "\n";
}
}
}
}
//------------------------------------------------------------------------------
// void RefreshFiles()
//------------------------------------------------------------------------------
void FileManager::RefreshFiles()
{
mRunMode = "";
mPlotMode = "";
mMatlabMode = "";
mDebugMatlab = "";
mDebugMissionTree = "";
mWriteParameterInfo = "";
mWriteFilePathInfo = "";
mWriteGmatKeyword = "";
mLastFilePathMessage = "";
mPathMap.clear();
mGmatFunctionPaths.clear();
mMatlabFunctionPaths.clear();
mGmatFunctionFullPaths.clear();
mSavedComments.clear();
mPluginList.clear();
for (std::map<std::string, FileInfo*>::iterator iter = mFileMap.begin();
iter != mFileMap.begin(); ++iter)
delete iter->second;
mFileMap.clear();
//-------------------------------------------------------
// add root and data path
//-------------------------------------------------------
AddFileType("ROOT_PATH", "../");
AddFileType("DATA_PATH", "ROOT_PATH/data");
AddFileType("FILE_UPDATE_PATH", "ROOT_PATH/data");
//-------------------------------------------------------
// add default output paths and files
//-------------------------------------------------------
std::string defOutPath = "../output";
if (!DoesDirectoryExist(defOutPath))
defOutPath = "./";
AddFileType("OUTPUT_PATH", defOutPath);
AddFileType("LOG_FILE", "OUTPUT_PATH/GmatLog.txt");
AddFileType("REPORT_FILE", "OUTPUT_PATH/ReportFile.txt");
AddFileType("EPHEM_OUTPUT_FILE", "OUTPUT_PATH/EphemerisFile.eph");
AddFileType("MEASUREMENT_PATH", "OUTPUT_PATH");
AddFileType("VEHICLE_EPHEM_CCSDS_PATH", "OUTPUT_PATH");
AddFileType("SCREENSHOT_FILE", "OUTPUT_PATH");
// Should we add default input paths and files?
// Yes, for now in case of startup file doesn't specify all the required
// input path and files (LOJ: 2011.03.21)
// Currently #define __FM_ADD_DEFAULT_INPUT__ was commented out
#ifdef __FM_ADD_DEFAULT_INPUT__
#ifdef DEBUG_REFRESH_FILES
MessageInterface::ShowMessage
("FileManager::RefreshFiles() creatng default input paths and files\n");
#endif
//-------------------------------------------------------
// create default input paths and files
//-------------------------------------------------------
// planetary de files
AddFileType("PLANETARY_EPHEM_DE_PATH", "DATA_PATH/planetary_ephem/de/");
AddFileType("DE405_FILE", "PLANETARY_EPHEM_DE_PATH/leDE1941.405");
// planetary spk files
AddFileType("PLANETARY_EPHEM_SPK_PATH", "DATA_PATH/planetary_ephem/spk/");
AddFileType("PLANETARY_SPK_FILE", "PLANETARY_EPHEM_SPK_PATH/de421.bsp");
// vehicle spk files
AddFileType("VEHICLE_EPHEM_SPK_PATH", "DATA_PATH/vehicle/ephem/spk/");
// earth gravity files
AddFileType("EARTH_POT_PATH", "DATA_PATH/gravity/earth/");
AddFileType("JGM2_FILE", "EARTH_POT_PATH/JGM2.cof");
AddFileType("JGM3_FILE", "EARTH_POT_PATH/JGM3.cof");
AddFileType("EGM96_FILE", "EARTH_POT_PATH/EGM96.cof");
// luna gravity files
AddFileType("LUNA_POT_PATH", "DATA_PATH/gravity/luna/");
AddFileType("LP165P_FILE", "LUNA_POT_PATH/lp165p.cof");
// venus gravity files
AddFileType("VENUS_POT_PATH", "DATA_PATH/gravity/venus/");
AddFileType("MGNP180U_FILE", "VENUS_POT_PATH/MGNP180U.cof");
// mars gravity files
AddFileType("MARS_POT_PATH", "DATA_PATH/gravity/mars/");
AddFileType("MARS50C_FILE", "MARS_POT_PATH/Mars50c.cof");
// planetary coeff. files
AddFileType("PLANETARY_COEFF_PATH", "DATA_PATH/planetary_coeff/");
AddFileType("EOP_FILE", "PLANETARY_COEFF_PATH/eopc04.62-now");
// wcs 2013.03.04 PLANETARY_COEFF_FILE is CURRENTLY not used, since our
// default is PLANETARY_1980 and PLANETARY_1996 is not allowed; however,
// we will leave this here as a placeholder anyway
AddFileType("PLANETARY_COEFF_FILE", "PLANETARY_COEFF_PATH/NUT85.DAT");
AddFileType("NUTATION_COEFF_FILE", "PLANETARY_COEFF_PATH/NUTATION.DAT");
AddFileType("PLANETARY_PCK_FILE", "PLANETARY_COEFF_PATH/SPICEPlanetaryConstantsKernel.tpc");
AddFileType("EARTH_LATEST_PCK_FILE", "PLANETARY_COEFF_PATH/earth_latest_high_prec.bpc");
AddFileType("EARTH_PCK_PREDICTED_FILE", "PLANETARY_COEFF_PATH/SPICEEarthPredictedKernel.bpc");
AddFileType("EARTH_PCK_CURRENT_FILE", "PLANETARY_COEFF_PATH/SPICEEarthCurrentKernel.bpc");
AddFileType("LUNA_PCK_CURRENT_FILE", "PLANETARY_COEFF_PATH/SPICELunaCurrentKernel.bpc");
AddFileType("LUNA_FRAME_KERNEL_FILE", "PLANETARY_COEFF_PATH/SPICELunaFrameKernel.tf");
// time path and files
AddFileType("TIME_PATH", "DATA_PATH/time/");
AddFileType("LEAP_SECS_FILE", "TIME_PATH/tai-utc.dat");
AddFileType("LSK_FILE", "TIME_PATH/naif0010.tls");
// atmosphere path and files
AddFileType("ATMOSPHERE_PATH", "DATA_PATH/atmosphere/earth/");
AddFileType("CSSI_FLUX_FILE", "ATMOSPHERE_PATH/CSSI_2004To2026.txt");
AddFileType("SCHATTEN_FILE", "ATMOSPHERE_PATH/SchattenPredict.txt");
AddFileType("MARINI_TROPO_FILE", "ATMOSPHERE_PATH/marini.dat");
// gui config file path
AddFileType("GUI_CONFIG_PATH", "DATA_PATH/gui_config/");
// personalization file
AddFileType("PERSONALIZATION_FILE", "OUTPUT_PATH/MyGmat.ini");
// icon path and main icon file
AddFileType("ICON_PATH", "DATA_PATH/graphics/icons/");
#if defined __WXMSW__
AddFileType("MAIN_ICON_FILE", "ICON_PATH/GMATWin32.ico");
#elif defined __WXGTK__
AddFileType("MAIN_ICON_FILE", "ICON_PATH/GMATLinux48.xpm");
#elif defined __WXMAC__
AddFileType("MAIN_ICON_FILE", "ICON_PATH/GMATIcon.icns");
#endif
// splash file path
AddFileType("SPLASH_PATH", "DATA_PATH/graphics/splash/");
AddFileType("SPLASH_FILE", "SPLASH_PATH/GMATSplashScreen.tif");
// texture file path
AddFileType("TEXTURE_PATH", "DATA_PATH/graphics/texture/");
AddFileType("SUN_TEXTURE_FILE", "TEXTURE_PATH/Sun.jpg");
AddFileType("MERCURY_TEXTURE_FILE", "TEXTURE_PATH/Mercury_JPLCaltech.jpg");
AddFileType("EARTH_TEXTURE_FILE", "TEXTURE_PATH/ModifiedBlueMarble.jpg");
AddFileType("MARS_TEXTURE_FILE", "TEXTURE_PATH/Mars_JPLCaltechUSGS.jpg");
AddFileType("JUPITER_TEXTURE_FILE", "TEXTURE_PATH/Jupiter_HermesCelestiaMotherlode.jpg");
AddFileType("SATRUN_TEXTURE_FILE", "TEXTURE_PATH/Saturn_gradiusCelestiaMotherlode.jpg");
AddFileType("URANUS_TEXTURE_FILE", "TEXTURE_PATH/Uranus_JPLCaltech.jpg");
AddFileType("NEPTUNE_TEXTURE_FILE", "TEXTURE_PATH/Neptune_BjornJonsson.jpg");
AddFileType("PLUTO_TEXTURE_FILE", "TEXTURE_PATH/Pluto_JPLCaltech.jpg");
AddFileType("LUNA_TEXTURE_FILE", "TEXTURE_PATH/Moon_HermesCelestiaMotherlode.jpg");
// star path and files
AddFileType("STAR_PATH", "DATA_PATH/graphics/stars/");
AddFileType("STAR_FILE", "STAR_PATH/inp_StarCatalog.txt");
AddFileType("CONSTELLATION_FILE", "STAR_PATH/inp_Constellation.txt");
// models
AddFileType("VEHICLE_MODEL_PATH", "DATA_PATH/vehicle/models/");
AddFileType("SPACECRAFT_MODEL_FILE", "VEHICLE_MODEL_PATH/aura.3ds");
// help file
AddFileType("HELP_FILE", "");
#endif
}
//------------------------------------------------------------------------------
// void ShowMaps(const std::string &msg)
//------------------------------------------------------------------------------
void FileManager::ShowMaps(const std::string &msg)
{
MessageInterface::ShowMessage("%s\n", msg.c_str());
MessageInterface::ShowMessage("Here is path map, there are %d items\n", mPathMap.size());
for (std::map<std::string, std::string>::iterator pos = mPathMap.begin();
pos != mPathMap.end(); ++pos)
{
MessageInterface::ShowMessage("%20s: %s\n", (pos->first).c_str(), (pos->second).c_str());
}
MessageInterface::ShowMessage("Here is file map, there are %d items\n", mFileMap.size());
for (std::map<std::string, FileInfo*>::iterator pos = mFileMap.begin();
pos != mFileMap.end(); ++pos)
{
MessageInterface::ShowMessage
("%20s: %20s %s\n", (pos->first).c_str(), (pos->second)->mPath.c_str(), (pos->second)->mFile.c_str());
}
}
//------------------------------------------------------------------------------
// FileManager(const std::string &appName = "GMAT.exe")
//------------------------------------------------------------------------------
/*
* Constructor
*/
//------------------------------------------------------------------------------
FileManager::FileManager(const std::string &appName)
{
MessageInterface::SetLogEnable(false); // so that debug can be written from here
#ifdef DEBUG_FILE_MANAGER
MessageInterface::ShowMessage
("FileManager::FileManager() entered, MAX_PATH = %d, MAX_PATH_LEN = %d\n",
MAX_PATH, GmatFile::MAX_PATH_LEN);
#endif
// Set only bin directory
SetBinDirectory(appName);
// Set platform dependent data
mIsOsWindows = GmatFileUtil::IsOsWindows();
mPathSeparator = GetPathSeparator();
mStartupFileDir = GmatFileUtil::GetCurrentWorkingDirectory() + mPathSeparator;
// Set GMAT startup file
mStartupFileName = "gmat_startup_file.txt";
GmatGlobal::Instance()->AddHiddenCommand("SaveMission");
#ifdef DEBUG_STARTUP_FILE
MessageInterface::ShowMessage
("FileManager::FileManager() entered, mPathSeparator='%s', "
"mStartupFileDir='%s', mStartupFileName='%s'\n", mPathSeparator.c_str(),
mStartupFileDir.c_str(), mStartupFileName.c_str());
#endif
RefreshFiles();
}
//------------------------------------------------------------------------------
// void SetPathsAbsolute()
//------------------------------------------------------------------------------
/*
* Sets the paths read from the startup file to absolute paths
*
* This method is separate from ReadStartupFile so that if it is broken, it can
* just be commented out.
*/
//------------------------------------------------------------------------------
void FileManager::SetPathsAbsolute()
{
std::string mGmatBinDir = GmatFileUtil::GetGmatPath();
#ifdef DEBUG_STARTUP_WITH_ABSOLUTE_PATH
MessageInterface::ShowMessage("Real bin folder = %s\nPaths:\n",
mGmatBinDir.c_str());
for (std::map<std::string, std::string>::iterator path = mPathMap.begin();
path != mPathMap.end(); ++path)
MessageInterface::ShowMessage(" %s\n", path->second.c_str());
MessageInterface::ShowMessage("Files:\n");
for (std::map<std::string, FileInfo*>::iterator file = mFileMap.begin();
file != mFileMap.end(); ++file)
MessageInterface::ShowMessage(" %s %s\n", file->second->mPath.c_str(),
file->second->mFile.c_str());
#endif
for (std::map<std::string, std::string>::iterator path = mPathMap.begin();
path != mPathMap.end(); ++path)
{
#ifdef DEBUG_STARTUP_WITH_ABSOLUTE_PATH
MessageInterface::ShowMessage("Checking %s: ", path->second.c_str());
#endif
const char* setting = path->second.c_str();
if (setting[0] == '.')
{
path->second = mGmatBinDir + path->second;
#ifdef DEBUG_STARTUP_WITH_ABSOLUTE_PATH
MessageInterface::ShowMessage("reset to %s", path->second.c_str());
#endif
}
#ifdef DEBUG_STARTUP_WITH_ABSOLUTE_PATH
MessageInterface::ShowMessage("\n");
#endif
}
#ifdef DEBUG_STARTUP_WITH_ABSOLUTE_PATH
MessageInterface::ShowMessage("Paths:\n");
for (std::map<std::string, std::string>::iterator path = mPathMap.begin();
path != mPathMap.end(); ++path)
MessageInterface::ShowMessage(" %s\n", path->second.c_str());
MessageInterface::ShowMessage("Files:\n");
for (std::map<std::string, FileInfo*>::iterator file = mFileMap.begin();
file != mFileMap.end(); ++file)
MessageInterface::ShowMessage(" %s %s\n", file->second->mPath.c_str(),
file->second->mFile.c_str());
#endif
}
//------------------------------------------------------------------------------
// void ValidatePaths()
//------------------------------------------------------------------------------
/*
* Validate all paths in file manager
*/
//------------------------------------------------------------------------------
bool FileManager::ValidatePaths()
{
std::string s = "";
int i = 0;
FileType type;
for ( int fooInt = BEGIN_OF_PATH; fooInt != END_OF_PATH; fooInt++ )
{
type = FileType(fooInt);
switch (type)
{
case BEGIN_OF_PATH:
case END_OF_PATH:
break;
// non fatal paths?
case TEXTURE_PATH:
case BODY_3D_MODEL_PATH:
case MEASUREMENT_PATH:
case GUI_CONFIG_PATH:
case SPLASH_PATH:
case ICON_PATH:
case VEHICLE_MODEL_PATH:
try
{
if (!DoesDirectoryExist(GetFullPathname(type)))
{
MessageInterface::ShowMessage("%s directory does not exist: %s",
FileManager::FILE_TYPE_STRING[type].c_str(),
GetFullPathname(type).c_str());
}
}
catch (UtilityException &e)
{
MessageInterface::ShowMessage("%s directory not specified in gmat_startup_file",
FileManager::FILE_TYPE_STRING[type].c_str());
}
break;
default:
try
{
if (!DoesDirectoryExist(GetFullPathname(type)))
{
i++;
if (i > 9) goto loopexit;
if (i > 1)
s = s + "\n";
s = s + FileManager::FILE_TYPE_STRING[type] + " = " +
GetFullPathname(type);
}
}
catch (UtilityException &e)
{
i++;
if (i > 9) goto loopexit;
if (i > 1)
s = s + "\n";
s = s + FileManager::FILE_TYPE_STRING[type] + " = MISSING in gmat_startup_file";
}
}
}
loopexit:
UtilityException ue;
if (i == 1)
{
ue.SetDetails("The following directory does not exist:\n%s", s.c_str());
throw ue;
}
else if (i > 1)
{
ue.SetDetails("At least %d directories do not exist, including:\n%s", i, s.c_str());
throw ue;
}
return i == 0;
}
| 36.217058
| 113
| 0.510774
|
saichikine
|
1d59edc709c378b84a287bcf43f2028ea41d680f
| 1,326
|
cpp
|
C++
|
sevenfw/anti_arp_tab.cpp
|
codereba/bittrace
|
6826559565aaafc9412d20427d21b73e23febcfe
|
[
"Unlicense"
] | 10
|
2018-11-09T01:08:15.000Z
|
2020-06-21T05:39:54.000Z
|
sevenfw/anti_arp_tab.cpp
|
codereba/bittrace
|
6826559565aaafc9412d20427d21b73e23febcfe
|
[
"Unlicense"
] | null | null | null |
sevenfw/anti_arp_tab.cpp
|
codereba/bittrace
|
6826559565aaafc9412d20427d21b73e23febcfe
|
[
"Unlicense"
] | 4
|
2018-11-09T03:29:52.000Z
|
2021-07-23T03:30:03.000Z
|
/*
* Copyright 2010 JiJie Shi
*
* This file is part of NetMonitor.
*
* NetMonitor 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.
*
* NetMonitor 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 NetMonitor. If not, see <http://www.gnu.org/licenses/>.
*
*
* 2007.6.10 Ji Jie Shi modified it for this ui lib.
*/
#include "common_func.h"
#include "ui_ctrl.h"
#include "anti_arp_tab.h"
INT32 anti_arp_ui_output( ULONG ui_action_id,
INT32 ret_val,
PBYTE data,
ULONG length,
PVOID param )
{
INT32 ret;
anti_arp_tab *output_wnd;
ret = 0;
switch( ui_action_id )
{
case ANTI_ARP_INIT:
break;
case ANTI_ARP_GET_ARP_INFO:
output_wnd = ( anti_arp_tab* )param;
ret = output_wnd->output_arp_info( ( PARP_HOST_MAC_LISTS ) data );
break;
}
return ret;
}
| 25.5
| 72
| 0.674208
|
codereba
|
1d5a74b971140fa7f04ed54d1d66f635bf3bfb49
| 439
|
cpp
|
C++
|
GlacierFormats/src/Export/PNGExporter.cpp
|
pawREP/GlacierFormats
|
9eece4541d863e288fc950087c4f6ec111258fe9
|
[
"MIT"
] | 3
|
2020-04-03T00:01:35.000Z
|
2021-02-04T04:20:58.000Z
|
GlacierFormats/src/Export/PNGExporter.cpp
|
pawREP/GlacierFormats
|
9eece4541d863e288fc950087c4f6ec111258fe9
|
[
"MIT"
] | 1
|
2021-03-02T05:31:10.000Z
|
2021-03-02T05:31:10.000Z
|
GlacierFormats/src/Export/PNGExporter.cpp
|
pawREP/GlacierFormats
|
9eece4541d863e288fc950087c4f6ec111258fe9
|
[
"MIT"
] | null | null | null |
#include "PNGExporter.h"
using namespace GlacierFormats;
using namespace GlacierFormats::Export;
void PNGExporter::operator()(const IRenderAsset& asset, const std::filesystem::path& export_dir) const {
for (const auto& material : asset.materials()) {
for (int i = 0; i < material->getTextureCount(); ++i) {
auto texd = material->getTextureResourceByIndex(i);
if (!texd)
continue;
texd->saveToTGAFile(export_dir);
}
}
}
| 29.266667
| 104
| 0.712984
|
pawREP
|
1d5ca670aaa3d5ded10453cc0fa0951db647dca4
| 9,287
|
hpp
|
C++
|
src/include/miopen/conv/asm_implicit_gemm.hpp
|
j4yan/MIOpen
|
dc38f79bee97e047d866d9c1e25289cba86fab56
|
[
"MIT"
] | 745
|
2017-07-01T22:03:25.000Z
|
2022-03-26T23:46:27.000Z
|
src/include/miopen/conv/asm_implicit_gemm.hpp
|
j4yan/MIOpen
|
dc38f79bee97e047d866d9c1e25289cba86fab56
|
[
"MIT"
] | 1,348
|
2017-07-02T12:37:48.000Z
|
2022-03-31T23:45:51.000Z
|
src/include/miopen/conv/asm_implicit_gemm.hpp
|
j4yan/MIOpen
|
dc38f79bee97e047d866d9c1e25289cba86fab56
|
[
"MIT"
] | 158
|
2017-07-01T19:37:04.000Z
|
2022-03-30T11:57:04.000Z
|
/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2020 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#ifndef CK_ASM_IMPLICITGEMM_HPP_
#define CK_ASM_IMPLICITGEMM_HPP_
#include <string>
#include <ostream>
#include <tuple>
#include <vector>
#include <limits>
namespace miopen {
namespace solver {
struct TunableImplicitGemmGTCDynamic_t
{
std::string direction = " ";
miopenDataType_t precision = miopenFloat;
int nxb = 0;
int nxe = 0;
int gemm_m_per_block = 0;
int gemm_n_per_block = 0;
int gemm_k_per_block = 0;
int wave_tile_m = 0;
int wave_tile_n = 0;
int wave_tile_k = 0;
int wave_step_m = 0;
int wave_step_n = 0;
int wave_repeat_m = 0;
int wave_repeat_n = 0;
int tensor_a_thread_lengths[4] = {0, 0, 0, 0};
int tensor_a_cluster_lengths[4] = {0, 0, 0, 0};
int tensor_b_thread_lengths[4] = {0, 0, 0, 0};
int tensor_b_cluster_lengths[4] = {0, 0, 0, 0};
int gemm_k_global_split = 0;
int GetBlockSize() const
{
const auto WaveSize = 64;
const auto divisor_m = wave_tile_m * wave_step_m * wave_repeat_m;
const auto divisor_n = wave_tile_n * wave_step_n * wave_repeat_n;
assert(divisor_m != 0 && divisor_n != 0);
return (gemm_m_per_block / divisor_m) * (gemm_n_per_block / divisor_n) * WaveSize;
}
std::string GetKernelName() const
{
std::ostringstream kernel_name;
std::string kernel_precision = precision == miopenFloat ? "fp32" : "fp16";
kernel_name << "igemm_" << direction << "_gtcx_nchw_" << kernel_precision << "_bx" << nxb
<< "_ex" << nxe << "_bt" << gemm_m_per_block << "x" << gemm_n_per_block << "x"
<< gemm_k_per_block << "_wt" << wave_tile_m << "x" << wave_tile_n << "x"
<< wave_tile_k << "_ws" << wave_step_m << "x" << wave_step_n << "_wr"
<< wave_repeat_m << "x" << wave_repeat_n << "_ta" << tensor_a_thread_lengths[0]
<< "x" << tensor_a_thread_lengths[1] << "x" << tensor_a_thread_lengths[2] << "x"
<< tensor_a_thread_lengths[3] << "_" << tensor_a_cluster_lengths[0] << "x"
<< tensor_a_cluster_lengths[1] << "x" << tensor_a_cluster_lengths[2] << "x"
<< tensor_a_cluster_lengths[3] << "_tb" << tensor_b_thread_lengths[0] << "x"
<< tensor_b_thread_lengths[1] << "x" << tensor_b_thread_lengths[2] << "x"
<< tensor_b_thread_lengths[3] << "_" << tensor_b_cluster_lengths[0] << "x"
<< tensor_b_cluster_lengths[1] << "x" << tensor_b_cluster_lengths[2] << "x"
<< tensor_b_cluster_lengths[3];
if(this->gemm_k_global_split != 0)
kernel_name << "_gkgs";
return kernel_name.str();
}
};
// calculate log2_gemm_k_global_splits
// with assumption that dimension_0, _1 will merge into a single dimension, and do split only along
// dimension_0
static inline size_t ComputeLog2GemmKGlobalSplitsWith2DMerge(size_t current_grid_size,
size_t max_grid_size,
size_t merge_dimension_0,
size_t merge_dimensoin_1,
size_t gemm_k_per_block,
size_t max_log2_splits)
{
size_t log2_gemm_k_global_splits = 0;
for(size_t gs = 0; gs < max_log2_splits; gs++)
{
if((current_grid_size << gs) > max_grid_size)
break;
if((merge_dimension_0 % (1 << gs)) != 0)
{
break;
}
if((merge_dimension_0 >> gs) * merge_dimensoin_1 % gemm_k_per_block != 0)
{
break;
}
log2_gemm_k_global_splits = gs;
}
return log2_gemm_k_global_splits;
}
// calculate gemm_k_global_splits
// with assumption that some dimensions will merge into a single dimension
static inline size_t ComputeGemmKGlobalSplitsWith2DMerge(size_t current_grid_size,
// size_t merge_dimension,
// size_t gemm_k_per_block,
size_t occupancy,
size_t num_cus)
{
size_t gemm_k_global_splits = num_cus * occupancy / current_grid_size;
// int gemm_k_per_wg = math::integer_divide_ceil(merge_dimension / gemm_k_global_splits);
// gemm_k_per_wg = (gemm_k_per_wg + gemm_k_per_block - 1) / gemm_k_per_block * gemm_k_per_block;
// gemm_k_global_splits = math::integer_divide_ceil(merge_dimension / gemm_k_per_wg);
return gemm_k_global_splits;
}
static inline size_t
ComputeMatrixPadSize(size_t col, size_t col_per_block, size_t row, size_t row_per_block)
{
size_t col_padded = ((col + col_per_block - 1) / col_per_block) * col_per_block;
size_t row_padded = ((row + row_per_block - 1) / row_per_block) * row_per_block;
size_t col_extra = col_padded - col;
size_t row_extra = row_padded - row;
return col_extra * row + row_extra * col + col_extra * row_extra;
}
static inline std::tuple<int, int, int> // m_per_block, n_per_block, k_per_block
HeuristicInitMacroTileNoPadGemmK(size_t gemm_m,
size_t gemm_n,
size_t gemm_k,
const std::vector<std::tuple<int, int, int>>& tile_list)
{
int m_per_block, n_per_block, k_per_block;
bool found = false;
// find exact divide
for(const auto& tile : tile_list)
{
int mpb, npb, kpb;
std::tie(mpb, npb, kpb) = tile;
if(gemm_m % mpb == 0 && gemm_n % npb == 0 && gemm_k % kpb == 0)
{
m_per_block = mpb;
n_per_block = npb;
k_per_block = kpb;
found = true;
break;
}
}
if(!found)
{
size_t min_pad_pixel = std::numeric_limits<std::size_t>::max();
int mpb_pad = 0;
int npb_pad = 0;
// first try gemm_m, gemm_n padding
for(const auto& tile : tile_list)
{
int mpb, npb, kpb;
std::tie(mpb, npb, kpb) = tile;
if(gemm_k % kpb != 0)
continue;
size_t cur_pad_pixel = ComputeMatrixPadSize(gemm_m, mpb, gemm_k, kpb) +
ComputeMatrixPadSize(gemm_n, npb, gemm_k, kpb) +
ComputeMatrixPadSize(gemm_m, mpb, gemm_n, npb);
if(cur_pad_pixel < min_pad_pixel)
{
min_pad_pixel = cur_pad_pixel;
mpb_pad = mpb;
npb_pad = npb;
}
}
// second, we need find the max k_per_block among the same mpb/npb per block
for(const auto& tile : tile_list)
{
int mpb, npb, kpb;
std::tie(mpb, npb, kpb) = tile;
if(mpb == mpb_pad && npb == npb_pad)
{
if(gemm_k % kpb == 0)
{
m_per_block = mpb;
n_per_block = npb;
k_per_block = kpb;
found = true;
break;
}
}
}
}
if(found)
return std::make_tuple(m_per_block, n_per_block, k_per_block);
else
return std::make_tuple(0, 0, 0);
}
template <int L, int H>
inline static bool IsLinear(const int v)
{
static_assert(L <= H, "L <= H");
return L <= v && v <= H;
}
template <int L, int H>
inline static bool NextLinear(int& v)
{
assert((IsLinear<L, H>(v)));
if(H == v)
{
v = L;
return true;
}
++v;
return false;
}
} // namespace solver
} // namespace miopen
#endif
| 37.447581
| 100
| 0.555077
|
j4yan
|
1d5d88e523272fa832c7c041a317b8b86657295f
| 3,916
|
cpp
|
C++
|
test/test_list.cpp
|
Junology/tsukimade
|
f76ca34f54796c3254655d5fba9015a60604d890
|
[
"MIT"
] | null | null | null |
test/test_list.cpp
|
Junology/tsukimade
|
f76ca34f54796c3254655d5fba9015a60604d890
|
[
"MIT"
] | null | null | null |
test/test_list.cpp
|
Junology/tsukimade
|
f76ca34f54796c3254655d5fba9015a60604d890
|
[
"MIT"
] | null | null | null |
/*!
* \file test_list.cpp
* \brief A test with elementary operations on simple lists.
* \details
* The aim of the test is to verify the following functionality of the library:
* - to pass pointers to data structures to Lua;
* - to manipulate passed data structures in Lua;
* - to receive functions as arguments;
* - received functions may admit arguments of function types;
* - to push and check enum data.
*
* \copyright (c) 2019 Jun Yoshida.
* The project is released under MIT License.
* \date April 29, 2019: created
*/
#include <iostream>
extern "C" {
#include "list.h"
}
#include "common.hpp"
void reg_enum_Ordering(lua_State* L)
{
// Create empty table
lua_newtable(L);
// Create metatable
lua_newtable(L);
lua_pushstring(L, "__index");
tsukimade::push_enum_table(
L,
tsukimade::MK_ENUMENTRY(LT),
tsukimade::MK_ENUMENTRY(GT),
tsukimade::MK_ENUMENTRY(EQ) );
lua_rawset(L, -3);
lua_pushstring(L, "__newindex");
lua_pushcfunction(L, lua_error);
lua_rawset(L, -3);
lua_pushstring(L, "__metatable");
lua_pushboolean(L, 0);
lua_rawset(L, -3);
lua_setmetatable(L, -2);
lua_setglobal(L, "Ordering");
}
simple_flist* create_empty_list()
{
return nullptr;
}
int main(int argc, char** argv)
{
if(argc <= 1) {
std::cerr << "Too few arguments." << std::endl;
return -1;
}
const luaL_Reg testlib[] = {
REGISTER(create_empty_list),
REGISTER(get_last),
REGISTER(get_length),
REGISTER(get_value),
REGISTER(push_front),
REGISTER(pop_front),
REGISTER(push_back),
REGISTER(pop_back),
REGISTER(destroy),
REGISTER(filter),
REGISTER(order_canonical),
REGISTER(order_opposite),
REGISTER(bubble_sort),
REGISTER(get_median),
{NULL, NULL} };
TestEnv env;
env.register_library(testlib, "list");
reg_enum_Ordering(env.get_luastate());
/* Basic test for list library */ {
simple_flist* testlist = nullptr;
testlist = push_back(testlist, 3);
testlist = push_back(testlist, 1);
testlist = push_front(testlist, 4);
testlist = push_back(testlist, 1);
testlist = push_front(testlist, 5);
testlist = push_front(testlist, 9);
testlist = push_back(testlist, 2);
testlist = push_back(testlist, 6);
testlist = push_front(testlist, 5);
testlist = push_front(testlist, 3);
testlist = push_back(testlist, 5);
testlist = push_front(testlist, 8);
testlist = push_back(testlist, 9);
testlist = push_back(testlist, 7);
testlist = push_front(testlist, 9);
// 9, 8, 3, 5, 9, 5, 4, 3, 1, 1, 2, 6, 5, 9, 7
// sorted -> 1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 7, 8, 9, 9, 9
try {
if(get_length(testlist) != 15 && get_value(testlist, 3) != 5)
throw __LINE__;
testlist = push_front(testlist, 57);
if(get_length(testlist) != 16 && get_value(testlist, 0) != 57)
throw __LINE__;
testlist = pop_back(testlist);
if(get_length(testlist) != 15)
throw __LINE__;
testlist = push_back(testlist, 128);
testlist = bubble_sort(testlist, order_opposite);
if(get_value(testlist, 0) != 128)
throw __LINE__;
int med = get_median(testlist, order_canonical, bubble_sort);
if(med != 5)
throw __LINE__;
}
catch (int line) {
std::cerr << "Error in basic test at line " << line << std::endl;
env.write_result(false);
}
destroy(testlist);
}
int error = env.dofile(argv[1]);
if(error)
std::cerr << "Error: " << env.get_errmsg() << std::endl;
return env.get_result() ? 0 : -1;
}
| 27.77305
| 79
| 0.586568
|
Junology
|
1d62174fbed0986cfa385a1edbbd3852aac7e5e8
| 851
|
cpp
|
C++
|
public/plagiarism_plugin/input/24/24/24 24 5113100152--Bounce.cpp
|
laurensiusadi/elearning-pweb
|
c72ae1fc414895919ef71ae370686353d9086bce
|
[
"MIT"
] | null | null | null |
public/plagiarism_plugin/input/24/24/24 24 5113100152--Bounce.cpp
|
laurensiusadi/elearning-pweb
|
c72ae1fc414895919ef71ae370686353d9086bce
|
[
"MIT"
] | null | null | null |
public/plagiarism_plugin/input/24/24/24 24 5113100152--Bounce.cpp
|
laurensiusadi/elearning-pweb
|
c72ae1fc414895919ef71ae370686353d9086bce
|
[
"MIT"
] | null | null | null |
#include "wx/wx.h"
#include "Bounce.h"
Bounce::Bounce(void)
{
// TODO Auto-generated constructor stub
}
Bounce::~Bounce(void)
{
// TODO Auto-generated destructor stub
}
void Bounce::Render(wxDc *dc){
dc->SetPen(*wxWHITE_PEN);
dc->Setbrush(*this->brush);
x = x + speedX;
y = y + speedY;
dc = DrawCircle(x, y, radius);
t += 0.01f;
}
void Bounce::HitWallTest(int x1, int y1, int x2, int y2)
{
if ((y - radius) < y1 || (y + radius) > y2)
{
speedY = -speedY;
}
if ((x - radius) < x1 || (x + radius) > x2)
{
speedX = -speedX;
}
}
void Bounce::Collides(Ball *otherBall)
{
int xd = x - otherBall->x;
int yd = y - otherBall->y;
float sumRadius = radius + otherBall->radius;
float sqrRadius = sumRadius = sumRadius*sumRadius;
float distSqr = (xd*xd) + (yd*yd);
if (distSqr <= sqrRadius)
{
speedX *= -1;
speedY *= -1;
}
}
| 16.056604
| 56
| 0.608696
|
laurensiusadi
|
1d6d076af710df8b40ce11d5a994c9143cebbf99
| 4,875
|
cpp
|
C++
|
modules/core/statistics/unit/scalar/expinv.cpp
|
psiha/nt2
|
5e829807f6b57b339ca1be918a6b60a2507c54d0
|
[
"BSL-1.0"
] | 34
|
2017-05-19T18:10:17.000Z
|
2022-01-04T02:18:13.000Z
|
modules/core/statistics/unit/scalar/expinv.cpp
|
psiha/nt2
|
5e829807f6b57b339ca1be918a6b60a2507c54d0
|
[
"BSL-1.0"
] | null | null | null |
modules/core/statistics/unit/scalar/expinv.cpp
|
psiha/nt2
|
5e829807f6b57b339ca1be918a6b60a2507c54d0
|
[
"BSL-1.0"
] | 7
|
2017-12-02T12:59:17.000Z
|
2021-07-31T12:46:14.000Z
|
//==============================================================================
// Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#include <nt2/include/functions/expinv.hpp>
#include <nt2/include/functions/expcdf.hpp>
#include <nt2/include/constants/zero.hpp>
#include <nt2/include/constants/one.hpp>
#include <nt2/include/functions/ones.hpp>
#include <nt2/include/constants/nan.hpp>
#include <nt2/include/constants/log_2.hpp>
#include <nt2/include/functions/size.hpp>
#include <nt2/include/functions/transpose.hpp>
#include <nt2/include/functions/cons.hpp>
#include <nt2/sdk/unit/tests/ulp.hpp>
#include <nt2/sdk/unit/module.hpp>
#include <nt2/table.hpp>
NT2_TEST_CASE_TPL ( expinv_1, NT2_REAL_TYPES)
{
using nt2::expinv;
using nt2::tag::expinv_;
using nt2::_;
using nt2::container::table;
// specific values tests
NT2_TEST_ULP_EQUAL(expinv(nt2::Nan<T>()), nt2::Nan<T>(), 0);
NT2_TEST_ULP_EQUAL(expinv(nt2::One<T>()), nt2::Inf<T>(), 0);
NT2_TEST_ULP_EQUAL(expinv(nt2::Zero<T>()), nt2::Zero<T>(), 0);
NT2_TEST_ULP_EQUAL(expinv(nt2::Half<T>()), nt2::Log_2<T>(), 0);
table<T> a = _(T(0), T(0.5), T(5))/T(5);
NT2_TEST_ULP_EQUAL(a, nt2::expcdf(expinv(a)), T(3));
table<T> b = _(T(0), T(0.5), T(10))/T(5);
NT2_TEST_ULP_EQUAL(b, nt2::expinv(nt2::expcdf(b)), T(3));
} // end of test for floating_
NT2_TEST_CASE_TPL ( expinv_2, NT2_REAL_TYPES)
{
using nt2::expinv;
using nt2::tag::expinv_;
using nt2::_;
using nt2::container::table;
// specific values tests
NT2_TEST_ULP_EQUAL(expinv(nt2::Nan<T>(), nt2::One<T>()), nt2::Nan<T>(), 0);
NT2_TEST_ULP_EQUAL(expinv(nt2::Zero<T>(), nt2::One<T>() ), nt2::Zero<T>(), 0);
NT2_TEST_ULP_EQUAL(expinv(nt2::One<T>(), nt2::One<T>()), nt2::Inf<T>(), 0);
NT2_TEST_ULP_EQUAL(expinv(nt2::Half<T>(), nt2::One<T>()), nt2::Log_2<T>(), 0);
table<T> a = _(T(0), T(1), T(10))/T(10);
table<T> r, plo, pup;
a = nt2::reshape(_(T(1), T(16)), 4, 4)/T(16);
table<T> z = expinv(a, a+T(10));
table<T> zz = nt2::trans(nt2::cons<T>(nt2::of_size(4, 4),
0.64941886894681000175, 3.8640261973645477767, 8.7317924292609419012, 18.099870187993698067,
1.3520053503232916103, 4.8762876534245069848, 10.42131081324959041, 22.61392676576821259,
2.1153260286783659438, 6.0053632624309258858, 12.431174279798213433, 30.325189149497607133,
2.9487412426307542113, 7.2780453958794257829, 14.902664382038823376, nt2::Inf<double>()
));
NT2_TEST_ULP_EQUAL(z, zz, 1);
a = _(T(0), T(1), T(10))/T(10);
table<T> b = _(T(1), T(1), T(11));
nt2::tie(r, plo, pup) = nt2::expinv(a, nt2::ones(nt2::size(a), nt2::meta::as_<T>()), T(0.5), T(0.05));
table<T> rr = nt2::cons<T>(0.0, 0.10536051565782630912, 0.22314355131420976486,
0.35667494393873239167, 0.51082562376599072174, 0.69314718055994528623,
0.91629073187415499557, 1.2039728043259358969, 1.6094379124341005038,
2.3025850929940459011, nt2::Inf<double>());
table<T> pplo = nt2:: cons<T>(0.0, 0.026350417712275989168, 0.055807678523765377743,
0.08920356645568566778, 0.12775628972890218371, 0.17335448322176297276,
0.22916216174552833662, 0.30111077295066512871, 0.40251664496729139264,
0.57587112818905439315, nt2::Inf<double>());
table<T> ppup = nt2::cons<T>(0.0,0.42127750614410425234, 0.89222569026793119296, 1.4261427058176698868,
2.0425046661078845034, 2.7715061358037331729, 3.6637318260716642548,
4.8140108019116167881, 6.4352379618753978718, 9.2067440976791310447,
nt2::Inf<double>());
NT2_TEST_ULP_EQUAL(r, rr, 1);
NT2_TEST_ULP_EQUAL(plo, pplo, 2);
NT2_TEST_ULP_EQUAL(pup, ppup, 2);
r = nt2::expinv(a, nt2::ones(nt2::size(a), nt2::meta::as_<T>()), T(0.5), T(0.05));
rr = nt2::cons<T>(0.0,0.10536051565782630912, 0.22314355131420976486, 0.35667494393873239167,
0.51082562376599072174, 0.69314718055994528623, 0.91629073187415499557,
1.2039728043259358969, 1.6094379124341005038, 2.3025850929940459011,
nt2::Inf<double>());
NT2_TEST_ULP_EQUAL(r, rr, 1);
} // end of test for floating_
| 50.78125
| 137
| 0.592615
|
psiha
|
1d71f2fc2d32771424c328540fda08a7d035076f
| 1,388
|
hpp
|
C++
|
Examples/Telemetry/recorder.hpp
|
raving-bots/expansim-sdk
|
22f5c794523abbe9c27688963b607b13671ff118
|
[
"BSL-1.0"
] | 1
|
2020-01-17T14:10:22.000Z
|
2020-01-17T14:10:22.000Z
|
Examples/Telemetry/recorder.hpp
|
raving-bots/expansim-sdk
|
22f5c794523abbe9c27688963b607b13671ff118
|
[
"BSL-1.0"
] | null | null | null |
Examples/Telemetry/recorder.hpp
|
raving-bots/expansim-sdk
|
22f5c794523abbe9c27688963b607b13671ff118
|
[
"BSL-1.0"
] | null | null | null |
// Copyright Raving Bots 2018-2020
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file SDK-LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <fstream>
#include <filesystem>
namespace xsim
{
struct BodyTelemetryDataV1;
struct RigidTransformV1;
struct VehicleSetupInfoV1;
struct DashboardStateV1;
}
namespace plugin
{
struct TelemetryRecorder final
{
TelemetryRecorder(const TelemetryRecorder& other) = delete;
TelemetryRecorder(TelemetryRecorder&& other) noexcept = delete;
TelemetryRecorder& operator=(const TelemetryRecorder& other) = delete;
TelemetryRecorder& operator=(TelemetryRecorder&& other) noexcept = delete;
explicit TelemetryRecorder(const std::filesystem::path& basePath);
~TelemetryRecorder() = default;
void Start(const xsim::VehicleSetupInfoV1& vehicleSetup);
void RecordTelemetry(
float dt,
const xsim::RigidTransformV1& transform,
const xsim::BodyTelemetryDataV1& telemetry
);
void RecordDashboard(
float dt,
const xsim::DashboardStateV1& dashboard
);
private:
std::filesystem::path m_OutputPath{};
std::ofstream m_TelemetryFile{};
std::ofstream m_DashboardFile{};
float m_TelemetryTime{};
float m_TelemetryFlushTime{};
float m_DashboardTime{};
float m_DashboardFlushTime{};
};
}
| 25.703704
| 88
| 0.731988
|
raving-bots
|
1d72f491b71728130b623288a39f21da371c1c83
| 18,794
|
cc
|
C++
|
mozy/src/help/help_cache.cc
|
wrcad/xictools
|
f46ba6d42801426739cc8b2940a809b74f1641e2
|
[
"Apache-2.0"
] | 73
|
2017-10-26T12:40:24.000Z
|
2022-03-02T16:59:43.000Z
|
mozy/src/help/help_cache.cc
|
chris-ayala/xictools
|
4ea72c118679caed700dab3d49a8d36445acaec3
|
[
"Apache-2.0"
] | 12
|
2017-11-01T10:18:22.000Z
|
2022-03-20T19:35:36.000Z
|
mozy/src/help/help_cache.cc
|
chris-ayala/xictools
|
4ea72c118679caed700dab3d49a8d36445acaec3
|
[
"Apache-2.0"
] | 34
|
2017-10-06T17:04:21.000Z
|
2022-02-18T16:22:03.000Z
|
/*========================================================================*
* *
* Distributed by Whiteley Research Inc., Sunnyvale, California, USA *
* http://wrcad.com *
* Copyright (C) 2017 Whiteley Research Inc., all rights reserved. *
* Author: Stephen R. Whiteley, except as indicated. *
* *
* As fully as possible recognizing licensing terms and conditions *
* imposed by earlier work from which this work was derived, if any, *
* this work is released under the Apache License, Version 2.0 (the *
* "License"). You may not use this file except in compliance with *
* the License, and compliance with inherited licenses which are *
* specified in a sub-header below this one if applicable. A copy *
* of the License is provided with this distribution, or you may *
* obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* See the License for the specific language governing permissions *
* and limitations under the License. *
* *
* 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 NON- *
* INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED *
* OR STEPHEN R. WHITELEY 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. *
* *
*========================================================================*
* XicTools Integrated Circuit Design System *
* *
* Help System Files *
* *
*========================================================================*
$Id:$
*========================================================================*/
#include "config.h"
#include "help_cache.h"
#include "miscutil/filestat.h"
#include "miscutil/pathlist.h"
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
// default cache size (number of saved files)
int HLPcache::cache_size = CACHE_NUMFILES;
/*=======================================================================
=
= The URL Cache Functions
=
=======================================================================*/
HLPcache::HLPcache()
{
dirname = 0;
tagcnt = 0;
nocache_ent = 0;
entries = new HLPcacheEnt* [cache_size];
memset(entries, 0, cache_size*sizeof(HLPcacheEnt*));
memset(table, 0, sizeof(table));
use_ext = true;
set_dir();
load();
}
// The "front end" functions get(), add(), set_complete(), and
// remove() constitute the basic interface to the application. The
// dump()/load() functions are used to write/read the directory file
// directly, and should be used with care if called by the
// application. The external functions (suffixed with "_ext") are
// similar, but maintain the external directory file. These are
// called from the non-suffixed functions if "use_ext" is set, in
// which case we have an internal "local" cache, and an external cache
// with state maintained in the directory file.
// Get the entry for url from the cache, or return 0 if not found. If
// the entry is found, the directory is consulted to make sure that it
// is still current, if use_ext is set. Note that this function always
// fails if nocache is set.
//
HLPcacheEnt *
HLPcache::get(const char *url, bool nocache)
{
if (!nocache) {
int ix = tab_get(url);
if (ix >= 0) {
if (!entries[ix])
// shouldn't happen
tab_remove(url);
else {
if (use_ext) {
HLPcache *c = new HLPcache;
c->load();
HLPcacheEnt *ce = c->get_ext(url, nocache);
if (!ce || c->entries[ix] != ce) {
// Not found in ext cache, or has a different
// index from the ext cache, not acceptable so
// delete entry
tab_remove(url);
delete entries[ix];
entries[ix] = 0;
// pop_up_cache(0, MODE_UPD);
}
delete c;
}
return (entries[ix]);
}
}
}
return (0);
}
// Get the entry for url from the cache, or return 0 if not found.
// Note that this function always fails if nocache is set.
//
HLPcacheEnt *
HLPcache::get_ext(const char *url, bool nocache)
{
if (!nocache) {
int ix = tab_get(url);
if (ix >= 0) {
if (!entries[ix])
// shouldn't happen
tab_remove(url);
else
return (entries[ix]);
}
}
return (0);
}
// Add en entry for url into the cache, and return the new entry. The
// set_complete() function should be called once the file status is
// known. The HLPcacheEnt pointer is returned, which provides the name
// of the file associated with this url. If nocache is set, the
// return value points to a single struct which is used for all
// accesses.
//
HLPcacheEnt *
HLPcache::add(const char *url, bool nocache)
{
set_dir();
if (!nocache) {
if (dirname) {
int ix = tab_get(url);
if (ix >= 0) {
// entry exists, delete old one
tab_remove(url);
delete entries[ix];
entries[ix] = 0;
}
if (use_ext) {
HLPcache *c = new HLPcache;
c->load();
c->add_ext(url, nocache);
tagcnt = c->tagcnt - 1;
delete c;
}
const char *fn = CACHE_DIR + 1;
ix = tagcnt % cache_size;
char buf[256];
sprintf(buf, "%s/%s%d", dirname, fn, ix);
if (entries[ix]) {
tab_remove(entries[ix]->url);
delete entries[ix];
}
entries[ix] = new HLPcacheEnt(url, buf);
tab_add(entries[ix]->url, ix);
if (!use_ext)
tagcnt++;
// pop_up_cache(0, MODE_UPD);
return (entries[ix]);
}
}
// If we get here, we aren't caching. Create a single entry with
// a temp file to use.
//
if (!nocache_ent)
nocache_ent = new HLPcacheEnt(url, 0);
else {
delete [] nocache_ent->url;
nocache_ent->url = lstring::copy(url);
delete [] nocache_ent->filename;
}
nocache_ent->filename = filestat::make_temp("htp");
filestat::queue_deletion(nocache_ent->filename);
return (nocache_ent);
}
// Add en entry for url into the cache, update the directory, and
// return the new entry. The set_complete_ext() function should be
// called once the file status is known. The HLPcacheEnt pointer is
// returned, which provides the name of the file associated with this
// url. If nocache is set, the return value points to a single struct
// which is used for all accesses.
//
HLPcacheEnt *
HLPcache::add_ext(const char *url, bool nocache)
{
set_dir();
if (!nocache) {
if (dirname) {
HLPcacheEnt *ctmp = 0;
int ix = tab_get(url);
if (ix >= 0) {
// old version exists, delete it and save file for
// deletion *after* the directory is updated
tab_remove(url);
ctmp = entries[ix];
entries[ix] = 0;
int iy = tagcnt % cache_size;
if ((ix == cache_size-1 && iy == 0) || ix == iy - 1)
// slot was at top, so it can be reused
tagcnt--;
}
const char *fn = CACHE_DIR + 1;
ix = tagcnt % cache_size;
char buf[256];
sprintf(buf, "%s/%s%d", dirname, fn, ix);
if (entries[ix]) {
// slot has prior entry, delete it, no need to delete
// file since it is done anyway
tab_remove(entries[ix]->url);
delete entries[ix];
}
entries[ix] = new HLPcacheEnt(url, buf);
tab_add(entries[ix]->url, ix);
tagcnt++;
dump();
unlink(buf);
if (ctmp) {
unlink(ctmp->filename);
delete ctmp;
}
return (entries[ix]);
}
}
// If we get here, we aren't caching. Create a single entry with
// a temp file to use.
//
if (!nocache_ent)
nocache_ent = new HLPcacheEnt(url, 0);
else {
delete [] nocache_ent->url;
nocache_ent->url = lstring::copy(url);
delete [] nocache_ent->filename;
}
nocache_ent->filename = filestat::make_temp("htp");
filestat::queue_deletion(nocache_ent->filename);
return (nocache_ent);
}
// After calling HLPcache::add(), one must supply the file named in the
// struct returned. When this is done (ok is true), or if it can't be
// done (ok is false) this function completes the add process
//
void
HLPcache::set_complete(HLPcacheEnt *cent, DLstatus status)
{
if (cent) {
DLstatus old_status = cent->get_status();
cent->set_status(status);
if (status == DLnogo)
// The external cache doesn't use nogo, so we can try download
// again after reloading external cache
status = DLincomplete;
if (use_ext && old_status != status) {
HLPcache *c = new HLPcache;
c->load();
int ix = c->tab_get(cent->url);
if (ix >= 0)
c->set_complete_ext(c->entries[ix], status);
delete c;
}
}
}
// After calling HLPcache::add_ext(), one must supply the file named in the
// struct returned. When this is done (ok is true), or if it can't be
// done (ok is false) this function completes the add process, updating
// the directory
//
void
HLPcache::set_complete_ext(HLPcacheEnt *cent, DLstatus status)
{
if (cent) {
cent->set_status(status);
dump();
}
}
// Remove the entry for url from the cache, return true if the object was
// deleted. The directory is modified only if the entry existed in the
// local cache, and use_ext is set. If nocache is set, nothing is done.
//
bool
HLPcache::remove(const char *url, bool nocache)
{
if (!nocache) {
int ix = tab_get(url);
if (ix >= 0) {
tab_remove(url);
if (use_ext) {
HLPcache *c = new HLPcache;
c->load();
c->remove_ext(url, nocache);
delete c;
}
delete entries[ix];
entries[ix] = 0;
// pop_up_cache(0, MODE_UPD);
return (true);
}
}
return (false);
}
// Remove the entry for url from the cache, and update the directory.
// If an entry was removed, true is returned. This is a no-op if
// nocache is set.
//
bool
HLPcache::remove_ext(const char *url, bool nocache)
{
if (!nocache) {
int ix = tab_get(url);
if (ix >= 0) {
tab_remove(url);
HLPcacheEnt *ctmp = entries[ix];
entries[ix] = 0;
dump();
unlink(ctmp->filename);
delete ctmp;
return (true);
}
}
return (false);
}
// Clear the cache. This clears only the cache struct and does not touch
// the directory.
//
void
HLPcache::clear()
{
for (int i = 0; i < CACHE_NUMHASH; i++) {
HLPcacheTabEnt *t = table[i];
while (t) {
HLPcacheTabEnt *tn = t->next;
delete t;
t = tn;
}
table[i] = 0;
}
for (int i = 0; i < cache_size; i++) {
delete entries[i];
entries[i] = 0;
}
tagcnt = 0;
// pop_up_cache(0, MODE_UPD);
}
// Create a file named "directory" in the cache directory, and dump a
// listing of the current cache contents. The first line of the file
// contains the file prefix, and the current integer index (two tokens).
// Additional lines describe the entries (three tokens): the first token
// is the index, the second token is '0' if the file is ok, '1' otherwise,
// and the third token is the url.
//
// Note that calling this function overwrites the directory, so the
// previous contents should be read and merged first.
//
void
HLPcache::dump()
{
char buf[256];
if (dirname) {
sprintf(buf, "%s/%s", dirname, "directory");
FILE *fp = fopen(buf, "w");
if (fp) {
fprintf(fp, "%s %d\n", CACHE_DIR + 1, tagcnt % cache_size);
for (int i = 0; i < cache_size; i++) {
if (entries[i])
fprintf(fp, "%-4d %d %s\n", i,
entries[i]->get_status(), entries[i]->url);
}
fclose (fp);
}
}
}
// Initialize the cache from the "directory" file. The cache is cleared
// before reading the directory.
//
void
HLPcache::load()
{
char buf[256];
set_dir();
if (dirname) {
const char *fn = CACHE_DIR + 1;
sprintf(buf, "%s/%s", dirname, "directory");
FILE *fp = fopen(buf, "r");
if (fp) {
int tc = 0;
if (fgets(buf, 256, fp) != 0) {
if (!lstring::prefix(fn, buf)) {
fclose (fp);
return;
}
if (sscanf(buf, "%*s %d", &tc) < 1 || tc < 0) {
fclose (fp);
return;
}
if (tc >= cache_size)
tc = 0;
}
clear();
tagcnt = tc;
char tbuf[256];
sprintf(tbuf, "%s/%s", dirname, CACHE_DIR + 1);
int fend = strlen(tbuf);
while (fgets(buf, 256, fp) != 0) {
char *s = buf;
char *fnum = lstring::gettok(&s);
char *inc = lstring::gettok(&s);
char *url = lstring::gettok(&s);
if (!url) {
delete [] fnum;
delete [] inc;
continue;
}
int ix;
if (sscanf(fnum, "%d", &ix) < 1 || ix < 0 ||
ix >= cache_size) {
delete [] url;
delete [] inc;
delete [] fnum;
break;
}
strcpy(tbuf + fend, fnum);
entries[ix] = new HLPcacheEnt(url, tbuf);
if (*inc == '0')
entries[ix]->set_status(DLok);
tab_add(entries[ix]->url, ix);
delete [] url;
delete [] inc;
delete [] fnum;
}
// pop_up_cache(0, MODE_UPD);
fclose(fp);
}
}
}
// Resize the cache size to newsize
//
void
HLPcache::resize(int newsize)
{
if (newsize == cache_size)
return;
HLPcacheEnt **tmp = new HLPcacheEnt* [newsize];
if (newsize > cache_size) {
int i;
for (i = 0; i < cache_size; i++)
tmp[i] = entries[i];
for ( ; i < newsize; i++)
tmp[i] = 0;
delete [] entries;
entries = tmp;
}
else {
int i;
for (i = 0; i < newsize; i++)
tmp[i] = entries[i];
for ( ; i < cache_size; i++) {
tab_remove(entries[i]->url);
delete entries[i];
}
delete [] entries;
entries = tmp;
if (tagcnt >= newsize)
tagcnt = 0;
}
cache_size = newsize;
// pop_up_cache(0, MODE_UPD);
}
// Private function to remove the url from the hash table
//
void
HLPcache::tab_remove(const char *url)
{
int i = hash(url);
HLPcacheTabEnt *ctep = 0;
for (HLPcacheTabEnt *cte = table[i]; cte; cte = cte->next) {
if (!strcmp(url, cte->url)) {
if (ctep)
ctep->next = cte->next;
else
table[i] = cte->next;
delete cte;
return;
}
ctep = cte;
}
}
// Private function to obtain the directory where cache files are
// stored
//
void
HLPcache::set_dir()
{
if (!dirname) {
char *home = pathlist::get_home(0);
if (home) {
char *pbuf = pathlist::mk_path(home, CACHE_DIR);
delete [] home;
struct stat st;
if (stat(pbuf, &st)) {
if (errno != ENOENT ||
#ifdef WIN32
mkdir(pbuf)) {
#else
mkdir(pbuf, 0755)) {
#endif
delete [] pbuf;
return;
}
}
else if (!S_ISDIR(st.st_mode)) {
delete [] pbuf;
return;
}
dirname = pbuf;
}
}
}
// Return a string list of the current valid entries.
//
stringlist *
HLPcache::list_entries()
{
stringlist *s0 = 0, *se = 0;
int c1 = 2;
if (HLPcache::cache_size > 99)
c1 = 3;
if (HLPcache::cache_size > 999)
c1 = 4;
for (int i = 0; i < cache_size; i++) {
if (entries[i] && entries[i]->get_status() == DLok) {
int len = strlen(entries[i]->url);
char *buf = new char[len + 12];
sprintf(buf, "%-*d %s", c1, i, entries[i]->url);
stringlist *s = new stringlist(buf, 0);
if (s0) {
se->next = s;
se = se->next;
}
else
s0 = se = s;
}
}
return (s0);
}
// End of HLPcache functions
| 31.375626
| 76
| 0.481803
|
wrcad
|
1d76067a750b361e65b85753922d415b7dac0769
| 987
|
hpp
|
C++
|
include/boost/sql/detail/service_base.hpp
|
purpleKarrot/async-db
|
172124e5657e3085e8ac7729c4e578c0d766bf7b
|
[
"BSL-1.0"
] | 5
|
2016-09-19T01:02:33.000Z
|
2019-10-23T07:15:00.000Z
|
include/boost/sql/detail/service_base.hpp
|
purpleKarrot/async-db
|
172124e5657e3085e8ac7729c4e578c0d766bf7b
|
[
"BSL-1.0"
] | null | null | null |
include/boost/sql/detail/service_base.hpp
|
purpleKarrot/async-db
|
172124e5657e3085e8ac7729c4e578c0d766bf7b
|
[
"BSL-1.0"
] | null | null | null |
/**************************************************************
* Copyright (c) 2008-2009 Daniel Pfeifer *
* *
* Distributed under the Boost Software License, Version 1.0. *
**************************************************************/
#ifndef BOOST_SQL_DETAIL_SERVICE_BASE_HPP
#define BOOST_SQL_DETAIL_SERVICE_BASE_HPP
#include <boost/asio/io_service.hpp>
namespace boost
{
namespace sql
{
namespace detail
{
template<typename Type>
class service_id: public asio::io_service::id
{
};
template<typename Type>
class service_base: public asio::io_service::service
{
public:
static service_id<Type> id;
protected:
service_base(asio::io_service& io_service) :
asio::io_service::service(io_service)
{
}
};
template<typename Type>
service_id<Type> service_base<Type>::id;
} // end namespace detail
} // end namespace sql
} // end namespace boost
#endif /* BOOST_SQL_DETAIL_SERVICE_BASE_HPP */
| 21.933333
| 64
| 0.599797
|
purpleKarrot
|
1d7b2fe6b0f1d1621736cc7491c56aaf6abb0c71
| 164
|
cpp
|
C++
|
Society2.0/Society2.0/ProposeMeetingToPersonUI.cpp
|
simsim314/Society2.0
|
a95e42122e2541b7544dd641247681996f1e625a
|
[
"Unlicense"
] | 1
|
2019-07-11T13:10:43.000Z
|
2019-07-11T13:10:43.000Z
|
Society2.0/Society2.0/ProposeMeetingToPersonUI.cpp
|
mdheller/Society2.0
|
a95e42122e2541b7544dd641247681996f1e625a
|
[
"Unlicense"
] | 1
|
2019-02-19T12:32:52.000Z
|
2019-03-07T20:49:50.000Z
|
Society2.0/Society2.0/ProposeMeetingToPersonUI.cpp
|
mdheller/Society2.0
|
a95e42122e2541b7544dd641247681996f1e625a
|
[
"Unlicense"
] | 1
|
2020-01-10T12:37:30.000Z
|
2020-01-10T12:37:30.000Z
|
#include "ProposeMeetingToPersonUI.h"
ProposeMeetingToPersonUI::ProposeMeetingToPersonUI()
{
}
ProposeMeetingToPersonUI::~ProposeMeetingToPersonUI()
{
}
| 16.4
| 54
| 0.780488
|
simsim314
|
1d7bb55de785b8146ac241ca0fe4c04b117bbddf
| 820
|
cpp
|
C++
|
naive_simulation_works/systemc_for_dummies/full_adder/main.cpp
|
VSPhaneendraPaluri/pvsdrudgeworks
|
5827f45567eecbcf0bb606de6adb1fb94fe2d8c6
|
[
"MIT"
] | null | null | null |
naive_simulation_works/systemc_for_dummies/full_adder/main.cpp
|
VSPhaneendraPaluri/pvsdrudgeworks
|
5827f45567eecbcf0bb606de6adb1fb94fe2d8c6
|
[
"MIT"
] | null | null | null |
naive_simulation_works/systemc_for_dummies/full_adder/main.cpp
|
VSPhaneendraPaluri/pvsdrudgeworks
|
5827f45567eecbcf0bb606de6adb1fb94fe2d8c6
|
[
"MIT"
] | null | null | null |
#include <systemc.h>
#include "Full_Adder.h"
#include "MyTestBenchDriver.h"
#include "MyTestBenchMonitor.h"
int sc_main(int sc_argc, char* sc_argv[])
{
sc_signal<bool> pb_a, pb_b, pb_c_in, pb_sum, pb_c_out;
Full_Adder MyFullAdder("MyFullAdder");
MyFullAdder.a(pb_a);
MyFullAdder.b(pb_b);
MyFullAdder.c_in(pb_c_in);
MyFullAdder.sum_out(pb_sum);
MyFullAdder.c_out(pb_c_out);
MyTestBenchDriver MyTBDriver("MyTBDriver");
MyTBDriver.TBDriver_a(pb_a);
MyTBDriver.TBDriver_b(pb_b);
MyTBDriver.TBDriver_c(pb_c_in);
MyTestBenchMonitor MyTBMonitor("MyTBMonitor");
MyTBMonitor.TBMonitor_a(pb_a);
MyTBMonitor.TBMonitor_b(pb_b);
MyTBMonitor.TBMonitor_c(pb_c_in);
MyTBMonitor.TBMonitor_sum(pb_sum);
MyTBMonitor.TBMonitor_carry(pb_c_out);
sc_set_time_resolution(1, SC_NS);
sc_start(100.0, SC_NS);
return 0;
}
| 24.117647
| 55
| 0.780488
|
VSPhaneendraPaluri
|
1d7e864e133c0e01805f410caad1669adec00b6b
| 2,131
|
cpp
|
C++
|
src/utils.cpp
|
SohilZidan/point-cloud-registration
|
5e7f52fbf04f3a58238a2c92393143d5e110c8e4
|
[
"MIT"
] | null | null | null |
src/utils.cpp
|
SohilZidan/point-cloud-registration
|
5e7f52fbf04f3a58238a2c92393143d5e110c8e4
|
[
"MIT"
] | 1
|
2021-11-27T17:52:07.000Z
|
2021-11-28T07:04:05.000Z
|
src/utils.cpp
|
SohilZidan/point-cloud-registration
|
5e7f52fbf04f3a58238a2c92393143d5e110c8e4
|
[
"MIT"
] | null | null | null |
#include <vector>
#include <tuple>
#include <cmath>
#include <numeric>
#include <Eigen/Dense>
#include "../happly.h"
#include "../nanoflann.hpp"
#include "utils.hpp"
float icp::mse_cost(std::vector<std::tuple<float, int, int>>& distances, float xi)
{
size_t Np = distances.size();
size_t Npo = xi*Np;
float Sts = std::accumulate(distances.begin(), distances.begin() + Npo, 0, tupleAccumulateOP);
xi = (float)std::pow(xi, 3);
float e = Sts/Npo;
return e/xi;
}
bool icp::comparePairs(const std::tuple<float, int, int>& lhs, const std::tuple<float, int, int>& rhs)
{
return std::get<0>(lhs) < std::get<0>(rhs);
}
float icp::tupleAccumulateOP(const float &a, const std::tuple<float, int, int> &b)
{
return a+std::get<0>(b);
}
icp::PointCloud icp::readPointCloud(const std::string filename)
{
//"../data/fountain_a.ply"
happly::PLYData plyData(filename);
// auto propsNames = plyData.getElement("vertex").getPropertyNames();
std::vector<std::array<double, 3>> vPos = plyData.getVertexPositions();
size_t dim = 3;
size_t N = vPos.size();
icp::PointCloud mat(N, dim);
mat.resize(N, dim);
for (size_t i = 0; i < N; i++)
for (size_t d = 0; d < dim; d++)
mat(i, d) = vPos[i][d];
// for(const auto& prop: propsNames)
// std::cout<<prop<<std::endl;
return mat;
}
icp::PointCloud icp::addNoise(icp::PointCloud M)
{
// get dimentions
size_t rows = M.rows();
size_t cols = M.cols();
return icp::PointCloud::Random(rows, cols);
}
// rotation
Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> icp::rotate(icp::PointCloud& M, float deg, Eigen::Vector3f axis)
{
// float deg = 10.f;
float rad = deg * M_PI / 180;
// Eigen::Vector3f axis(0,1,1);
Eigen::Transform<float, 3, Eigen::Affine> t;
Eigen::AngleAxis<float> rot(rad, axis);
t = rot;
// std::cout<<t.linear()<<std::endl;
// std::cout<<t.linear().inverse()<<std::endl;
// std::cout<<t.linear().inverse().matrix()<<std::endl;
M = (t.linear() * M.transpose()).transpose();
return t.linear().matrix();
}
| 27.320513
| 117
| 0.610042
|
SohilZidan
|
1d86650d1d6904f114f7114b4d8211bde89cc8de
| 5,315
|
hpp
|
C++
|
include/ssGUI/GUIObjectClasses/GUIObject.hpp
|
Neko-Box-Coder/ssGUI
|
25e218fd79fea105a30737a63381cf8d0be943f6
|
[
"Apache-2.0"
] | 15
|
2022-01-21T10:48:04.000Z
|
2022-03-27T17:55:11.000Z
|
include/ssGUI/GUIObjectClasses/GUIObject.hpp
|
Neko-Box-Coder/ssGUI
|
25e218fd79fea105a30737a63381cf8d0be943f6
|
[
"Apache-2.0"
] | null | null | null |
include/ssGUI/GUIObjectClasses/GUIObject.hpp
|
Neko-Box-Coder/ssGUI
|
25e218fd79fea105a30737a63381cf8d0be943f6
|
[
"Apache-2.0"
] | 4
|
2022-01-21T10:48:05.000Z
|
2022-01-22T15:42:34.000Z
|
#ifndef SSGUI_GUI_OBJECT
#define SSGUI_GUI_OBJECT
#include "ssGUI/Enums/GUIObjectType.hpp"
#include "ssGUI/DataClasses/Transform.hpp"
#include "ssGUI/DataClasses/Renderer.hpp"
#include "ssGUI/DataClasses/Hierarchy.hpp"
#include "ssGUI/DataClasses/ExtensionManager.hpp"
#include "ssGUI/DataClasses/EventCallbackManager.hpp"
#include "ssGUI/EventCallbacks/EventCallback.hpp"
#include "glm/vec4.hpp"
#include <vector>
#include <list>
#include <limits>
#include <unordered_set>
#include <unordered_map>
//namespace: ssGUI
namespace ssGUI
{
class Menu;
/*class: ssGUI::GUIObject
This is the implementation class for <ssGUI::GUIObject>. See <ssGUI::GUIObject> for more details about the functions
Variables & Constructor:
============================== C++ ==============================
protected:
glm::vec2 LastGlobalPosition;//Cache rendering
std::unordered_set<std::string> CurrentTags;
ssGUI::Menu* RightClickMenu;
=================================================================
============================== C++ ==============================
GUIObject::GUIObject(GUIObject const& other) : Transform(other), Renderer(other), Hierarchy(other), ExtensionManager(other),
EventCallbackManager(other)
{
LastGlobalPosition = other.LastGlobalPosition;
CurrentTags = other.CurrentTags;// std::unordered_set<std::string>();
RightClickMenu = other.RightClickMenu;
SetupComponents();
SetParent(other.GetParent()); //Note : Reason of using SetParent is to inform the parent to add this as a child
}
=================================================================
*/
class GUIObject : public Transform, public Renderer, public Hierarchy, public ExtensionManager, public EventCallbackManager
{
private:
GUIObject& operator=(GUIObject const& other);
protected:
glm::vec2 LastGlobalPosition;//Cache rendering
std::unordered_set<std::string> CurrentTags;
ssGUI::Menu* RightClickMenu;
GUIObject(GUIObject const& other);
virtual void SetupComponents();
virtual ssGUI::GUIObject* CloneChildren(ssGUI::GUIObject* originalRoot, ssGUI::GUIObject* clonedRoot);
virtual void CloneExtensionsAndEventCallbacks(ssGUI::GUIObject* clonedObj);
virtual void CheckRightClickMenu(ssGUI::Backend::BackendSystemInputInterface* inputInterface, ssGUI::InputStatus& globalInputStatus,
ssGUI::InputStatus& windowInputStatus, ssGUI::GUIObject* mainWindow);
virtual void MainLogic(ssGUI::Backend::BackendSystemInputInterface* inputInterface, ssGUI::InputStatus& globalInputStatus,
ssGUI::InputStatus& windowInputStatus, ssGUI::GUIObject* mainWindow);
public:
//TODO : Maybe make this thread safe?
inline static std::vector<ssGUI::GUIObject*> ObjsToDelete = std::vector<ssGUI::GUIObject*>();
GUIObject();
virtual ~GUIObject();
//function: GetType
//Returns the type of this GUI Object. Note that <ssGUI::Enums::GUIObjectType> is a bit-operated enum class.
virtual ssGUI::Enums::GUIObjectType GetType() const;
//function: AddTag
//Adds a tag to this GUI Object
virtual void AddTag(std::string tag);
//function: RemoveTag
//Removes the tag on this GUI Object
virtual void RemoveTag(std::string tag);
//function: HasTag
//Returns true if the tag exists on this GUI Object
virtual bool HasTag(std::string tag) const;
//function: RegisterRightClickMenu
//Register this GUI Object to a menu that can be triggered by right click
virtual void RegisterRightClickMenu(ssGUI::Menu* menu);
//function: ClearRightClickMenu
//Clears the right click menu
virtual void ClearRightClickMenu();
//function: Internal_Draw
//(Internal ssGUI function) Draw function called by <ssGUIManager>
virtual void Internal_Draw(ssGUI::Backend::BackendDrawingInterface* drawingInterface, ssGUI::GUIObject* mainWindow, glm::vec2 mainWindowPositionOffset);
//function: Internal_Update
//(Internal ssGUI function) Update function called by <ssGUIManager>
virtual void Internal_Update(ssGUI::Backend::BackendSystemInputInterface* inputInterface, ssGUI::InputStatus& globalInputStatus, ssGUI::InputStatus& windowInputStatus, ssGUI::GUIObject* mainWindow);
//function: Clone
//Clone function for cloning the object. Use this function instead of assignment operator or copy constructor.
//The cloned object will be allocated on the heap and the clean up will be managed by ssGUI.
//Setting cloneChildren will clone all the children recursively with all the ObjectsReferences respectively.
virtual GUIObject* Clone(bool cloneChildren);
};
}
#endif
| 45.42735
| 211
| 0.621825
|
Neko-Box-Coder
|
1d87cdc304e12262f8bd72bc10ce67210914e054
| 427
|
hpp
|
C++
|
library/ATF/CCheckSumBaseConverter.hpp
|
lemkova/Yorozuya
|
f445d800078d9aba5de28f122cedfa03f26a38e4
|
[
"MIT"
] | 29
|
2017-07-01T23:08:31.000Z
|
2022-02-19T10:22:45.000Z
|
library/ATF/CCheckSumBaseConverter.hpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 90
|
2017-10-18T21:24:51.000Z
|
2019-06-06T02:30:33.000Z
|
library/ATF/CCheckSumBaseConverter.hpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 44
|
2017-12-19T08:02:59.000Z
|
2022-02-24T23:15:01.000Z
|
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
START_ATF_NAMESPACE
struct CCheckSumBaseConverter
{
public:
long double ProcCode(char byIndex, unsigned int dwSerial, long double dValue);
unsigned int ProcCode(char byIndex, unsigned int dwSerial, unsigned int dwValue);
};
END_ATF_NAMESPACE
| 28.466667
| 108
| 0.740047
|
lemkova
|
1d8a38af7e296e995cbd7a78019d63a48fed2a82
| 1,954
|
cpp
|
C++
|
prismdll/menu_nodes/BGCheckbox.cpp
|
MagneticPrism/prismdll
|
d00d45fa7017d48cae8ce9e30542ac43ed3936cd
|
[
"CC0-1.0"
] | null | null | null |
prismdll/menu_nodes/BGCheckbox.cpp
|
MagneticPrism/prismdll
|
d00d45fa7017d48cae8ce9e30542ac43ed3936cd
|
[
"CC0-1.0"
] | null | null | null |
prismdll/menu_nodes/BGCheckbox.cpp
|
MagneticPrism/prismdll
|
d00d45fa7017d48cae8ce9e30542ac43ed3936cd
|
[
"CC0-1.0"
] | null | null | null |
#include "BGCheckbox.hpp"
bool BGCheckbox::init(const char* _text) {
if (!cocos2d::CCNode::init())
return false;
this->m_pBGLayer = cocos2d::extension::CCScale9Sprite::create(
"square02b_001.png", { 0.0f, 0.0f, 80.0f, 80.0f }
);
this->m_pBGLayer->setScale(.5f);
this->m_pBGLayer->setColor({ 0, 0, 0 });
this->m_pBGLayer->setOpacity(75);
auto menu = cocos2d::CCMenu::create();
float fMenuPadding = 5.0f;
auto pToggleOnSpr = cocos2d::CCSprite::createWithSpriteFrameName("GJ_checkOn_001.png");
auto pToggleOffSpr = cocos2d::CCSprite::createWithSpriteFrameName("GJ_checkOff_001.png");
pToggleOnSpr->setScale(.8f);
pToggleOffSpr->setScale(.8f);
this->m_pToggler = gd::CCMenuItemToggler::create(
pToggleOffSpr,
pToggleOnSpr,
this,
nullptr
);
menu->addChild(this->m_pToggler);
this->m_pLabel = cocos2d::CCLabelBMFont::create(_text, "bigFont.fnt");
this->m_pLabel->setScale(.6f);
menu->addChild(this->m_pLabel);
menu->alignItemsHorizontallyWithPadding(fMenuPadding);
menu->setContentSize({ this->m_pLabel->getScaledContentSize().width +
this->m_pToggler->getScaledContentSize().width +
fMenuPadding + 20.0f,
40.0f
});
menu->setPosition(0, 0);
this->m_pBGLayer->setContentSize(menu->getContentSize() * 2);
this->setContentSize(menu->getContentSize());
this->addChild(this->m_pBGLayer);
this->addChild(menu);
return true;
}
void BGCheckbox::setEnabled(bool _e) {
this->m_pToggler->setEnabled(_e);
this->m_pLabel->setColor(
_e ? cocos2d::ccColor3B { 255, 255, 255 } :
cocos2d::ccColor3B { 130, 130, 130 }
);
}
BGCheckbox* BGCheckbox::create(const char* _text) {
auto pRet = new BGCheckbox();
if (pRet && pRet->init(_text)) {
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return nullptr;
}
| 25.710526
| 93
| 0.642784
|
MagneticPrism
|
1d8e16a65d2c190eb51fdfcf0198278739ee2b9f
| 9,172
|
cc
|
C++
|
src/demo/hud.cc
|
auygun/kaliber
|
c6501323cf5c447334a2bfb6b7a5899dea0776e6
|
[
"MIT"
] | 3
|
2020-06-22T19:37:49.000Z
|
2020-11-14T10:45:27.000Z
|
src/demo/hud.cc
|
auygun/kaliber
|
c6501323cf5c447334a2bfb6b7a5899dea0776e6
|
[
"MIT"
] | 1
|
2020-06-03T13:05:24.000Z
|
2020-06-03T13:05:24.000Z
|
src/demo/hud.cc
|
auygun/kaliber
|
c6501323cf5c447334a2bfb6b7a5899dea0776e6
|
[
"MIT"
] | null | null | null |
#include "hud.h"
#include "../base/interpolation.h"
#include "../base/log.h"
#include "../base/vecmath.h"
#include "../engine/engine.h"
#include "../engine/font.h"
#include "../engine/image.h"
#include "demo.h"
using namespace std::string_literals;
using namespace base;
using namespace eng;
namespace {
constexpr float kHorizontalMargin = 0.07f;
constexpr float kVerticalMargin = 0.025f;
const Vector4f kPprogressBarColor[2] = {{0.256f, 0.434f, 0.72f, 1},
{0.905f, 0.493f, 0.194f, 1}};
const Vector4f kTextColor = {0.895f, 0.692f, 0.24f, 1};
void SetupFadeOutAnim(Animator& animator, float delay) {
animator.SetEndCallback(Animator::kTimer, [&]() -> void {
animator.SetBlending({1, 1, 1, 0}, 0.5f,
std::bind(Acceleration, std::placeholders::_1, -1));
animator.Play(Animator::kBlending, false);
});
animator.SetEndCallback(Animator::kBlending,
[&]() -> void { animator.SetVisible(false); });
animator.SetTimer(delay);
}
} // namespace
Hud::Hud() = default;
Hud::~Hud() = default;
bool Hud::Initialize() {
Engine& engine = Engine::Get();
const Font& font = static_cast<Demo*>(engine.GetGame())->GetFont();
int tmp;
font.CalculateBoundingBox("big_enough_text", max_text_width_, tmp);
Engine::Get().SetImageSource("text0",
std::bind(&Hud::CreateScoreImage, this));
Engine::Get().SetImageSource("text1", std::bind(&Hud::CreateWaveImage, this));
Engine::Get().SetImageSource("message",
std::bind(&Hud::CreateMessageImage, this));
Engine::Get().SetImageSource("bonus_tex",
std::bind(&Hud::CreateBonusImage, this));
for (int i = 0; i < 2; ++i) {
text_[i].Create("text"s + std::to_string(i));
text_[i].SetZOrder(30);
text_[i].SetColor(kTextColor * Vector4f(1, 1, 1, 0));
Vector2f pos = (engine.GetScreenSize() / 2 - text_[i].GetSize() / 2);
pos -=
engine.GetScreenSize() * Vector2f(kHorizontalMargin, kVerticalMargin);
Vector2f scale = engine.GetScreenSize() * Vector2f(1, 0);
scale -= engine.GetScreenSize() * Vector2f(kHorizontalMargin * 4, 0);
scale += text_[0].GetSize() * Vector2f(0, 0.3f);
progress_bar_[i].SetZOrder(30);
progress_bar_[i].SetSize(scale);
progress_bar_[i].Translate(pos * Vector2f(0, 1));
progress_bar_[i].SetColor(kPprogressBarColor[i] * Vector4f(1, 1, 1, 0));
pos -= progress_bar_[i].GetSize() * Vector2f(0, 4);
text_[i].Translate(pos * Vector2f(i ? 1 : -1, 1));
progress_bar_animator_[i].Attach(&progress_bar_[i]);
text_animator_cb_[i] = [&, i]() -> void {
text_animator_[i].SetEndCallback(Animator::kBlending, nullptr);
text_animator_[i].SetBlending(
kTextColor, 2, std::bind(Acceleration, std::placeholders::_1, -1));
text_animator_[i].Play(Animator::kBlending, false);
};
text_animator_[i].Attach(&text_[i]);
}
message_.Create("message");
message_.SetZOrder(30);
message_animator_.SetEndCallback(Animator::kTimer, [&]() -> void {
message_animator_.SetEndCallback(Animator::kBlending, [&]() -> void {
message_animator_.SetVisible(false);
});
message_animator_.SetBlending({1, 1, 1, 0}, 0.5f);
message_animator_.Play(Animator::kBlending, false);
});
message_animator_.Attach(&message_);
bonus_.Create("bonus_tex");
bonus_.SetZOrder(30);
SetupFadeOutAnim(bonus_animator_, 1.0f);
bonus_animator_.SetMovement({0, Engine::Get().GetScreenSize().y / 2}, 2.0f);
bonus_animator_.Attach(&bonus_);
return true;
}
void Hud::Pause(bool pause) {
message_animator_.PauseOrResumeAll(pause);
bonus_animator_.PauseOrResumeAll(pause);
}
void Hud::Show() {
if (text_[0].IsVisible() && text_[1].IsVisible() &&
progress_bar_[0].IsVisible() && progress_bar_[1].IsVisible())
return;
for (int i = 0; i < 2; ++i) {
progress_bar_[i].SetVisible(true);
text_[i].SetVisible(true);
progress_bar_animator_[i].SetBlending(kPprogressBarColor[i], 0.5f);
progress_bar_animator_[i].Play(Animator::kBlending, false);
}
}
void Hud::Hide() {
if (!text_[0].IsVisible() && !text_[1].IsVisible() &&
!progress_bar_[0].IsVisible() && !progress_bar_[1].IsVisible())
return;
for (int i = 0; i < 2; ++i) {
text_animator_[i].SetEndCallback(Animator::kBlending, [&, i]() -> void {
text_animator_[i].SetEndCallback(Animator::kBlending, nullptr);
text_[i].SetVisible(false);
});
text_animator_[i].SetBlending(kTextColor * Vector4f(1, 1, 1, 0), 0.5f);
text_animator_[i].Play(Animator::kBlending, false);
}
HideProgress();
}
void Hud::HideProgress() {
if (!progress_bar_[0].IsVisible())
return;
for (int i = 0; i < 2; ++i) {
progress_bar_animator_[i].SetEndCallback(
Animator::kBlending, [&, i]() -> void {
progress_bar_animator_[i].SetEndCallback(Animator::kBlending,
nullptr);
progress_bar_animator_[1].SetVisible(false);
});
progress_bar_animator_[i].SetBlending(
kPprogressBarColor[i] * Vector4f(1, 1, 1, 0), 0.5f);
progress_bar_animator_[i].Play(Animator::kBlending, false);
}
}
void Hud::SetScore(size_t score, bool flash) {
last_score_ = score;
Engine::Get().RefreshImage("text0");
if (flash) {
text_animator_[0].SetEndCallback(Animator::kBlending, text_animator_cb_[0]);
text_animator_[0].SetBlending(
{1, 1, 1, 1}, 0.1f, std::bind(Acceleration, std::placeholders::_1, 1));
text_animator_[0].Play(Animator::kBlending, false);
}
}
void Hud::SetWave(int wave, bool flash) {
last_wave_ = wave;
Engine::Get().RefreshImage("text1");
if (flash) {
text_animator_[1].SetEndCallback(Animator::kBlending, text_animator_cb_[1]);
text_animator_[1].SetBlending(
{1, 1, 1, 1}, 0.1f, std::bind(Acceleration, std::placeholders::_1, 1));
text_animator_[1].Play(Animator::kBlending, false);
}
}
void Hud::SetProgress(float progress) {
progress = std::min(std::max(0.0f, progress), 1.0f);
last_progress_ = progress;
Vector2f s = progress_bar_[0].GetSize() * Vector2f(progress, 1);
float t = (s.x - progress_bar_[1].GetSize().x) / 2;
progress_bar_[1].SetSize(s);
progress_bar_[1].Translate({t, 0});
}
void Hud::ShowMessage(const std::string& text, float duration) {
message_text_ = text;
Engine::Get().RefreshImage("message");
message_.AutoScale();
message_.Scale(1.5f);
message_.SetColor({1, 1, 1, 0});
message_.SetVisible(true);
message_animator_.SetEndCallback(
Animator::kBlending, [&, duration]() -> void {
message_animator_.SetTimer(duration);
message_animator_.Play(Animator::kTimer, false);
});
message_animator_.SetBlending({1, 1, 1, 1}, 0.5f);
message_animator_.Play(Animator::kBlending, false);
}
void Hud::ShowBonus(size_t bonus) {
bonus_score_ = bonus;
Engine::Get().RefreshImage("bonus_tex");
bonus_.AutoScale();
bonus_.Scale(1.3f);
bonus_.SetColor({1, 1, 1, 1});
bonus_.SetVisible(true);
bonus_animator_.Play(Animator::kTimer | Animator::kMovement, false);
}
std::unique_ptr<eng::Image> Hud::CreateScoreImage() {
return Print(0, std::to_string(last_score_));
}
std::unique_ptr<eng::Image> Hud::CreateWaveImage() {
return Print(1, "wave "s + std::to_string(last_wave_));
}
std::unique_ptr<Image> Hud::CreateMessageImage() {
const Font& font = static_cast<Demo*>(Engine::Get().GetGame())->GetFont();
auto image = std::make_unique<Image>();
image->Create(max_text_width_, font.GetLineHeight());
image->GradientV({0.80f, 0.87f, 0.93f, 0}, {0.003f, 0.91f, 0.99f, 0},
font.GetLineHeight());
int w, h;
font.CalculateBoundingBox(message_text_.c_str(), w, h);
float x = (image->GetWidth() - w) / 2;
font.Print(x, 0, message_text_.c_str(), image->GetBuffer(),
image->GetWidth());
image->Compress();
return image;
}
std::unique_ptr<Image> Hud::CreateBonusImage() {
const Font& font = static_cast<Demo*>(Engine::Get().GetGame())->GetFont();
if (bonus_score_ == 0)
return nullptr;
std::string text = std::to_string(bonus_score_);
int width, height;
font.CalculateBoundingBox(text.c_str(), width, height);
auto image = std::make_unique<Image>();
image->Create(width, height);
image->Clear({1, 1, 1, 0});
font.Print(0, 0, text.c_str(), image->GetBuffer(), image->GetWidth());
image->Compress();
return image;
}
std::unique_ptr<Image> Hud::Print(int i, const std::string& text) {
const Font& font = static_cast<Demo*>(Engine::Get().GetGame())->GetFont();
auto image = CreateImage();
float x = 0;
if (i == 1) {
int w, h;
font.CalculateBoundingBox(text.c_str(), w, h);
x = image->GetWidth() - w;
}
font.Print(x, 0, text.c_str(), image->GetBuffer(), image->GetWidth());
return image;
}
std::unique_ptr<Image> Hud::CreateImage() {
const Font& font = static_cast<Demo*>(Engine::Get().GetGame())->GetFont();
auto image = std::make_unique<Image>();
image->Create(max_text_width_, font.GetLineHeight());
image->Clear({1, 1, 1, 0});
return image;
}
| 30.986486
| 80
| 0.646097
|
auygun
|
1d924e4a4b07e61bcfe8b3c5a376d846f332bdd7
| 72,472
|
inl
|
C++
|
GameJam_v3.2/GameEngineBase/externals/Havok/includes/Source/Common/Base/Math/Vector/Fpu/hkFpuVector4d.inl
|
aditgoyal19/Tropical-Go-Kart-Bananas
|
ed3c0489402f8a559c77b56545bd8ebc79c4c563
|
[
"MIT"
] | null | null | null |
GameJam_v3.2/GameEngineBase/externals/Havok/includes/Source/Common/Base/Math/Vector/Fpu/hkFpuVector4d.inl
|
aditgoyal19/Tropical-Go-Kart-Bananas
|
ed3c0489402f8a559c77b56545bd8ebc79c4c563
|
[
"MIT"
] | null | null | null |
GameJam_v3.2/GameEngineBase/externals/Havok/includes/Source/Common/Base/Math/Vector/Fpu/hkFpuVector4d.inl
|
aditgoyal19/Tropical-Go-Kart-Bananas
|
ed3c0489402f8a559c77b56545bd8ebc79c4c563
|
[
"MIT"
] | null | null | null |
/*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2013 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
/* quad, here for inlining */
#ifndef HK_DISABLE_MATH_CONSTRUCTORS
HK_FORCE_INLINE hkVector4d::hkVector4d(hkDouble64 a, hkDouble64 b, hkDouble64 c, hkDouble64 d)
{
m_quad.v[0] = a;
m_quad.v[1] = b;
m_quad.v[2] = c;
m_quad.v[3] = d;
}
HK_FORCE_INLINE hkVector4d::hkVector4d(const hkQuadDouble64& q)
{
m_quad.v[0] = q.v[0];
m_quad.v[1] = q.v[1];
m_quad.v[2] = q.v[2];
m_quad.v[3] = q.v[3];
}
HK_FORCE_INLINE hkVector4d::hkVector4d( const hkVector4d& v)
{
m_quad.v[0] = v.m_quad.v[0];
m_quad.v[1] = v.m_quad.v[1];
m_quad.v[2] = v.m_quad.v[2];
m_quad.v[3] = v.m_quad.v[3];
}
#endif
HK_FORCE_INLINE void hkVector4d::set(hkDouble64 a, hkDouble64 b, hkDouble64 c, hkDouble64 d)
{
m_quad.v[0] = a;
m_quad.v[1] = b;
m_quad.v[2] = c;
m_quad.v[3] = d;
}
HK_FORCE_INLINE void hkVector4d::set( hkSimdDouble64Parameter a, hkSimdDouble64Parameter b, hkSimdDouble64Parameter c, hkSimdDouble64Parameter d )
{
m_quad.v[0] = a.getReal();
m_quad.v[1] = b.getReal();
m_quad.v[2] = c.getReal();
m_quad.v[3] = d.getReal();
}
HK_FORCE_INLINE void hkVector4d::setAll(const hkDouble64& a)
{
m_quad.v[0] = a;
m_quad.v[1] = a;
m_quad.v[2] = a;
m_quad.v[3] = a;
}
HK_FORCE_INLINE void hkVector4d::setAll(hkSimdDouble64Parameter a)
{
setAll( a.getReal() );
}
HK_FORCE_INLINE void hkVector4d::setZero()
{
m_quad.v[0] = hkDouble64(0);
m_quad.v[1] = hkDouble64(0);
m_quad.v[2] = hkDouble64(0);
m_quad.v[3] = hkDouble64(0);
}
template <int I>
HK_FORCE_INLINE void hkVector4d::zeroComponent()
{
HK_VECTOR4d_SUBINDEX_CHECK;
m_quad.v[I] = hkDouble64(0);
}
HK_FORCE_INLINE void hkVector4d::zeroComponent(const int i)
{
HK_MATH_ASSERT(0x3bc36625, (i>=0) && (i<4), "Component index out of range");
m_quad.v[i] = hkDouble64(0);
}
HK_FORCE_INLINE void hkVector4d::setAdd(hkVector4dParameter v0, hkVector4dParameter v1)
{
m_quad.v[0] = v0.m_quad.v[0] + v1.m_quad.v[0];
m_quad.v[1] = v0.m_quad.v[1] + v1.m_quad.v[1];
m_quad.v[2] = v0.m_quad.v[2] + v1.m_quad.v[2];
m_quad.v[3] = v0.m_quad.v[3] + v1.m_quad.v[3];
}
HK_FORCE_INLINE void hkVector4d::setSub(hkVector4dParameter v0, hkVector4dParameter v1)
{
m_quad.v[0] = v0.m_quad.v[0] - v1.m_quad.v[0];
m_quad.v[1] = v0.m_quad.v[1] - v1.m_quad.v[1];
m_quad.v[2] = v0.m_quad.v[2] - v1.m_quad.v[2];
m_quad.v[3] = v0.m_quad.v[3] - v1.m_quad.v[3];
}
HK_FORCE_INLINE void hkVector4d::setMul(hkVector4dParameter v0, hkVector4dParameter v1)
{
m_quad.v[0] = v0.m_quad.v[0] * v1.m_quad.v[0];
m_quad.v[1] = v0.m_quad.v[1] * v1.m_quad.v[1];
m_quad.v[2] = v0.m_quad.v[2] * v1.m_quad.v[2];
m_quad.v[3] = v0.m_quad.v[3] * v1.m_quad.v[3];
}
HK_FORCE_INLINE void hkVector4d::setMul(hkVector4dParameter a, hkSimdDouble64Parameter rs)
{
const hkDouble64 r = rs.getReal();
m_quad.v[0] = r * a.m_quad.v[0];
m_quad.v[1] = r * a.m_quad.v[1];
m_quad.v[2] = r * a.m_quad.v[2];
m_quad.v[3] = r * a.m_quad.v[3];
}
HK_FORCE_INLINE void hkVector4d::setSubMul(hkVector4dParameter a, hkVector4dParameter b, hkSimdDouble64Parameter r)
{
const hkDouble64 rr = r.getReal();
m_quad.v[0] = a.m_quad.v[0] - rr * b.m_quad.v[0];
m_quad.v[1] = a.m_quad.v[1] - rr * b.m_quad.v[1];
m_quad.v[2] = a.m_quad.v[2] - rr * b.m_quad.v[2];
m_quad.v[3] = a.m_quad.v[3] - rr * b.m_quad.v[3];
}
HK_FORCE_INLINE void hkVector4d::setAddMul(hkVector4dParameter a, hkVector4dParameter b, hkSimdDouble64Parameter r)
{
const hkDouble64 rr = r.getReal();
m_quad.v[0] = a.m_quad.v[0] + rr * b.m_quad.v[0];
m_quad.v[1] = a.m_quad.v[1] + rr * b.m_quad.v[1];
m_quad.v[2] = a.m_quad.v[2] + rr * b.m_quad.v[2];
m_quad.v[3] = a.m_quad.v[3] + rr * b.m_quad.v[3];
}
HK_FORCE_INLINE void hkVector4d::setAddMul(hkVector4dParameter a, hkVector4dParameter m0, hkVector4dParameter m1)
{
m_quad.v[0] = a.m_quad.v[0] + m0.m_quad.v[0] * m1.m_quad.v[0];
m_quad.v[1] = a.m_quad.v[1] + m0.m_quad.v[1] * m1.m_quad.v[1];
m_quad.v[2] = a.m_quad.v[2] + m0.m_quad.v[2] * m1.m_quad.v[2];
m_quad.v[3] = a.m_quad.v[3] + m0.m_quad.v[3] * m1.m_quad.v[3];
}
HK_FORCE_INLINE void hkVector4d::setSubMul(hkVector4dParameter a, hkVector4dParameter m0, hkVector4dParameter m1)
{
m_quad.v[0] = a.m_quad.v[0] - m0.m_quad.v[0] * m1.m_quad.v[0];
m_quad.v[1] = a.m_quad.v[1] - m0.m_quad.v[1] * m1.m_quad.v[1];
m_quad.v[2] = a.m_quad.v[2] - m0.m_quad.v[2] * m1.m_quad.v[2];
m_quad.v[3] = a.m_quad.v[3] - m0.m_quad.v[3] * m1.m_quad.v[3];
}
HK_FORCE_INLINE void hkVector4d::setCross( hkVector4dParameter v1, hkVector4dParameter v2 )
{
const hkDouble64 nx = v1.m_quad.v[1]*v2.m_quad.v[2] - v1.m_quad.v[2]*v2.m_quad.v[1];
const hkDouble64 ny = v1.m_quad.v[2]*v2.m_quad.v[0] - v1.m_quad.v[0]*v2.m_quad.v[2];
const hkDouble64 nz = v1.m_quad.v[0]*v2.m_quad.v[1] - v1.m_quad.v[1]*v2.m_quad.v[0];
set( nx, ny, nz , hkDouble64(0) );
}
HK_FORCE_INLINE const hkVector4dComparison hkVector4d::equal(hkVector4dParameter a) const
{
hkVector4dComparison ret;
ret.m_mask =
((m_quad.v[0]==a.m_quad.v[0]) ? hkVector4ComparisonMask::MASK_X : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[1]==a.m_quad.v[1]) ? hkVector4ComparisonMask::MASK_Y : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[2]==a.m_quad.v[2]) ? hkVector4ComparisonMask::MASK_Z : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[3]==a.m_quad.v[3]) ? hkVector4ComparisonMask::MASK_W : hkVector4ComparisonMask::MASK_NONE);
return ret;
}
HK_FORCE_INLINE const hkVector4dComparison hkVector4d::notEqual(hkVector4dParameter a) const
{
hkVector4dComparison ret;
ret.m_mask =
((m_quad.v[0]==a.m_quad.v[0]) ? hkVector4ComparisonMask::MASK_NONE : hkVector4ComparisonMask::MASK_X) |
((m_quad.v[1]==a.m_quad.v[1]) ? hkVector4ComparisonMask::MASK_NONE : hkVector4ComparisonMask::MASK_Y) |
((m_quad.v[2]==a.m_quad.v[2]) ? hkVector4ComparisonMask::MASK_NONE : hkVector4ComparisonMask::MASK_Z) |
((m_quad.v[3]==a.m_quad.v[3]) ? hkVector4ComparisonMask::MASK_NONE : hkVector4ComparisonMask::MASK_W);
return ret;
}
HK_FORCE_INLINE const hkVector4dComparison hkVector4d::less(hkVector4dParameter a) const
{
hkVector4dComparison ret;
ret.m_mask =
((m_quad.v[0]<a.m_quad.v[0]) ? hkVector4ComparisonMask::MASK_X : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[1]<a.m_quad.v[1]) ? hkVector4ComparisonMask::MASK_Y : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[2]<a.m_quad.v[2]) ? hkVector4ComparisonMask::MASK_Z : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[3]<a.m_quad.v[3]) ? hkVector4ComparisonMask::MASK_W : hkVector4ComparisonMask::MASK_NONE);
return ret;
}
HK_FORCE_INLINE const hkVector4dComparison hkVector4d::lessEqual(hkVector4dParameter a) const
{
hkVector4dComparison ret;
ret.m_mask =
((m_quad.v[0]<=a.m_quad.v[0]) ? hkVector4ComparisonMask::MASK_X : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[1]<=a.m_quad.v[1]) ? hkVector4ComparisonMask::MASK_Y : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[2]<=a.m_quad.v[2]) ? hkVector4ComparisonMask::MASK_Z : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[3]<=a.m_quad.v[3]) ? hkVector4ComparisonMask::MASK_W : hkVector4ComparisonMask::MASK_NONE);
return ret;
}
HK_FORCE_INLINE const hkVector4dComparison hkVector4d::greater(hkVector4dParameter a) const
{
hkVector4dComparison ret;
ret.m_mask =
((m_quad.v[0]>a.m_quad.v[0]) ? hkVector4ComparisonMask::MASK_X : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[1]>a.m_quad.v[1]) ? hkVector4ComparisonMask::MASK_Y : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[2]>a.m_quad.v[2]) ? hkVector4ComparisonMask::MASK_Z : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[3]>a.m_quad.v[3]) ? hkVector4ComparisonMask::MASK_W : hkVector4ComparisonMask::MASK_NONE);
return ret;
}
HK_FORCE_INLINE const hkVector4dComparison hkVector4d::greaterEqual(hkVector4dParameter a) const
{
hkVector4dComparison ret;
ret.m_mask =
((m_quad.v[0]>=a.m_quad.v[0]) ? hkVector4ComparisonMask::MASK_X : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[1]>=a.m_quad.v[1]) ? hkVector4ComparisonMask::MASK_Y : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[2]>=a.m_quad.v[2]) ? hkVector4ComparisonMask::MASK_Z : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[3]>=a.m_quad.v[3]) ? hkVector4ComparisonMask::MASK_W : hkVector4ComparisonMask::MASK_NONE);
return ret;
}
HK_FORCE_INLINE const hkVector4dComparison hkVector4d::lessZero() const
{
hkVector4dComparison ret;
ret.m_mask =
((m_quad.v[0]<hkDouble64(0)) ? hkVector4ComparisonMask::MASK_X : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[1]<hkDouble64(0)) ? hkVector4ComparisonMask::MASK_Y : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[2]<hkDouble64(0)) ? hkVector4ComparisonMask::MASK_Z : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[3]<hkDouble64(0)) ? hkVector4ComparisonMask::MASK_W : hkVector4ComparisonMask::MASK_NONE);
return ret;
}
HK_FORCE_INLINE const hkVector4dComparison hkVector4d::lessEqualZero() const
{
hkVector4dComparison ret;
ret.m_mask =
((m_quad.v[0]<=hkDouble64(0)) ? hkVector4ComparisonMask::MASK_X : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[1]<=hkDouble64(0)) ? hkVector4ComparisonMask::MASK_Y : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[2]<=hkDouble64(0)) ? hkVector4ComparisonMask::MASK_Z : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[3]<=hkDouble64(0)) ? hkVector4ComparisonMask::MASK_W : hkVector4ComparisonMask::MASK_NONE);
return ret;
}
HK_FORCE_INLINE const hkVector4dComparison hkVector4d::greaterZero() const
{
hkVector4dComparison ret;
ret.m_mask =
((m_quad.v[0]>hkDouble64(0)) ? hkVector4ComparisonMask::MASK_X : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[1]>hkDouble64(0)) ? hkVector4ComparisonMask::MASK_Y : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[2]>hkDouble64(0)) ? hkVector4ComparisonMask::MASK_Z : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[3]>hkDouble64(0)) ? hkVector4ComparisonMask::MASK_W : hkVector4ComparisonMask::MASK_NONE);
return ret;
}
HK_FORCE_INLINE const hkVector4dComparison hkVector4d::greaterEqualZero() const
{
hkVector4dComparison ret;
ret.m_mask =
((m_quad.v[0]>=hkDouble64(0)) ? hkVector4ComparisonMask::MASK_X : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[1]>=hkDouble64(0)) ? hkVector4ComparisonMask::MASK_Y : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[2]>=hkDouble64(0)) ? hkVector4ComparisonMask::MASK_Z : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[3]>=hkDouble64(0)) ? hkVector4ComparisonMask::MASK_W : hkVector4ComparisonMask::MASK_NONE);
return ret;
}
HK_FORCE_INLINE const hkVector4dComparison hkVector4d::equalZero() const
{
hkVector4dComparison ret;
ret.m_mask =
((m_quad.v[0]==hkDouble64(0)) ? hkVector4ComparisonMask::MASK_X : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[1]==hkDouble64(0)) ? hkVector4ComparisonMask::MASK_Y : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[2]==hkDouble64(0)) ? hkVector4ComparisonMask::MASK_Z : hkVector4ComparisonMask::MASK_NONE) |
((m_quad.v[3]==hkDouble64(0)) ? hkVector4ComparisonMask::MASK_W : hkVector4ComparisonMask::MASK_NONE);
return ret;
}
HK_FORCE_INLINE const hkVector4dComparison hkVector4d::notEqualZero() const
{
hkVector4dComparison ret;
ret.m_mask =
((m_quad.v[0]==hkDouble64(0)) ? hkVector4ComparisonMask::MASK_NONE : hkVector4ComparisonMask::MASK_X) |
((m_quad.v[1]==hkDouble64(0)) ? hkVector4ComparisonMask::MASK_NONE : hkVector4ComparisonMask::MASK_Y) |
((m_quad.v[2]==hkDouble64(0)) ? hkVector4ComparisonMask::MASK_NONE : hkVector4ComparisonMask::MASK_Z) |
((m_quad.v[3]==hkDouble64(0)) ? hkVector4ComparisonMask::MASK_NONE : hkVector4ComparisonMask::MASK_W);
return ret;
}
HK_FORCE_INLINE void hkVector4d::setSelect( hkVector4dComparisonParameter comp, hkVector4dParameter trueValue, hkVector4dParameter falseValue )
{
m_quad.v[0] = comp.anyIsSet<hkVector4ComparisonMask::MASK_X>() ? trueValue.m_quad.v[0] : falseValue.m_quad.v[0];
m_quad.v[1] = comp.anyIsSet<hkVector4ComparisonMask::MASK_Y>() ? trueValue.m_quad.v[1] : falseValue.m_quad.v[1];
m_quad.v[2] = comp.anyIsSet<hkVector4ComparisonMask::MASK_Z>() ? trueValue.m_quad.v[2] : falseValue.m_quad.v[2];
m_quad.v[3] = comp.anyIsSet<hkVector4ComparisonMask::MASK_W>() ? trueValue.m_quad.v[3] : falseValue.m_quad.v[3];
}
template<hkVector4ComparisonMask::Mask M>
HK_FORCE_INLINE void hkVector4d::setSelect( hkVector4dParameter trueValue, hkVector4dParameter falseValue )
{
m_quad.v[0] = (M & hkVector4ComparisonMask::MASK_X) ? trueValue.m_quad.v[0] : falseValue.m_quad.v[0];
m_quad.v[1] = (M & hkVector4ComparisonMask::MASK_Y) ? trueValue.m_quad.v[1] : falseValue.m_quad.v[1];
m_quad.v[2] = (M & hkVector4ComparisonMask::MASK_Z) ? trueValue.m_quad.v[2] : falseValue.m_quad.v[2];
m_quad.v[3] = (M & hkVector4ComparisonMask::MASK_W) ? trueValue.m_quad.v[3] : falseValue.m_quad.v[3];
}
HK_FORCE_INLINE void hkVector4d::zeroIfFalse( hkVector4dComparisonParameter comp )
{
m_quad.v[0] = comp.anyIsSet<hkVector4ComparisonMask::MASK_X>() ? m_quad.v[0] : hkDouble64(0);
m_quad.v[1] = comp.anyIsSet<hkVector4ComparisonMask::MASK_Y>() ? m_quad.v[1] : hkDouble64(0);
m_quad.v[2] = comp.anyIsSet<hkVector4ComparisonMask::MASK_Z>() ? m_quad.v[2] : hkDouble64(0);
m_quad.v[3] = comp.anyIsSet<hkVector4ComparisonMask::MASK_W>() ? m_quad.v[3] : hkDouble64(0);
}
HK_FORCE_INLINE void hkVector4d::zeroIfTrue( hkVector4dComparisonParameter comp )
{
m_quad.v[0] = comp.anyIsSet<hkVector4ComparisonMask::MASK_X>() ? hkDouble64(0) : m_quad.v[0];
m_quad.v[1] = comp.anyIsSet<hkVector4ComparisonMask::MASK_Y>() ? hkDouble64(0) : m_quad.v[1];
m_quad.v[2] = comp.anyIsSet<hkVector4ComparisonMask::MASK_Z>() ? hkDouble64(0) : m_quad.v[2];
m_quad.v[3] = comp.anyIsSet<hkVector4ComparisonMask::MASK_W>() ? hkDouble64(0) : m_quad.v[3];
}
template <int N>
HK_FORCE_INLINE void hkVector4d::setNeg(hkVector4dParameter v)
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
m_quad.v[0] = (N>0) ? -v.m_quad.v[0] : v.m_quad.v[0];
m_quad.v[1] = (N>1) ? -v.m_quad.v[1] : v.m_quad.v[1];
m_quad.v[2] = (N>2) ? -v.m_quad.v[2] : v.m_quad.v[2];
m_quad.v[3] = (N>3) ? -v.m_quad.v[3] : v.m_quad.v[3];
}
HK_FORCE_INLINE void hkVector4d::setAbs(hkVector4dParameter v)
{
m_quad.v[0] = hkMath::fabs(v.m_quad.v[0]);
m_quad.v[1] = hkMath::fabs(v.m_quad.v[1]);
m_quad.v[2] = hkMath::fabs(v.m_quad.v[2]);
m_quad.v[3] = hkMath::fabs(v.m_quad.v[3]);
}
HK_FORCE_INLINE void hkVector4d::setMin(hkVector4dParameter a, hkVector4dParameter b)
{
m_quad.v[0] = hkMath::min2(a.m_quad.v[0], b.m_quad.v[0]);
m_quad.v[1] = hkMath::min2(a.m_quad.v[1], b.m_quad.v[1]);
m_quad.v[2] = hkMath::min2(a.m_quad.v[2], b.m_quad.v[2]);
m_quad.v[3] = hkMath::min2(a.m_quad.v[3], b.m_quad.v[3]);
}
HK_FORCE_INLINE void hkVector4d::setMax(hkVector4dParameter a, hkVector4dParameter b)
{
m_quad.v[0] = hkMath::max2(a.m_quad.v[0], b.m_quad.v[0]);
m_quad.v[1] = hkMath::max2(a.m_quad.v[1], b.m_quad.v[1]);
m_quad.v[2] = hkMath::max2(a.m_quad.v[2], b.m_quad.v[2]);
m_quad.v[3] = hkMath::max2(a.m_quad.v[3], b.m_quad.v[3]);
}
HK_FORCE_INLINE void hkVector4d::_setRotatedDir(const hkMatrix3d& r, hkVector4dParameter v )
{
const hkSimdDouble64 v0 = v.getComponent<0>();
const hkSimdDouble64 v1 = v.getComponent<1>();
const hkSimdDouble64 v2 = v.getComponent<2>();
setMul(r.getColumn<0>(),v0);
addMul(r.getColumn<1>(),v1);
addMul(r.getColumn<2>(),v2);
}
template <int N>
HK_FORCE_INLINE const hkSimdDouble64 hkVector4d::dot(hkVector4dParameter a) const
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
hkDouble64 sum = m_quad.v[0] * a.m_quad.v[0];
if (N>1)sum += m_quad.v[1] * a.m_quad.v[1];
if (N>2)sum += m_quad.v[2] * a.m_quad.v[2];
if (N>3)sum += m_quad.v[3] * a.m_quad.v[3];
return hkSimdDouble64::convert(sum);
}
HK_FORCE_INLINE const hkSimdDouble64 hkVector4d::dot4xyz1(hkVector4dParameter a) const
{
return hkSimdDouble64::convert(
(m_quad.v[0] * a.m_quad.v[0]) +
(m_quad.v[1] * a.m_quad.v[1]) +
(m_quad.v[2] * a.m_quad.v[2]) +
m_quad.v[3] );
}
HK_FORCE_INLINE void hkVector4d::_setRotatedInverseDir(const hkMatrix3d& r, hkVector4dParameter v )
{
const hkSimdDouble64 d0 = r.getColumn<0>().dot<3>(v);
const hkSimdDouble64 d1 = r.getColumn<1>().dot<3>(v);
const hkSimdDouble64 d2 = r.getColumn<2>().dot<3>(v);
set(d0,d1,d2,d2);
}
template <int N>
HK_FORCE_INLINE const hkSimdDouble64 hkVector4d::horizontalAdd() const
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
hkDouble64 sum = m_quad.v[0];
if (N>1)sum += m_quad.v[1];
if (N>2)sum += m_quad.v[2];
if (N>3)sum += m_quad.v[3];
return hkSimdDouble64::convert(sum);
}
template <int N>
HK_FORCE_INLINE const hkSimdDouble64 hkVector4d::horizontalMul() const
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
hkDouble64 product = m_quad.v[0];
if (N>1) product *= m_quad.v[1];
if (N>2) product *= m_quad.v[2];
if (N>3) product *= m_quad.v[3];
return hkSimdDouble64::convert(product);
}
template <>
HK_FORCE_INLINE const hkSimdDouble64 hkVector4d::horizontalMax<1>() const
{
return getComponent<0>();
}
template <>
HK_FORCE_INLINE const hkSimdDouble64 hkVector4d::horizontalMax<2>() const
{
return hkSimdDouble64::convert(hkMath::max2(m_quad.v[0], m_quad.v[1]));
}
template <>
HK_FORCE_INLINE const hkSimdDouble64 hkVector4d::horizontalMax<3>() const
{
const hkDouble64 m = hkMath::max2(m_quad.v[0], m_quad.v[1]);
return hkSimdDouble64::convert(hkMath::max2(m, m_quad.v[2]));
}
template <>
HK_FORCE_INLINE const hkSimdDouble64 hkVector4d::horizontalMax<4>() const
{
const hkDouble64 ma = hkMath::max2(m_quad.v[0], m_quad.v[1]);
const hkDouble64 mb = hkMath::max2(m_quad.v[2], m_quad.v[3]);
return hkSimdDouble64::convert(hkMath::max2(ma, mb));
}
template <int N>
HK_FORCE_INLINE const hkSimdDouble64 hkVector4d::horizontalMax() const
{
HK_VECTOR4d_NOT_IMPLEMENTED;
return hkSimdDouble64::getConstant<HK_QUADREAL_0>();
}
template <>
HK_FORCE_INLINE const hkSimdDouble64 hkVector4d::horizontalMin<1>() const
{
return getComponent<0>();
}
template <>
HK_FORCE_INLINE const hkSimdDouble64 hkVector4d::horizontalMin<2>() const
{
return hkSimdDouble64::convert(hkMath::min2(m_quad.v[0], m_quad.v[1]));
}
template <>
HK_FORCE_INLINE const hkSimdDouble64 hkVector4d::horizontalMin<3>() const
{
const hkDouble64 m = hkMath::min2(m_quad.v[0], m_quad.v[1]);
return hkSimdDouble64::convert(hkMath::min2(m, m_quad.v[2]));
}
template <>
HK_FORCE_INLINE const hkSimdDouble64 hkVector4d::horizontalMin<4>() const
{
const hkDouble64 ma = hkMath::min2(m_quad.v[0], m_quad.v[1]);
const hkDouble64 mb = hkMath::min2(m_quad.v[2], m_quad.v[3]);
return hkSimdDouble64::convert(hkMath::min2(ma, mb));
}
template <int N>
HK_FORCE_INLINE const hkSimdDouble64 hkVector4d::horizontalMin() const
{
HK_VECTOR4d_NOT_IMPLEMENTED;
return hkSimdDouble64::getConstant<HK_QUADREAL_0>();
}
/* operator () */
HK_FORCE_INLINE hkDouble64& hkVector4d::operator() (int a)
{
HK_MATH_ASSERT(0x6d0c31d7, a>=0 && a<4, "index out of bounds for component access");
return m_quad.v[a];
}
HK_FORCE_INLINE const hkDouble64& hkVector4d::operator() (int a) const
{
HK_MATH_ASSERT(0x6d0c31d7, a>=0 && a<4, "index out of bounds for component access");
return const_cast<const hkDouble64&>(m_quad.v[a]);
}
HK_FORCE_INLINE void hkVector4d::setXYZ_W(hkVector4dParameter xyz, hkVector4dParameter ww)
{
m_quad.v[0] = xyz.m_quad.v[0];
m_quad.v[1] = xyz.m_quad.v[1];
m_quad.v[2] = xyz.m_quad.v[2];
m_quad.v[3] = ww.m_quad.v[3];
}
HK_FORCE_INLINE void hkVector4d::setXYZ_W(hkVector4dParameter xyz, hkSimdDouble64Parameter ww)
{
m_quad.v[0] = xyz.m_quad.v[0];
m_quad.v[1] = xyz.m_quad.v[1];
m_quad.v[2] = xyz.m_quad.v[2];
m_quad.v[3] = ww.getReal();
}
HK_FORCE_INLINE void hkVector4d::setW(hkVector4dParameter w)
{
m_quad.v[3] = w.m_quad.v[3];
}
HK_FORCE_INLINE void hkVector4d::setXYZ(hkVector4dParameter xyz)
{
m_quad.v[0] = xyz.m_quad.v[0];
m_quad.v[1] = xyz.m_quad.v[1];
m_quad.v[2] = xyz.m_quad.v[2];
}
HK_FORCE_INLINE void hkVector4d::addXYZ(hkVector4dParameter xyz)
{
m_quad.v[0] += xyz.m_quad.v[0];
m_quad.v[1] += xyz.m_quad.v[1];
m_quad.v[2] += xyz.m_quad.v[2];
#if defined(HK_REAL_IS_DOUBLE)
HK_ON_DEBUG( *((hkUint64*)&(m_quad.v[3])) = 0xffffffffffffffffull; )
#else
HK_ON_DEBUG( *((hkUint32*)&(m_quad.v[3])) = 0xffffffff; )
#endif
}
HK_FORCE_INLINE void hkVector4d::subXYZ(hkVector4dParameter xyz)
{
m_quad.v[0] -= xyz.m_quad.v[0];
m_quad.v[1] -= xyz.m_quad.v[1];
m_quad.v[2] -= xyz.m_quad.v[2];
#if defined(HK_REAL_IS_DOUBLE)
HK_ON_DEBUG( *((hkUint64*)&(m_quad.v[3])) = 0xffffffffffffffffull; )
#else
HK_ON_DEBUG( *((hkUint32*)&(m_quad.v[3])) = 0xffffffff; )
#endif
}
HK_FORCE_INLINE void hkVector4d::setXYZ(hkDouble64 v)
{
m_quad.v[0] = v;
m_quad.v[1] = v;
m_quad.v[2] = v;
}
HK_FORCE_INLINE void hkVector4d::setXYZ(hkSimdDouble64Parameter vv)
{
setXYZ( vv.getReal() );
}
HK_FORCE_INLINE void hkVector4d::setXYZ_0(hkVector4dParameter xyz)
{
setXYZ( xyz );
m_quad.v[3] = hkDouble64(0);
}
HK_FORCE_INLINE void hkVector4d::setBroadcastXYZ(const int i, hkVector4dParameter v)
{
HK_MATH_ASSERT(0x6d0c31d7, i>=0 && i<4, "index out of bounds for component access");
setXYZ( v.m_quad.v[i] );
#if defined(HK_REAL_IS_DOUBLE)
HK_ON_DEBUG( *((hkUint64*)&(m_quad.v[3])) = 0xffffffffffffffffull; )
#else
HK_ON_DEBUG( *((hkUint32*)&(m_quad.v[3])) = 0xffffffff; )
#endif
}
HK_FORCE_INLINE const hkSimdDouble64 hkVector4d::getComponent(const int i) const
{
HK_MATH_ASSERT(0x6d0c31d7, i>=0 && i<4, "index out of bounds for component access");
return hkSimdDouble64::convert(m_quad.v[i]);
}
template <int I>
HK_FORCE_INLINE const hkSimdDouble64 hkVector4d::getComponent() const
{
HK_VECTOR4d_SUBINDEX_CHECK;
return hkSimdDouble64::convert(m_quad.v[I]);
}
HK_FORCE_INLINE void hkVector4d::setComponent(const int i, hkSimdDouble64Parameter val)
{
HK_MATH_ASSERT(0x6d0c31d7, i>=0 && i<4, "index out of bounds for component access");
m_quad.v[i] = val.getReal();
}
template <int I>
HK_FORCE_INLINE void hkVector4d::setComponent(hkSimdDouble64Parameter val)
{
HK_VECTOR4d_SUBINDEX_CHECK;
m_quad.v[I] = val.getReal();
}
HK_FORCE_INLINE void hkVector4d::reduceToHalfPrecision()
{
#if defined(HK_HALF_IS_FLOAT)
#if defined(HK_REAL_IS_DOUBLE)
static const hkUint64 precisionMask = 0xffffffff00000000ull;
const hkUint64* src = reinterpret_cast<const hkUint64*>( &m_quad );
hkUint64* dest = reinterpret_cast<hkUint64*>( &m_quad );
dest[0] = src[0] & precisionMask;
dest[1] = src[1] & precisionMask;
dest[2] = src[2] & precisionMask;
dest[3] = src[3] & precisionMask;
#endif
#else
static const hkUint32 precisionMask = 0xffff0000;
#if defined(HK_REAL_IS_DOUBLE)
hkFloat32 fsrc[4];
fsrc[0] = hkFloat32(m_quad.v[0]);
fsrc[1] = hkFloat32(m_quad.v[1]);
fsrc[2] = hkFloat32(m_quad.v[2]);
fsrc[3] = hkFloat32(m_quad.v[3]);
const hkUint32* src = reinterpret_cast<const hkUint32*>( fsrc );
hkUint32* dest = reinterpret_cast<hkUint32*>( fsrc );
dest[0] = src[0] & precisionMask;
dest[1] = src[1] & precisionMask;
dest[2] = src[2] & precisionMask;
dest[3] = src[3] & precisionMask;
m_quad.v[0] = hkDouble64(fsrc[0]);
m_quad.v[1] = hkDouble64(fsrc[1]);
m_quad.v[2] = hkDouble64(fsrc[2]);
m_quad.v[3] = hkDouble64(fsrc[3]);
#else
const hkUint32* src = reinterpret_cast<const hkUint32*>( &m_quad );
hkUint32* dest = reinterpret_cast<hkUint32*>( &m_quad );
dest[0] = src[0] & precisionMask;
dest[1] = src[1] & precisionMask;
dest[2] = src[2] & precisionMask;
dest[3] = src[3] & precisionMask;
#endif
#endif
}
template <int N>
HK_FORCE_INLINE hkBool32 hkVector4d::isOk() const
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
if ( !hkMath::isFinite(m_quad.v[0]) ) return false;
if ((N>1)&&(!hkMath::isFinite(m_quad.v[1]))) return false;
if ((N>2)&&(!hkMath::isFinite(m_quad.v[2]))) return false;
if ((N>3)&&(!hkMath::isFinite(m_quad.v[3]))) return false;
return true;
}
template <>
HK_FORCE_INLINE void hkVector4d::setPermutation<hkVectorPermutation::XYZW>(hkVector4dParameter v)
{
m_quad = v.m_quad;
}
template <hkVectorPermutation::Permutation P>
HK_FORCE_INLINE void hkVector4d::setPermutation(hkVector4dParameter v)
{
// Store in regs before writing to the destination - to handle case when v and this are the same
const hkDouble64 t0 = v.m_quad.v[(P & 0x3000) >> 12];
const hkDouble64 t1 = v.m_quad.v[(P & 0x0300) >> 8];
const hkDouble64 t2 = v.m_quad.v[(P & 0x0030) >> 4];
const hkDouble64 t3 = v.m_quad.v[(P & 0x0003) >> 0];
m_quad.v[0] = t0;
m_quad.v[1] = t1;
m_quad.v[2] = t2;
m_quad.v[3] = t3;
}
HK_FORCE_INLINE const hkVector4dComparison hkVector4d::signBitSet() const
{
hkVector4dComparison mask;
mask.m_mask = hkVector4ComparisonMask::MASK_NONE;
mask.m_mask |= hkMath::signBitSet(m_quad.v[0]) ? hkVector4ComparisonMask::MASK_X : hkVector4ComparisonMask::MASK_NONE;
mask.m_mask |= hkMath::signBitSet(m_quad.v[1]) ? hkVector4ComparisonMask::MASK_Y : hkVector4ComparisonMask::MASK_NONE;
mask.m_mask |= hkMath::signBitSet(m_quad.v[2]) ? hkVector4ComparisonMask::MASK_Z : hkVector4ComparisonMask::MASK_NONE;
mask.m_mask |= hkMath::signBitSet(m_quad.v[3]) ? hkVector4ComparisonMask::MASK_W : hkVector4ComparisonMask::MASK_NONE;
return mask;
}
HK_FORCE_INLINE const hkVector4dComparison hkVector4d::signBitClear() const
{
hkVector4dComparison mask;
mask.m_mask = hkVector4ComparisonMask::MASK_NONE;
mask.m_mask |= hkMath::signBitSet(m_quad.v[0]) ? hkVector4ComparisonMask::MASK_NONE : hkVector4ComparisonMask::MASK_X;
mask.m_mask |= hkMath::signBitSet(m_quad.v[1]) ? hkVector4ComparisonMask::MASK_NONE : hkVector4ComparisonMask::MASK_Y;
mask.m_mask |= hkMath::signBitSet(m_quad.v[2]) ? hkVector4ComparisonMask::MASK_NONE : hkVector4ComparisonMask::MASK_Z;
mask.m_mask |= hkMath::signBitSet(m_quad.v[3]) ? hkVector4ComparisonMask::MASK_NONE : hkVector4ComparisonMask::MASK_W;
return mask;
}
HK_FORCE_INLINE void hkVector4d::setFlipSign(hkVector4dParameter v, hkVector4dComparisonParameter mask)
{
m_quad.v[0] = mask.anyIsSet<hkVector4ComparisonMask::MASK_X>() ? -v.m_quad.v[0] : v.m_quad.v[0];
m_quad.v[1] = mask.anyIsSet<hkVector4ComparisonMask::MASK_Y>() ? -v.m_quad.v[1] : v.m_quad.v[1];
m_quad.v[2] = mask.anyIsSet<hkVector4ComparisonMask::MASK_Z>() ? -v.m_quad.v[2] : v.m_quad.v[2];
m_quad.v[3] = mask.anyIsSet<hkVector4ComparisonMask::MASK_W>() ? -v.m_quad.v[3] : v.m_quad.v[3];
}
HK_FORCE_INLINE void hkVector4d::setFlipSign(hkVector4dParameter a, hkVector4dParameter signs)
{
m_quad.v[0] = hkMath::signBitSet(signs.m_quad.v[0]) ? -a.m_quad.v[0] : a.m_quad.v[0];
m_quad.v[1] = hkMath::signBitSet(signs.m_quad.v[1]) ? -a.m_quad.v[1] : a.m_quad.v[1];
m_quad.v[2] = hkMath::signBitSet(signs.m_quad.v[2]) ? -a.m_quad.v[2] : a.m_quad.v[2];
m_quad.v[3] = hkMath::signBitSet(signs.m_quad.v[3]) ? -a.m_quad.v[3] : a.m_quad.v[3];
}
HK_FORCE_INLINE void hkVector4d::setFlipSign(hkVector4dParameter a, hkSimdDouble64Parameter sharedSign)
{
const bool flip = hkMath::signBitSet(sharedSign.getReal());
if (flip)
{
m_quad.v[0] = -a.m_quad.v[0];
m_quad.v[1] = -a.m_quad.v[1];
m_quad.v[2] = -a.m_quad.v[2];
m_quad.v[3] = -a.m_quad.v[3];
}
else
{
m_quad.v[0] = a.m_quad.v[0];
m_quad.v[1] = a.m_quad.v[1];
m_quad.v[2] = a.m_quad.v[2];
m_quad.v[3] = a.m_quad.v[3];
}
}
//
// advanced interface
//
namespace hkVector4_AdvancedInterface
{
template <hkMathAccuracyMode A, hkMathDivByZeroMode D>
struct unrolld_setReciprocal { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, hkVector4dParameter a)
{
HK_VECTOR4d_TEMPLATE_CONFIG_NOT_IMPLEMENTED;
} };
template <hkMathAccuracyMode A>
struct unrolld_setReciprocal<A, HK_DIV_IGNORE> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, hkVector4dParameter a)
{
switch (A)
{
case HK_ACC_23_BIT:
{
self.v[0] = hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(a.m_quad.v[0])));
self.v[1] = hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(a.m_quad.v[1])));
self.v[2] = hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(a.m_quad.v[2])));
self.v[3] = hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(a.m_quad.v[3])));
}
break;
case HK_ACC_12_BIT:
{
self.v[0] = hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(a.m_quad.v[0])));
self.v[1] = hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(a.m_quad.v[1])));
self.v[2] = hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(a.m_quad.v[2])));
self.v[3] = hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(a.m_quad.v[3])));
}
break;
default:
{
self.v[0] = hkDouble64(1) / a.m_quad.v[0];
self.v[1] = hkDouble64(1) / a.m_quad.v[1];
self.v[2] = hkDouble64(1) / a.m_quad.v[2];
self.v[3] = hkDouble64(1) / a.m_quad.v[3];
}
break; // HK_ACC_FULL
}
} };
template <hkMathAccuracyMode A>
struct unrolld_setReciprocal<A, HK_DIV_SET_ZERO> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, hkVector4dParameter a)
{
switch (A)
{
case HK_ACC_23_BIT:
{
self.v[0] = ((a.m_quad.v[0] == hkDouble64(0)) ? hkDouble64(0) : hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(a.m_quad.v[0]))));
self.v[1] = ((a.m_quad.v[1] == hkDouble64(0)) ? hkDouble64(0) : hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(a.m_quad.v[1]))));
self.v[2] = ((a.m_quad.v[2] == hkDouble64(0)) ? hkDouble64(0) : hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(a.m_quad.v[2]))));
self.v[3] = ((a.m_quad.v[3] == hkDouble64(0)) ? hkDouble64(0) : hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(a.m_quad.v[3]))));
}
break;
case HK_ACC_12_BIT:
{
self.v[0] = ((a.m_quad.v[0] == hkDouble64(0)) ? hkDouble64(0) : hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(a.m_quad.v[0]))));
self.v[1] = ((a.m_quad.v[1] == hkDouble64(0)) ? hkDouble64(0) : hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(a.m_quad.v[1]))));
self.v[2] = ((a.m_quad.v[2] == hkDouble64(0)) ? hkDouble64(0) : hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(a.m_quad.v[2]))));
self.v[3] = ((a.m_quad.v[3] == hkDouble64(0)) ? hkDouble64(0) : hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(a.m_quad.v[3]))));
}
break;
default:
{
self.v[0] = ((a.m_quad.v[0] == hkDouble64(0)) ? hkDouble64(0) : hkDouble64(1) / a.m_quad.v[0]);
self.v[1] = ((a.m_quad.v[1] == hkDouble64(0)) ? hkDouble64(0) : hkDouble64(1) / a.m_quad.v[1]);
self.v[2] = ((a.m_quad.v[2] == hkDouble64(0)) ? hkDouble64(0) : hkDouble64(1) / a.m_quad.v[2]);
self.v[3] = ((a.m_quad.v[3] == hkDouble64(0)) ? hkDouble64(0) : hkDouble64(1) / a.m_quad.v[3]);
}
break; // HK_ACC_FULL
}
} };
template <hkMathAccuracyMode A>
struct unrolld_setReciprocal<A, HK_DIV_SET_HIGH> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, hkVector4dParameter a)
{
hkDouble64 high0 = hkMath::signBitSet(a.m_quad.v[0]) ? -HK_DOUBLE_HIGH : HK_DOUBLE_HIGH;
hkDouble64 high1 = hkMath::signBitSet(a.m_quad.v[1]) ? -HK_DOUBLE_HIGH : HK_DOUBLE_HIGH;
hkDouble64 high2 = hkMath::signBitSet(a.m_quad.v[2]) ? -HK_DOUBLE_HIGH : HK_DOUBLE_HIGH;
hkDouble64 high3 = hkMath::signBitSet(a.m_quad.v[3]) ? -HK_DOUBLE_HIGH : HK_DOUBLE_HIGH;
switch (A)
{
case HK_ACC_23_BIT:
{
self.v[0] = ((a.m_quad.v[0] == hkDouble64(0)) ? high0 : hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(a.m_quad.v[0]))));
self.v[1] = ((a.m_quad.v[1] == hkDouble64(0)) ? high1 : hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(a.m_quad.v[1]))));
self.v[2] = ((a.m_quad.v[2] == hkDouble64(0)) ? high2 : hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(a.m_quad.v[2]))));
self.v[3] = ((a.m_quad.v[3] == hkDouble64(0)) ? high3 : hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(a.m_quad.v[3]))));
}
break;
case HK_ACC_12_BIT:
{
self.v[0] = ((a.m_quad.v[0] == hkDouble64(0)) ? high0 : hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(a.m_quad.v[0]))));
self.v[1] = ((a.m_quad.v[1] == hkDouble64(0)) ? high1 : hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(a.m_quad.v[1]))));
self.v[2] = ((a.m_quad.v[2] == hkDouble64(0)) ? high2 : hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(a.m_quad.v[2]))));
self.v[3] = ((a.m_quad.v[3] == hkDouble64(0)) ? high3 : hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(a.m_quad.v[3]))));
}
break;
default:
{
self.v[0] = ((a.m_quad.v[0] == hkDouble64(0)) ? high0 : hkDouble64(1) / a.m_quad.v[0]);
self.v[1] = ((a.m_quad.v[1] == hkDouble64(0)) ? high1 : hkDouble64(1) / a.m_quad.v[1]);
self.v[2] = ((a.m_quad.v[2] == hkDouble64(0)) ? high2 : hkDouble64(1) / a.m_quad.v[2]);
self.v[3] = ((a.m_quad.v[3] == hkDouble64(0)) ? high3 : hkDouble64(1) / a.m_quad.v[3]);
}
break; // HK_ACC_FULL
}
} };
template <hkMathAccuracyMode A>
struct unrolld_setReciprocal<A, HK_DIV_SET_MAX> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, hkVector4dParameter a)
{
hkDouble64 max0 = hkMath::signBitSet(a.m_quad.v[0]) ? -HK_DOUBLE_MAX : HK_DOUBLE_MAX;
hkDouble64 max1 = hkMath::signBitSet(a.m_quad.v[1]) ? -HK_DOUBLE_MAX : HK_DOUBLE_MAX;
hkDouble64 max2 = hkMath::signBitSet(a.m_quad.v[2]) ? -HK_DOUBLE_MAX : HK_DOUBLE_MAX;
hkDouble64 max3 = hkMath::signBitSet(a.m_quad.v[3]) ? -HK_DOUBLE_MAX : HK_DOUBLE_MAX;
switch (A)
{
case HK_ACC_23_BIT:
{
self.v[0] = ((a.m_quad.v[0] == hkDouble64(0)) ? max0 : hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(a.m_quad.v[0]))));
self.v[1] = ((a.m_quad.v[1] == hkDouble64(0)) ? max1 : hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(a.m_quad.v[1]))));
self.v[2] = ((a.m_quad.v[2] == hkDouble64(0)) ? max2 : hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(a.m_quad.v[2]))));
self.v[3] = ((a.m_quad.v[3] == hkDouble64(0)) ? max3 : hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(a.m_quad.v[3]))));
}
break;
case HK_ACC_12_BIT:
{
self.v[0] = ((a.m_quad.v[0] == hkDouble64(0)) ? max0 : hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(a.m_quad.v[0]))));
self.v[1] = ((a.m_quad.v[1] == hkDouble64(0)) ? max1 : hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(a.m_quad.v[1]))));
self.v[2] = ((a.m_quad.v[2] == hkDouble64(0)) ? max2 : hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(a.m_quad.v[2]))));
self.v[3] = ((a.m_quad.v[3] == hkDouble64(0)) ? max3 : hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(a.m_quad.v[3]))));
}
break;
default:
{
self.v[0] = ((a.m_quad.v[0] == hkDouble64(0)) ? max0 : hkDouble64(1) / a.m_quad.v[0]);
self.v[1] = ((a.m_quad.v[1] == hkDouble64(0)) ? max1 : hkDouble64(1) / a.m_quad.v[1]);
self.v[2] = ((a.m_quad.v[2] == hkDouble64(0)) ? max2 : hkDouble64(1) / a.m_quad.v[2]);
self.v[3] = ((a.m_quad.v[3] == hkDouble64(0)) ? max3 : hkDouble64(1) / a.m_quad.v[3]);
}
break; // HK_ACC_FULL
}
} };
template <hkMathAccuracyMode A>
struct unrolld_setReciprocal<A, HK_DIV_SET_ZERO_AND_ONE> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, hkVector4dParameter a)
{
hkQuadDouble64 val; unrolld_setReciprocal<A, HK_DIV_SET_ZERO>::apply(val,a);
hkQuadDouble64 absValLessOne;
absValLessOne.v[0] = hkMath::fabs(val.v[0] - hkDouble64(1));
absValLessOne.v[1] = hkMath::fabs(val.v[1] - hkDouble64(1));
absValLessOne.v[2] = hkMath::fabs(val.v[2] - hkDouble64(1));
absValLessOne.v[3] = hkMath::fabs(val.v[3] - hkDouble64(1));
self.v[0] = ((absValLessOne.v[0] <= HK_DOUBLE_EPSILON) ? hkDouble64(1) : val.v[0]);
self.v[1] = ((absValLessOne.v[1] <= HK_DOUBLE_EPSILON) ? hkDouble64(1) : val.v[1]);
self.v[2] = ((absValLessOne.v[2] <= HK_DOUBLE_EPSILON) ? hkDouble64(1) : val.v[2]);
self.v[3] = ((absValLessOne.v[3] <= HK_DOUBLE_EPSILON) ? hkDouble64(1) : val.v[3]);
} };
} // namespace
template <hkMathAccuracyMode A, hkMathDivByZeroMode D>
HK_FORCE_INLINE void hkVector4d::setReciprocal(hkVector4dParameter v)
{
hkVector4_AdvancedInterface::unrolld_setReciprocal<A,D>::apply(m_quad,v);
}
HK_FORCE_INLINE void hkVector4d::setReciprocal(hkVector4dParameter v)
{
hkVector4_AdvancedInterface::unrolld_setReciprocal<HK_ACC_23_BIT,HK_DIV_IGNORE>::apply(m_quad,v);
}
namespace hkVector4_AdvancedInterface
{
template <hkMathAccuracyMode A, hkMathDivByZeroMode D>
struct unrolld_setDiv { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, hkVector4dParameter a, hkVector4dParameter b)
{
HK_VECTOR4d_TEMPLATE_CONFIG_NOT_IMPLEMENTED;
} };
template <hkMathAccuracyMode A>
struct unrolld_setDiv<A, HK_DIV_IGNORE> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, hkVector4dParameter a, hkVector4dParameter b)
{
switch (A)
{
case HK_ACC_23_BIT:
{
self.v[0] = a.m_quad.v[0] * hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(b.m_quad.v[0])));
self.v[1] = a.m_quad.v[1] * hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(b.m_quad.v[1])));
self.v[2] = a.m_quad.v[2] * hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(b.m_quad.v[2])));
self.v[3] = a.m_quad.v[3] * hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(b.m_quad.v[3])));
}
break;
case HK_ACC_12_BIT:
{
self.v[0] = a.m_quad.v[0] * hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(b.m_quad.v[0])));
self.v[1] = a.m_quad.v[1] * hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(b.m_quad.v[1])));
self.v[2] = a.m_quad.v[2] * hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(b.m_quad.v[2])));
self.v[3] = a.m_quad.v[3] * hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(b.m_quad.v[3])));
}
break;
default:
{
self.v[0] = a.m_quad.v[0] / b.m_quad.v[0];
self.v[1] = a.m_quad.v[1] / b.m_quad.v[1];
self.v[2] = a.m_quad.v[2] / b.m_quad.v[2];
self.v[3] = a.m_quad.v[3] / b.m_quad.v[3];
}
break; // HK_ACC_FULL
}
} };
template <hkMathAccuracyMode A>
struct unrolld_setDiv<A, HK_DIV_SET_ZERO> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, hkVector4dParameter a, hkVector4dParameter b)
{
switch (A)
{
case HK_ACC_23_BIT:
{
self.v[0] = ((b.m_quad.v[0] == hkDouble64(0)) ? hkDouble64(0) : (a.m_quad.v[0] * hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(b.m_quad.v[0])))));
self.v[1] = ((b.m_quad.v[1] == hkDouble64(0)) ? hkDouble64(0) : (a.m_quad.v[1] * hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(b.m_quad.v[1])))));
self.v[2] = ((b.m_quad.v[2] == hkDouble64(0)) ? hkDouble64(0) : (a.m_quad.v[2] * hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(b.m_quad.v[2])))));
self.v[3] = ((b.m_quad.v[3] == hkDouble64(0)) ? hkDouble64(0) : (a.m_quad.v[3] * hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(b.m_quad.v[3])))));
}
break;
case HK_ACC_12_BIT:
{
self.v[0] = ((b.m_quad.v[0] == hkDouble64(0)) ? hkDouble64(0) : (a.m_quad.v[0] * hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(b.m_quad.v[0])))));
self.v[1] = ((b.m_quad.v[1] == hkDouble64(0)) ? hkDouble64(0) : (a.m_quad.v[1] * hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(b.m_quad.v[1])))));
self.v[2] = ((b.m_quad.v[2] == hkDouble64(0)) ? hkDouble64(0) : (a.m_quad.v[2] * hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(b.m_quad.v[2])))));
self.v[3] = ((b.m_quad.v[3] == hkDouble64(0)) ? hkDouble64(0) : (a.m_quad.v[3] * hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(b.m_quad.v[3])))));
}
break;
default:
{
self.v[0] = ((b.m_quad.v[0] == hkDouble64(0)) ? hkDouble64(0) : (a.m_quad.v[0] / b.m_quad.v[0]));
self.v[1] = ((b.m_quad.v[1] == hkDouble64(0)) ? hkDouble64(0) : (a.m_quad.v[1] / b.m_quad.v[1]));
self.v[2] = ((b.m_quad.v[2] == hkDouble64(0)) ? hkDouble64(0) : (a.m_quad.v[2] / b.m_quad.v[2]));
self.v[3] = ((b.m_quad.v[3] == hkDouble64(0)) ? hkDouble64(0) : (a.m_quad.v[3] / b.m_quad.v[3]));
}
break; // HK_ACC_FULL
}
} };
template <hkMathAccuracyMode A>
struct unrolld_setDiv<A, HK_DIV_SET_HIGH> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, hkVector4dParameter a, hkVector4dParameter b)
{
switch (A)
{
case HK_ACC_23_BIT:
{
self.v[0] = ((b.m_quad.v[0] == hkDouble64(0)) ? ((a.m_quad.v[0] < hkDouble64(0)) ? -HK_DOUBLE_HIGH : HK_DOUBLE_HIGH) : (a.m_quad.v[0] * hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(b.m_quad.v[0])))));
self.v[1] = ((b.m_quad.v[1] == hkDouble64(0)) ? ((a.m_quad.v[1] < hkDouble64(0)) ? -HK_DOUBLE_HIGH : HK_DOUBLE_HIGH) : (a.m_quad.v[1] * hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(b.m_quad.v[1])))));
self.v[2] = ((b.m_quad.v[2] == hkDouble64(0)) ? ((a.m_quad.v[2] < hkDouble64(0)) ? -HK_DOUBLE_HIGH : HK_DOUBLE_HIGH) : (a.m_quad.v[2] * hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(b.m_quad.v[2])))));
self.v[3] = ((b.m_quad.v[3] == hkDouble64(0)) ? ((a.m_quad.v[3] < hkDouble64(0)) ? -HK_DOUBLE_HIGH : HK_DOUBLE_HIGH) : (a.m_quad.v[3] * hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(b.m_quad.v[3])))));
}
break;
case HK_ACC_12_BIT:
{
self.v[0] = ((b.m_quad.v[0] == hkDouble64(0)) ? ((a.m_quad.v[0] < hkDouble64(0)) ? -HK_DOUBLE_HIGH : HK_DOUBLE_HIGH) : (a.m_quad.v[0] * hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(b.m_quad.v[0])))));
self.v[1] = ((b.m_quad.v[1] == hkDouble64(0)) ? ((a.m_quad.v[1] < hkDouble64(0)) ? -HK_DOUBLE_HIGH : HK_DOUBLE_HIGH) : (a.m_quad.v[1] * hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(b.m_quad.v[1])))));
self.v[2] = ((b.m_quad.v[2] == hkDouble64(0)) ? ((a.m_quad.v[2] < hkDouble64(0)) ? -HK_DOUBLE_HIGH : HK_DOUBLE_HIGH) : (a.m_quad.v[2] * hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(b.m_quad.v[2])))));
self.v[3] = ((b.m_quad.v[3] == hkDouble64(0)) ? ((a.m_quad.v[3] < hkDouble64(0)) ? -HK_DOUBLE_HIGH : HK_DOUBLE_HIGH) : (a.m_quad.v[3] * hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(b.m_quad.v[3])))));
}
break;
default:
{
self.v[0] = ((b.m_quad.v[0] == hkDouble64(0)) ? ((a.m_quad.v[0] < hkDouble64(0)) ? -HK_DOUBLE_HIGH : HK_DOUBLE_HIGH) : (a.m_quad.v[0] / b.m_quad.v[0]));
self.v[1] = ((b.m_quad.v[1] == hkDouble64(0)) ? ((a.m_quad.v[1] < hkDouble64(0)) ? -HK_DOUBLE_HIGH : HK_DOUBLE_HIGH) : (a.m_quad.v[1] / b.m_quad.v[1]));
self.v[2] = ((b.m_quad.v[2] == hkDouble64(0)) ? ((a.m_quad.v[2] < hkDouble64(0)) ? -HK_DOUBLE_HIGH : HK_DOUBLE_HIGH) : (a.m_quad.v[2] / b.m_quad.v[2]));
self.v[3] = ((b.m_quad.v[3] == hkDouble64(0)) ? ((a.m_quad.v[3] < hkDouble64(0)) ? -HK_DOUBLE_HIGH : HK_DOUBLE_HIGH) : (a.m_quad.v[3] / b.m_quad.v[3]));
}
break; // HK_ACC_FULL
}
} };
template <hkMathAccuracyMode A>
struct unrolld_setDiv<A, HK_DIV_SET_MAX> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, hkVector4dParameter a, hkVector4dParameter b)
{
switch (A)
{
case HK_ACC_23_BIT:
{
self.v[0] = ((b.m_quad.v[0] == hkDouble64(0)) ? ((a.m_quad.v[0] < hkDouble64(0)) ? -HK_DOUBLE_MAX : HK_DOUBLE_MAX) : (a.m_quad.v[0] * hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(b.m_quad.v[0])))));
self.v[1] = ((b.m_quad.v[1] == hkDouble64(0)) ? ((a.m_quad.v[1] < hkDouble64(0)) ? -HK_DOUBLE_MAX : HK_DOUBLE_MAX) : (a.m_quad.v[1] * hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(b.m_quad.v[1])))));
self.v[2] = ((b.m_quad.v[2] == hkDouble64(0)) ? ((a.m_quad.v[2] < hkDouble64(0)) ? -HK_DOUBLE_MAX : HK_DOUBLE_MAX) : (a.m_quad.v[2] * hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(b.m_quad.v[2])))));
self.v[3] = ((b.m_quad.v[3] == hkDouble64(0)) ? ((a.m_quad.v[3] < hkDouble64(0)) ? -HK_DOUBLE_MAX : HK_DOUBLE_MAX) : (a.m_quad.v[3] * hkDouble64(hkMath::rcpF32Approx23Bit(hkFloat32(b.m_quad.v[3])))));
}
break;
case HK_ACC_12_BIT:
{
self.v[0] = ((b.m_quad.v[0] == hkDouble64(0)) ? ((a.m_quad.v[0] < hkDouble64(0)) ? -HK_DOUBLE_MAX : HK_DOUBLE_MAX) : (a.m_quad.v[0] * hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(b.m_quad.v[0])))));
self.v[1] = ((b.m_quad.v[1] == hkDouble64(0)) ? ((a.m_quad.v[1] < hkDouble64(0)) ? -HK_DOUBLE_MAX : HK_DOUBLE_MAX) : (a.m_quad.v[1] * hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(b.m_quad.v[1])))));
self.v[2] = ((b.m_quad.v[2] == hkDouble64(0)) ? ((a.m_quad.v[2] < hkDouble64(0)) ? -HK_DOUBLE_MAX : HK_DOUBLE_MAX) : (a.m_quad.v[2] * hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(b.m_quad.v[2])))));
self.v[3] = ((b.m_quad.v[3] == hkDouble64(0)) ? ((a.m_quad.v[3] < hkDouble64(0)) ? -HK_DOUBLE_MAX : HK_DOUBLE_MAX) : (a.m_quad.v[3] * hkDouble64(hkMath::rcpF32Approx12Bit(hkFloat32(b.m_quad.v[3])))));
}
break;
default:
{
self.v[0] = ((b.m_quad.v[0] == hkDouble64(0)) ? ((a.m_quad.v[0] < hkDouble64(0)) ? -HK_DOUBLE_MAX : HK_DOUBLE_MAX) : (a.m_quad.v[0] / b.m_quad.v[0]));
self.v[1] = ((b.m_quad.v[1] == hkDouble64(0)) ? ((a.m_quad.v[1] < hkDouble64(0)) ? -HK_DOUBLE_MAX : HK_DOUBLE_MAX) : (a.m_quad.v[1] / b.m_quad.v[1]));
self.v[2] = ((b.m_quad.v[2] == hkDouble64(0)) ? ((a.m_quad.v[2] < hkDouble64(0)) ? -HK_DOUBLE_MAX : HK_DOUBLE_MAX) : (a.m_quad.v[2] / b.m_quad.v[2]));
self.v[3] = ((b.m_quad.v[3] == hkDouble64(0)) ? ((a.m_quad.v[3] < hkDouble64(0)) ? -HK_DOUBLE_MAX : HK_DOUBLE_MAX) : (a.m_quad.v[3] / b.m_quad.v[3]));
}
break; // HK_ACC_FULL
}
} };
template <hkMathAccuracyMode A>
struct unrolld_setDiv<A, HK_DIV_SET_ZERO_AND_ONE> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, hkVector4dParameter a, hkVector4dParameter b)
{
hkQuadDouble64 val; unrolld_setDiv<A, HK_DIV_SET_ZERO>::apply(val,a,b);
hkQuadDouble64 absValLessOne;
absValLessOne.v[0] = hkMath::fabs(val.v[0]) - hkDouble64(1);
absValLessOne.v[1] = hkMath::fabs(val.v[1]) - hkDouble64(1);
absValLessOne.v[2] = hkMath::fabs(val.v[2]) - hkDouble64(1);
absValLessOne.v[3] = hkMath::fabs(val.v[3]) - hkDouble64(1);
self.v[0] = ((absValLessOne.v[0] <= HK_DOUBLE_EPSILON) ? hkDouble64(1) : val.v[0]);
self.v[1] = ((absValLessOne.v[1] <= HK_DOUBLE_EPSILON) ? hkDouble64(1) : val.v[1]);
self.v[2] = ((absValLessOne.v[2] <= HK_DOUBLE_EPSILON) ? hkDouble64(1) : val.v[2]);
self.v[3] = ((absValLessOne.v[3] <= HK_DOUBLE_EPSILON) ? hkDouble64(1) : val.v[3]);
} };
} // namespace
template <hkMathAccuracyMode A, hkMathDivByZeroMode D>
HK_FORCE_INLINE void hkVector4d::setDiv(hkVector4dParameter v0, hkVector4dParameter v1)
{
hkVector4_AdvancedInterface::unrolld_setDiv<A,D>::apply(m_quad,v0,v1);
}
HK_FORCE_INLINE void hkVector4d::setDiv(hkVector4dParameter v0, hkVector4dParameter v1)
{
hkVector4_AdvancedInterface::unrolld_setDiv<HK_ACC_23_BIT,HK_DIV_IGNORE>::apply(m_quad,v0,v1);
}
template <hkMathAccuracyMode A, hkMathDivByZeroMode D>
HK_FORCE_INLINE void hkVector4d::div(hkVector4dParameter a)
{
setDiv<A,D>( *this, a );
}
HK_FORCE_INLINE void hkVector4d::div(hkVector4dParameter a)
{
setDiv( *this, a );
}
namespace hkVector4_AdvancedInterface
{
template <hkMathAccuracyMode A, hkMathNegSqrtMode S>
struct unrolld_setSqrt { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, hkVector4dParameter a)
{
HK_VECTOR4d_TEMPLATE_CONFIG_NOT_IMPLEMENTED;
} };
template <hkMathAccuracyMode A>
struct unrolld_setSqrt<A, HK_SQRT_IGNORE> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, hkVector4dParameter a)
{
switch (A)
{
case HK_ACC_23_BIT:
{
self.v[0] = hkDouble64(hkMath::rcpF32Approx23Bit(hkMath::invSqrtF32Approx23Bit(hkFloat32(a.m_quad.v[0]))));
self.v[1] = hkDouble64(hkMath::rcpF32Approx23Bit(hkMath::invSqrtF32Approx23Bit(hkFloat32(a.m_quad.v[1]))));
self.v[2] = hkDouble64(hkMath::rcpF32Approx23Bit(hkMath::invSqrtF32Approx23Bit(hkFloat32(a.m_quad.v[2]))));
self.v[3] = hkDouble64(hkMath::rcpF32Approx23Bit(hkMath::invSqrtF32Approx23Bit(hkFloat32(a.m_quad.v[3]))));
}
break;
case HK_ACC_12_BIT:
{
self.v[0] = hkDouble64(hkMath::rcpF32Approx12Bit(hkMath::invSqrtF32Approx12Bit(hkFloat32(a.m_quad.v[0]))));
self.v[1] = hkDouble64(hkMath::rcpF32Approx12Bit(hkMath::invSqrtF32Approx12Bit(hkFloat32(a.m_quad.v[1]))));
self.v[2] = hkDouble64(hkMath::rcpF32Approx12Bit(hkMath::invSqrtF32Approx12Bit(hkFloat32(a.m_quad.v[2]))));
self.v[3] = hkDouble64(hkMath::rcpF32Approx12Bit(hkMath::invSqrtF32Approx12Bit(hkFloat32(a.m_quad.v[3]))));
}
break;
default:
{
self.v[0] = hkMath::sqrt(a.m_quad.v[0]);
self.v[1] = hkMath::sqrt(a.m_quad.v[1]);
self.v[2] = hkMath::sqrt(a.m_quad.v[2]);
self.v[3] = hkMath::sqrt(a.m_quad.v[3]);
}
break; // HK_ACC_FULL
}
} };
template <hkMathAccuracyMode A>
struct unrolld_setSqrt<A, HK_SQRT_SET_ZERO> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, hkVector4dParameter a)
{
switch (A)
{
case HK_ACC_23_BIT:
{
self.v[0] = ((a.m_quad.v[0] <= hkDouble64(0)) ? hkDouble64(0) : hkDouble64(hkMath::rcpF32Approx23Bit(hkMath::invSqrtF32Approx23Bit(hkFloat32(a.m_quad.v[0])))));
self.v[1] = ((a.m_quad.v[1] <= hkDouble64(0)) ? hkDouble64(0) : hkDouble64(hkMath::rcpF32Approx23Bit(hkMath::invSqrtF32Approx23Bit(hkFloat32(a.m_quad.v[1])))));
self.v[2] = ((a.m_quad.v[2] <= hkDouble64(0)) ? hkDouble64(0) : hkDouble64(hkMath::rcpF32Approx23Bit(hkMath::invSqrtF32Approx23Bit(hkFloat32(a.m_quad.v[2])))));
self.v[3] = ((a.m_quad.v[3] <= hkDouble64(0)) ? hkDouble64(0) : hkDouble64(hkMath::rcpF32Approx23Bit(hkMath::invSqrtF32Approx23Bit(hkFloat32(a.m_quad.v[3])))));
}
break;
case HK_ACC_12_BIT:
{
self.v[0] = ((a.m_quad.v[0] <= hkDouble64(0)) ? hkDouble64(0) : hkDouble64(hkMath::rcpF32Approx12Bit(hkMath::invSqrtF32Approx12Bit(hkFloat32(a.m_quad.v[0])))));
self.v[1] = ((a.m_quad.v[1] <= hkDouble64(0)) ? hkDouble64(0) : hkDouble64(hkMath::rcpF32Approx12Bit(hkMath::invSqrtF32Approx12Bit(hkFloat32(a.m_quad.v[1])))));
self.v[2] = ((a.m_quad.v[2] <= hkDouble64(0)) ? hkDouble64(0) : hkDouble64(hkMath::rcpF32Approx12Bit(hkMath::invSqrtF32Approx12Bit(hkFloat32(a.m_quad.v[2])))));
self.v[3] = ((a.m_quad.v[3] <= hkDouble64(0)) ? hkDouble64(0) : hkDouble64(hkMath::rcpF32Approx12Bit(hkMath::invSqrtF32Approx12Bit(hkFloat32(a.m_quad.v[3])))));
}
break;
default:
{
self.v[0] = ((a.m_quad.v[0] <= hkDouble64(0)) ? hkDouble64(0) : hkMath::sqrt(a.m_quad.v[0]));
self.v[1] = ((a.m_quad.v[1] <= hkDouble64(0)) ? hkDouble64(0) : hkMath::sqrt(a.m_quad.v[1]));
self.v[2] = ((a.m_quad.v[2] <= hkDouble64(0)) ? hkDouble64(0) : hkMath::sqrt(a.m_quad.v[2]));
self.v[3] = ((a.m_quad.v[3] <= hkDouble64(0)) ? hkDouble64(0) : hkMath::sqrt(a.m_quad.v[3]));
}
break; // HK_ACC_FULL
}
} };
} // namespace
template <hkMathAccuracyMode A, hkMathNegSqrtMode S>
HK_FORCE_INLINE void hkVector4d::setSqrt(hkVector4dParameter a)
{
hkVector4_AdvancedInterface::unrolld_setSqrt<A,S>::apply(m_quad, a);
}
HK_FORCE_INLINE void hkVector4d::setSqrt(hkVector4dParameter a)
{
hkVector4_AdvancedInterface::unrolld_setSqrt<HK_ACC_23_BIT,HK_SQRT_SET_ZERO>::apply(m_quad, a);
}
namespace hkVector4_AdvancedInterface
{
template <hkMathAccuracyMode A, hkMathNegSqrtMode S>
struct unrolld_setSqrtInverse { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, hkVector4dParameter a)
{
HK_VECTOR4d_TEMPLATE_CONFIG_NOT_IMPLEMENTED;
} };
template <hkMathAccuracyMode A>
struct unrolld_setSqrtInverse<A, HK_SQRT_IGNORE> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, hkVector4dParameter a)
{
switch (A)
{
case HK_ACC_23_BIT:
{
self.v[0] = hkDouble64(hkMath::invSqrtF32Approx23Bit(hkFloat32(a.m_quad.v[0])));
self.v[1] = hkDouble64(hkMath::invSqrtF32Approx23Bit(hkFloat32(a.m_quad.v[1])));
self.v[2] = hkDouble64(hkMath::invSqrtF32Approx23Bit(hkFloat32(a.m_quad.v[2])));
self.v[3] = hkDouble64(hkMath::invSqrtF32Approx23Bit(hkFloat32(a.m_quad.v[3])));
}
break;
case HK_ACC_12_BIT:
{
self.v[0] = hkDouble64(hkMath::invSqrtF32Approx12Bit(hkFloat32(a.m_quad.v[0])));
self.v[1] = hkDouble64(hkMath::invSqrtF32Approx12Bit(hkFloat32(a.m_quad.v[1])));
self.v[2] = hkDouble64(hkMath::invSqrtF32Approx12Bit(hkFloat32(a.m_quad.v[2])));
self.v[3] = hkDouble64(hkMath::invSqrtF32Approx12Bit(hkFloat32(a.m_quad.v[3])));
}
break;
default:
{
self.v[0] = hkMath::sqrtInverse(a.m_quad.v[0]);
self.v[1] = hkMath::sqrtInverse(a.m_quad.v[1]);
self.v[2] = hkMath::sqrtInverse(a.m_quad.v[2]);
self.v[3] = hkMath::sqrtInverse(a.m_quad.v[3]);
}
break; // HK_ACC_FULL
}
} };
template <hkMathAccuracyMode A>
struct unrolld_setSqrtInverse<A, HK_SQRT_SET_ZERO> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, hkVector4dParameter a)
{
switch (A)
{
case HK_ACC_23_BIT:
{
self.v[0] = ((a.m_quad.v[0] <= hkDouble64(0)) ? hkDouble64(0) : hkDouble64(hkMath::invSqrtF32Approx23Bit(hkFloat32(a.m_quad.v[0]))));
self.v[1] = ((a.m_quad.v[1] <= hkDouble64(0)) ? hkDouble64(0) : hkDouble64(hkMath::invSqrtF32Approx23Bit(hkFloat32(a.m_quad.v[1]))));
self.v[2] = ((a.m_quad.v[2] <= hkDouble64(0)) ? hkDouble64(0) : hkDouble64(hkMath::invSqrtF32Approx23Bit(hkFloat32(a.m_quad.v[2]))));
self.v[3] = ((a.m_quad.v[3] <= hkDouble64(0)) ? hkDouble64(0) : hkDouble64(hkMath::invSqrtF32Approx23Bit(hkFloat32(a.m_quad.v[3]))));
}
break;
case HK_ACC_12_BIT:
{
self.v[0] = ((a.m_quad.v[0] <= hkDouble64(0)) ? hkDouble64(0) : hkDouble64(hkMath::invSqrtF32Approx12Bit(hkFloat32(a.m_quad.v[0]))));
self.v[1] = ((a.m_quad.v[1] <= hkDouble64(0)) ? hkDouble64(0) : hkDouble64(hkMath::invSqrtF32Approx12Bit(hkFloat32(a.m_quad.v[1]))));
self.v[2] = ((a.m_quad.v[2] <= hkDouble64(0)) ? hkDouble64(0) : hkDouble64(hkMath::invSqrtF32Approx12Bit(hkFloat32(a.m_quad.v[2]))));
self.v[3] = ((a.m_quad.v[3] <= hkDouble64(0)) ? hkDouble64(0) : hkDouble64(hkMath::invSqrtF32Approx12Bit(hkFloat32(a.m_quad.v[3]))));
}
break;
default:
{
self.v[0] = ((a.m_quad.v[0] <= hkDouble64(0)) ? hkDouble64(0) : hkMath::sqrtInverse(a.m_quad.v[0]));
self.v[1] = ((a.m_quad.v[1] <= hkDouble64(0)) ? hkDouble64(0) : hkMath::sqrtInverse(a.m_quad.v[1]));
self.v[2] = ((a.m_quad.v[2] <= hkDouble64(0)) ? hkDouble64(0) : hkMath::sqrtInverse(a.m_quad.v[2]));
self.v[3] = ((a.m_quad.v[3] <= hkDouble64(0)) ? hkDouble64(0) : hkMath::sqrtInverse(a.m_quad.v[3]));
}
break; // HK_ACC_FULL
}
} };
} // namespace
template <hkMathAccuracyMode A, hkMathNegSqrtMode S>
HK_FORCE_INLINE void hkVector4d::setSqrtInverse(hkVector4dParameter a)
{
hkVector4_AdvancedInterface::unrolld_setSqrtInverse<A,S>::apply(m_quad, a);
}
HK_FORCE_INLINE void hkVector4d::setSqrtInverse(hkVector4dParameter a)
{
hkVector4_AdvancedInterface::unrolld_setSqrtInverse<HK_ACC_23_BIT,HK_SQRT_SET_ZERO>::apply(m_quad, a);
}
namespace hkVector4_AdvancedInterface
{
template <int N, hkMathIoMode A>
struct unrolld_load { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, const hkFloat32* HK_RESTRICT p)
{
HK_VECTOR4d_TEMPLATE_CONFIG_NOT_IMPLEMENTED;
} };
template <int N, hkMathIoMode A>
struct unrolld_load_D { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, const hkDouble64* HK_RESTRICT p)
{
HK_VECTOR4d_TEMPLATE_CONFIG_NOT_IMPLEMENTED;
} };
template <int N>
struct unrolld_load<N, HK_IO_BYTE_ALIGNED> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, const hkFloat32* HK_RESTRICT p)
{
self.v[0] = hkDouble64(p[0]);
if ( N >= 2){ self.v[1] = hkDouble64(p[1]); }
if ( N >= 3){ self.v[2] = hkDouble64(p[2]); }
if ( N >= 4){ self.v[3] = hkDouble64(p[3]); }
#if defined(HK_DEBUG)
#if defined(HK_REAL_IS_DOUBLE)
for(int i=N; i<4; ++i) *((hkUint64*)&(self.v[i])) = 0xffffffffffffffffull;
#else
for(int i=N; i<4; ++i) *((hkUint32*)&(self.v[i])) = 0xffffffff;
#endif
#endif
} };
template <int N>
struct unrolld_load_D<N, HK_IO_BYTE_ALIGNED> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, const hkDouble64* HK_RESTRICT p)
{
self.v[0] = hkDouble64(p[0]);
if ( N >= 2){ self.v[1] = hkDouble64(p[1]); }
if ( N >= 3){ self.v[2] = hkDouble64(p[2]); }
if ( N >= 4){ self.v[3] = hkDouble64(p[3]); }
#if defined(HK_DEBUG)
#if defined(HK_REAL_IS_DOUBLE)
for(int i=N; i<4; ++i) *((hkUint64*)&(self.v[i])) = 0xffffffffffffffffull;
#else
for(int i=N; i<4; ++i) *((hkUint32*)&(self.v[i])) = 0xffffffff;
#endif
#endif
} };
template <int N>
struct unrolld_load<N, HK_IO_NATIVE_ALIGNED> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, const hkFloat32* HK_RESTRICT p)
{
HK_MATH_ASSERT(0x64211c2f, ( ((hkUlong)p) & (sizeof(hkFloat32)-1) ) == 0, "pointer must be aligned to native size of hkFloat32.");
unrolld_load<N, HK_IO_BYTE_ALIGNED>::apply(self,p);
} };
template <int N>
struct unrolld_load_D<N, HK_IO_NATIVE_ALIGNED> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, const hkDouble64* HK_RESTRICT p)
{
HK_MATH_ASSERT(0x64211c2f, ( ((hkUlong)p) & (sizeof(hkDouble64)-1) ) == 0, "pointer must be aligned to native size of hkDouble64.");
unrolld_load_D<N, HK_IO_BYTE_ALIGNED>::apply(self,p);
} };
template <int N>
struct unrolld_load<N, HK_IO_SIMD_ALIGNED> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, const hkFloat32* HK_RESTRICT p)
{
#if !defined(HK_ALIGN_RELAX_CHECKS)
HK_MATH_ASSERT(0x64211c2f, ( ((hkUlong)p) & ((sizeof(hkFloat32)*(N!=3?N:4) )-1) ) == 0, "pointer must be aligned for SIMD.");
#endif
unrolld_load<N, HK_IO_NATIVE_ALIGNED>::apply(self,p);
} };
template <int N>
struct unrolld_load_D<N, HK_IO_SIMD_ALIGNED> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, const hkDouble64* HK_RESTRICT p)
{
#if !defined(HK_ALIGN_RELAX_CHECKS)
HK_MATH_ASSERT(0x64211c2f, ( ((hkUlong)p) & ((sizeof(hkDouble64)*(N!=3?N:4) )-1) ) == 0, "pointer must be aligned for SIMD.");
#endif
unrolld_load_D<N, HK_IO_NATIVE_ALIGNED>::apply(self,p);
} };
template <int N>
struct unrolld_load<N, HK_IO_NOT_CACHED> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, const hkFloat32* HK_RESTRICT p)
{
unrolld_load<N, HK_IO_SIMD_ALIGNED>::apply(self,p);
} };
template <int N>
struct unrolld_load_D<N, HK_IO_NOT_CACHED> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, const hkDouble64* HK_RESTRICT p)
{
unrolld_load_D<N, HK_IO_SIMD_ALIGNED>::apply(self,p);
} };
} // namespace
template <int N, hkMathIoMode A>
HK_FORCE_INLINE void hkVector4d::load(const hkFloat32* p)
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
hkVector4_AdvancedInterface::unrolld_load<N,A>::apply(m_quad, p);
}
template <int N, hkMathIoMode A>
HK_FORCE_INLINE void hkVector4d::load(const hkDouble64* p)
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
hkVector4_AdvancedInterface::unrolld_load_D<N,A>::apply(m_quad, p);
}
template <int N>
HK_FORCE_INLINE void hkVector4d::load(const hkFloat32* p)
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
hkVector4_AdvancedInterface::unrolld_load<N,HK_IO_SIMD_ALIGNED>::apply(m_quad, p);
}
template <int N>
HK_FORCE_INLINE void hkVector4d::load(const hkDouble64* p)
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
hkVector4_AdvancedInterface::unrolld_load_D<N,HK_IO_SIMD_ALIGNED>::apply(m_quad, p);
}
namespace hkVector4_AdvancedInterface
{
template <int N, hkMathIoMode A>
struct unrolld_loadH { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, const hkHalf* HK_RESTRICT p)
{
HK_VECTOR4d_TEMPLATE_CONFIG_NOT_IMPLEMENTED;
} };
template <int N>
struct unrolld_loadH<N, HK_IO_BYTE_ALIGNED> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, const hkHalf* HK_RESTRICT p)
{
switch (N)
{
case 4: self.v[3] = p[3].getReal();
case 3: self.v[2] = p[2].getReal();
case 2: self.v[1] = p[1].getReal();
default: self.v[0] = p[0].getReal(); break;
}
#if defined(HK_REAL_IS_DOUBLE)
for(int i=N; i<4; ++i) *((hkUint64*)&(self.v[i])) = 0xffffffffffffffffull;
#else
for(int i=N; i<4; ++i) *((hkUint32*)&(self.v[i])) = 0xffffffff;
#endif
} };
template <int N>
struct unrolld_loadH<N, HK_IO_NATIVE_ALIGNED> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, const hkHalf* HK_RESTRICT p)
{
HK_MATH_ASSERT(0x64211c2f, ( ((hkUlong)p) & (sizeof(hkHalf)-1) ) == 0, "pointer must be aligned to native size of hkHalf.");
unrolld_loadH<N, HK_IO_BYTE_ALIGNED>::apply(self,p);
} };
template <int N>
struct unrolld_loadH<N, HK_IO_SIMD_ALIGNED> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, const hkHalf* HK_RESTRICT p)
{
#if !defined(HK_ALIGN_RELAX_CHECKS)
HK_MATH_ASSERT(0x64211c2f, ( ((hkUlong)p) & ((sizeof(hkHalf)*(N!=3?N:4) )-1) ) == 0, "pointer must be aligned for SIMD.");
#endif
unrolld_loadH<N, HK_IO_NATIVE_ALIGNED>::apply(self,p);
} };
template <int N>
struct unrolld_loadH<N, HK_IO_NOT_CACHED> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, const hkHalf* HK_RESTRICT p)
{
unrolld_loadH<N, HK_IO_SIMD_ALIGNED>::apply(self,p);
} };
} // namespace
template <int N, hkMathIoMode A>
HK_FORCE_INLINE void hkVector4d::load(const hkHalf* p)
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
hkVector4_AdvancedInterface::unrolld_loadH<N,A>::apply(m_quad, p);
}
template <int N>
HK_FORCE_INLINE void hkVector4d::load(const hkHalf* p)
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
hkVector4_AdvancedInterface::unrolld_loadH<N,HK_IO_SIMD_ALIGNED>::apply(m_quad, p);
}
namespace hkVector4_AdvancedInterface
{
template <int N, hkMathIoMode A>
struct unrolld_loadF16 { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, const hkFloat16* HK_RESTRICT p)
{
HK_VECTOR4d_TEMPLATE_CONFIG_NOT_IMPLEMENTED;
} };
template <int N>
struct unrolld_loadF16<N, HK_IO_BYTE_ALIGNED> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, const hkFloat16* HK_RESTRICT p)
{
switch (N)
{
case 4: self.v[3] = p[3].getReal();
case 3: self.v[2] = p[2].getReal();
case 2: self.v[1] = p[1].getReal();
default: self.v[0] = p[0].getReal(); break;
}
#if defined(HK_DEBUG)
#if defined(HK_REAL_IS_DOUBLE)
for(int i=N; i<4; ++i) *((hkUint64*)&(self.v[i])) = 0xffffffffffffffffull;
#else
for(int i=N; i<4; ++i) *((hkUint32*)&(self.v[i])) = 0xffffffff;
#endif
#endif
} };
template <int N>
struct unrolld_loadF16<N, HK_IO_NATIVE_ALIGNED> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, const hkFloat16* HK_RESTRICT p)
{
HK_MATH_ASSERT(0x64211c2f, ( ((hkUlong)p) & (sizeof(hkFloat16)-1) ) == 0, "pointer must be aligned to native size of hkFloat16.");
unrolld_loadF16<N, HK_IO_BYTE_ALIGNED>::apply(self,p);
} };
template <int N>
struct unrolld_loadF16<N, HK_IO_SIMD_ALIGNED> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, const hkFloat16* HK_RESTRICT p)
{
#if !defined(HK_ALIGN_RELAX_CHECKS)
HK_MATH_ASSERT(0x64211c2f, ( ((hkUlong)p) & ((sizeof(hkFloat16)*(N!=3?N:4) )-1) ) == 0, "pointer must be aligned for SIMD.");
#endif
unrolld_loadF16<N, HK_IO_NATIVE_ALIGNED>::apply(self,p);
} };
template <int N>
struct unrolld_loadF16<N, HK_IO_NOT_CACHED> { HK_FORCE_INLINE static void apply(hkQuadDouble64& self, const hkFloat16* HK_RESTRICT p)
{
unrolld_loadF16<N, HK_IO_SIMD_ALIGNED>::apply(self,p);
} };
} // namespace
template <int N, hkMathIoMode A>
HK_FORCE_INLINE void hkVector4d::load(const hkFloat16* p)
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
hkVector4_AdvancedInterface::unrolld_loadF16<N,A>::apply(m_quad, p);
}
template <int N>
HK_FORCE_INLINE void hkVector4d::load(const hkFloat16* p)
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
hkVector4_AdvancedInterface::unrolld_loadF16<N,HK_IO_SIMD_ALIGNED>::apply(m_quad, p);
}
namespace hkVector4_AdvancedInterface
{
template <int N, hkMathIoMode A>
struct unrolld_store { HK_FORCE_INLINE static void apply(const hkQuadDouble64& self, hkFloat32* HK_RESTRICT p)
{
HK_VECTOR4d_TEMPLATE_CONFIG_NOT_IMPLEMENTED;
} };
template <int N, hkMathIoMode A>
struct unrolld_store_D { HK_FORCE_INLINE static void apply(const hkQuadDouble64& self, hkDouble64* HK_RESTRICT p)
{
HK_VECTOR4d_TEMPLATE_CONFIG_NOT_IMPLEMENTED;
} };
template <int N>
struct unrolld_store<N, HK_IO_BYTE_ALIGNED> { HK_FORCE_INLINE static void apply(const hkQuadDouble64& self, hkFloat32* HK_RESTRICT p)
{
p[0] = hkFloat32(self.v[0]);
if ( N >= 2){ p[1] = hkFloat32(self.v[1]); }
if ( N >= 3){ p[2] = hkFloat32(self.v[2]); }
if ( N >= 4){ p[3] = hkFloat32(self.v[3]); }
} };
template <int N>
struct unrolld_store_D<N, HK_IO_BYTE_ALIGNED> { HK_FORCE_INLINE static void apply(const hkQuadDouble64& self, hkDouble64* HK_RESTRICT p)
{
p[0] = hkDouble64(self.v[0]);
if ( N >= 2){ p[1] = hkDouble64(self.v[1]); }
if ( N >= 3){ p[2] = hkDouble64(self.v[2]); }
if ( N >= 4){ p[3] = hkDouble64(self.v[3]); }
} };
template <int N>
struct unrolld_store<N, HK_IO_NATIVE_ALIGNED> { HK_FORCE_INLINE static void apply(const hkQuadDouble64& self, hkFloat32* HK_RESTRICT p)
{
HK_MATH_ASSERT(0x64211c2f, ( ((hkUlong)p) & (sizeof(hkFloat32)-1) ) == 0, "pointer must be aligned to native size of hkFloat32.");
unrolld_store<N, HK_IO_BYTE_ALIGNED>::apply(self,p);
} };
template <int N>
struct unrolld_store_D<N, HK_IO_NATIVE_ALIGNED> { HK_FORCE_INLINE static void apply(const hkQuadDouble64& self, hkDouble64* HK_RESTRICT p)
{
HK_MATH_ASSERT(0x64211c2f, ( ((hkUlong)p) & (sizeof(hkDouble64)-1) ) == 0, "pointer must be aligned to native size of hkDouble64.");
unrolld_store_D<N, HK_IO_BYTE_ALIGNED>::apply(self,p);
} };
template <int N>
struct unrolld_store<N, HK_IO_SIMD_ALIGNED> { HK_FORCE_INLINE static void apply(const hkQuadDouble64& self, hkFloat32* HK_RESTRICT p)
{
#if !defined(HK_ALIGN_RELAX_CHECKS)
HK_MATH_ASSERT(0x64211c2f, ( ((hkUlong)p) & ((sizeof(hkFloat32)*(N!=3?N:4) )-1) ) == 0, "pointer must be aligned for SIMD.");
#endif
unrolld_store<N, HK_IO_NATIVE_ALIGNED>::apply(self,p);
} };
template <int N>
struct unrolld_store_D<N, HK_IO_SIMD_ALIGNED> { HK_FORCE_INLINE static void apply(const hkQuadDouble64& self, hkDouble64* HK_RESTRICT p)
{
#if !defined(HK_ALIGN_RELAX_CHECKS)
HK_MATH_ASSERT(0x64211c2f, ( ((hkUlong)p) & ((sizeof(hkDouble64)*(N!=3?N:4) )-1) ) == 0, "pointer must be aligned for SIMD.");
#endif
unrolld_store_D<N, HK_IO_NATIVE_ALIGNED>::apply(self,p);
} };
template <int N>
struct unrolld_store<N, HK_IO_NOT_CACHED> { HK_FORCE_INLINE static void apply(const hkQuadDouble64& self, hkFloat32* HK_RESTRICT p)
{
unrolld_store<N, HK_IO_SIMD_ALIGNED>::apply(self,p);
} };
template <int N>
struct unrolld_store_D<N, HK_IO_NOT_CACHED> { HK_FORCE_INLINE static void apply(const hkQuadDouble64& self, hkDouble64* HK_RESTRICT p)
{
unrolld_store_D<N, HK_IO_SIMD_ALIGNED>::apply(self,p);
} };
} // namespace
template <int N, hkMathIoMode A, hkMathRoundingMode R>
HK_FORCE_INLINE void hkVector4d::store(hkFloat32* p) const
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
hkVector4_AdvancedInterface::unrolld_store<N,A>::apply(m_quad, p);
}
template <int N, hkMathIoMode A, hkMathRoundingMode R>
HK_FORCE_INLINE void hkVector4d::store(hkDouble64* p) const
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
hkVector4_AdvancedInterface::unrolld_store_D<N,A>::apply(m_quad, p);
}
template <int N, hkMathIoMode A>
HK_FORCE_INLINE void hkVector4d::store(hkFloat32* p) const
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
hkVector4_AdvancedInterface::unrolld_store<N,A>::apply(m_quad, p);
}
template <int N, hkMathIoMode A>
HK_FORCE_INLINE void hkVector4d::store(hkDouble64* p) const
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
hkVector4_AdvancedInterface::unrolld_store_D<N,A>::apply(m_quad, p);
}
template <int N>
HK_FORCE_INLINE void hkVector4d::store(hkFloat32* p) const
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
hkVector4_AdvancedInterface::unrolld_store<N,HK_IO_SIMD_ALIGNED>::apply(m_quad, p);
}
template <int N>
HK_FORCE_INLINE void hkVector4d::store(hkDouble64* p) const
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
hkVector4_AdvancedInterface::unrolld_store_D<N,HK_IO_SIMD_ALIGNED>::apply(m_quad, p);
}
namespace hkVector4_AdvancedInterface
{
template <int N, hkMathIoMode A, hkMathRoundingMode R>
struct unrolld_storeH { HK_FORCE_INLINE static void apply(const hkQuadDouble64& self, hkHalf* HK_RESTRICT p)
{
HK_VECTOR4d_TEMPLATE_CONFIG_NOT_IMPLEMENTED;
} };
template <int N, hkMathRoundingMode R>
struct unrolld_storeH<N, HK_IO_BYTE_ALIGNED, R> { HK_FORCE_INLINE static void apply(const hkQuadDouble64& self, hkHalf* HK_RESTRICT p)
{
switch (N)
{
case 4: p[3].set<(R == HK_ROUND_NEAREST)>(self.v[3]);
case 3: p[2].set<(R == HK_ROUND_NEAREST)>(self.v[2]);
case 2: p[1].set<(R == HK_ROUND_NEAREST)>(self.v[1]);
default: p[0].set<(R == HK_ROUND_NEAREST)>(self.v[0]); break;
}
} };
template <int N, hkMathRoundingMode R>
struct unrolld_storeH<N, HK_IO_NATIVE_ALIGNED, R> { HK_FORCE_INLINE static void apply(const hkQuadDouble64& self, hkHalf* HK_RESTRICT p)
{
HK_MATH_ASSERT(0x64211c2f, ( ((hkUlong)p) & (sizeof(hkHalf)-1) ) == 0, "pointer must be aligned to native size of hkHalf.");
unrolld_storeH<N, HK_IO_BYTE_ALIGNED, R>::apply(self,p);
} };
template <int N, hkMathRoundingMode R>
struct unrolld_storeH<N, HK_IO_SIMD_ALIGNED, R> { HK_FORCE_INLINE static void apply(const hkQuadDouble64& self, hkHalf* HK_RESTRICT p)
{
#if !defined(HK_ALIGN_RELAX_CHECKS)
HK_MATH_ASSERT(0x64211c2f, ( ((hkUlong)p) & ((sizeof(hkHalf)*(N!=3?N:4) )-1) ) == 0, "pointer must be aligned for SIMD.");
#endif
unrolld_storeH<N, HK_IO_NATIVE_ALIGNED, R>::apply(self,p);
} };
template <int N, hkMathRoundingMode R>
struct unrolld_storeH<N, HK_IO_NOT_CACHED, R> { HK_FORCE_INLINE static void apply(const hkQuadDouble64& self, hkHalf* HK_RESTRICT p)
{
unrolld_storeH<N, HK_IO_SIMD_ALIGNED, R>::apply(self,p);
} };
} // namespace
template <int N, hkMathIoMode A, hkMathRoundingMode R>
HK_FORCE_INLINE void hkVector4d::store(hkHalf* p) const
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
hkVector4_AdvancedInterface::unrolld_storeH<N,A,R>::apply(m_quad, p);
}
template <int N, hkMathIoMode A>
HK_FORCE_INLINE void hkVector4d::store(hkHalf* p) const
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
hkVector4_AdvancedInterface::unrolld_storeH<N,A,HK_ROUND_DEFAULT>::apply(m_quad, p);
}
template <int N>
HK_FORCE_INLINE void hkVector4d::store(hkHalf* p) const
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
hkVector4_AdvancedInterface::unrolld_storeH<N,HK_IO_SIMD_ALIGNED,HK_ROUND_DEFAULT>::apply(m_quad, p);
}
namespace hkVector4_AdvancedInterface
{
template <int N, hkMathIoMode A, hkMathRoundingMode R>
struct unrolld_storeF16 { HK_FORCE_INLINE static void apply(const hkQuadDouble64& self, hkFloat16* HK_RESTRICT p)
{
HK_VECTOR4d_TEMPLATE_CONFIG_NOT_IMPLEMENTED;
} };
template <int N, hkMathRoundingMode R>
struct unrolld_storeF16<N, HK_IO_BYTE_ALIGNED, R> { HK_FORCE_INLINE static void apply(const hkQuadDouble64& self, hkFloat16* HK_RESTRICT p)
{
switch (N)
{
case 4: p[3].setReal<(R == HK_ROUND_NEAREST)>(self.v[3]);
case 3: p[2].setReal<(R == HK_ROUND_NEAREST)>(self.v[2]);
case 2: p[1].setReal<(R == HK_ROUND_NEAREST)>(self.v[1]);
default: p[0].setReal<(R == HK_ROUND_NEAREST)>(self.v[0]); break;
}
} };
template <int N, hkMathRoundingMode R>
struct unrolld_storeF16<N, HK_IO_NATIVE_ALIGNED, R> { HK_FORCE_INLINE static void apply(const hkQuadDouble64& self, hkFloat16* HK_RESTRICT p)
{
HK_MATH_ASSERT(0x64211c2f, ( ((hkUlong)p) & (sizeof(hkFloat16)-1) ) == 0, "pointer must be aligned to native size of hkFloat16.");
unrolld_storeF16<N, HK_IO_BYTE_ALIGNED, R>::apply(self,p);
} };
template <int N, hkMathRoundingMode R>
struct unrolld_storeF16<N, HK_IO_SIMD_ALIGNED, R> { HK_FORCE_INLINE static void apply(const hkQuadDouble64& self, hkFloat16* HK_RESTRICT p)
{
#if !defined(HK_ALIGN_RELAX_CHECKS)
HK_MATH_ASSERT(0x64211c2f, ( ((hkUlong)p) & ((sizeof(hkFloat16)*(N!=3?N:4) )-1) ) == 0, "pointer must be aligned for SIMD.");
#endif
unrolld_storeF16<N, HK_IO_NATIVE_ALIGNED, R>::apply(self,p);
} };
template <int N, hkMathRoundingMode R>
struct unrolld_storeF16<N, HK_IO_NOT_CACHED, R> { HK_FORCE_INLINE static void apply(const hkQuadDouble64& self, hkFloat16* HK_RESTRICT p)
{
unrolld_storeF16<N, HK_IO_SIMD_ALIGNED, R>::apply(self,p);
} };
} // namespace
template <int N, hkMathIoMode A, hkMathRoundingMode R>
HK_FORCE_INLINE void hkVector4d::store(hkFloat16* p) const
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
hkVector4_AdvancedInterface::unrolld_storeF16<N,A,R>::apply(m_quad, p);
}
template <int N, hkMathIoMode A>
HK_FORCE_INLINE void hkVector4d::store(hkFloat16* p) const
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
hkVector4_AdvancedInterface::unrolld_storeF16<N,A,HK_ROUND_DEFAULT>::apply(m_quad, p);
}
template <int N>
HK_FORCE_INLINE void hkVector4d::store(hkFloat16* p) const
{
HK_VECTOR4d_UNSUPPORTED_LENGTH_CHECK;
hkVector4_AdvancedInterface::unrolld_storeF16<N,HK_IO_SIMD_ALIGNED,HK_ROUND_DEFAULT>::apply(m_quad, p);
}
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20130718)
*
* Confidential Information of Havok. (C) Copyright 1999-2013
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at www.havok.com/tryhavok.
*
*/
| 41.014148
| 251
| 0.711682
|
aditgoyal19
|
1d93653231cf943e781ad1604b86d76d83d0a698
| 1,150
|
cpp
|
C++
|
src/btr/native_io.win.cpp
|
vector-of-bool/batteries
|
8be07c729e0461e8e0b50c89c5ac9b90e48452a8
|
[
"BSL-1.0"
] | 2
|
2021-08-02T15:04:33.000Z
|
2021-08-10T05:07:46.000Z
|
src/btr/native_io.win.cpp
|
vector-of-bool/batteries
|
8be07c729e0461e8e0b50c89c5ac9b90e48452a8
|
[
"BSL-1.0"
] | null | null | null |
src/btr/native_io.win.cpp
|
vector-of-bool/batteries
|
8be07c729e0461e8e0b50c89c5ac9b90e48452a8
|
[
"BSL-1.0"
] | null | null | null |
#include "./native_io.hpp"
#include "./syserror.hpp"
using namespace btr;
#if _WIN32
#include <windows.h>
void win32_handle_traits::close(HANDLE h) noexcept { ::CloseHandle(h); }
std::size_t win32_handle_traits::write(HANDLE h, const_buffer buf) {
neo_assert(expects,
h != null_handle,
"Attempted to write data to a closed HANDLE",
std::string_view(buf),
buf.size());
DWORD nwritten = 0;
auto okay = ::WriteFile(h, buf.data(), static_cast<DWORD>(buf.size()), &nwritten, nullptr);
if (!okay) {
throw_current_error("::WriteFile() failed");
}
return static_cast<std::size_t>(nwritten);
}
std::size_t win32_handle_traits::read(HANDLE h, mutable_buffer buf) {
neo_assert(expects,
h != null_handle,
"Attempted to read data from a closed HANDLE",
buf.size());
DWORD nread = 0;
auto okay = ::ReadFile(h, buf.data(), static_cast<DWORD>(buf.size()), &nread, nullptr);
if (!okay) {
throw_current_error("::ReadFile() failed");
}
return static_cast<std::size_t>(nread);
}
#endif
| 28.04878
| 100
| 0.607826
|
vector-of-bool
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.